clang  3.7.0
ExprConstant.cpp
Go to the documentation of this file.
1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Expr constant evaluator.
11 //
12 // Constant expression evaluation produces four main results:
13 //
14 // * A success/failure flag indicating whether constant folding was successful.
15 // This is the 'bool' return value used by most of the code in this file. A
16 // 'false' return value indicates that constant folding has failed, and any
17 // appropriate diagnostic has already been produced.
18 //
19 // * An evaluated result, valid only if constant folding has not failed.
20 //
21 // * A flag indicating if evaluation encountered (unevaluated) side-effects.
22 // These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
23 // where it is possible to determine the evaluated result regardless.
24 //
25 // * A set of notes indicating why the evaluation was not a constant expression
26 // (under the C++11 / C++1y rules only, at the moment), or, if folding failed
27 // too, why the expression could not be folded.
28 //
29 // If we are checking for a potential constant expression, failure to constant
30 // fold a potential constant sub-expression will be indicated by a 'false'
31 // return value (the expression could not be folded) and no diagnostic (the
32 // expression is not necessarily non-constant).
33 //
34 //===----------------------------------------------------------------------===//
35 
36 #include "clang/AST/APValue.h"
37 #include "clang/AST/ASTContext.h"
39 #include "clang/AST/CharUnits.h"
40 #include "clang/AST/Expr.h"
41 #include "clang/AST/RecordLayout.h"
42 #include "clang/AST/StmtVisitor.h"
43 #include "clang/AST/TypeLoc.h"
44 #include "clang/Basic/Builtins.h"
45 #include "clang/Basic/TargetInfo.h"
46 #include "llvm/ADT/SmallString.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include <cstring>
49 #include <functional>
50 
51 using namespace clang;
52 using llvm::APSInt;
53 using llvm::APFloat;
54 
55 static bool IsGlobalLValue(APValue::LValueBase B);
56 
57 namespace {
58  struct LValue;
59  struct CallStackFrame;
60  struct EvalInfo;
61 
62  static QualType getType(APValue::LValueBase B) {
63  if (!B) return QualType();
64  if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
65  return D->getType();
66 
67  const Expr *Base = B.get<const Expr*>();
68 
69  // For a materialized temporary, the type of the temporary we materialized
70  // may not be the type of the expression.
71  if (const MaterializeTemporaryExpr *MTE =
72  dyn_cast<MaterializeTemporaryExpr>(Base)) {
75  const Expr *Temp = MTE->GetTemporaryExpr();
76  const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
77  Adjustments);
78  // Keep any cv-qualifiers from the reference if we generated a temporary
79  // for it.
80  if (Inner != Temp)
81  return Inner->getType();
82  }
83 
84  return Base->getType();
85  }
86 
87  /// Get an LValue path entry, which is known to not be an array index, as a
88  /// field or base class.
89  static
92  Value.setFromOpaqueValue(E.BaseOrMember);
93  return Value;
94  }
95 
96  /// Get an LValue path entry, which is known to not be an array index, as a
97  /// field declaration.
98  static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
99  return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
100  }
101  /// Get an LValue path entry, which is known to not be an array index, as a
102  /// base class declaration.
103  static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
104  return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
105  }
106  /// Determine whether this LValue path entry for a base class names a virtual
107  /// base class.
108  static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
109  return getAsBaseOrMember(E).getInt();
110  }
111 
112  /// Find the path length and type of the most-derived subobject in the given
113  /// path, and find the size of the containing array, if any.
114  static
115  unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
117  uint64_t &ArraySize, QualType &Type) {
118  unsigned MostDerivedLength = 0;
119  Type = Base;
120  for (unsigned I = 0, N = Path.size(); I != N; ++I) {
121  if (Type->isArrayType()) {
122  const ConstantArrayType *CAT =
123  cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
124  Type = CAT->getElementType();
125  ArraySize = CAT->getSize().getZExtValue();
126  MostDerivedLength = I + 1;
127  } else if (Type->isAnyComplexType()) {
128  const ComplexType *CT = Type->castAs<ComplexType>();
129  Type = CT->getElementType();
130  ArraySize = 2;
131  MostDerivedLength = I + 1;
132  } else if (const FieldDecl *FD = getAsField(Path[I])) {
133  Type = FD->getType();
134  ArraySize = 0;
135  MostDerivedLength = I + 1;
136  } else {
137  // Path[I] describes a base class.
138  ArraySize = 0;
139  }
140  }
141  return MostDerivedLength;
142  }
143 
144  // The order of this enum is important for diagnostics.
146  CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
147  CSK_This, CSK_Real, CSK_Imag
148  };
149 
150  /// A path from a glvalue to a subobject of that glvalue.
151  struct SubobjectDesignator {
152  /// True if the subobject was named in a manner not supported by C++11. Such
153  /// lvalues can still be folded, but they are not core constant expressions
154  /// and we cannot perform lvalue-to-rvalue conversions on them.
155  bool Invalid : 1;
156 
157  /// Is this a pointer one past the end of an object?
158  bool IsOnePastTheEnd : 1;
159 
160  /// The length of the path to the most-derived object of which this is a
161  /// subobject.
162  unsigned MostDerivedPathLength : 30;
163 
164  /// The size of the array of which the most-derived object is an element, or
165  /// 0 if the most-derived object is not an array element.
166  uint64_t MostDerivedArraySize;
167 
168  /// The type of the most derived object referred to by this address.
169  QualType MostDerivedType;
170 
171  typedef APValue::LValuePathEntry PathEntry;
172 
173  /// The entries on the path from the glvalue to the designated subobject.
175 
176  SubobjectDesignator() : Invalid(true) {}
177 
178  explicit SubobjectDesignator(QualType T)
179  : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
180  MostDerivedArraySize(0), MostDerivedType(T) {}
181 
182  SubobjectDesignator(ASTContext &Ctx, const APValue &V)
183  : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
184  MostDerivedPathLength(0), MostDerivedArraySize(0) {
185  if (!Invalid) {
186  IsOnePastTheEnd = V.isLValueOnePastTheEnd();
187  ArrayRef<PathEntry> VEntries = V.getLValuePath();
188  Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
189  if (V.getLValueBase())
190  MostDerivedPathLength =
191  findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
192  V.getLValuePath(), MostDerivedArraySize,
193  MostDerivedType);
194  }
195  }
196 
197  void setInvalid() {
198  Invalid = true;
199  Entries.clear();
200  }
201 
202  /// Determine whether this is a one-past-the-end pointer.
203  bool isOnePastTheEnd() const {
204  assert(!Invalid);
205  if (IsOnePastTheEnd)
206  return true;
207  if (MostDerivedArraySize &&
208  Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
209  return true;
210  return false;
211  }
212 
213  /// Check that this refers to a valid subobject.
214  bool isValidSubobject() const {
215  if (Invalid)
216  return false;
217  return !isOnePastTheEnd();
218  }
219  /// Check that this refers to a valid subobject, and if not, produce a
220  /// relevant diagnostic and set the designator as invalid.
221  bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
222 
223  /// Update this designator to refer to the first element within this array.
224  void addArrayUnchecked(const ConstantArrayType *CAT) {
225  PathEntry Entry;
226  Entry.ArrayIndex = 0;
227  Entries.push_back(Entry);
228 
229  // This is a most-derived object.
230  MostDerivedType = CAT->getElementType();
231  MostDerivedArraySize = CAT->getSize().getZExtValue();
232  MostDerivedPathLength = Entries.size();
233  }
234  /// Update this designator to refer to the given base or member of this
235  /// object.
236  void addDeclUnchecked(const Decl *D, bool Virtual = false) {
237  PathEntry Entry;
238  APValue::BaseOrMemberType Value(D, Virtual);
239  Entry.BaseOrMember = Value.getOpaqueValue();
240  Entries.push_back(Entry);
241 
242  // If this isn't a base class, it's a new most-derived object.
243  if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
244  MostDerivedType = FD->getType();
245  MostDerivedArraySize = 0;
246  MostDerivedPathLength = Entries.size();
247  }
248  }
249  /// Update this designator to refer to the given complex component.
250  void addComplexUnchecked(QualType EltTy, bool Imag) {
251  PathEntry Entry;
252  Entry.ArrayIndex = Imag;
253  Entries.push_back(Entry);
254 
255  // This is technically a most-derived object, though in practice this
256  // is unlikely to matter.
257  MostDerivedType = EltTy;
258  MostDerivedArraySize = 2;
259  MostDerivedPathLength = Entries.size();
260  }
261  void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
262  /// Add N to the address of this subobject.
263  void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
264  if (Invalid) return;
265  if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
266  Entries.back().ArrayIndex += N;
267  if (Entries.back().ArrayIndex > MostDerivedArraySize) {
268  diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
269  setInvalid();
270  }
271  return;
272  }
273  // [expr.add]p4: For the purposes of these operators, a pointer to a
274  // nonarray object behaves the same as a pointer to the first element of
275  // an array of length one with the type of the object as its element type.
276  if (IsOnePastTheEnd && N == (uint64_t)-1)
277  IsOnePastTheEnd = false;
278  else if (!IsOnePastTheEnd && N == 1)
279  IsOnePastTheEnd = true;
280  else if (N != 0) {
281  diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
282  setInvalid();
283  }
284  }
285  };
286 
287  /// A stack frame in the constexpr call stack.
288  struct CallStackFrame {
289  EvalInfo &Info;
290 
291  /// Parent - The caller of this stack frame.
292  CallStackFrame *Caller;
293 
294  /// CallLoc - The location of the call expression for this call.
295  SourceLocation CallLoc;
296 
297  /// Callee - The function which was called.
298  const FunctionDecl *Callee;
299 
300  /// Index - The call index of this call.
301  unsigned Index;
302 
303  /// This - The binding for the this pointer in this call, if any.
304  const LValue *This;
305 
306  /// Arguments - Parameter bindings for this function call, indexed by
307  /// parameters' function scope indices.
308  APValue *Arguments;
309 
310  // Note that we intentionally use std::map here so that references to
311  // values are stable.
312  typedef std::map<const void*, APValue> MapTy;
313  typedef MapTy::const_iterator temp_iterator;
314  /// Temporaries - Temporary lvalues materialized within this stack frame.
315  MapTy Temporaries;
316 
317  CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
318  const FunctionDecl *Callee, const LValue *This,
319  APValue *Arguments);
320  ~CallStackFrame();
321 
322  APValue *getTemporary(const void *Key) {
323  MapTy::iterator I = Temporaries.find(Key);
324  return I == Temporaries.end() ? nullptr : &I->second;
325  }
326  APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
327  };
328 
329  /// Temporarily override 'this'.
330  class ThisOverrideRAII {
331  public:
332  ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
333  : Frame(Frame), OldThis(Frame.This) {
334  if (Enable)
335  Frame.This = NewThis;
336  }
337  ~ThisOverrideRAII() {
338  Frame.This = OldThis;
339  }
340  private:
341  CallStackFrame &Frame;
342  const LValue *OldThis;
343  };
344 
345  /// A partial diagnostic which we might know in advance that we are not going
346  /// to emit.
347  class OptionalDiagnostic {
349 
350  public:
351  explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
352  : Diag(Diag) {}
353 
354  template<typename T>
355  OptionalDiagnostic &operator<<(const T &v) {
356  if (Diag)
357  *Diag << v;
358  return *this;
359  }
360 
361  OptionalDiagnostic &operator<<(const APSInt &I) {
362  if (Diag) {
363  SmallVector<char, 32> Buffer;
364  I.toString(Buffer);
365  *Diag << StringRef(Buffer.data(), Buffer.size());
366  }
367  return *this;
368  }
369 
370  OptionalDiagnostic &operator<<(const APFloat &F) {
371  if (Diag) {
372  // FIXME: Force the precision of the source value down so we don't
373  // print digits which are usually useless (we don't really care here if
374  // we truncate a digit by accident in edge cases). Ideally,
375  // APFloat::toString would automatically print the shortest
376  // representation which rounds to the correct value, but it's a bit
377  // tricky to implement.
378  unsigned precision =
379  llvm::APFloat::semanticsPrecision(F.getSemantics());
380  precision = (precision * 59 + 195) / 196;
381  SmallVector<char, 32> Buffer;
382  F.toString(Buffer, precision);
383  *Diag << StringRef(Buffer.data(), Buffer.size());
384  }
385  return *this;
386  }
387  };
388 
389  /// A cleanup, and a flag indicating whether it is lifetime-extended.
390  class Cleanup {
391  llvm::PointerIntPair<APValue*, 1, bool> Value;
392 
393  public:
394  Cleanup(APValue *Val, bool IsLifetimeExtended)
395  : Value(Val, IsLifetimeExtended) {}
396 
397  bool isLifetimeExtended() const { return Value.getInt(); }
398  void endLifetime() {
399  *Value.getPointer() = APValue();
400  }
401  };
402 
403  /// EvalInfo - This is a private struct used by the evaluator to capture
404  /// information about a subexpression as it is folded. It retains information
405  /// about the AST context, but also maintains information about the folded
406  /// expression.
407  ///
408  /// If an expression could be evaluated, it is still possible it is not a C
409  /// "integer constant expression" or constant expression. If not, this struct
410  /// captures information about how and why not.
411  ///
412  /// One bit of information passed *into* the request for constant folding
413  /// indicates whether the subexpression is "evaluated" or not according to C
414  /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
415  /// evaluate the expression regardless of what the RHS is, but C only allows
416  /// certain things in certain situations.
417  struct EvalInfo {
418  ASTContext &Ctx;
419 
420  /// EvalStatus - Contains information about the evaluation.
421  Expr::EvalStatus &EvalStatus;
422 
423  /// CurrentCall - The top of the constexpr call stack.
424  CallStackFrame *CurrentCall;
425 
426  /// CallStackDepth - The number of calls in the call stack right now.
427  unsigned CallStackDepth;
428 
429  /// NextCallIndex - The next call index to assign.
430  unsigned NextCallIndex;
431 
432  /// StepsLeft - The remaining number of evaluation steps we're permitted
433  /// to perform. This is essentially a limit for the number of statements
434  /// we will evaluate.
435  unsigned StepsLeft;
436 
437  /// BottomFrame - The frame in which evaluation started. This must be
438  /// initialized after CurrentCall and CallStackDepth.
439  CallStackFrame BottomFrame;
440 
441  /// A stack of values whose lifetimes end at the end of some surrounding
442  /// evaluation frame.
443  llvm::SmallVector<Cleanup, 16> CleanupStack;
444 
445  /// EvaluatingDecl - This is the declaration whose initializer is being
446  /// evaluated, if any.
447  APValue::LValueBase EvaluatingDecl;
448 
449  /// EvaluatingDeclValue - This is the value being constructed for the
450  /// declaration whose initializer is being evaluated, if any.
451  APValue *EvaluatingDeclValue;
452 
453  /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
454  /// notes attached to it will also be stored, otherwise they will not be.
455  bool HasActiveDiagnostic;
456 
457  enum EvaluationMode {
458  /// Evaluate as a constant expression. Stop if we find that the expression
459  /// is not a constant expression.
460  EM_ConstantExpression,
461 
462  /// Evaluate as a potential constant expression. Keep going if we hit a
463  /// construct that we can't evaluate yet (because we don't yet know the
464  /// value of something) but stop if we hit something that could never be
465  /// a constant expression.
466  EM_PotentialConstantExpression,
467 
468  /// Fold the expression to a constant. Stop if we hit a side-effect that
469  /// we can't model.
470  EM_ConstantFold,
471 
472  /// Evaluate the expression looking for integer overflow and similar
473  /// issues. Don't worry about side-effects, and try to visit all
474  /// subexpressions.
475  EM_EvaluateForOverflow,
476 
477  /// Evaluate in any way we know how. Don't worry about side-effects that
478  /// can't be modeled.
479  EM_IgnoreSideEffects,
480 
481  /// Evaluate as a constant expression. Stop if we find that the expression
482  /// is not a constant expression. Some expressions can be retried in the
483  /// optimizer if we don't constant fold them here, but in an unevaluated
484  /// context we try to fold them immediately since the optimizer never
485  /// gets a chance to look at it.
486  EM_ConstantExpressionUnevaluated,
487 
488  /// Evaluate as a potential constant expression. Keep going if we hit a
489  /// construct that we can't evaluate yet (because we don't yet know the
490  /// value of something) but stop if we hit something that could never be
491  /// a constant expression. Some expressions can be retried in the
492  /// optimizer if we don't constant fold them here, but in an unevaluated
493  /// context we try to fold them immediately since the optimizer never
494  /// gets a chance to look at it.
495  EM_PotentialConstantExpressionUnevaluated
496  } EvalMode;
497 
498  /// Are we checking whether the expression is a potential constant
499  /// expression?
500  bool checkingPotentialConstantExpression() const {
501  return EvalMode == EM_PotentialConstantExpression ||
502  EvalMode == EM_PotentialConstantExpressionUnevaluated;
503  }
504 
505  /// Are we checking an expression for overflow?
506  // FIXME: We should check for any kind of undefined or suspicious behavior
507  // in such constructs, not just overflow.
508  bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
509 
510  EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
511  : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
512  CallStackDepth(0), NextCallIndex(1),
513  StepsLeft(getLangOpts().ConstexprStepLimit),
514  BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
515  EvaluatingDecl((const ValueDecl *)nullptr),
516  EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
517  EvalMode(Mode) {}
518 
519  void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
520  EvaluatingDecl = Base;
521  EvaluatingDeclValue = &Value;
522  }
523 
524  const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
525 
526  bool CheckCallLimit(SourceLocation Loc) {
527  // Don't perform any constexpr calls (other than the call we're checking)
528  // when checking a potential constant expression.
529  if (checkingPotentialConstantExpression() && CallStackDepth > 1)
530  return false;
531  if (NextCallIndex == 0) {
532  // NextCallIndex has wrapped around.
533  Diag(Loc, diag::note_constexpr_call_limit_exceeded);
534  return false;
535  }
536  if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
537  return true;
538  Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
539  << getLangOpts().ConstexprCallDepth;
540  return false;
541  }
542 
543  CallStackFrame *getCallFrame(unsigned CallIndex) {
544  assert(CallIndex && "no call index in getCallFrame");
545  // We will eventually hit BottomFrame, which has Index 1, so Frame can't
546  // be null in this loop.
547  CallStackFrame *Frame = CurrentCall;
548  while (Frame->Index > CallIndex)
549  Frame = Frame->Caller;
550  return (Frame->Index == CallIndex) ? Frame : nullptr;
551  }
552 
553  bool nextStep(const Stmt *S) {
554  if (!StepsLeft) {
555  Diag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
556  return false;
557  }
558  --StepsLeft;
559  return true;
560  }
561 
562  private:
563  /// Add a diagnostic to the diagnostics list.
564  PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
565  PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
566  EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
567  return EvalStatus.Diag->back().second;
568  }
569 
570  /// Add notes containing a call stack to the current point of evaluation.
571  void addCallStack(unsigned Limit);
572 
573  public:
574  /// Diagnose that the evaluation cannot be folded.
575  OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
576  = diag::note_invalid_subexpr_in_const_expr,
577  unsigned ExtraNotes = 0) {
578  if (EvalStatus.Diag) {
579  // If we have a prior diagnostic, it will be noting that the expression
580  // isn't a constant expression. This diagnostic is more important,
581  // unless we require this evaluation to produce a constant expression.
582  //
583  // FIXME: We might want to show both diagnostics to the user in
584  // EM_ConstantFold mode.
585  if (!EvalStatus.Diag->empty()) {
586  switch (EvalMode) {
587  case EM_ConstantFold:
588  case EM_IgnoreSideEffects:
589  case EM_EvaluateForOverflow:
590  if (!EvalStatus.HasSideEffects)
591  break;
592  // We've had side-effects; we want the diagnostic from them, not
593  // some later problem.
594  case EM_ConstantExpression:
595  case EM_PotentialConstantExpression:
596  case EM_ConstantExpressionUnevaluated:
597  case EM_PotentialConstantExpressionUnevaluated:
598  HasActiveDiagnostic = false;
599  return OptionalDiagnostic();
600  }
601  }
602 
603  unsigned CallStackNotes = CallStackDepth - 1;
604  unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
605  if (Limit)
606  CallStackNotes = std::min(CallStackNotes, Limit + 1);
607  if (checkingPotentialConstantExpression())
608  CallStackNotes = 0;
609 
610  HasActiveDiagnostic = true;
611  EvalStatus.Diag->clear();
612  EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
613  addDiag(Loc, DiagId);
614  if (!checkingPotentialConstantExpression())
615  addCallStack(Limit);
616  return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
617  }
618  HasActiveDiagnostic = false;
619  return OptionalDiagnostic();
620  }
621 
622  OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
623  = diag::note_invalid_subexpr_in_const_expr,
624  unsigned ExtraNotes = 0) {
625  if (EvalStatus.Diag)
626  return Diag(E->getExprLoc(), DiagId, ExtraNotes);
627  HasActiveDiagnostic = false;
628  return OptionalDiagnostic();
629  }
630 
631  /// Diagnose that the evaluation does not produce a C++11 core constant
632  /// expression.
633  ///
634  /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
635  /// EM_PotentialConstantExpression mode and we produce one of these.
636  template<typename LocArg>
637  OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
638  = diag::note_invalid_subexpr_in_const_expr,
639  unsigned ExtraNotes = 0) {
640  // Don't override a previous diagnostic. Don't bother collecting
641  // diagnostics if we're evaluating for overflow.
642  if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
643  HasActiveDiagnostic = false;
644  return OptionalDiagnostic();
645  }
646  return Diag(Loc, DiagId, ExtraNotes);
647  }
648 
649  /// Add a note to a prior diagnostic.
650  OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
651  if (!HasActiveDiagnostic)
652  return OptionalDiagnostic();
653  return OptionalDiagnostic(&addDiag(Loc, DiagId));
654  }
655 
656  /// Add a stack of notes to a prior diagnostic.
657  void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
658  if (HasActiveDiagnostic) {
659  EvalStatus.Diag->insert(EvalStatus.Diag->end(),
660  Diags.begin(), Diags.end());
661  }
662  }
663 
664  /// Should we continue evaluation after encountering a side-effect that we
665  /// couldn't model?
666  bool keepEvaluatingAfterSideEffect() {
667  switch (EvalMode) {
668  case EM_PotentialConstantExpression:
669  case EM_PotentialConstantExpressionUnevaluated:
670  case EM_EvaluateForOverflow:
671  case EM_IgnoreSideEffects:
672  return true;
673 
674  case EM_ConstantExpression:
675  case EM_ConstantExpressionUnevaluated:
676  case EM_ConstantFold:
677  return false;
678  }
679  llvm_unreachable("Missed EvalMode case");
680  }
681 
682  /// Note that we have had a side-effect, and determine whether we should
683  /// keep evaluating.
684  bool noteSideEffect() {
685  EvalStatus.HasSideEffects = true;
686  return keepEvaluatingAfterSideEffect();
687  }
688 
689  /// Should we continue evaluation as much as possible after encountering a
690  /// construct which can't be reduced to a value?
691  bool keepEvaluatingAfterFailure() {
692  if (!StepsLeft)
693  return false;
694 
695  switch (EvalMode) {
696  case EM_PotentialConstantExpression:
697  case EM_PotentialConstantExpressionUnevaluated:
698  case EM_EvaluateForOverflow:
699  return true;
700 
701  case EM_ConstantExpression:
702  case EM_ConstantExpressionUnevaluated:
703  case EM_ConstantFold:
704  case EM_IgnoreSideEffects:
705  return false;
706  }
707  llvm_unreachable("Missed EvalMode case");
708  }
709  };
710 
711  /// Object used to treat all foldable expressions as constant expressions.
712  struct FoldConstant {
713  EvalInfo &Info;
714  bool Enabled;
715  bool HadNoPriorDiags;
716  EvalInfo::EvaluationMode OldMode;
717 
718  explicit FoldConstant(EvalInfo &Info, bool Enabled)
719  : Info(Info),
720  Enabled(Enabled),
721  HadNoPriorDiags(Info.EvalStatus.Diag &&
722  Info.EvalStatus.Diag->empty() &&
723  !Info.EvalStatus.HasSideEffects),
724  OldMode(Info.EvalMode) {
725  if (Enabled &&
726  (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
727  Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
728  Info.EvalMode = EvalInfo::EM_ConstantFold;
729  }
730  void keepDiagnostics() { Enabled = false; }
731  ~FoldConstant() {
732  if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
733  !Info.EvalStatus.HasSideEffects)
734  Info.EvalStatus.Diag->clear();
735  Info.EvalMode = OldMode;
736  }
737  };
738 
739  /// RAII object used to suppress diagnostics and side-effects from a
740  /// speculative evaluation.
741  class SpeculativeEvaluationRAII {
742  EvalInfo &Info;
743  Expr::EvalStatus Old;
744 
745  public:
746  SpeculativeEvaluationRAII(EvalInfo &Info,
747  SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
748  : Info(Info), Old(Info.EvalStatus) {
749  Info.EvalStatus.Diag = NewDiag;
750  // If we're speculatively evaluating, we may have skipped over some
751  // evaluations and missed out a side effect.
752  Info.EvalStatus.HasSideEffects = true;
753  }
754  ~SpeculativeEvaluationRAII() {
755  Info.EvalStatus = Old;
756  }
757  };
758 
759  /// RAII object wrapping a full-expression or block scope, and handling
760  /// the ending of the lifetime of temporaries created within it.
761  template<bool IsFullExpression>
762  class ScopeRAII {
763  EvalInfo &Info;
764  unsigned OldStackSize;
765  public:
766  ScopeRAII(EvalInfo &Info)
767  : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
768  ~ScopeRAII() {
769  // Body moved to a static method to encourage the compiler to inline away
770  // instances of this class.
771  cleanup(Info, OldStackSize);
772  }
773  private:
774  static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
775  unsigned NewEnd = OldStackSize;
776  for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
777  I != N; ++I) {
778  if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
779  // Full-expression cleanup of a lifetime-extended temporary: nothing
780  // to do, just move this cleanup to the right place in the stack.
781  std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
782  ++NewEnd;
783  } else {
784  // End the lifetime of the object.
785  Info.CleanupStack[I].endLifetime();
786  }
787  }
788  Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
789  Info.CleanupStack.end());
790  }
791  };
792  typedef ScopeRAII<false> BlockScopeRAII;
793  typedef ScopeRAII<true> FullExpressionRAII;
794 }
795 
796 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
797  CheckSubobjectKind CSK) {
798  if (Invalid)
799  return false;
800  if (isOnePastTheEnd()) {
801  Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
802  << CSK;
803  setInvalid();
804  return false;
805  }
806  return true;
807 }
808 
809 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
810  const Expr *E, uint64_t N) {
811  if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
812  Info.CCEDiag(E, diag::note_constexpr_array_index)
813  << static_cast<int>(N) << /*array*/ 0
814  << static_cast<unsigned>(MostDerivedArraySize);
815  else
816  Info.CCEDiag(E, diag::note_constexpr_array_index)
817  << static_cast<int>(N) << /*non-array*/ 1;
818  setInvalid();
819 }
820 
821 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
822  const FunctionDecl *Callee, const LValue *This,
823  APValue *Arguments)
824  : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
825  Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
826  Info.CurrentCall = this;
827  ++Info.CallStackDepth;
828 }
829 
830 CallStackFrame::~CallStackFrame() {
831  assert(Info.CurrentCall == this && "calls retired out of order");
832  --Info.CallStackDepth;
833  Info.CurrentCall = Caller;
834 }
835 
836 APValue &CallStackFrame::createTemporary(const void *Key,
837  bool IsLifetimeExtended) {
838  APValue &Result = Temporaries[Key];
839  assert(Result.isUninit() && "temporary created multiple times");
840  Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
841  return Result;
842 }
843 
844 static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
845 
846 void EvalInfo::addCallStack(unsigned Limit) {
847  // Determine which calls to skip, if any.
848  unsigned ActiveCalls = CallStackDepth - 1;
849  unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
850  if (Limit && Limit < ActiveCalls) {
851  SkipStart = Limit / 2 + Limit % 2;
852  SkipEnd = ActiveCalls - Limit / 2;
853  }
854 
855  // Walk the call stack and add the diagnostics.
856  unsigned CallIdx = 0;
857  for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
858  Frame = Frame->Caller, ++CallIdx) {
859  // Skip this call?
860  if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
861  if (CallIdx == SkipStart) {
862  // Note that we're skipping calls.
863  addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
864  << unsigned(ActiveCalls - Limit);
865  }
866  continue;
867  }
868 
869  SmallVector<char, 128> Buffer;
870  llvm::raw_svector_ostream Out(Buffer);
871  describeCall(Frame, Out);
872  addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
873  }
874 }
875 
876 namespace {
877  struct ComplexValue {
878  private:
879  bool IsInt;
880 
881  public:
882  APSInt IntReal, IntImag;
883  APFloat FloatReal, FloatImag;
884 
885  ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
886 
887  void makeComplexFloat() { IsInt = false; }
888  bool isComplexFloat() const { return !IsInt; }
889  APFloat &getComplexFloatReal() { return FloatReal; }
890  APFloat &getComplexFloatImag() { return FloatImag; }
891 
892  void makeComplexInt() { IsInt = true; }
893  bool isComplexInt() const { return IsInt; }
894  APSInt &getComplexIntReal() { return IntReal; }
895  APSInt &getComplexIntImag() { return IntImag; }
896 
897  void moveInto(APValue &v) const {
898  if (isComplexFloat())
899  v = APValue(FloatReal, FloatImag);
900  else
901  v = APValue(IntReal, IntImag);
902  }
903  void setFrom(const APValue &v) {
904  assert(v.isComplexFloat() || v.isComplexInt());
905  if (v.isComplexFloat()) {
906  makeComplexFloat();
907  FloatReal = v.getComplexFloatReal();
908  FloatImag = v.getComplexFloatImag();
909  } else {
910  makeComplexInt();
911  IntReal = v.getComplexIntReal();
912  IntImag = v.getComplexIntImag();
913  }
914  }
915  };
916 
917  struct LValue {
918  APValue::LValueBase Base;
920  unsigned CallIndex;
921  SubobjectDesignator Designator;
922 
923  const APValue::LValueBase getLValueBase() const { return Base; }
924  CharUnits &getLValueOffset() { return Offset; }
925  const CharUnits &getLValueOffset() const { return Offset; }
926  unsigned getLValueCallIndex() const { return CallIndex; }
927  SubobjectDesignator &getLValueDesignator() { return Designator; }
928  const SubobjectDesignator &getLValueDesignator() const { return Designator;}
929 
930  void moveInto(APValue &V) const {
931  if (Designator.Invalid)
932  V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
933  else
934  V = APValue(Base, Offset, Designator.Entries,
935  Designator.IsOnePastTheEnd, CallIndex);
936  }
937  void setFrom(ASTContext &Ctx, const APValue &V) {
938  assert(V.isLValue());
939  Base = V.getLValueBase();
940  Offset = V.getLValueOffset();
941  CallIndex = V.getLValueCallIndex();
942  Designator = SubobjectDesignator(Ctx, V);
943  }
944 
945  void set(APValue::LValueBase B, unsigned I = 0) {
946  Base = B;
947  Offset = CharUnits::Zero();
948  CallIndex = I;
949  Designator = SubobjectDesignator(getType(B));
950  }
951 
952  // Check that this LValue is not based on a null pointer. If it is, produce
953  // a diagnostic and mark the designator as invalid.
954  bool checkNullPointer(EvalInfo &Info, const Expr *E,
955  CheckSubobjectKind CSK) {
956  if (Designator.Invalid)
957  return false;
958  if (!Base) {
959  Info.CCEDiag(E, diag::note_constexpr_null_subobject)
960  << CSK;
961  Designator.setInvalid();
962  return false;
963  }
964  return true;
965  }
966 
967  // Check this LValue refers to an object. If not, set the designator to be
968  // invalid and emit a diagnostic.
969  bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
970  // Outside C++11, do not build a designator referring to a subobject of
971  // any object: we won't use such a designator for anything.
972  if (!Info.getLangOpts().CPlusPlus11)
973  Designator.setInvalid();
974  return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
975  Designator.checkSubobject(Info, E, CSK);
976  }
977 
978  void addDecl(EvalInfo &Info, const Expr *E,
979  const Decl *D, bool Virtual = false) {
980  if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
981  Designator.addDeclUnchecked(D, Virtual);
982  }
983  void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
984  if (checkSubobject(Info, E, CSK_ArrayToPointer))
985  Designator.addArrayUnchecked(CAT);
986  }
987  void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
988  if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
989  Designator.addComplexUnchecked(EltTy, Imag);
990  }
991  void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
992  if (N && checkNullPointer(Info, E, CSK_ArrayIndex))
993  Designator.adjustIndex(Info, E, N);
994  }
995  };
996 
997  struct MemberPtr {
998  MemberPtr() {}
999  explicit MemberPtr(const ValueDecl *Decl) :
1000  DeclAndIsDerivedMember(Decl, false), Path() {}
1001 
1002  /// The member or (direct or indirect) field referred to by this member
1003  /// pointer, or 0 if this is a null member pointer.
1004  const ValueDecl *getDecl() const {
1005  return DeclAndIsDerivedMember.getPointer();
1006  }
1007  /// Is this actually a member of some type derived from the relevant class?
1008  bool isDerivedMember() const {
1009  return DeclAndIsDerivedMember.getInt();
1010  }
1011  /// Get the class which the declaration actually lives in.
1012  const CXXRecordDecl *getContainingRecord() const {
1013  return cast<CXXRecordDecl>(
1014  DeclAndIsDerivedMember.getPointer()->getDeclContext());
1015  }
1016 
1017  void moveInto(APValue &V) const {
1018  V = APValue(getDecl(), isDerivedMember(), Path);
1019  }
1020  void setFrom(const APValue &V) {
1021  assert(V.isMemberPointer());
1022  DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1023  DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1024  Path.clear();
1026  Path.insert(Path.end(), P.begin(), P.end());
1027  }
1028 
1029  /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1030  /// whether the member is a member of some class derived from the class type
1031  /// of the member pointer.
1032  llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1033  /// Path - The path of base/derived classes from the member declaration's
1034  /// class (exclusive) to the class type of the member pointer (inclusive).
1036 
1037  /// Perform a cast towards the class of the Decl (either up or down the
1038  /// hierarchy).
1039  bool castBack(const CXXRecordDecl *Class) {
1040  assert(!Path.empty());
1041  const CXXRecordDecl *Expected;
1042  if (Path.size() >= 2)
1043  Expected = Path[Path.size() - 2];
1044  else
1045  Expected = getContainingRecord();
1046  if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1047  // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1048  // if B does not contain the original member and is not a base or
1049  // derived class of the class containing the original member, the result
1050  // of the cast is undefined.
1051  // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1052  // (D::*). We consider that to be a language defect.
1053  return false;
1054  }
1055  Path.pop_back();
1056  return true;
1057  }
1058  /// Perform a base-to-derived member pointer cast.
1059  bool castToDerived(const CXXRecordDecl *Derived) {
1060  if (!getDecl())
1061  return true;
1062  if (!isDerivedMember()) {
1063  Path.push_back(Derived);
1064  return true;
1065  }
1066  if (!castBack(Derived))
1067  return false;
1068  if (Path.empty())
1069  DeclAndIsDerivedMember.setInt(false);
1070  return true;
1071  }
1072  /// Perform a derived-to-base member pointer cast.
1073  bool castToBase(const CXXRecordDecl *Base) {
1074  if (!getDecl())
1075  return true;
1076  if (Path.empty())
1077  DeclAndIsDerivedMember.setInt(true);
1078  if (isDerivedMember()) {
1079  Path.push_back(Base);
1080  return true;
1081  }
1082  return castBack(Base);
1083  }
1084  };
1085 
1086  /// Compare two member pointers, which are assumed to be of the same type.
1087  static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1088  if (!LHS.getDecl() || !RHS.getDecl())
1089  return !LHS.getDecl() && !RHS.getDecl();
1090  if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1091  return false;
1092  return LHS.Path == RHS.Path;
1093  }
1094 }
1095 
1096 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1097 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1098  const LValue &This, const Expr *E,
1099  bool AllowNonLiteralTypes = false);
1100 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
1101 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
1102 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1103  EvalInfo &Info);
1104 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1105 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1106 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1107  EvalInfo &Info);
1108 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1109 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1110 static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
1111 
1112 //===----------------------------------------------------------------------===//
1113 // Misc utilities
1114 //===----------------------------------------------------------------------===//
1115 
1116 /// Produce a string describing the given constexpr call.
1117 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1118  unsigned ArgIndex = 0;
1119  bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1120  !isa<CXXConstructorDecl>(Frame->Callee) &&
1121  cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1122 
1123  if (!IsMemberCall)
1124  Out << *Frame->Callee << '(';
1125 
1126  if (Frame->This && IsMemberCall) {
1127  APValue Val;
1128  Frame->This->moveInto(Val);
1129  Val.printPretty(Out, Frame->Info.Ctx,
1130  Frame->This->Designator.MostDerivedType);
1131  // FIXME: Add parens around Val if needed.
1132  Out << "->" << *Frame->Callee << '(';
1133  IsMemberCall = false;
1134  }
1135 
1136  for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1137  E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1138  if (ArgIndex > (unsigned)IsMemberCall)
1139  Out << ", ";
1140 
1141  const ParmVarDecl *Param = *I;
1142  const APValue &Arg = Frame->Arguments[ArgIndex];
1143  Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1144 
1145  if (ArgIndex == 0 && IsMemberCall)
1146  Out << "->" << *Frame->Callee << '(';
1147  }
1148 
1149  Out << ')';
1150 }
1151 
1152 /// Evaluate an expression to see if it had side-effects, and discard its
1153 /// result.
1154 /// \return \c true if the caller should keep evaluating.
1155 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1156  APValue Scratch;
1157  if (!Evaluate(Scratch, Info, E))
1158  // We don't need the value, but we might have skipped a side effect here.
1159  return Info.noteSideEffect();
1160  return true;
1161 }
1162 
1163 /// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
1164 /// return its existing value.
1165 static int64_t getExtValue(const APSInt &Value) {
1166  return Value.isSigned() ? Value.getSExtValue()
1167  : static_cast<int64_t>(Value.getZExtValue());
1168 }
1169 
1170 /// Should this call expression be treated as a string literal?
1171 static bool IsStringLiteralCall(const CallExpr *E) {
1172  unsigned Builtin = E->getBuiltinCallee();
1173  return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1174  Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1175 }
1176 
1178  // C++11 [expr.const]p3 An address constant expression is a prvalue core
1179  // constant expression of pointer type that evaluates to...
1180 
1181  // ... a null pointer value, or a prvalue core constant expression of type
1182  // std::nullptr_t.
1183  if (!B) return true;
1184 
1185  if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1186  // ... the address of an object with static storage duration,
1187  if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1188  return VD->hasGlobalStorage();
1189  // ... the address of a function,
1190  return isa<FunctionDecl>(D);
1191  }
1192 
1193  const Expr *E = B.get<const Expr*>();
1194  switch (E->getStmtClass()) {
1195  default:
1196  return false;
1197  case Expr::CompoundLiteralExprClass: {
1198  const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1199  return CLE->isFileScope() && CLE->isLValue();
1200  }
1201  case Expr::MaterializeTemporaryExprClass:
1202  // A materialized temporary might have been lifetime-extended to static
1203  // storage duration.
1204  return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1205  // A string literal has static storage duration.
1206  case Expr::StringLiteralClass:
1207  case Expr::PredefinedExprClass:
1208  case Expr::ObjCStringLiteralClass:
1209  case Expr::ObjCEncodeExprClass:
1210  case Expr::CXXTypeidExprClass:
1211  case Expr::CXXUuidofExprClass:
1212  return true;
1213  case Expr::CallExprClass:
1214  return IsStringLiteralCall(cast<CallExpr>(E));
1215  // For GCC compatibility, &&label has static storage duration.
1216  case Expr::AddrLabelExprClass:
1217  return true;
1218  // A Block literal expression may be used as the initialization value for
1219  // Block variables at global or local static scope.
1220  case Expr::BlockExprClass:
1221  return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1222  case Expr::ImplicitValueInitExprClass:
1223  // FIXME:
1224  // We can never form an lvalue with an implicit value initialization as its
1225  // base through expression evaluation, so these only appear in one case: the
1226  // implicit variable declaration we invent when checking whether a constexpr
1227  // constructor can produce a constant expression. We must assume that such
1228  // an expression might be a global lvalue.
1229  return true;
1230  }
1231 }
1232 
1233 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1234  assert(Base && "no location for a null lvalue");
1235  const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1236  if (VD)
1237  Info.Note(VD->getLocation(), diag::note_declared_at);
1238  else
1239  Info.Note(Base.get<const Expr*>()->getExprLoc(),
1240  diag::note_constexpr_temporary_here);
1241 }
1242 
1243 /// Check that this reference or pointer core constant expression is a valid
1244 /// value for an address or reference constant expression. Return true if we
1245 /// can fold this expression, whether or not it's a constant expression.
1246 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1247  QualType Type, const LValue &LVal) {
1248  bool IsReferenceType = Type->isReferenceType();
1249 
1250  APValue::LValueBase Base = LVal.getLValueBase();
1251  const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1252 
1253  // Check that the object is a global. Note that the fake 'this' object we
1254  // manufacture when checking potential constant expressions is conservatively
1255  // assumed to be global here.
1256  if (!IsGlobalLValue(Base)) {
1257  if (Info.getLangOpts().CPlusPlus11) {
1258  const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1259  Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1260  << IsReferenceType << !Designator.Entries.empty()
1261  << !!VD << VD;
1262  NoteLValueLocation(Info, Base);
1263  } else {
1264  Info.Diag(Loc);
1265  }
1266  // Don't allow references to temporaries to escape.
1267  return false;
1268  }
1269  assert((Info.checkingPotentialConstantExpression() ||
1270  LVal.getLValueCallIndex() == 0) &&
1271  "have call index for global lvalue");
1272 
1273  if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1274  if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
1275  // Check if this is a thread-local variable.
1276  if (Var->getTLSKind())
1277  return false;
1278 
1279  // A dllimport variable never acts like a constant.
1280  if (Var->hasAttr<DLLImportAttr>())
1281  return false;
1282  }
1283  if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1284  // __declspec(dllimport) must be handled very carefully:
1285  // We must never initialize an expression with the thunk in C++.
1286  // Doing otherwise would allow the same id-expression to yield
1287  // different addresses for the same function in different translation
1288  // units. However, this means that we must dynamically initialize the
1289  // expression with the contents of the import address table at runtime.
1290  //
1291  // The C language has no notion of ODR; furthermore, it has no notion of
1292  // dynamic initialization. This means that we are permitted to
1293  // perform initialization with the address of the thunk.
1294  if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
1295  return false;
1296  }
1297  }
1298 
1299  // Allow address constant expressions to be past-the-end pointers. This is
1300  // an extension: the standard requires them to point to an object.
1301  if (!IsReferenceType)
1302  return true;
1303 
1304  // A reference constant expression must refer to an object.
1305  if (!Base) {
1306  // FIXME: diagnostic
1307  Info.CCEDiag(Loc);
1308  return true;
1309  }
1310 
1311  // Does this refer one past the end of some object?
1312  if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
1313  const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1314  Info.Diag(Loc, diag::note_constexpr_past_end, 1)
1315  << !Designator.Entries.empty() << !!VD << VD;
1316  NoteLValueLocation(Info, Base);
1317  }
1318 
1319  return true;
1320 }
1321 
1322 /// Check that this core constant expression is of literal type, and if not,
1323 /// produce an appropriate diagnostic.
1324 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1325  const LValue *This = nullptr) {
1326  if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
1327  return true;
1328 
1329  // C++1y: A constant initializer for an object o [...] may also invoke
1330  // constexpr constructors for o and its subobjects even if those objects
1331  // are of non-literal class types.
1332  if (Info.getLangOpts().CPlusPlus14 && This &&
1333  Info.EvaluatingDecl == This->getLValueBase())
1334  return true;
1335 
1336  // Prvalue constant expressions must be of literal types.
1337  if (Info.getLangOpts().CPlusPlus11)
1338  Info.Diag(E, diag::note_constexpr_nonliteral)
1339  << E->getType();
1340  else
1341  Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1342  return false;
1343 }
1344 
1345 /// Check that this core constant expression value is a valid value for a
1346 /// constant expression. If not, report an appropriate diagnostic. Does not
1347 /// check that the expression is of literal type.
1348 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1349  QualType Type, const APValue &Value) {
1350  if (Value.isUninit()) {
1351  Info.Diag(DiagLoc, diag::note_constexpr_uninitialized)
1352  << true << Type;
1353  return false;
1354  }
1355 
1356  // We allow _Atomic(T) to be initialized from anything that T can be
1357  // initialized from.
1358  if (const AtomicType *AT = Type->getAs<AtomicType>())
1359  Type = AT->getValueType();
1360 
1361  // Core issue 1454: For a literal constant expression of array or class type,
1362  // each subobject of its value shall have been initialized by a constant
1363  // expression.
1364  if (Value.isArray()) {
1365  QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1366  for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1367  if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1368  Value.getArrayInitializedElt(I)))
1369  return false;
1370  }
1371  if (!Value.hasArrayFiller())
1372  return true;
1373  return CheckConstantExpression(Info, DiagLoc, EltTy,
1374  Value.getArrayFiller());
1375  }
1376  if (Value.isUnion() && Value.getUnionField()) {
1377  return CheckConstantExpression(Info, DiagLoc,
1378  Value.getUnionField()->getType(),
1379  Value.getUnionValue());
1380  }
1381  if (Value.isStruct()) {
1382  RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1383  if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1384  unsigned BaseIndex = 0;
1385  for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1386  End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1387  if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1388  Value.getStructBase(BaseIndex)))
1389  return false;
1390  }
1391  }
1392  for (const auto *I : RD->fields()) {
1393  if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1394  Value.getStructField(I->getFieldIndex())))
1395  return false;
1396  }
1397  }
1398 
1399  if (Value.isLValue()) {
1400  LValue LVal;
1401  LVal.setFrom(Info.Ctx, Value);
1402  return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1403  }
1404 
1405  // Everything else is fine.
1406  return true;
1407 }
1408 
1409 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1410  return LVal.Base.dyn_cast<const ValueDecl*>();
1411 }
1412 
1413 static bool IsLiteralLValue(const LValue &Value) {
1414  if (Value.CallIndex)
1415  return false;
1416  const Expr *E = Value.Base.dyn_cast<const Expr*>();
1417  return E && !isa<MaterializeTemporaryExpr>(E);
1418 }
1419 
1420 static bool IsWeakLValue(const LValue &Value) {
1421  const ValueDecl *Decl = GetLValueBaseDecl(Value);
1422  return Decl && Decl->isWeak();
1423 }
1424 
1425 static bool isZeroSized(const LValue &Value) {
1426  const ValueDecl *Decl = GetLValueBaseDecl(Value);
1427  if (Decl && isa<VarDecl>(Decl)) {
1428  QualType Ty = Decl->getType();
1429  if (Ty->isArrayType())
1430  return Ty->isIncompleteType() ||
1431  Decl->getASTContext().getTypeSize(Ty) == 0;
1432  }
1433  return false;
1434 }
1435 
1436 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
1437  // A null base expression indicates a null pointer. These are always
1438  // evaluatable, and they are false unless the offset is zero.
1439  if (!Value.getLValueBase()) {
1440  Result = !Value.getLValueOffset().isZero();
1441  return true;
1442  }
1443 
1444  // We have a non-null base. These are generally known to be true, but if it's
1445  // a weak declaration it can be null at runtime.
1446  Result = true;
1447  const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
1448  return !Decl || !Decl->isWeak();
1449 }
1450 
1451 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
1452  switch (Val.getKind()) {
1454  return false;
1455  case APValue::Int:
1456  Result = Val.getInt().getBoolValue();
1457  return true;
1458  case APValue::Float:
1459  Result = !Val.getFloat().isZero();
1460  return true;
1461  case APValue::ComplexInt:
1462  Result = Val.getComplexIntReal().getBoolValue() ||
1463  Val.getComplexIntImag().getBoolValue();
1464  return true;
1465  case APValue::ComplexFloat:
1466  Result = !Val.getComplexFloatReal().isZero() ||
1467  !Val.getComplexFloatImag().isZero();
1468  return true;
1469  case APValue::LValue:
1470  return EvalPointerValueAsBool(Val, Result);
1471  case APValue::MemberPointer:
1472  Result = Val.getMemberPointerDecl();
1473  return true;
1474  case APValue::Vector:
1475  case APValue::Array:
1476  case APValue::Struct:
1477  case APValue::Union:
1478  case APValue::AddrLabelDiff:
1479  return false;
1480  }
1481 
1482  llvm_unreachable("unknown APValue kind");
1483 }
1484 
1485 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1486  EvalInfo &Info) {
1487  assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
1488  APValue Val;
1489  if (!Evaluate(Val, Info, E))
1490  return false;
1491  return HandleConversionToBool(Val, Result);
1492 }
1493 
1494 template<typename T>
1495 static void HandleOverflow(EvalInfo &Info, const Expr *E,
1496  const T &SrcValue, QualType DestType) {
1497  Info.CCEDiag(E, diag::note_constexpr_overflow)
1498  << SrcValue << DestType;
1499 }
1500 
1501 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1502  QualType SrcType, const APFloat &Value,
1503  QualType DestType, APSInt &Result) {
1504  unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1505  // Determine whether we are converting to unsigned or signed.
1506  bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
1507 
1508  Result = APSInt(DestWidth, !DestSigned);
1509  bool ignored;
1510  if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1511  & APFloat::opInvalidOp)
1512  HandleOverflow(Info, E, Value, DestType);
1513  return true;
1514 }
1515 
1516 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1517  QualType SrcType, QualType DestType,
1518  APFloat &Result) {
1519  APFloat Value = Result;
1520  bool ignored;
1521  if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1522  APFloat::rmNearestTiesToEven, &ignored)
1523  & APFloat::opOverflow)
1524  HandleOverflow(Info, E, Value, DestType);
1525  return true;
1526 }
1527 
1528 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1529  QualType DestType, QualType SrcType,
1530  APSInt &Value) {
1531  unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1532  APSInt Result = Value;
1533  // Figure out if this is a truncate, extend or noop cast.
1534  // If the input is signed, do a sign extend, noop, or truncate.
1535  Result = Result.extOrTrunc(DestWidth);
1536  Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
1537  return Result;
1538 }
1539 
1540 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1541  QualType SrcType, const APSInt &Value,
1542  QualType DestType, APFloat &Result) {
1543  Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1544  if (Result.convertFromAPInt(Value, Value.isSigned(),
1545  APFloat::rmNearestTiesToEven)
1546  & APFloat::opOverflow)
1547  HandleOverflow(Info, E, Value, DestType);
1548  return true;
1549 }
1550 
1551 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1552  APValue &Value, const FieldDecl *FD) {
1553  assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1554 
1555  if (!Value.isInt()) {
1556  // Trying to store a pointer-cast-to-integer into a bitfield.
1557  // FIXME: In this case, we should provide the diagnostic for casting
1558  // a pointer to an integer.
1559  assert(Value.isLValue() && "integral value neither int nor lvalue?");
1560  Info.Diag(E);
1561  return false;
1562  }
1563 
1564  APSInt &Int = Value.getInt();
1565  unsigned OldBitWidth = Int.getBitWidth();
1566  unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1567  if (NewBitWidth < OldBitWidth)
1568  Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1569  return true;
1570 }
1571 
1572 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1573  llvm::APInt &Res) {
1574  APValue SVal;
1575  if (!Evaluate(SVal, Info, E))
1576  return false;
1577  if (SVal.isInt()) {
1578  Res = SVal.getInt();
1579  return true;
1580  }
1581  if (SVal.isFloat()) {
1582  Res = SVal.getFloat().bitcastToAPInt();
1583  return true;
1584  }
1585  if (SVal.isVector()) {
1586  QualType VecTy = E->getType();
1587  unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1588  QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1589  unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1590  bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1591  Res = llvm::APInt::getNullValue(VecSize);
1592  for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1593  APValue &Elt = SVal.getVectorElt(i);
1594  llvm::APInt EltAsInt;
1595  if (Elt.isInt()) {
1596  EltAsInt = Elt.getInt();
1597  } else if (Elt.isFloat()) {
1598  EltAsInt = Elt.getFloat().bitcastToAPInt();
1599  } else {
1600  // Don't try to handle vectors of anything other than int or float
1601  // (not sure if it's possible to hit this case).
1602  Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1603  return false;
1604  }
1605  unsigned BaseEltSize = EltAsInt.getBitWidth();
1606  if (BigEndian)
1607  Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1608  else
1609  Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1610  }
1611  return true;
1612  }
1613  // Give up if the input isn't an int, float, or vector. For example, we
1614  // reject "(v4i16)(intptr_t)&a".
1615  Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1616  return false;
1617 }
1618 
1619 /// Perform the given integer operation, which is known to need at most BitWidth
1620 /// bits, and check for overflow in the original type (if that type was not an
1621 /// unsigned type).
1622 template<typename Operation>
1623 static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1624  const APSInt &LHS, const APSInt &RHS,
1625  unsigned BitWidth, Operation Op) {
1626  if (LHS.isUnsigned())
1627  return Op(LHS, RHS);
1628 
1629  APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
1630  APSInt Result = Value.trunc(LHS.getBitWidth());
1631  if (Result.extend(BitWidth) != Value) {
1632  if (Info.checkingForOverflow())
1633  Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1634  diag::warn_integer_constant_overflow)
1635  << Result.toString(10) << E->getType();
1636  else
1637  HandleOverflow(Info, E, Value, E->getType());
1638  }
1639  return Result;
1640 }
1641 
1642 /// Perform the given binary integer operation.
1643 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1644  BinaryOperatorKind Opcode, APSInt RHS,
1645  APSInt &Result) {
1646  switch (Opcode) {
1647  default:
1648  Info.Diag(E);
1649  return false;
1650  case BO_Mul:
1651  Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1652  std::multiplies<APSInt>());
1653  return true;
1654  case BO_Add:
1655  Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1656  std::plus<APSInt>());
1657  return true;
1658  case BO_Sub:
1659  Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1660  std::minus<APSInt>());
1661  return true;
1662  case BO_And: Result = LHS & RHS; return true;
1663  case BO_Xor: Result = LHS ^ RHS; return true;
1664  case BO_Or: Result = LHS | RHS; return true;
1665  case BO_Div:
1666  case BO_Rem:
1667  if (RHS == 0) {
1668  Info.Diag(E, diag::note_expr_divide_by_zero);
1669  return false;
1670  }
1671  // Check for overflow case: INT_MIN / -1 or INT_MIN % -1.
1672  if (RHS.isNegative() && RHS.isAllOnesValue() &&
1673  LHS.isSigned() && LHS.isMinSignedValue())
1674  HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
1675  Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1676  return true;
1677  case BO_Shl: {
1678  if (Info.getLangOpts().OpenCL)
1679  // OpenCL 6.3j: shift values are effectively % word size of LHS.
1680  RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1681  static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1682  RHS.isUnsigned());
1683  else if (RHS.isSigned() && RHS.isNegative()) {
1684  // During constant-folding, a negative shift is an opposite shift. Such
1685  // a shift is not a constant expression.
1686  Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1687  RHS = -RHS;
1688  goto shift_right;
1689  }
1690  shift_left:
1691  // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1692  // the shifted type.
1693  unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1694  if (SA != RHS) {
1695  Info.CCEDiag(E, diag::note_constexpr_large_shift)
1696  << RHS << E->getType() << LHS.getBitWidth();
1697  } else if (LHS.isSigned()) {
1698  // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1699  // operand, and must not overflow the corresponding unsigned type.
1700  if (LHS.isNegative())
1701  Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1702  else if (LHS.countLeadingZeros() < SA)
1703  Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1704  }
1705  Result = LHS << SA;
1706  return true;
1707  }
1708  case BO_Shr: {
1709  if (Info.getLangOpts().OpenCL)
1710  // OpenCL 6.3j: shift values are effectively % word size of LHS.
1711  RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1712  static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1713  RHS.isUnsigned());
1714  else if (RHS.isSigned() && RHS.isNegative()) {
1715  // During constant-folding, a negative shift is an opposite shift. Such a
1716  // shift is not a constant expression.
1717  Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1718  RHS = -RHS;
1719  goto shift_left;
1720  }
1721  shift_right:
1722  // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1723  // shifted type.
1724  unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1725  if (SA != RHS)
1726  Info.CCEDiag(E, diag::note_constexpr_large_shift)
1727  << RHS << E->getType() << LHS.getBitWidth();
1728  Result = LHS >> SA;
1729  return true;
1730  }
1731 
1732  case BO_LT: Result = LHS < RHS; return true;
1733  case BO_GT: Result = LHS > RHS; return true;
1734  case BO_LE: Result = LHS <= RHS; return true;
1735  case BO_GE: Result = LHS >= RHS; return true;
1736  case BO_EQ: Result = LHS == RHS; return true;
1737  case BO_NE: Result = LHS != RHS; return true;
1738  }
1739 }
1740 
1741 /// Perform the given binary floating-point operation, in-place, on LHS.
1742 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1743  APFloat &LHS, BinaryOperatorKind Opcode,
1744  const APFloat &RHS) {
1745  switch (Opcode) {
1746  default:
1747  Info.Diag(E);
1748  return false;
1749  case BO_Mul:
1750  LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1751  break;
1752  case BO_Add:
1753  LHS.add(RHS, APFloat::rmNearestTiesToEven);
1754  break;
1755  case BO_Sub:
1756  LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1757  break;
1758  case BO_Div:
1759  LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1760  break;
1761  }
1762 
1763  if (LHS.isInfinity() || LHS.isNaN())
1764  Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
1765  return true;
1766 }
1767 
1768 /// Cast an lvalue referring to a base subobject to a derived class, by
1769 /// truncating the lvalue's path to the given length.
1770 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1771  const RecordDecl *TruncatedType,
1772  unsigned TruncatedElements) {
1773  SubobjectDesignator &D = Result.Designator;
1774 
1775  // Check we actually point to a derived class object.
1776  if (TruncatedElements == D.Entries.size())
1777  return true;
1778  assert(TruncatedElements >= D.MostDerivedPathLength &&
1779  "not casting to a derived class");
1780  if (!Result.checkSubobject(Info, E, CSK_Derived))
1781  return false;
1782 
1783  // Truncate the path to the subobject, and remove any derived-to-base offsets.
1784  const RecordDecl *RD = TruncatedType;
1785  for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
1786  if (RD->isInvalidDecl()) return false;
1787  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1788  const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
1789  if (isVirtualBaseClass(D.Entries[I]))
1790  Result.Offset -= Layout.getVBaseClassOffset(Base);
1791  else
1792  Result.Offset -= Layout.getBaseClassOffset(Base);
1793  RD = Base;
1794  }
1795  D.Entries.resize(TruncatedElements);
1796  return true;
1797 }
1798 
1799 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
1800  const CXXRecordDecl *Derived,
1801  const CXXRecordDecl *Base,
1802  const ASTRecordLayout *RL = nullptr) {
1803  if (!RL) {
1804  if (Derived->isInvalidDecl()) return false;
1805  RL = &Info.Ctx.getASTRecordLayout(Derived);
1806  }
1807 
1808  Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
1809  Obj.addDecl(Info, E, Base, /*Virtual*/ false);
1810  return true;
1811 }
1812 
1813 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
1814  const CXXRecordDecl *DerivedDecl,
1815  const CXXBaseSpecifier *Base) {
1816  const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1817 
1818  if (!Base->isVirtual())
1819  return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
1820 
1821  SubobjectDesignator &D = Obj.Designator;
1822  if (D.Invalid)
1823  return false;
1824 
1825  // Extract most-derived object and corresponding type.
1826  DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1827  if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1828  return false;
1829 
1830  // Find the virtual base class.
1831  if (DerivedDecl->isInvalidDecl()) return false;
1832  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1833  Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
1834  Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
1835  return true;
1836 }
1837 
1838 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
1839  QualType Type, LValue &Result) {
1840  for (CastExpr::path_const_iterator PathI = E->path_begin(),
1841  PathE = E->path_end();
1842  PathI != PathE; ++PathI) {
1843  if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
1844  *PathI))
1845  return false;
1846  Type = (*PathI)->getType();
1847  }
1848  return true;
1849 }
1850 
1851 /// Update LVal to refer to the given field, which must be a member of the type
1852 /// currently described by LVal.
1853 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
1854  const FieldDecl *FD,
1855  const ASTRecordLayout *RL = nullptr) {
1856  if (!RL) {
1857  if (FD->getParent()->isInvalidDecl()) return false;
1858  RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1859  }
1860 
1861  unsigned I = FD->getFieldIndex();
1862  LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
1863  LVal.addDecl(Info, E, FD);
1864  return true;
1865 }
1866 
1867 /// Update LVal to refer to the given indirect field.
1868 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
1869  LValue &LVal,
1870  const IndirectFieldDecl *IFD) {
1871  for (const auto *C : IFD->chain())
1872  if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
1873  return false;
1874  return true;
1875 }
1876 
1877 /// Get the size of the given type in char units.
1878 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1879  QualType Type, CharUnits &Size) {
1880  // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1881  // extension.
1882  if (Type->isVoidType() || Type->isFunctionType()) {
1883  Size = CharUnits::One();
1884  return true;
1885  }
1886 
1887  if (!Type->isConstantSizeType()) {
1888  // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1889  // FIXME: Better diagnostic.
1890  Info.Diag(Loc);
1891  return false;
1892  }
1893 
1894  Size = Info.Ctx.getTypeSizeInChars(Type);
1895  return true;
1896 }
1897 
1898 /// Update a pointer value to model pointer arithmetic.
1899 /// \param Info - Information about the ongoing evaluation.
1900 /// \param E - The expression being evaluated, for diagnostic purposes.
1901 /// \param LVal - The pointer value to be updated.
1902 /// \param EltTy - The pointee type represented by LVal.
1903 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
1904 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1905  LValue &LVal, QualType EltTy,
1906  int64_t Adjustment) {
1907  CharUnits SizeOfPointee;
1908  if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
1909  return false;
1910 
1911  // Compute the new offset in the appropriate width.
1912  LVal.Offset += Adjustment * SizeOfPointee;
1913  LVal.adjustIndex(Info, E, Adjustment);
1914  return true;
1915 }
1916 
1917 /// Update an lvalue to refer to a component of a complex number.
1918 /// \param Info - Information about the ongoing evaluation.
1919 /// \param LVal - The lvalue to be updated.
1920 /// \param EltTy - The complex number's component type.
1921 /// \param Imag - False for the real component, true for the imaginary.
1922 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1923  LValue &LVal, QualType EltTy,
1924  bool Imag) {
1925  if (Imag) {
1926  CharUnits SizeOfComponent;
1927  if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1928  return false;
1929  LVal.Offset += SizeOfComponent;
1930  }
1931  LVal.addComplex(Info, E, EltTy, Imag);
1932  return true;
1933 }
1934 
1935 /// Try to evaluate the initializer for a variable declaration.
1936 ///
1937 /// \param Info Information about the ongoing evaluation.
1938 /// \param E An expression to be used when printing diagnostics.
1939 /// \param VD The variable whose initializer should be obtained.
1940 /// \param Frame The frame in which the variable was created. Must be null
1941 /// if this variable is not local to the evaluation.
1942 /// \param Result Filled in with a pointer to the value of the variable.
1943 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1944  const VarDecl *VD, CallStackFrame *Frame,
1945  APValue *&Result) {
1946  // If this is a parameter to an active constexpr function call, perform
1947  // argument substitution.
1948  if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
1949  // Assume arguments of a potential constant expression are unknown
1950  // constant expressions.
1951  if (Info.checkingPotentialConstantExpression())
1952  return false;
1953  if (!Frame || !Frame->Arguments) {
1954  Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1955  return false;
1956  }
1957  Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
1958  return true;
1959  }
1960 
1961  // If this is a local variable, dig out its value.
1962  if (Frame) {
1963  Result = Frame->getTemporary(VD);
1964  assert(Result && "missing value for local variable");
1965  return true;
1966  }
1967 
1968  // Dig out the initializer, and use the declaration which it's attached to.
1969  const Expr *Init = VD->getAnyInitializer(VD);
1970  if (!Init || Init->isValueDependent()) {
1971  // If we're checking a potential constant expression, the variable could be
1972  // initialized later.
1973  if (!Info.checkingPotentialConstantExpression())
1974  Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1975  return false;
1976  }
1977 
1978  // If we're currently evaluating the initializer of this declaration, use that
1979  // in-flight value.
1980  if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
1981  Result = Info.EvaluatingDeclValue;
1982  return true;
1983  }
1984 
1985  // Never evaluate the initializer of a weak variable. We can't be sure that
1986  // this is the definition which will be used.
1987  if (VD->isWeak()) {
1988  Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1989  return false;
1990  }
1991 
1992  // Check that we can fold the initializer. In C++, we will have already done
1993  // this in the cases where it matters for conformance.
1995  if (!VD->evaluateValue(Notes)) {
1996  Info.Diag(E, diag::note_constexpr_var_init_non_constant,
1997  Notes.size() + 1) << VD;
1998  Info.Note(VD->getLocation(), diag::note_declared_at);
1999  Info.addNotes(Notes);
2000  return false;
2001  } else if (!VD->checkInitIsICE()) {
2002  Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
2003  Notes.size() + 1) << VD;
2004  Info.Note(VD->getLocation(), diag::note_declared_at);
2005  Info.addNotes(Notes);
2006  }
2007 
2008  Result = VD->getEvaluatedValue();
2009  return true;
2010 }
2011 
2013  Qualifiers Quals = T.getQualifiers();
2014  return Quals.hasConst() && !Quals.hasVolatile();
2015 }
2016 
2017 /// Get the base index of the given base class within an APValue representing
2018 /// the given derived class.
2019 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2020  const CXXRecordDecl *Base) {
2021  Base = Base->getCanonicalDecl();
2022  unsigned Index = 0;
2024  E = Derived->bases_end(); I != E; ++I, ++Index) {
2025  if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2026  return Index;
2027  }
2028 
2029  llvm_unreachable("base class missing from derived class's bases list");
2030 }
2031 
2032 /// Extract the value of a character from a string literal.
2033 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2034  uint64_t Index) {
2035  // FIXME: Support ObjCEncodeExpr, MakeStringConstant
2036  if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2037  Lit = PE->getFunctionName();
2038  const StringLiteral *S = cast<StringLiteral>(Lit);
2039  const ConstantArrayType *CAT =
2040  Info.Ctx.getAsConstantArrayType(S->getType());
2041  assert(CAT && "string literal isn't an array");
2042  QualType CharType = CAT->getElementType();
2043  assert(CharType->isIntegerType() && "unexpected character type");
2044 
2045  APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2046  CharType->isUnsignedIntegerType());
2047  if (Index < S->getLength())
2048  Value = S->getCodeUnit(Index);
2049  return Value;
2050 }
2051 
2052 // Expand a string literal into an array of characters.
2053 static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2054  APValue &Result) {
2055  const StringLiteral *S = cast<StringLiteral>(Lit);
2056  const ConstantArrayType *CAT =
2057  Info.Ctx.getAsConstantArrayType(S->getType());
2058  assert(CAT && "string literal isn't an array");
2059  QualType CharType = CAT->getElementType();
2060  assert(CharType->isIntegerType() && "unexpected character type");
2061 
2062  unsigned Elts = CAT->getSize().getZExtValue();
2063  Result = APValue(APValue::UninitArray(),
2064  std::min(S->getLength(), Elts), Elts);
2065  APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2066  CharType->isUnsignedIntegerType());
2067  if (Result.hasArrayFiller())
2068  Result.getArrayFiller() = APValue(Value);
2069  for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2070  Value = S->getCodeUnit(I);
2071  Result.getArrayInitializedElt(I) = APValue(Value);
2072  }
2073 }
2074 
2075 // Expand an array so that it has more than Index filled elements.
2076 static void expandArray(APValue &Array, unsigned Index) {
2077  unsigned Size = Array.getArraySize();
2078  assert(Index < Size);
2079 
2080  // Always at least double the number of elements for which we store a value.
2081  unsigned OldElts = Array.getArrayInitializedElts();
2082  unsigned NewElts = std::max(Index+1, OldElts * 2);
2083  NewElts = std::min(Size, std::max(NewElts, 8u));
2084 
2085  // Copy the data across.
2086  APValue NewValue(APValue::UninitArray(), NewElts, Size);
2087  for (unsigned I = 0; I != OldElts; ++I)
2088  NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2089  for (unsigned I = OldElts; I != NewElts; ++I)
2090  NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2091  if (NewValue.hasArrayFiller())
2092  NewValue.getArrayFiller() = Array.getArrayFiller();
2093  Array.swap(NewValue);
2094 }
2095 
2096 /// Determine whether a type would actually be read by an lvalue-to-rvalue
2097 /// conversion. If it's of class type, we may assume that the copy operation
2098 /// is trivial. Note that this is never true for a union type with fields
2099 /// (because the copy always "reads" the active member) and always true for
2100 /// a non-class type.
2103  if (!RD || (RD->isUnion() && !RD->field_empty()))
2104  return true;
2105  if (RD->isEmpty())
2106  return false;
2107 
2108  for (auto *Field : RD->fields())
2109  if (isReadByLvalueToRvalueConversion(Field->getType()))
2110  return true;
2111 
2112  for (auto &BaseSpec : RD->bases())
2113  if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2114  return true;
2115 
2116  return false;
2117 }
2118 
2119 /// Diagnose an attempt to read from any unreadable field within the specified
2120 /// type, which might be a class type.
2121 static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2122  QualType T) {
2124  if (!RD)
2125  return false;
2126 
2127  if (!RD->hasMutableFields())
2128  return false;
2129 
2130  for (auto *Field : RD->fields()) {
2131  // If we're actually going to read this field in some way, then it can't
2132  // be mutable. If we're in a union, then assigning to a mutable field
2133  // (even an empty one) can change the active member, so that's not OK.
2134  // FIXME: Add core issue number for the union case.
2135  if (Field->isMutable() &&
2136  (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2137  Info.Diag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2138  Info.Note(Field->getLocation(), diag::note_declared_at);
2139  return true;
2140  }
2141 
2142  if (diagnoseUnreadableFields(Info, E, Field->getType()))
2143  return true;
2144  }
2145 
2146  for (auto &BaseSpec : RD->bases())
2147  if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2148  return true;
2149 
2150  // All mutable fields were empty, and thus not actually read.
2151  return false;
2152 }
2153 
2154 /// Kinds of access we can perform on an object, for diagnostics.
2160 };
2161 
2162 /// A handle to a complete object (an object that is not a subobject of
2163 /// another object).
2165  /// The value of the complete object.
2167  /// The type of the complete object.
2169 
2170  CompleteObject() : Value(nullptr) {}
2172  : Value(Value), Type(Type) {
2173  assert(Value && "missing value for complete object");
2174  }
2175 
2176  explicit operator bool() const { return Value; }
2177 };
2178 
2179 /// Find the designated sub-object of an rvalue.
2180 template<typename SubobjectHandler>
2181 typename SubobjectHandler::result_type
2182 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
2183  const SubobjectDesignator &Sub, SubobjectHandler &handler) {
2184  if (Sub.Invalid)
2185  // A diagnostic will have already been produced.
2186  return handler.failed();
2187  if (Sub.isOnePastTheEnd()) {
2188  if (Info.getLangOpts().CPlusPlus11)
2189  Info.Diag(E, diag::note_constexpr_access_past_end)
2190  << handler.AccessKind;
2191  else
2192  Info.Diag(E);
2193  return handler.failed();
2194  }
2195 
2196  APValue *O = Obj.Value;
2197  QualType ObjType = Obj.Type;
2198  const FieldDecl *LastField = nullptr;
2199 
2200  // Walk the designator's path to find the subobject.
2201  for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2202  if (O->isUninit()) {
2203  if (!Info.checkingPotentialConstantExpression())
2204  Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2205  return handler.failed();
2206  }
2207 
2208  if (I == N) {
2209  // If we are reading an object of class type, there may still be more
2210  // things we need to check: if there are any mutable subobjects, we
2211  // cannot perform this read. (This only happens when performing a trivial
2212  // copy or assignment.)
2213  if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2214  diagnoseUnreadableFields(Info, E, ObjType))
2215  return handler.failed();
2216 
2217  if (!handler.found(*O, ObjType))
2218  return false;
2219 
2220  // If we modified a bit-field, truncate it to the right width.
2221  if (handler.AccessKind != AK_Read &&
2222  LastField && LastField->isBitField() &&
2223  !truncateBitfieldValue(Info, E, *O, LastField))
2224  return false;
2225 
2226  return true;
2227  }
2228 
2229  LastField = nullptr;
2230  if (ObjType->isArrayType()) {
2231  // Next subobject is an array element.
2232  const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
2233  assert(CAT && "vla in literal type?");
2234  uint64_t Index = Sub.Entries[I].ArrayIndex;
2235  if (CAT->getSize().ule(Index)) {
2236  // Note, it should not be possible to form a pointer with a valid
2237  // designator which points more than one past the end of the array.
2238  if (Info.getLangOpts().CPlusPlus11)
2239  Info.Diag(E, diag::note_constexpr_access_past_end)
2240  << handler.AccessKind;
2241  else
2242  Info.Diag(E);
2243  return handler.failed();
2244  }
2245 
2246  ObjType = CAT->getElementType();
2247 
2248  // An array object is represented as either an Array APValue or as an
2249  // LValue which refers to a string literal.
2250  if (O->isLValue()) {
2251  assert(I == N - 1 && "extracting subobject of character?");
2252  assert(!O->hasLValuePath() || O->getLValuePath().empty());
2253  if (handler.AccessKind != AK_Read)
2254  expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2255  *O);
2256  else
2257  return handler.foundString(*O, ObjType, Index);
2258  }
2259 
2260  if (O->getArrayInitializedElts() > Index)
2261  O = &O->getArrayInitializedElt(Index);
2262  else if (handler.AccessKind != AK_Read) {
2263  expandArray(*O, Index);
2264  O = &O->getArrayInitializedElt(Index);
2265  } else
2266  O = &O->getArrayFiller();
2267  } else if (ObjType->isAnyComplexType()) {
2268  // Next subobject is a complex number.
2269  uint64_t Index = Sub.Entries[I].ArrayIndex;
2270  if (Index > 1) {
2271  if (Info.getLangOpts().CPlusPlus11)
2272  Info.Diag(E, diag::note_constexpr_access_past_end)
2273  << handler.AccessKind;
2274  else
2275  Info.Diag(E);
2276  return handler.failed();
2277  }
2278 
2279  bool WasConstQualified = ObjType.isConstQualified();
2280  ObjType = ObjType->castAs<ComplexType>()->getElementType();
2281  if (WasConstQualified)
2282  ObjType.addConst();
2283 
2284  assert(I == N - 1 && "extracting subobject of scalar?");
2285  if (O->isComplexInt()) {
2286  return handler.found(Index ? O->getComplexIntImag()
2287  : O->getComplexIntReal(), ObjType);
2288  } else {
2289  assert(O->isComplexFloat());
2290  return handler.found(Index ? O->getComplexFloatImag()
2291  : O->getComplexFloatReal(), ObjType);
2292  }
2293  } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
2294  if (Field->isMutable() && handler.AccessKind == AK_Read) {
2295  Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
2296  << Field;
2297  Info.Note(Field->getLocation(), diag::note_declared_at);
2298  return handler.failed();
2299  }
2300 
2301  // Next subobject is a class, struct or union field.
2302  RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2303  if (RD->isUnion()) {
2304  const FieldDecl *UnionField = O->getUnionField();
2305  if (!UnionField ||
2306  UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
2307  Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
2308  << handler.AccessKind << Field << !UnionField << UnionField;
2309  return handler.failed();
2310  }
2311  O = &O->getUnionValue();
2312  } else
2313  O = &O->getStructField(Field->getFieldIndex());
2314 
2315  bool WasConstQualified = ObjType.isConstQualified();
2316  ObjType = Field->getType();
2317  if (WasConstQualified && !Field->isMutable())
2318  ObjType.addConst();
2319 
2320  if (ObjType.isVolatileQualified()) {
2321  if (Info.getLangOpts().CPlusPlus) {
2322  // FIXME: Include a description of the path to the volatile subobject.
2323  Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2324  << handler.AccessKind << 2 << Field;
2325  Info.Note(Field->getLocation(), diag::note_declared_at);
2326  } else {
2327  Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
2328  }
2329  return handler.failed();
2330  }
2331 
2332  LastField = Field;
2333  } else {
2334  // Next subobject is a base class.
2335  const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2336  const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2337  O = &O->getStructBase(getBaseIndex(Derived, Base));
2338 
2339  bool WasConstQualified = ObjType.isConstQualified();
2340  ObjType = Info.Ctx.getRecordType(Base);
2341  if (WasConstQualified)
2342  ObjType.addConst();
2343  }
2344  }
2345 }
2346 
2347 namespace {
2348 struct ExtractSubobjectHandler {
2349  EvalInfo &Info;
2350  APValue &Result;
2351 
2352  static const AccessKinds AccessKind = AK_Read;
2353 
2354  typedef bool result_type;
2355  bool failed() { return false; }
2356  bool found(APValue &Subobj, QualType SubobjType) {
2357  Result = Subobj;
2358  return true;
2359  }
2360  bool found(APSInt &Value, QualType SubobjType) {
2361  Result = APValue(Value);
2362  return true;
2363  }
2364  bool found(APFloat &Value, QualType SubobjType) {
2365  Result = APValue(Value);
2366  return true;
2367  }
2368  bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2370  Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2371  return true;
2372  }
2373 };
2374 } // end anonymous namespace
2375 
2377 
2378 /// Extract the designated sub-object of an rvalue.
2379 static bool extractSubobject(EvalInfo &Info, const Expr *E,
2380  const CompleteObject &Obj,
2381  const SubobjectDesignator &Sub,
2382  APValue &Result) {
2383  ExtractSubobjectHandler Handler = { Info, Result };
2384  return findSubobject(Info, E, Obj, Sub, Handler);
2385 }
2386 
2387 namespace {
2388 struct ModifySubobjectHandler {
2389  EvalInfo &Info;
2390  APValue &NewVal;
2391  const Expr *E;
2392 
2393  typedef bool result_type;
2394  static const AccessKinds AccessKind = AK_Assign;
2395 
2396  bool checkConst(QualType QT) {
2397  // Assigning to a const object has undefined behavior.
2398  if (QT.isConstQualified()) {
2399  Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2400  return false;
2401  }
2402  return true;
2403  }
2404 
2405  bool failed() { return false; }
2406  bool found(APValue &Subobj, QualType SubobjType) {
2407  if (!checkConst(SubobjType))
2408  return false;
2409  // We've been given ownership of NewVal, so just swap it in.
2410  Subobj.swap(NewVal);
2411  return true;
2412  }
2413  bool found(APSInt &Value, QualType SubobjType) {
2414  if (!checkConst(SubobjType))
2415  return false;
2416  if (!NewVal.isInt()) {
2417  // Maybe trying to write a cast pointer value into a complex?
2418  Info.Diag(E);
2419  return false;
2420  }
2421  Value = NewVal.getInt();
2422  return true;
2423  }
2424  bool found(APFloat &Value, QualType SubobjType) {
2425  if (!checkConst(SubobjType))
2426  return false;
2427  Value = NewVal.getFloat();
2428  return true;
2429  }
2430  bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2431  llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2432  }
2433 };
2434 } // end anonymous namespace
2435 
2437 
2438 /// Update the designated sub-object of an rvalue to the given value.
2439 static bool modifySubobject(EvalInfo &Info, const Expr *E,
2440  const CompleteObject &Obj,
2441  const SubobjectDesignator &Sub,
2442  APValue &NewVal) {
2443  ModifySubobjectHandler Handler = { Info, NewVal, E };
2444  return findSubobject(Info, E, Obj, Sub, Handler);
2445 }
2446 
2447 /// Find the position where two subobject designators diverge, or equivalently
2448 /// the length of the common initial subsequence.
2449 static unsigned FindDesignatorMismatch(QualType ObjType,
2450  const SubobjectDesignator &A,
2451  const SubobjectDesignator &B,
2452  bool &WasArrayIndex) {
2453  unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2454  for (/**/; I != N; ++I) {
2455  if (!ObjType.isNull() &&
2456  (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
2457  // Next subobject is an array element.
2458  if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2459  WasArrayIndex = true;
2460  return I;
2461  }
2462  if (ObjType->isAnyComplexType())
2463  ObjType = ObjType->castAs<ComplexType>()->getElementType();
2464  else
2465  ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
2466  } else {
2467  if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2468  WasArrayIndex = false;
2469  return I;
2470  }
2471  if (const FieldDecl *FD = getAsField(A.Entries[I]))
2472  // Next subobject is a field.
2473  ObjType = FD->getType();
2474  else
2475  // Next subobject is a base class.
2476  ObjType = QualType();
2477  }
2478  }
2479  WasArrayIndex = false;
2480  return I;
2481 }
2482 
2483 /// Determine whether the given subobject designators refer to elements of the
2484 /// same array object.
2485 static bool AreElementsOfSameArray(QualType ObjType,
2486  const SubobjectDesignator &A,
2487  const SubobjectDesignator &B) {
2488  if (A.Entries.size() != B.Entries.size())
2489  return false;
2490 
2491  bool IsArray = A.MostDerivedArraySize != 0;
2492  if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2493  // A is a subobject of the array element.
2494  return false;
2495 
2496  // If A (and B) designates an array element, the last entry will be the array
2497  // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2498  // of length 1' case, and the entire path must match.
2499  bool WasArrayIndex;
2500  unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2501  return CommonLength >= A.Entries.size() - IsArray;
2502 }
2503 
2504 /// Find the complete object to which an LValue refers.
2505 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2506  AccessKinds AK, const LValue &LVal,
2507  QualType LValType) {
2508  if (!LVal.Base) {
2509  Info.Diag(E, diag::note_constexpr_access_null) << AK;
2510  return CompleteObject();
2511  }
2512 
2513  CallStackFrame *Frame = nullptr;
2514  if (LVal.CallIndex) {
2515  Frame = Info.getCallFrame(LVal.CallIndex);
2516  if (!Frame) {
2517  Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2518  << AK << LVal.Base.is<const ValueDecl*>();
2519  NoteLValueLocation(Info, LVal.Base);
2520  return CompleteObject();
2521  }
2522  }
2523 
2524  // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2525  // is not a constant expression (even if the object is non-volatile). We also
2526  // apply this rule to C++98, in order to conform to the expected 'volatile'
2527  // semantics.
2528  if (LValType.isVolatileQualified()) {
2529  if (Info.getLangOpts().CPlusPlus)
2530  Info.Diag(E, diag::note_constexpr_access_volatile_type)
2531  << AK << LValType;
2532  else
2533  Info.Diag(E);
2534  return CompleteObject();
2535  }
2536 
2537  // Compute value storage location and type of base object.
2538  APValue *BaseVal = nullptr;
2539  QualType BaseType = getType(LVal.Base);
2540 
2541  if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2542  // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2543  // In C++11, constexpr, non-volatile variables initialized with constant
2544  // expressions are constant expressions too. Inside constexpr functions,
2545  // parameters are constant expressions even if they're non-const.
2546  // In C++1y, objects local to a constant expression (those with a Frame) are
2547  // both readable and writable inside constant expressions.
2548  // In C, such things can also be folded, although they are not ICEs.
2549  const VarDecl *VD = dyn_cast<VarDecl>(D);
2550  if (VD) {
2551  if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2552  VD = VDef;
2553  }
2554  if (!VD || VD->isInvalidDecl()) {
2555  Info.Diag(E);
2556  return CompleteObject();
2557  }
2558 
2559  // Accesses of volatile-qualified objects are not allowed.
2560  if (BaseType.isVolatileQualified()) {
2561  if (Info.getLangOpts().CPlusPlus) {
2562  Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2563  << AK << 1 << VD;
2564  Info.Note(VD->getLocation(), diag::note_declared_at);
2565  } else {
2566  Info.Diag(E);
2567  }
2568  return CompleteObject();
2569  }
2570 
2571  // Unless we're looking at a local variable or argument in a constexpr call,
2572  // the variable we're reading must be const.
2573  if (!Frame) {
2574  if (Info.getLangOpts().CPlusPlus14 &&
2575  VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2576  // OK, we can read and modify an object if we're in the process of
2577  // evaluating its initializer, because its lifetime began in this
2578  // evaluation.
2579  } else if (AK != AK_Read) {
2580  // All the remaining cases only permit reading.
2581  Info.Diag(E, diag::note_constexpr_modify_global);
2582  return CompleteObject();
2583  } else if (VD->isConstexpr()) {
2584  // OK, we can read this variable.
2585  } else if (BaseType->isIntegralOrEnumerationType()) {
2586  if (!BaseType.isConstQualified()) {
2587  if (Info.getLangOpts().CPlusPlus) {
2588  Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2589  Info.Note(VD->getLocation(), diag::note_declared_at);
2590  } else {
2591  Info.Diag(E);
2592  }
2593  return CompleteObject();
2594  }
2595  } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2596  // We support folding of const floating-point types, in order to make
2597  // static const data members of such types (supported as an extension)
2598  // more useful.
2599  if (Info.getLangOpts().CPlusPlus11) {
2600  Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2601  Info.Note(VD->getLocation(), diag::note_declared_at);
2602  } else {
2603  Info.CCEDiag(E);
2604  }
2605  } else {
2606  // FIXME: Allow folding of values of any literal type in all languages.
2607  if (Info.getLangOpts().CPlusPlus11) {
2608  Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2609  Info.Note(VD->getLocation(), diag::note_declared_at);
2610  } else {
2611  Info.Diag(E);
2612  }
2613  return CompleteObject();
2614  }
2615  }
2616 
2617  if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2618  return CompleteObject();
2619  } else {
2620  const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2621 
2622  if (!Frame) {
2623  if (const MaterializeTemporaryExpr *MTE =
2624  dyn_cast<MaterializeTemporaryExpr>(Base)) {
2625  assert(MTE->getStorageDuration() == SD_Static &&
2626  "should have a frame for a non-global materialized temporary");
2627 
2628  // Per C++1y [expr.const]p2:
2629  // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2630  // - a [...] glvalue of integral or enumeration type that refers to
2631  // a non-volatile const object [...]
2632  // [...]
2633  // - a [...] glvalue of literal type that refers to a non-volatile
2634  // object whose lifetime began within the evaluation of e.
2635  //
2636  // C++11 misses the 'began within the evaluation of e' check and
2637  // instead allows all temporaries, including things like:
2638  // int &&r = 1;
2639  // int x = ++r;
2640  // constexpr int k = r;
2641  // Therefore we use the C++1y rules in C++11 too.
2642  const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2643  const ValueDecl *ED = MTE->getExtendingDecl();
2644  if (!(BaseType.isConstQualified() &&
2645  BaseType->isIntegralOrEnumerationType()) &&
2646  !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
2647  Info.Diag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
2648  Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2649  return CompleteObject();
2650  }
2651 
2652  BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2653  assert(BaseVal && "got reference to unevaluated temporary");
2654  } else {
2655  Info.Diag(E);
2656  return CompleteObject();
2657  }
2658  } else {
2659  BaseVal = Frame->getTemporary(Base);
2660  assert(BaseVal && "missing value for temporary");
2661  }
2662 
2663  // Volatile temporary objects cannot be accessed in constant expressions.
2664  if (BaseType.isVolatileQualified()) {
2665  if (Info.getLangOpts().CPlusPlus) {
2666  Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2667  << AK << 0;
2668  Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2669  } else {
2670  Info.Diag(E);
2671  }
2672  return CompleteObject();
2673  }
2674  }
2675 
2676  // During the construction of an object, it is not yet 'const'.
2677  // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2678  // and this doesn't do quite the right thing for const subobjects of the
2679  // object under construction.
2680  if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2681  BaseType = Info.Ctx.getCanonicalType(BaseType);
2682  BaseType.removeLocalConst();
2683  }
2684 
2685  // In C++1y, we can't safely access any mutable state when we might be
2686  // evaluating after an unmodeled side effect or an evaluation failure.
2687  //
2688  // FIXME: Not all local state is mutable. Allow local constant subobjects
2689  // to be read here (but take care with 'mutable' fields).
2690  if (Frame && Info.getLangOpts().CPlusPlus14 &&
2691  (Info.EvalStatus.HasSideEffects || Info.keepEvaluatingAfterFailure()))
2692  return CompleteObject();
2693 
2694  return CompleteObject(BaseVal, BaseType);
2695 }
2696 
2697 /// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2698 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2699 /// glvalue referred to by an entity of reference type.
2700 ///
2701 /// \param Info - Information about the ongoing evaluation.
2702 /// \param Conv - The expression for which we are performing the conversion.
2703 /// Used for diagnostics.
2704 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2705 /// case of a non-class type).
2706 /// \param LVal - The glvalue on which we are attempting to perform this action.
2707 /// \param RVal - The produced value will be placed here.
2708 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2709  QualType Type,
2710  const LValue &LVal, APValue &RVal) {
2711  if (LVal.Designator.Invalid)
2712  return false;
2713 
2714  // Check for special cases where there is no existing APValue to look at.
2715  const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2716  if (!LVal.Designator.Invalid && Base && !LVal.CallIndex &&
2717  !Type.isVolatileQualified()) {
2718  if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2719  // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2720  // initializer until now for such expressions. Such an expression can't be
2721  // an ICE in C, so this only matters for fold.
2722  assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2723  if (Type.isVolatileQualified()) {
2724  Info.Diag(Conv);
2725  return false;
2726  }
2727  APValue Lit;
2728  if (!Evaluate(Lit, Info, CLE->getInitializer()))
2729  return false;
2730  CompleteObject LitObj(&Lit, Base->getType());
2731  return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
2732  } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
2733  // We represent a string literal array as an lvalue pointing at the
2734  // corresponding expression, rather than building an array of chars.
2735  // FIXME: Support ObjCEncodeExpr, MakeStringConstant
2736  APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2737  CompleteObject StrObj(&Str, Base->getType());
2738  return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
2739  }
2740  }
2741 
2742  CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2743  return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
2744 }
2745 
2746 /// Perform an assignment of Val to LVal. Takes ownership of Val.
2747 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
2748  QualType LValType, APValue &Val) {
2749  if (LVal.Designator.Invalid)
2750  return false;
2751 
2752  if (!Info.getLangOpts().CPlusPlus14) {
2753  Info.Diag(E);
2754  return false;
2755  }
2756 
2757  CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2758  return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
2759 }
2760 
2762  return T->isSignedIntegerType() &&
2763  Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2764 }
2765 
2766 namespace {
2767 struct CompoundAssignSubobjectHandler {
2768  EvalInfo &Info;
2769  const Expr *E;
2770  QualType PromotedLHSType;
2771  BinaryOperatorKind Opcode;
2772  const APValue &RHS;
2773 
2774  static const AccessKinds AccessKind = AK_Assign;
2775 
2776  typedef bool result_type;
2777 
2778  bool checkConst(QualType QT) {
2779  // Assigning to a const object has undefined behavior.
2780  if (QT.isConstQualified()) {
2781  Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2782  return false;
2783  }
2784  return true;
2785  }
2786 
2787  bool failed() { return false; }
2788  bool found(APValue &Subobj, QualType SubobjType) {
2789  switch (Subobj.getKind()) {
2790  case APValue::Int:
2791  return found(Subobj.getInt(), SubobjType);
2792  case APValue::Float:
2793  return found(Subobj.getFloat(), SubobjType);
2794  case APValue::ComplexInt:
2795  case APValue::ComplexFloat:
2796  // FIXME: Implement complex compound assignment.
2797  Info.Diag(E);
2798  return false;
2799  case APValue::LValue:
2800  return foundPointer(Subobj, SubobjType);
2801  default:
2802  // FIXME: can this happen?
2803  Info.Diag(E);
2804  return false;
2805  }
2806  }
2807  bool found(APSInt &Value, QualType SubobjType) {
2808  if (!checkConst(SubobjType))
2809  return false;
2810 
2811  if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2812  // We don't support compound assignment on integer-cast-to-pointer
2813  // values.
2814  Info.Diag(E);
2815  return false;
2816  }
2817 
2818  APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2819  SubobjType, Value);
2820  if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
2821  return false;
2822  Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
2823  return true;
2824  }
2825  bool found(APFloat &Value, QualType SubobjType) {
2826  return checkConst(SubobjType) &&
2827  HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
2828  Value) &&
2829  handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
2830  HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
2831  }
2832  bool foundPointer(APValue &Subobj, QualType SubobjType) {
2833  if (!checkConst(SubobjType))
2834  return false;
2835 
2836  QualType PointeeType;
2837  if (const PointerType *PT = SubobjType->getAs<PointerType>())
2838  PointeeType = PT->getPointeeType();
2839 
2840  if (PointeeType.isNull() || !RHS.isInt() ||
2841  (Opcode != BO_Add && Opcode != BO_Sub)) {
2842  Info.Diag(E);
2843  return false;
2844  }
2845 
2846  int64_t Offset = getExtValue(RHS.getInt());
2847  if (Opcode == BO_Sub)
2848  Offset = -Offset;
2849 
2850  LValue LVal;
2851  LVal.setFrom(Info.Ctx, Subobj);
2852  if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
2853  return false;
2854  LVal.moveInto(Subobj);
2855  return true;
2856  }
2857  bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2858  llvm_unreachable("shouldn't encounter string elements here");
2859  }
2860 };
2861 } // end anonymous namespace
2862 
2864 
2865 /// Perform a compound assignment of LVal <op>= RVal.
2867  EvalInfo &Info, const Expr *E,
2868  const LValue &LVal, QualType LValType, QualType PromotedLValType,
2869  BinaryOperatorKind Opcode, const APValue &RVal) {
2870  if (LVal.Designator.Invalid)
2871  return false;
2872 
2873  if (!Info.getLangOpts().CPlusPlus14) {
2874  Info.Diag(E);
2875  return false;
2876  }
2877 
2878  CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2879  CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
2880  RVal };
2881  return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2882 }
2883 
2884 namespace {
2885 struct IncDecSubobjectHandler {
2886  EvalInfo &Info;
2887  const Expr *E;
2889  APValue *Old;
2890 
2891  typedef bool result_type;
2892 
2893  bool checkConst(QualType QT) {
2894  // Assigning to a const object has undefined behavior.
2895  if (QT.isConstQualified()) {
2896  Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2897  return false;
2898  }
2899  return true;
2900  }
2901 
2902  bool failed() { return false; }
2903  bool found(APValue &Subobj, QualType SubobjType) {
2904  // Stash the old value. Also clear Old, so we don't clobber it later
2905  // if we're post-incrementing a complex.
2906  if (Old) {
2907  *Old = Subobj;
2908  Old = nullptr;
2909  }
2910 
2911  switch (Subobj.getKind()) {
2912  case APValue::Int:
2913  return found(Subobj.getInt(), SubobjType);
2914  case APValue::Float:
2915  return found(Subobj.getFloat(), SubobjType);
2916  case APValue::ComplexInt:
2917  return found(Subobj.getComplexIntReal(),
2918  SubobjType->castAs<ComplexType>()->getElementType()
2919  .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2920  case APValue::ComplexFloat:
2921  return found(Subobj.getComplexFloatReal(),
2922  SubobjType->castAs<ComplexType>()->getElementType()
2923  .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2924  case APValue::LValue:
2925  return foundPointer(Subobj, SubobjType);
2926  default:
2927  // FIXME: can this happen?
2928  Info.Diag(E);
2929  return false;
2930  }
2931  }
2932  bool found(APSInt &Value, QualType SubobjType) {
2933  if (!checkConst(SubobjType))
2934  return false;
2935 
2936  if (!SubobjType->isIntegerType()) {
2937  // We don't support increment / decrement on integer-cast-to-pointer
2938  // values.
2939  Info.Diag(E);
2940  return false;
2941  }
2942 
2943  if (Old) *Old = APValue(Value);
2944 
2945  // bool arithmetic promotes to int, and the conversion back to bool
2946  // doesn't reduce mod 2^n, so special-case it.
2947  if (SubobjType->isBooleanType()) {
2948  if (AccessKind == AK_Increment)
2949  Value = 1;
2950  else
2951  Value = !Value;
2952  return true;
2953  }
2954 
2955  bool WasNegative = Value.isNegative();
2956  if (AccessKind == AK_Increment) {
2957  ++Value;
2958 
2959  if (!WasNegative && Value.isNegative() &&
2960  isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2961  APSInt ActualValue(Value, /*IsUnsigned*/true);
2962  HandleOverflow(Info, E, ActualValue, SubobjType);
2963  }
2964  } else {
2965  --Value;
2966 
2967  if (WasNegative && !Value.isNegative() &&
2968  isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2969  unsigned BitWidth = Value.getBitWidth();
2970  APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
2971  ActualValue.setBit(BitWidth);
2972  HandleOverflow(Info, E, ActualValue, SubobjType);
2973  }
2974  }
2975  return true;
2976  }
2977  bool found(APFloat &Value, QualType SubobjType) {
2978  if (!checkConst(SubobjType))
2979  return false;
2980 
2981  if (Old) *Old = APValue(Value);
2982 
2983  APFloat One(Value.getSemantics(), 1);
2984  if (AccessKind == AK_Increment)
2985  Value.add(One, APFloat::rmNearestTiesToEven);
2986  else
2987  Value.subtract(One, APFloat::rmNearestTiesToEven);
2988  return true;
2989  }
2990  bool foundPointer(APValue &Subobj, QualType SubobjType) {
2991  if (!checkConst(SubobjType))
2992  return false;
2993 
2994  QualType PointeeType;
2995  if (const PointerType *PT = SubobjType->getAs<PointerType>())
2996  PointeeType = PT->getPointeeType();
2997  else {
2998  Info.Diag(E);
2999  return false;
3000  }
3001 
3002  LValue LVal;
3003  LVal.setFrom(Info.Ctx, Subobj);
3004  if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3005  AccessKind == AK_Increment ? 1 : -1))
3006  return false;
3007  LVal.moveInto(Subobj);
3008  return true;
3009  }
3010  bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3011  llvm_unreachable("shouldn't encounter string elements here");
3012  }
3013 };
3014 } // end anonymous namespace
3015 
3016 /// Perform an increment or decrement on LVal.
3017 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3018  QualType LValType, bool IsIncrement, APValue *Old) {
3019  if (LVal.Designator.Invalid)
3020  return false;
3021 
3022  if (!Info.getLangOpts().CPlusPlus14) {
3023  Info.Diag(E);
3024  return false;
3025  }
3026 
3027  AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3028  CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3029  IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3030  return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3031 }
3032 
3033 /// Build an lvalue for the object argument of a member function call.
3034 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3035  LValue &This) {
3036  if (Object->getType()->isPointerType())
3037  return EvaluatePointer(Object, This, Info);
3038 
3039  if (Object->isGLValue())
3040  return EvaluateLValue(Object, This, Info);
3041 
3042  if (Object->getType()->isLiteralType(Info.Ctx))
3043  return EvaluateTemporary(Object, This, Info);
3044 
3045  Info.Diag(Object, diag::note_constexpr_nonliteral) << Object->getType();
3046  return false;
3047 }
3048 
3049 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
3050 /// lvalue referring to the result.
3051 ///
3052 /// \param Info - Information about the ongoing evaluation.
3053 /// \param LV - An lvalue referring to the base of the member pointer.
3054 /// \param RHS - The member pointer expression.
3055 /// \param IncludeMember - Specifies whether the member itself is included in
3056 /// the resulting LValue subobject designator. This is not possible when
3057 /// creating a bound member function.
3058 /// \return The field or method declaration to which the member pointer refers,
3059 /// or 0 if evaluation fails.
3060 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3061  QualType LVType,
3062  LValue &LV,
3063  const Expr *RHS,
3064  bool IncludeMember = true) {
3065  MemberPtr MemPtr;
3066  if (!EvaluateMemberPointer(RHS, MemPtr, Info))
3067  return nullptr;
3068 
3069  // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3070  // member value, the behavior is undefined.
3071  if (!MemPtr.getDecl()) {
3072  // FIXME: Specific diagnostic.
3073  Info.Diag(RHS);
3074  return nullptr;
3075  }
3076 
3077  if (MemPtr.isDerivedMember()) {
3078  // This is a member of some derived class. Truncate LV appropriately.
3079  // The end of the derived-to-base path for the base object must match the
3080  // derived-to-base path for the member pointer.
3081  if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
3082  LV.Designator.Entries.size()) {
3083  Info.Diag(RHS);
3084  return nullptr;
3085  }
3086  unsigned PathLengthToMember =
3087  LV.Designator.Entries.size() - MemPtr.Path.size();
3088  for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3089  const CXXRecordDecl *LVDecl = getAsBaseClass(
3090  LV.Designator.Entries[PathLengthToMember + I]);
3091  const CXXRecordDecl *MPDecl = MemPtr.Path[I];
3092  if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3093  Info.Diag(RHS);
3094  return nullptr;
3095  }
3096  }
3097 
3098  // Truncate the lvalue to the appropriate derived class.
3099  if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
3100  PathLengthToMember))
3101  return nullptr;
3102  } else if (!MemPtr.Path.empty()) {
3103  // Extend the LValue path with the member pointer's path.
3104  LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3105  MemPtr.Path.size() + IncludeMember);
3106 
3107  // Walk down to the appropriate base class.
3108  if (const PointerType *PT = LVType->getAs<PointerType>())
3109  LVType = PT->getPointeeType();
3110  const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3111  assert(RD && "member pointer access on non-class-type expression");
3112  // The first class in the path is that of the lvalue.
3113  for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3114  const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
3115  if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
3116  return nullptr;
3117  RD = Base;
3118  }
3119  // Finally cast to the class containing the member.
3120  if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3121  MemPtr.getContainingRecord()))
3122  return nullptr;
3123  }
3124 
3125  // Add the member. Note that we cannot build bound member functions here.
3126  if (IncludeMember) {
3127  if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
3128  if (!HandleLValueMember(Info, RHS, LV, FD))
3129  return nullptr;
3130  } else if (const IndirectFieldDecl *IFD =
3131  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
3132  if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
3133  return nullptr;
3134  } else {
3135  llvm_unreachable("can't construct reference to bound member function");
3136  }
3137  }
3138 
3139  return MemPtr.getDecl();
3140 }
3141 
3142 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3143  const BinaryOperator *BO,
3144  LValue &LV,
3145  bool IncludeMember = true) {
3146  assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3147 
3148  if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3149  if (Info.keepEvaluatingAfterFailure()) {
3150  MemberPtr MemPtr;
3151  EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3152  }
3153  return nullptr;
3154  }
3155 
3156  return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3157  BO->getRHS(), IncludeMember);
3158 }
3159 
3160 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3161 /// the provided lvalue, which currently refers to the base object.
3162 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3163  LValue &Result) {
3164  SubobjectDesignator &D = Result.Designator;
3165  if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
3166  return false;
3167 
3168  QualType TargetQT = E->getType();
3169  if (const PointerType *PT = TargetQT->getAs<PointerType>())
3170  TargetQT = PT->getPointeeType();
3171 
3172  // Check this cast lands within the final derived-to-base subobject path.
3173  if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
3174  Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3175  << D.MostDerivedType << TargetQT;
3176  return false;
3177  }
3178 
3179  // Check the type of the final cast. We don't need to check the path,
3180  // since a cast can only be formed if the path is unique.
3181  unsigned NewEntriesSize = D.Entries.size() - E->path_size();
3182  const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3183  const CXXRecordDecl *FinalType;
3184  if (NewEntriesSize == D.MostDerivedPathLength)
3185  FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3186  else
3187  FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
3188  if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
3189  Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3190  << D.MostDerivedType << TargetQT;
3191  return false;
3192  }
3193 
3194  // Truncate the lvalue to the appropriate derived class.
3195  return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
3196 }
3197 
3198 namespace {
3200  /// Evaluation failed.
3201  ESR_Failed,
3202  /// Hit a 'return' statement.
3203  ESR_Returned,
3204  /// Evaluation succeeded.
3205  ESR_Succeeded,
3206  /// Hit a 'continue' statement.
3207  ESR_Continue,
3208  /// Hit a 'break' statement.
3209  ESR_Break,
3210  /// Still scanning for 'case' or 'default' statement.
3211  ESR_CaseNotFound
3212 };
3213 }
3214 
3215 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3216  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3217  // We don't need to evaluate the initializer for a static local.
3218  if (!VD->hasLocalStorage())
3219  return true;
3220 
3221  LValue Result;
3222  Result.set(VD, Info.CurrentCall->Index);
3223  APValue &Val = Info.CurrentCall->createTemporary(VD, true);
3224 
3225  const Expr *InitE = VD->getInit();
3226  if (!InitE) {
3227  Info.Diag(D->getLocStart(), diag::note_constexpr_uninitialized)
3228  << false << VD->getType();
3229  Val = APValue();
3230  return false;
3231  }
3232 
3233  if (InitE->isValueDependent())
3234  return false;
3235 
3236  if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3237  // Wipe out any partially-computed value, to allow tracking that this
3238  // evaluation failed.
3239  Val = APValue();
3240  return false;
3241  }
3242  }
3243 
3244  return true;
3245 }
3246 
3247 /// Evaluate a condition (either a variable declaration or an expression).
3248 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3249  const Expr *Cond, bool &Result) {
3250  FullExpressionRAII Scope(Info);
3251  if (CondDecl && !EvaluateDecl(Info, CondDecl))
3252  return false;
3253  return EvaluateAsBooleanCondition(Cond, Result, Info);
3254 }
3255 
3256 static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
3257  const Stmt *S,
3258  const SwitchCase *SC = nullptr);
3259 
3260 /// Evaluate the body of a loop, and translate the result as appropriate.
3261 static EvalStmtResult EvaluateLoopBody(APValue &Result, EvalInfo &Info,
3262  const Stmt *Body,
3263  const SwitchCase *Case = nullptr) {
3264  BlockScopeRAII Scope(Info);
3265  switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
3266  case ESR_Break:
3267  return ESR_Succeeded;
3268  case ESR_Succeeded:
3269  case ESR_Continue:
3270  return ESR_Continue;
3271  case ESR_Failed:
3272  case ESR_Returned:
3273  case ESR_CaseNotFound:
3274  return ESR;
3275  }
3276  llvm_unreachable("Invalid EvalStmtResult!");
3277 }
3278 
3279 /// Evaluate a switch statement.
3280 static EvalStmtResult EvaluateSwitch(APValue &Result, EvalInfo &Info,
3281  const SwitchStmt *SS) {
3282  BlockScopeRAII Scope(Info);
3283 
3284  // Evaluate the switch condition.
3285  APSInt Value;
3286  {
3287  FullExpressionRAII Scope(Info);
3288  if (SS->getConditionVariable() &&
3289  !EvaluateDecl(Info, SS->getConditionVariable()))
3290  return ESR_Failed;
3291  if (!EvaluateInteger(SS->getCond(), Value, Info))
3292  return ESR_Failed;
3293  }
3294 
3295  // Find the switch case corresponding to the value of the condition.
3296  // FIXME: Cache this lookup.
3297  const SwitchCase *Found = nullptr;
3298  for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3299  SC = SC->getNextSwitchCase()) {
3300  if (isa<DefaultStmt>(SC)) {
3301  Found = SC;
3302  continue;
3303  }
3304 
3305  const CaseStmt *CS = cast<CaseStmt>(SC);
3306  APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3307  APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3308  : LHS;
3309  if (LHS <= Value && Value <= RHS) {
3310  Found = SC;
3311  break;
3312  }
3313  }
3314 
3315  if (!Found)
3316  return ESR_Succeeded;
3317 
3318  // Search the switch body for the switch case and evaluate it from there.
3319  switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3320  case ESR_Break:
3321  return ESR_Succeeded;
3322  case ESR_Succeeded:
3323  case ESR_Continue:
3324  case ESR_Failed:
3325  case ESR_Returned:
3326  return ESR;
3327  case ESR_CaseNotFound:
3328  // This can only happen if the switch case is nested within a statement
3329  // expression. We have no intention of supporting that.
3330  Info.Diag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3331  return ESR_Failed;
3332  }
3333  llvm_unreachable("Invalid EvalStmtResult!");
3334 }
3335 
3336 // Evaluate a statement.
3337 static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
3338  const Stmt *S, const SwitchCase *Case) {
3339  if (!Info.nextStep(S))
3340  return ESR_Failed;
3341 
3342  // If we're hunting down a 'case' or 'default' label, recurse through
3343  // substatements until we hit the label.
3344  if (Case) {
3345  // FIXME: We don't start the lifetime of objects whose initialization we
3346  // jump over. However, such objects must be of class type with a trivial
3347  // default constructor that initialize all subobjects, so must be empty,
3348  // so this almost never matters.
3349  switch (S->getStmtClass()) {
3350  case Stmt::CompoundStmtClass:
3351  // FIXME: Precompute which substatement of a compound statement we
3352  // would jump to, and go straight there rather than performing a
3353  // linear scan each time.
3354  case Stmt::LabelStmtClass:
3355  case Stmt::AttributedStmtClass:
3356  case Stmt::DoStmtClass:
3357  break;
3358 
3359  case Stmt::CaseStmtClass:
3360  case Stmt::DefaultStmtClass:
3361  if (Case == S)
3362  Case = nullptr;
3363  break;
3364 
3365  case Stmt::IfStmtClass: {
3366  // FIXME: Precompute which side of an 'if' we would jump to, and go
3367  // straight there rather than scanning both sides.
3368  const IfStmt *IS = cast<IfStmt>(S);
3369 
3370  // Wrap the evaluation in a block scope, in case it's a DeclStmt
3371  // preceded by our switch label.
3372  BlockScopeRAII Scope(Info);
3373 
3374  EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3375  if (ESR != ESR_CaseNotFound || !IS->getElse())
3376  return ESR;
3377  return EvaluateStmt(Result, Info, IS->getElse(), Case);
3378  }
3379 
3380  case Stmt::WhileStmtClass: {
3381  EvalStmtResult ESR =
3382  EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3383  if (ESR != ESR_Continue)
3384  return ESR;
3385  break;
3386  }
3387 
3388  case Stmt::ForStmtClass: {
3389  const ForStmt *FS = cast<ForStmt>(S);
3390  EvalStmtResult ESR =
3391  EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3392  if (ESR != ESR_Continue)
3393  return ESR;
3394  if (FS->getInc()) {
3395  FullExpressionRAII IncScope(Info);
3396  if (!EvaluateIgnoredValue(Info, FS->getInc()))
3397  return ESR_Failed;
3398  }
3399  break;
3400  }
3401 
3402  case Stmt::DeclStmtClass:
3403  // FIXME: If the variable has initialization that can't be jumped over,
3404  // bail out of any immediately-surrounding compound-statement too.
3405  default:
3406  return ESR_CaseNotFound;
3407  }
3408  }
3409 
3410  switch (S->getStmtClass()) {
3411  default:
3412  if (const Expr *E = dyn_cast<Expr>(S)) {
3413  // Don't bother evaluating beyond an expression-statement which couldn't
3414  // be evaluated.
3415  FullExpressionRAII Scope(Info);
3416  if (!EvaluateIgnoredValue(Info, E))
3417  return ESR_Failed;
3418  return ESR_Succeeded;
3419  }
3420 
3421  Info.Diag(S->getLocStart());
3422  return ESR_Failed;
3423 
3424  case Stmt::NullStmtClass:
3425  return ESR_Succeeded;
3426 
3427  case Stmt::DeclStmtClass: {
3428  const DeclStmt *DS = cast<DeclStmt>(S);
3429  for (const auto *DclIt : DS->decls()) {
3430  // Each declaration initialization is its own full-expression.
3431  // FIXME: This isn't quite right; if we're performing aggregate
3432  // initialization, each braced subexpression is its own full-expression.
3433  FullExpressionRAII Scope(Info);
3434  if (!EvaluateDecl(Info, DclIt) && !Info.keepEvaluatingAfterFailure())
3435  return ESR_Failed;
3436  }
3437  return ESR_Succeeded;
3438  }
3439 
3440  case Stmt::ReturnStmtClass: {
3441  const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
3442  FullExpressionRAII Scope(Info);
3443  if (RetExpr && !Evaluate(Result, Info, RetExpr))
3444  return ESR_Failed;
3445  return ESR_Returned;
3446  }
3447 
3448  case Stmt::CompoundStmtClass: {
3449  BlockScopeRAII Scope(Info);
3450 
3451  const CompoundStmt *CS = cast<CompoundStmt>(S);
3452  for (const auto *BI : CS->body()) {
3453  EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
3454  if (ESR == ESR_Succeeded)
3455  Case = nullptr;
3456  else if (ESR != ESR_CaseNotFound)
3457  return ESR;
3458  }
3459  return Case ? ESR_CaseNotFound : ESR_Succeeded;
3460  }
3461 
3462  case Stmt::IfStmtClass: {
3463  const IfStmt *IS = cast<IfStmt>(S);
3464 
3465  // Evaluate the condition, as either a var decl or as an expression.
3466  BlockScopeRAII Scope(Info);
3467  bool Cond;
3468  if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
3469  return ESR_Failed;
3470 
3471  if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3472  EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3473  if (ESR != ESR_Succeeded)
3474  return ESR;
3475  }
3476  return ESR_Succeeded;
3477  }
3478 
3479  case Stmt::WhileStmtClass: {
3480  const WhileStmt *WS = cast<WhileStmt>(S);
3481  while (true) {
3482  BlockScopeRAII Scope(Info);
3483  bool Continue;
3484  if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3485  Continue))
3486  return ESR_Failed;
3487  if (!Continue)
3488  break;
3489 
3490  EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3491  if (ESR != ESR_Continue)
3492  return ESR;
3493  }
3494  return ESR_Succeeded;
3495  }
3496 
3497  case Stmt::DoStmtClass: {
3498  const DoStmt *DS = cast<DoStmt>(S);
3499  bool Continue;
3500  do {
3501  EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
3502  if (ESR != ESR_Continue)
3503  return ESR;
3504  Case = nullptr;
3505 
3506  FullExpressionRAII CondScope(Info);
3507  if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3508  return ESR_Failed;
3509  } while (Continue);
3510  return ESR_Succeeded;
3511  }
3512 
3513  case Stmt::ForStmtClass: {
3514  const ForStmt *FS = cast<ForStmt>(S);
3515  BlockScopeRAII Scope(Info);
3516  if (FS->getInit()) {
3517  EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3518  if (ESR != ESR_Succeeded)
3519  return ESR;
3520  }
3521  while (true) {
3522  BlockScopeRAII Scope(Info);
3523  bool Continue = true;
3524  if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3525  FS->getCond(), Continue))
3526  return ESR_Failed;
3527  if (!Continue)
3528  break;
3529 
3530  EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3531  if (ESR != ESR_Continue)
3532  return ESR;
3533 
3534  if (FS->getInc()) {
3535  FullExpressionRAII IncScope(Info);
3536  if (!EvaluateIgnoredValue(Info, FS->getInc()))
3537  return ESR_Failed;
3538  }
3539  }
3540  return ESR_Succeeded;
3541  }
3542 
3543  case Stmt::CXXForRangeStmtClass: {
3544  const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
3545  BlockScopeRAII Scope(Info);
3546 
3547  // Initialize the __range variable.
3548  EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3549  if (ESR != ESR_Succeeded)
3550  return ESR;
3551 
3552  // Create the __begin and __end iterators.
3553  ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
3554  if (ESR != ESR_Succeeded)
3555  return ESR;
3556 
3557  while (true) {
3558  // Condition: __begin != __end.
3559  {
3560  bool Continue = true;
3561  FullExpressionRAII CondExpr(Info);
3562  if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3563  return ESR_Failed;
3564  if (!Continue)
3565  break;
3566  }
3567 
3568  // User's variable declaration, initialized by *__begin.
3569  BlockScopeRAII InnerScope(Info);
3570  ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3571  if (ESR != ESR_Succeeded)
3572  return ESR;
3573 
3574  // Loop body.
3575  ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3576  if (ESR != ESR_Continue)
3577  return ESR;
3578 
3579  // Increment: ++__begin
3580  if (!EvaluateIgnoredValue(Info, FS->getInc()))
3581  return ESR_Failed;
3582  }
3583 
3584  return ESR_Succeeded;
3585  }
3586 
3587  case Stmt::SwitchStmtClass:
3588  return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3589 
3590  case Stmt::ContinueStmtClass:
3591  return ESR_Continue;
3592 
3593  case Stmt::BreakStmtClass:
3594  return ESR_Break;
3595 
3596  case Stmt::LabelStmtClass:
3597  return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3598 
3599  case Stmt::AttributedStmtClass:
3600  // As a general principle, C++11 attributes can be ignored without
3601  // any semantic impact.
3602  return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3603  Case);
3604 
3605  case Stmt::CaseStmtClass:
3606  case Stmt::DefaultStmtClass:
3607  return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
3608  }
3609 }
3610 
3611 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3612 /// default constructor. If so, we'll fold it whether or not it's marked as
3613 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
3614 /// so we need special handling.
3615 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
3616  const CXXConstructorDecl *CD,
3617  bool IsValueInitialization) {
3618  if (!CD->isTrivial() || !CD->isDefaultConstructor())
3619  return false;
3620 
3621  // Value-initialization does not call a trivial default constructor, so such a
3622  // call is a core constant expression whether or not the constructor is
3623  // constexpr.
3624  if (!CD->isConstexpr() && !IsValueInitialization) {
3625  if (Info.getLangOpts().CPlusPlus11) {
3626  // FIXME: If DiagDecl is an implicitly-declared special member function,
3627  // we should be much more explicit about why it's not constexpr.
3628  Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3629  << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3630  Info.Note(CD->getLocation(), diag::note_declared_at);
3631  } else {
3632  Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3633  }
3634  }
3635  return true;
3636 }
3637 
3638 /// CheckConstexprFunction - Check that a function can be called in a constant
3639 /// expression.
3640 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3641  const FunctionDecl *Declaration,
3642  const FunctionDecl *Definition) {
3643  // Potential constant expressions can contain calls to declared, but not yet
3644  // defined, constexpr functions.
3645  if (Info.checkingPotentialConstantExpression() && !Definition &&
3646  Declaration->isConstexpr())
3647  return false;
3648 
3649  // Bail out with no diagnostic if the function declaration itself is invalid.
3650  // We will have produced a relevant diagnostic while parsing it.
3651  if (Declaration->isInvalidDecl())
3652  return false;
3653 
3654  // Can we evaluate this function call?
3655  if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
3656  return true;
3657 
3658  if (Info.getLangOpts().CPlusPlus11) {
3659  const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
3660  // FIXME: If DiagDecl is an implicitly-declared special member function, we
3661  // should be much more explicit about why it's not constexpr.
3662  Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
3663  << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
3664  << DiagDecl;
3665  Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3666  } else {
3667  Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3668  }
3669  return false;
3670 }
3671 
3672 /// Determine if a class has any fields that might need to be copied by a
3673 /// trivial copy or move operation.
3674 static bool hasFields(const CXXRecordDecl *RD) {
3675  if (!RD || RD->isEmpty())
3676  return false;
3677  for (auto *FD : RD->fields()) {
3678  if (FD->isUnnamedBitfield())
3679  continue;
3680  return true;
3681  }
3682  for (auto &Base : RD->bases())
3683  if (hasFields(Base.getType()->getAsCXXRecordDecl()))
3684  return true;
3685  return false;
3686 }
3687 
3688 namespace {
3689 typedef SmallVector<APValue, 8> ArgVector;
3690 }
3691 
3692 /// EvaluateArgs - Evaluate the arguments to a function call.
3693 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3694  EvalInfo &Info) {
3695  bool Success = true;
3696  for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
3697  I != E; ++I) {
3698  if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3699  // If we're checking for a potential constant expression, evaluate all
3700  // initializers even if some of them fail.
3701  if (!Info.keepEvaluatingAfterFailure())
3702  return false;
3703  Success = false;
3704  }
3705  }
3706  return Success;
3707 }
3708 
3709 /// Evaluate a function call.
3711  const FunctionDecl *Callee, const LValue *This,
3712  ArrayRef<const Expr*> Args, const Stmt *Body,
3713  EvalInfo &Info, APValue &Result) {
3714  ArgVector ArgValues(Args.size());
3715  if (!EvaluateArgs(Args, ArgValues, Info))
3716  return false;
3717 
3718  if (!Info.CheckCallLimit(CallLoc))
3719  return false;
3720 
3721  CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
3722 
3723  // For a trivial copy or move assignment, perform an APValue copy. This is
3724  // essential for unions, where the operations performed by the assignment
3725  // operator cannot be represented as statements.
3726  //
3727  // Skip this for non-union classes with no fields; in that case, the defaulted
3728  // copy/move does not actually read the object.
3729  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
3730  if (MD && MD->isDefaulted() &&
3731  (MD->getParent()->isUnion() ||
3732  (MD->isTrivial() && hasFields(MD->getParent())))) {
3733  assert(This &&
3734  (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3735  LValue RHS;
3736  RHS.setFrom(Info.Ctx, ArgValues[0]);
3737  APValue RHSValue;
3738  if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3739  RHS, RHSValue))
3740  return false;
3741  if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3742  RHSValue))
3743  return false;
3744  This->moveInto(Result);
3745  return true;
3746  }
3747 
3748  EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
3749  if (ESR == ESR_Succeeded) {
3750  if (Callee->getReturnType()->isVoidType())
3751  return true;
3752  Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
3753  }
3754  return ESR == ESR_Returned;
3755 }
3756 
3757 /// Evaluate a constructor call.
3758 static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
3759  ArrayRef<const Expr*> Args,
3760  const CXXConstructorDecl *Definition,
3761  EvalInfo &Info, APValue &Result) {
3762  ArgVector ArgValues(Args.size());
3763  if (!EvaluateArgs(Args, ArgValues, Info))
3764  return false;
3765 
3766  if (!Info.CheckCallLimit(CallLoc))
3767  return false;
3768 
3769  const CXXRecordDecl *RD = Definition->getParent();
3770  if (RD->getNumVBases()) {
3771  Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3772  return false;
3773  }
3774 
3775  CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
3776 
3777  // If it's a delegating constructor, just delegate.
3778  if (Definition->isDelegatingConstructor()) {
3780  {
3781  FullExpressionRAII InitScope(Info);
3782  if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3783  return false;
3784  }
3785  return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
3786  }
3787 
3788  // For a trivial copy or move constructor, perform an APValue copy. This is
3789  // essential for unions (or classes with anonymous union members), where the
3790  // operations performed by the constructor cannot be represented by
3791  // ctor-initializers.
3792  //
3793  // Skip this for empty non-union classes; we should not perform an
3794  // lvalue-to-rvalue conversion on them because their copy constructor does not
3795  // actually read them.
3796  if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
3797  (Definition->getParent()->isUnion() ||
3798  (Definition->isTrivial() && hasFields(Definition->getParent())))) {
3799  LValue RHS;
3800  RHS.setFrom(Info.Ctx, ArgValues[0]);
3801  return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3802  RHS, Result);
3803  }
3804 
3805  // Reserve space for the struct members.
3806  if (!RD->isUnion() && Result.isUninit())
3807  Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3808  std::distance(RD->field_begin(), RD->field_end()));
3809 
3810  if (RD->isInvalidDecl()) return false;
3811  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3812 
3813  // A scope for temporaries lifetime-extended by reference members.
3814  BlockScopeRAII LifetimeExtendedScope(Info);
3815 
3816  bool Success = true;
3817  unsigned BasesSeen = 0;
3818 #ifndef NDEBUG
3820 #endif
3821  for (const auto *I : Definition->inits()) {
3822  LValue Subobject = This;
3823  APValue *Value = &Result;
3824 
3825  // Determine the subobject to initialize.
3826  FieldDecl *FD = nullptr;
3827  if (I->isBaseInitializer()) {
3828  QualType BaseType(I->getBaseClass(), 0);
3829 #ifndef NDEBUG
3830  // Non-virtual base classes are initialized in the order in the class
3831  // definition. We have already checked for virtual base classes.
3832  assert(!BaseIt->isVirtual() && "virtual base for literal type");
3833  assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
3834  "base class initializers not in expected order");
3835  ++BaseIt;
3836 #endif
3837  if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
3838  BaseType->getAsCXXRecordDecl(), &Layout))
3839  return false;
3840  Value = &Result.getStructBase(BasesSeen++);
3841  } else if ((FD = I->getMember())) {
3842  if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
3843  return false;
3844  if (RD->isUnion()) {
3845  Result = APValue(FD);
3846  Value = &Result.getUnionValue();
3847  } else {
3848  Value = &Result.getStructField(FD->getFieldIndex());
3849  }
3850  } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
3851  // Walk the indirect field decl's chain to find the object to initialize,
3852  // and make sure we've initialized every step along it.
3853  for (auto *C : IFD->chain()) {
3854  FD = cast<FieldDecl>(C);
3855  CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
3856  // Switch the union field if it differs. This happens if we had
3857  // preceding zero-initialization, and we're now initializing a union
3858  // subobject other than the first.
3859  // FIXME: In this case, the values of the other subobjects are
3860  // specified, since zero-initialization sets all padding bits to zero.
3861  if (Value->isUninit() ||
3862  (Value->isUnion() && Value->getUnionField() != FD)) {
3863  if (CD->isUnion())
3864  *Value = APValue(FD);
3865  else
3866  *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
3867  std::distance(CD->field_begin(), CD->field_end()));
3868  }
3869  if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
3870  return false;
3871  if (CD->isUnion())
3872  Value = &Value->getUnionValue();
3873  else
3874  Value = &Value->getStructField(FD->getFieldIndex());
3875  }
3876  } else {
3877  llvm_unreachable("unknown base initializer kind");
3878  }
3879 
3880  FullExpressionRAII InitScope(Info);
3881  if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
3882  (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
3883  *Value, FD))) {
3884  // If we're checking for a potential constant expression, evaluate all
3885  // initializers even if some of them fail.
3886  if (!Info.keepEvaluatingAfterFailure())
3887  return false;
3888  Success = false;
3889  }
3890  }
3891 
3892  return Success &&
3893  EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
3894 }
3895 
3896 //===----------------------------------------------------------------------===//
3897 // Generic Evaluation
3898 //===----------------------------------------------------------------------===//
3899 namespace {
3900 
3901 template <class Derived>
3902 class ExprEvaluatorBase
3903  : public ConstStmtVisitor<Derived, bool> {
3904 private:
3905  bool DerivedSuccess(const APValue &V, const Expr *E) {
3906  return static_cast<Derived*>(this)->Success(V, E);
3907  }
3908  bool DerivedZeroInitialization(const Expr *E) {
3909  return static_cast<Derived*>(this)->ZeroInitialization(E);
3910  }
3911 
3912  // Check whether a conditional operator with a non-constant condition is a
3913  // potential constant expression. If neither arm is a potential constant
3914  // expression, then the conditional operator is not either.
3915  template<typename ConditionalOperator>
3916  void CheckPotentialConstantConditional(const ConditionalOperator *E) {
3917  assert(Info.checkingPotentialConstantExpression());
3918 
3919  // Speculatively evaluate both arms.
3920  {
3922  SpeculativeEvaluationRAII Speculate(Info, &Diag);
3923 
3924  StmtVisitorTy::Visit(E->getFalseExpr());
3925  if (Diag.empty())
3926  return;
3927 
3928  Diag.clear();
3929  StmtVisitorTy::Visit(E->getTrueExpr());
3930  if (Diag.empty())
3931  return;
3932  }
3933 
3934  Error(E, diag::note_constexpr_conditional_never_const);
3935  }
3936 
3937 
3938  template<typename ConditionalOperator>
3939  bool HandleConditionalOperator(const ConditionalOperator *E) {
3940  bool BoolResult;
3941  if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
3942  if (Info.checkingPotentialConstantExpression())
3943  CheckPotentialConstantConditional(E);
3944  return false;
3945  }
3946 
3947  Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
3948  return StmtVisitorTy::Visit(EvalExpr);
3949  }
3950 
3951 protected:
3952  EvalInfo &Info;
3953  typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
3954  typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
3955 
3956  OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
3957  return Info.CCEDiag(E, D);
3958  }
3959 
3960  bool ZeroInitialization(const Expr *E) { return Error(E); }
3961 
3962 public:
3963  ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
3964 
3965  EvalInfo &getEvalInfo() { return Info; }
3966 
3967  /// Report an evaluation error. This should only be called when an error is
3968  /// first discovered. When propagating an error, just return false.
3969  bool Error(const Expr *E, diag::kind D) {
3970  Info.Diag(E, D);
3971  return false;
3972  }
3973  bool Error(const Expr *E) {
3974  return Error(E, diag::note_invalid_subexpr_in_const_expr);
3975  }
3976 
3977  bool VisitStmt(const Stmt *) {
3978  llvm_unreachable("Expression evaluator should not be called on stmts");
3979  }
3980  bool VisitExpr(const Expr *E) {
3981  return Error(E);
3982  }
3983 
3984  bool VisitParenExpr(const ParenExpr *E)
3985  { return StmtVisitorTy::Visit(E->getSubExpr()); }
3986  bool VisitUnaryExtension(const UnaryOperator *E)
3987  { return StmtVisitorTy::Visit(E->getSubExpr()); }
3988  bool VisitUnaryPlus(const UnaryOperator *E)
3989  { return StmtVisitorTy::Visit(E->getSubExpr()); }
3990  bool VisitChooseExpr(const ChooseExpr *E)
3991  { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
3992  bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
3993  { return StmtVisitorTy::Visit(E->getResultExpr()); }
3994  bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
3995  { return StmtVisitorTy::Visit(E->getReplacement()); }
3996  bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
3997  { return StmtVisitorTy::Visit(E->getExpr()); }
3998  bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
3999  // The initializer may not have been parsed yet, or might be erroneous.
4000  if (!E->getExpr())
4001  return Error(E);
4002  return StmtVisitorTy::Visit(E->getExpr());
4003  }
4004  // We cannot create any objects for which cleanups are required, so there is
4005  // nothing to do here; all cleanups must come from unevaluated subexpressions.
4006  bool VisitExprWithCleanups(const ExprWithCleanups *E)
4007  { return StmtVisitorTy::Visit(E->getSubExpr()); }
4008 
4009  bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
4010  CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4011  return static_cast<Derived*>(this)->VisitCastExpr(E);
4012  }
4013  bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
4014  CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4015  return static_cast<Derived*>(this)->VisitCastExpr(E);
4016  }
4017 
4018  bool VisitBinaryOperator(const BinaryOperator *E) {
4019  switch (E->getOpcode()) {
4020  default:
4021  return Error(E);
4022 
4023  case BO_Comma:
4024  VisitIgnoredValue(E->getLHS());
4025  return StmtVisitorTy::Visit(E->getRHS());
4026 
4027  case BO_PtrMemD:
4028  case BO_PtrMemI: {
4029  LValue Obj;
4030  if (!HandleMemberPointerAccess(Info, E, Obj))
4031  return false;
4032  APValue Result;
4033  if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
4034  return false;
4035  return DerivedSuccess(Result, E);
4036  }
4037  }
4038  }
4039 
4040  bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
4041  // Evaluate and cache the common expression. We treat it as a temporary,
4042  // even though it's not quite the same thing.
4043  if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
4044  Info, E->getCommon()))
4045  return false;
4046 
4047  return HandleConditionalOperator(E);
4048  }
4049 
4050  bool VisitConditionalOperator(const ConditionalOperator *E) {
4051  bool IsBcpCall = false;
4052  // If the condition (ignoring parens) is a __builtin_constant_p call,
4053  // the result is a constant expression if it can be folded without
4054  // side-effects. This is an important GNU extension. See GCC PR38377
4055  // for discussion.
4056  if (const CallExpr *CallCE =
4057  dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
4058  if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
4059  IsBcpCall = true;
4060 
4061  // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4062  // constant expression; we can't check whether it's potentially foldable.
4063  if (Info.checkingPotentialConstantExpression() && IsBcpCall)
4064  return false;
4065 
4066  FoldConstant Fold(Info, IsBcpCall);
4067  if (!HandleConditionalOperator(E)) {
4068  Fold.keepDiagnostics();
4069  return false;
4070  }
4071 
4072  return true;
4073  }
4074 
4075  bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
4076  if (APValue *Value = Info.CurrentCall->getTemporary(E))
4077  return DerivedSuccess(*Value, E);
4078 
4079  const Expr *Source = E->getSourceExpr();
4080  if (!Source)
4081  return Error(E);
4082  if (Source == E) { // sanity checking.
4083  assert(0 && "OpaqueValueExpr recursively refers to itself");
4084  return Error(E);
4085  }
4086  return StmtVisitorTy::Visit(Source);
4087  }
4088 
4089  bool VisitCallExpr(const CallExpr *E) {
4090  const Expr *Callee = E->getCallee()->IgnoreParens();
4091  QualType CalleeType = Callee->getType();
4092 
4093  const FunctionDecl *FD = nullptr;
4094  LValue *This = nullptr, ThisVal;
4095  auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
4096  bool HasQualifier = false;
4097 
4098  // Extract function decl and 'this' pointer from the callee.
4099  if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
4100  const ValueDecl *Member = nullptr;
4101  if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4102  // Explicit bound member calls, such as x.f() or p->g();
4103  if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
4104  return false;
4105  Member = ME->getMemberDecl();
4106  This = &ThisVal;
4107  HasQualifier = ME->hasQualifier();
4108  } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4109  // Indirect bound member calls ('.*' or '->*').
4110  Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4111  if (!Member) return false;
4112  This = &ThisVal;
4113  } else
4114  return Error(Callee);
4115 
4116  FD = dyn_cast<FunctionDecl>(Member);
4117  if (!FD)
4118  return Error(Callee);
4119  } else if (CalleeType->isFunctionPointerType()) {
4120  LValue Call;
4121  if (!EvaluatePointer(Callee, Call, Info))
4122  return false;
4123 
4124  if (!Call.getLValueOffset().isZero())
4125  return Error(Callee);
4126  FD = dyn_cast_or_null<FunctionDecl>(
4127  Call.getLValueBase().dyn_cast<const ValueDecl*>());
4128  if (!FD)
4129  return Error(Callee);
4130 
4131  // Overloaded operator calls to member functions are represented as normal
4132  // calls with '*this' as the first argument.
4133  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4134  if (MD && !MD->isStatic()) {
4135  // FIXME: When selecting an implicit conversion for an overloaded
4136  // operator delete, we sometimes try to evaluate calls to conversion
4137  // operators without a 'this' parameter!
4138  if (Args.empty())
4139  return Error(E);
4140 
4141  if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4142  return false;
4143  This = &ThisVal;
4144  Args = Args.slice(1);
4145  }
4146 
4147  // Don't call function pointers which have been cast to some other type.
4148  if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
4149  return Error(E);
4150  } else
4151  return Error(E);
4152 
4153  if (This && !This->checkSubobject(Info, E, CSK_This))
4154  return false;
4155 
4156  // DR1358 allows virtual constexpr functions in some cases. Don't allow
4157  // calls to such functions in constant expressions.
4158  if (This && !HasQualifier &&
4159  isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4160  return Error(E, diag::note_constexpr_virtual_call);
4161 
4162  const FunctionDecl *Definition = nullptr;
4163  Stmt *Body = FD->getBody(Definition);
4164  APValue Result;
4165 
4166  if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
4167  !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
4168  Info, Result))
4169  return false;
4170 
4171  return DerivedSuccess(Result, E);
4172  }
4173 
4174  bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
4175  return StmtVisitorTy::Visit(E->getInitializer());
4176  }
4177  bool VisitInitListExpr(const InitListExpr *E) {
4178  if (E->getNumInits() == 0)
4179  return DerivedZeroInitialization(E);
4180  if (E->getNumInits() == 1)
4181  return StmtVisitorTy::Visit(E->getInit(0));
4182  return Error(E);
4183  }
4184  bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
4185  return DerivedZeroInitialization(E);
4186  }
4187  bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
4188  return DerivedZeroInitialization(E);
4189  }
4190  bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
4191  return DerivedZeroInitialization(E);
4192  }
4193 
4194  /// A member expression where the object is a prvalue is itself a prvalue.
4195  bool VisitMemberExpr(const MemberExpr *E) {
4196  assert(!E->isArrow() && "missing call to bound member function?");
4197 
4198  APValue Val;
4199  if (!Evaluate(Val, Info, E->getBase()))
4200  return false;
4201 
4202  QualType BaseTy = E->getBase()->getType();
4203 
4204  const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
4205  if (!FD) return Error(E);
4206  assert(!FD->getType()->isReferenceType() && "prvalue reference?");
4207  assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4208  FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4209 
4210  CompleteObject Obj(&Val, BaseTy);
4211  SubobjectDesignator Designator(BaseTy);
4212  Designator.addDeclUnchecked(FD);
4213 
4214  APValue Result;
4215  return extractSubobject(Info, E, Obj, Designator, Result) &&
4216  DerivedSuccess(Result, E);
4217  }
4218 
4219  bool VisitCastExpr(const CastExpr *E) {
4220  switch (E->getCastKind()) {
4221  default:
4222  break;
4223 
4224  case CK_AtomicToNonAtomic: {
4225  APValue AtomicVal;
4226  if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4227  return false;
4228  return DerivedSuccess(AtomicVal, E);
4229  }
4230 
4231  case CK_NoOp:
4233  return StmtVisitorTy::Visit(E->getSubExpr());
4234 
4235  case CK_LValueToRValue: {
4236  LValue LVal;
4237  if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4238  return false;
4239  APValue RVal;
4240  // Note, we use the subexpression's type in order to retain cv-qualifiers.
4241  if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
4242  LVal, RVal))
4243  return false;
4244  return DerivedSuccess(RVal, E);
4245  }
4246  }
4247 
4248  return Error(E);
4249  }
4250 
4251  bool VisitUnaryPostInc(const UnaryOperator *UO) {
4252  return VisitUnaryPostIncDec(UO);
4253  }
4254  bool VisitUnaryPostDec(const UnaryOperator *UO) {
4255  return VisitUnaryPostIncDec(UO);
4256  }
4257  bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
4258  if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
4259  return Error(UO);
4260 
4261  LValue LVal;
4262  if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4263  return false;
4264  APValue RVal;
4265  if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4266  UO->isIncrementOp(), &RVal))
4267  return false;
4268  return DerivedSuccess(RVal, UO);
4269  }
4270 
4271  bool VisitStmtExpr(const StmtExpr *E) {
4272  // We will have checked the full-expressions inside the statement expression
4273  // when they were completed, and don't need to check them again now.
4274  if (Info.checkingForOverflow())
4275  return Error(E);
4276 
4277  BlockScopeRAII Scope(Info);
4278  const CompoundStmt *CS = E->getSubStmt();
4279  if (CS->body_empty())
4280  return true;
4281 
4283  BE = CS->body_end();
4284  /**/; ++BI) {
4285  if (BI + 1 == BE) {
4286  const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4287  if (!FinalExpr) {
4288  Info.Diag((*BI)->getLocStart(),
4289  diag::note_constexpr_stmt_expr_unsupported);
4290  return false;
4291  }
4292  return this->Visit(FinalExpr);
4293  }
4294 
4295  APValue ReturnValue;
4296  EvalStmtResult ESR = EvaluateStmt(ReturnValue, Info, *BI);
4297  if (ESR != ESR_Succeeded) {
4298  // FIXME: If the statement-expression terminated due to 'return',
4299  // 'break', or 'continue', it would be nice to propagate that to
4300  // the outer statement evaluation rather than bailing out.
4301  if (ESR != ESR_Failed)
4302  Info.Diag((*BI)->getLocStart(),
4303  diag::note_constexpr_stmt_expr_unsupported);
4304  return false;
4305  }
4306  }
4307 
4308  llvm_unreachable("Return from function from the loop above.");
4309  }
4310 
4311  /// Visit a value which is evaluated, but whose value is ignored.
4312  void VisitIgnoredValue(const Expr *E) {
4313  EvaluateIgnoredValue(Info, E);
4314  }
4315 };
4316 
4317 }
4318 
4319 //===----------------------------------------------------------------------===//
4320 // Common base class for lvalue and temporary evaluation.
4321 //===----------------------------------------------------------------------===//
4322 namespace {
4323 template<class Derived>
4324 class LValueExprEvaluatorBase
4325  : public ExprEvaluatorBase<Derived> {
4326 protected:
4327  LValue &Result;
4328  typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
4329  typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
4330 
4331  bool Success(APValue::LValueBase B) {
4332  Result.set(B);
4333  return true;
4334  }
4335 
4336 public:
4337  LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4338  ExprEvaluatorBaseTy(Info), Result(Result) {}
4339 
4340  bool Success(const APValue &V, const Expr *E) {
4341  Result.setFrom(this->Info.Ctx, V);
4342  return true;
4343  }
4344 
4345  bool VisitMemberExpr(const MemberExpr *E) {
4346  // Handle non-static data members.
4347  QualType BaseTy;
4348  if (E->isArrow()) {
4349  if (!EvaluatePointer(E->getBase(), Result, this->Info))
4350  return false;
4351  BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
4352  } else if (E->getBase()->isRValue()) {
4353  assert(E->getBase()->getType()->isRecordType());
4354  if (!EvaluateTemporary(E->getBase(), Result, this->Info))
4355  return false;
4356  BaseTy = E->getBase()->getType();
4357  } else {
4358  if (!this->Visit(E->getBase()))
4359  return false;
4360  BaseTy = E->getBase()->getType();
4361  }
4362 
4363  const ValueDecl *MD = E->getMemberDecl();
4364  if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4365  assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4366  FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4367  (void)BaseTy;
4368  if (!HandleLValueMember(this->Info, E, Result, FD))
4369  return false;
4370  } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
4371  if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4372  return false;
4373  } else
4374  return this->Error(E);
4375 
4376  if (MD->getType()->isReferenceType()) {
4377  APValue RefValue;
4378  if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
4379  RefValue))
4380  return false;
4381  return Success(RefValue, E);
4382  }
4383  return true;
4384  }
4385 
4386  bool VisitBinaryOperator(const BinaryOperator *E) {
4387  switch (E->getOpcode()) {
4388  default:
4389  return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4390 
4391  case BO_PtrMemD:
4392  case BO_PtrMemI:
4393  return HandleMemberPointerAccess(this->Info, E, Result);
4394  }
4395  }
4396 
4397  bool VisitCastExpr(const CastExpr *E) {
4398  switch (E->getCastKind()) {
4399  default:
4400  return ExprEvaluatorBaseTy::VisitCastExpr(E);
4401 
4402  case CK_DerivedToBase:
4404  if (!this->Visit(E->getSubExpr()))
4405  return false;
4406 
4407  // Now figure out the necessary offset to add to the base LV to get from
4408  // the derived class to the base class.
4409  return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4410  Result);
4411  }
4412  }
4413 };
4414 }
4415 
4416 //===----------------------------------------------------------------------===//
4417 // LValue Evaluation
4418 //
4419 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4420 // function designators (in C), decl references to void objects (in C), and
4421 // temporaries (if building with -Wno-address-of-temporary).
4422 //
4423 // LValue evaluation produces values comprising a base expression of one of the
4424 // following types:
4425 // - Declarations
4426 // * VarDecl
4427 // * FunctionDecl
4428 // - Literals
4429 // * CompoundLiteralExpr in C
4430 // * StringLiteral
4431 // * CXXTypeidExpr
4432 // * PredefinedExpr
4433 // * ObjCStringLiteralExpr
4434 // * ObjCEncodeExpr
4435 // * AddrLabelExpr
4436 // * BlockExpr
4437 // * CallExpr for a MakeStringConstant builtin
4438 // - Locals and temporaries
4439 // * MaterializeTemporaryExpr
4440 // * Any Expr, with a CallIndex indicating the function in which the temporary
4441 // was evaluated, for cases where the MaterializeTemporaryExpr is missing
4442 // from the AST (FIXME).
4443 // * A MaterializeTemporaryExpr that has static storage duration, with no
4444 // CallIndex, for a lifetime-extended temporary.
4445 // plus an offset in bytes.
4446 //===----------------------------------------------------------------------===//
4447 namespace {
4448 class LValueExprEvaluator
4449  : public LValueExprEvaluatorBase<LValueExprEvaluator> {
4450 public:
4451  LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4452  LValueExprEvaluatorBaseTy(Info, Result) {}
4453 
4454  bool VisitVarDecl(const Expr *E, const VarDecl *VD);
4455  bool VisitUnaryPreIncDec(const UnaryOperator *UO);
4456 
4457  bool VisitDeclRefExpr(const DeclRefExpr *E);
4458  bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
4459  bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
4460  bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4461  bool VisitMemberExpr(const MemberExpr *E);
4462  bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4463  bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
4464  bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
4465  bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
4466  bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4467  bool VisitUnaryDeref(const UnaryOperator *E);
4468  bool VisitUnaryReal(const UnaryOperator *E);
4469  bool VisitUnaryImag(const UnaryOperator *E);
4470  bool VisitUnaryPreInc(const UnaryOperator *UO) {
4471  return VisitUnaryPreIncDec(UO);
4472  }
4473  bool VisitUnaryPreDec(const UnaryOperator *UO) {
4474  return VisitUnaryPreIncDec(UO);
4475  }
4476  bool VisitBinAssign(const BinaryOperator *BO);
4477  bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
4478 
4479  bool VisitCastExpr(const CastExpr *E) {
4480  switch (E->getCastKind()) {
4481  default:
4482  return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
4483 
4484  case CK_LValueBitCast:
4485  this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4486  if (!Visit(E->getSubExpr()))
4487  return false;
4488  Result.Designator.setInvalid();
4489  return true;
4490 
4491  case CK_BaseToDerived:
4492  if (!Visit(E->getSubExpr()))
4493  return false;
4494  return HandleBaseToDerivedCast(Info, E, Result);
4495  }
4496  }
4497 };
4498 } // end anonymous namespace
4499 
4500 /// Evaluate an expression as an lvalue. This can be legitimately called on
4501 /// expressions which are not glvalues, in two cases:
4502 /// * function designators in C, and
4503 /// * "extern void" objects
4504 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4505  assert(E->isGLValue() || E->getType()->isFunctionType() ||
4506  E->getType()->isVoidType());
4507  return LValueExprEvaluator(Info, Result).Visit(E);
4508 }
4509 
4510 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
4511  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
4512  return Success(FD);
4513  if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
4514  return VisitVarDecl(E, VD);
4515  return Error(E);
4516 }
4517 
4518 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
4519  CallStackFrame *Frame = nullptr;
4520  if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
4521  Frame = Info.CurrentCall;
4522 
4523  if (!VD->getType()->isReferenceType()) {
4524  if (Frame) {
4525  Result.set(VD, Frame->Index);
4526  return true;
4527  }
4528  return Success(VD);
4529  }
4530 
4531  APValue *V;
4532  if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
4533  return false;
4534  if (V->isUninit()) {
4535  if (!Info.checkingPotentialConstantExpression())
4536  Info.Diag(E, diag::note_constexpr_use_uninit_reference);
4537  return false;
4538  }
4539  return Success(*V, E);
4540 }
4541 
4542 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4543  const MaterializeTemporaryExpr *E) {
4544  // Walk through the expression to find the materialized temporary itself.
4545  SmallVector<const Expr *, 2> CommaLHSs;
4547  const Expr *Inner = E->GetTemporaryExpr()->
4548  skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
4549 
4550  // If we passed any comma operators, evaluate their LHSs.
4551  for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4552  if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4553  return false;
4554 
4555  // A materialized temporary with static storage duration can appear within the
4556  // result of a constant expression evaluation, so we need to preserve its
4557  // value for use outside this evaluation.
4558  APValue *Value;
4559  if (E->getStorageDuration() == SD_Static) {
4560  Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
4561  *Value = APValue();
4562  Result.set(E);
4563  } else {
4564  Value = &Info.CurrentCall->
4565  createTemporary(E, E->getStorageDuration() == SD_Automatic);
4566  Result.set(E, Info.CurrentCall->Index);
4567  }
4568 
4569  QualType Type = Inner->getType();
4570 
4571  // Materialize the temporary itself.
4572  if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4573  (E->getStorageDuration() == SD_Static &&
4574  !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4575  *Value = APValue();
4576  return false;
4577  }
4578 
4579  // Adjust our lvalue to refer to the desired subobject.
4580  for (unsigned I = Adjustments.size(); I != 0; /**/) {
4581  --I;
4582  switch (Adjustments[I].Kind) {
4583  case SubobjectAdjustment::DerivedToBaseAdjustment:
4584  if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4585  Type, Result))
4586  return false;
4587  Type = Adjustments[I].DerivedToBase.BasePath->getType();
4588  break;
4589 
4590  case SubobjectAdjustment::FieldAdjustment:
4591  if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4592  return false;
4593  Type = Adjustments[I].Field->getType();
4594  break;
4595 
4596  case SubobjectAdjustment::MemberPointerAdjustment:
4597  if (!HandleMemberPointerAccess(this->Info, Type, Result,
4598  Adjustments[I].Ptr.RHS))
4599  return false;
4600  Type = Adjustments[I].Ptr.MPT->getPointeeType();
4601  break;
4602  }
4603  }
4604 
4605  return true;
4606 }
4607 
4608 bool
4609 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
4610  assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
4611  // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4612  // only see this when folding in C, so there's no standard to follow here.
4613  return Success(E);
4614 }
4615 
4616 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
4617  if (!E->isPotentiallyEvaluated())
4618  return Success(E);
4619 
4620  Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
4621  << E->getExprOperand()->getType()
4622  << E->getExprOperand()->getSourceRange();
4623  return false;
4624 }
4625 
4626 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4627  return Success(E);
4628 }
4629 
4630 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
4631  // Handle static data members.
4632  if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
4633  VisitIgnoredValue(E->getBase());
4634  return VisitVarDecl(E, VD);
4635  }
4636 
4637  // Handle static member functions.
4638  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4639  if (MD->isStatic()) {
4640  VisitIgnoredValue(E->getBase());
4641  return Success(MD);
4642  }
4643  }
4644 
4645  // Handle non-static data members.
4646  return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
4647 }
4648 
4649 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
4650  // FIXME: Deal with vectors as array subscript bases.
4651  if (E->getBase()->getType()->isVectorType())
4652  return Error(E);
4653 
4654  if (!EvaluatePointer(E->getBase(), Result, Info))
4655  return false;
4656 
4657  APSInt Index;
4658  if (!EvaluateInteger(E->getIdx(), Index, Info))
4659  return false;
4660 
4661  return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4662  getExtValue(Index));
4663 }
4664 
4665 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
4666  return EvaluatePointer(E->getSubExpr(), Result, Info);
4667 }
4668 
4669 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4670  if (!Visit(E->getSubExpr()))
4671  return false;
4672  // __real is a no-op on scalar lvalues.
4673  if (E->getSubExpr()->getType()->isAnyComplexType())
4674  HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4675  return true;
4676 }
4677 
4678 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4679  assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4680  "lvalue __imag__ on scalar?");
4681  if (!Visit(E->getSubExpr()))
4682  return false;
4683  HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4684  return true;
4685 }
4686 
4687 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
4688  if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
4689  return Error(UO);
4690 
4691  if (!this->Visit(UO->getSubExpr()))
4692  return false;
4693 
4694  return handleIncDec(
4695  this->Info, UO, Result, UO->getSubExpr()->getType(),
4696  UO->isIncrementOp(), nullptr);
4697 }
4698 
4699 bool LValueExprEvaluator::VisitCompoundAssignOperator(
4700  const CompoundAssignOperator *CAO) {
4701  if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
4702  return Error(CAO);
4703 
4704  APValue RHS;
4705 
4706  // The overall lvalue result is the result of evaluating the LHS.
4707  if (!this->Visit(CAO->getLHS())) {
4708  if (Info.keepEvaluatingAfterFailure())
4709  Evaluate(RHS, this->Info, CAO->getRHS());
4710  return false;
4711  }
4712 
4713  if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4714  return false;
4715 
4716  return handleCompoundAssignment(
4717  this->Info, CAO,
4718  Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4719  CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
4720 }
4721 
4722 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
4723  if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
4724  return Error(E);
4725 
4726  APValue NewVal;
4727 
4728  if (!this->Visit(E->getLHS())) {
4729  if (Info.keepEvaluatingAfterFailure())
4730  Evaluate(NewVal, this->Info, E->getRHS());
4731  return false;
4732  }
4733 
4734  if (!Evaluate(NewVal, this->Info, E->getRHS()))
4735  return false;
4736 
4737  return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
4738  NewVal);
4739 }
4740 
4741 //===----------------------------------------------------------------------===//
4742 // Pointer Evaluation
4743 //===----------------------------------------------------------------------===//
4744 
4745 namespace {
4746 class PointerExprEvaluator
4747  : public ExprEvaluatorBase<PointerExprEvaluator> {
4748  LValue &Result;
4749 
4750  bool Success(const Expr *E) {
4751  Result.set(E);
4752  return true;
4753  }
4754 public:
4755 
4756  PointerExprEvaluator(EvalInfo &info, LValue &Result)
4757  : ExprEvaluatorBaseTy(info), Result(Result) {}
4758 
4759  bool Success(const APValue &V, const Expr *E) {
4760  Result.setFrom(Info.Ctx, V);
4761  return true;
4762  }
4763  bool ZeroInitialization(const Expr *E) {
4764  return Success((Expr*)nullptr);
4765  }
4766 
4767  bool VisitBinaryOperator(const BinaryOperator *E);
4768  bool VisitCastExpr(const CastExpr* E);
4769  bool VisitUnaryAddrOf(const UnaryOperator *E);
4770  bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
4771  { return Success(E); }
4772  bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
4773  { return Success(E); }
4774  bool VisitAddrLabelExpr(const AddrLabelExpr *E)
4775  { return Success(E); }
4776  bool VisitCallExpr(const CallExpr *E);
4777  bool VisitBlockExpr(const BlockExpr *E) {
4778  if (!E->getBlockDecl()->hasCaptures())
4779  return Success(E);
4780  return Error(E);
4781  }
4782  bool VisitCXXThisExpr(const CXXThisExpr *E) {
4783  // Can't look at 'this' when checking a potential constant expression.
4784  if (Info.checkingPotentialConstantExpression())
4785  return false;
4786  if (!Info.CurrentCall->This) {
4787  if (Info.getLangOpts().CPlusPlus11)
4788  Info.Diag(E, diag::note_constexpr_this) << E->isImplicit();
4789  else
4790  Info.Diag(E);
4791  return false;
4792  }
4793  Result = *Info.CurrentCall->This;
4794  return true;
4795  }
4796 
4797  // FIXME: Missing: @protocol, @selector
4798 };
4799 } // end anonymous namespace
4800 
4801 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
4802  assert(E->isRValue() && E->getType()->hasPointerRepresentation());
4803  return PointerExprEvaluator(Info, Result).Visit(E);
4804 }
4805 
4806 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
4807  if (E->getOpcode() != BO_Add &&
4808  E->getOpcode() != BO_Sub)
4809  return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4810 
4811  const Expr *PExp = E->getLHS();
4812  const Expr *IExp = E->getRHS();
4813  if (IExp->getType()->isPointerType())
4814  std::swap(PExp, IExp);
4815 
4816  bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
4817  if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
4818  return false;
4819 
4820  llvm::APSInt Offset;
4821  if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
4822  return false;
4823 
4824  int64_t AdditionalOffset = getExtValue(Offset);
4825  if (E->getOpcode() == BO_Sub)
4826  AdditionalOffset = -AdditionalOffset;
4827 
4828  QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
4829  return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
4830  AdditionalOffset);
4831 }
4832 
4833 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4834  return EvaluateLValue(E->getSubExpr(), Result, Info);
4835 }
4836 
4837 bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
4838  const Expr* SubExpr = E->getSubExpr();
4839 
4840  switch (E->getCastKind()) {
4841  default:
4842  break;
4843 
4844  case CK_BitCast:
4849  if (!Visit(SubExpr))
4850  return false;
4851  // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
4852  // permitted in constant expressions in C++11. Bitcasts from cv void* are
4853  // also static_casts, but we disallow them as a resolution to DR1312.
4854  if (!E->getType()->isVoidPointerType()) {
4855  Result.Designator.setInvalid();
4856  if (SubExpr->getType()->isVoidPointerType())
4857  CCEDiag(E, diag::note_constexpr_invalid_cast)
4858  << 3 << SubExpr->getType();
4859  else
4860  CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4861  }
4862  return true;
4863 
4864  case CK_DerivedToBase:
4866  if (!EvaluatePointer(E->getSubExpr(), Result, Info))
4867  return false;
4868  if (!Result.Base && Result.Offset.isZero())
4869  return true;
4870 
4871  // Now figure out the necessary offset to add to the base LV to get from
4872  // the derived class to the base class.
4873  return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
4874  castAs<PointerType>()->getPointeeType(),
4875  Result);
4876 
4877  case CK_BaseToDerived:
4878  if (!Visit(E->getSubExpr()))
4879  return false;
4880  if (!Result.Base && Result.Offset.isZero())
4881  return true;
4882  return HandleBaseToDerivedCast(Info, E, Result);
4883 
4884  case CK_NullToPointer:
4885  VisitIgnoredValue(E->getSubExpr());
4886  return ZeroInitialization(E);
4887 
4888  case CK_IntegralToPointer: {
4889  CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4890 
4891  APValue Value;
4892  if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
4893  break;
4894 
4895  if (Value.isInt()) {
4896  unsigned Size = Info.Ctx.getTypeSize(E->getType());
4897  uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
4898  Result.Base = (Expr*)nullptr;
4899  Result.Offset = CharUnits::fromQuantity(N);
4900  Result.CallIndex = 0;
4901  Result.Designator.setInvalid();
4902  return true;
4903  } else {
4904  // Cast is of an lvalue, no need to change value.
4905  Result.setFrom(Info.Ctx, Value);
4906  return true;
4907  }
4908  }
4910  if (SubExpr->isGLValue()) {
4911  if (!EvaluateLValue(SubExpr, Result, Info))
4912  return false;
4913  } else {
4914  Result.set(SubExpr, Info.CurrentCall->Index);
4915  if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
4916  Info, Result, SubExpr))
4917  return false;
4918  }
4919  // The result is a pointer to the first element of the array.
4920  if (const ConstantArrayType *CAT
4921  = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
4922  Result.addArray(Info, E, CAT);
4923  else
4924  Result.Designator.setInvalid();
4925  return true;
4926 
4928  return EvaluateLValue(SubExpr, Result, Info);
4929  }
4930 
4931  return ExprEvaluatorBaseTy::VisitCastExpr(E);
4932 }
4933 
4934 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
4935  // C++ [expr.alignof]p3:
4936  // When alignof is applied to a reference type, the result is the
4937  // alignment of the referenced type.
4938  if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4939  T = Ref->getPointeeType();
4940 
4941  // __alignof is defined to return the preferred alignment.
4942  return Info.Ctx.toCharUnitsFromBits(
4943  Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
4944 }
4945 
4946 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
4947  E = E->IgnoreParens();
4948 
4949  // The kinds of expressions that we have special-case logic here for
4950  // should be kept up to date with the special checks for those
4951  // expressions in Sema.
4952 
4953  // alignof decl is always accepted, even if it doesn't make sense: we default
4954  // to 1 in those cases.
4955  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4956  return Info.Ctx.getDeclAlign(DRE->getDecl(),
4957  /*RefAsPointee*/true);
4958 
4959  if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
4960  return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4961  /*RefAsPointee*/true);
4962 
4963  return GetAlignOfType(Info, E->getType());
4964 }
4965 
4966 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
4967  if (IsStringLiteralCall(E))
4968  return Success(E);
4969 
4970  switch (E->getBuiltinCallee()) {
4971  case Builtin::BI__builtin_addressof:
4972  return EvaluateLValue(E->getArg(0), Result, Info);
4973  case Builtin::BI__builtin_assume_aligned: {
4974  // We need to be very careful here because: if the pointer does not have the
4975  // asserted alignment, then the behavior is undefined, and undefined
4976  // behavior is non-constant.
4977  if (!EvaluatePointer(E->getArg(0), Result, Info))
4978  return false;
4979 
4980  LValue OffsetResult(Result);
4981  APSInt Alignment;
4982  if (!EvaluateInteger(E->getArg(1), Alignment, Info))
4983  return false;
4984  CharUnits Align = CharUnits::fromQuantity(getExtValue(Alignment));
4985 
4986  if (E->getNumArgs() > 2) {
4987  APSInt Offset;
4988  if (!EvaluateInteger(E->getArg(2), Offset, Info))
4989  return false;
4990 
4991  int64_t AdditionalOffset = -getExtValue(Offset);
4992  OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
4993  }
4994 
4995  // If there is a base object, then it must have the correct alignment.
4996  if (OffsetResult.Base) {
4997  CharUnits BaseAlignment;
4998  if (const ValueDecl *VD =
4999  OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5000  BaseAlignment = Info.Ctx.getDeclAlign(VD);
5001  } else {
5002  BaseAlignment =
5003  GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5004  }
5005 
5006  if (BaseAlignment < Align) {
5007  Result.Designator.setInvalid();
5008  // FIXME: Quantities here cast to integers because the plural modifier
5009  // does not work on APSInts yet.
5010  CCEDiag(E->getArg(0),
5011  diag::note_constexpr_baa_insufficient_alignment) << 0
5012  << (int) BaseAlignment.getQuantity()
5013  << (unsigned) getExtValue(Alignment);
5014  return false;
5015  }
5016  }
5017 
5018  // The offset must also have the correct alignment.
5019  if (OffsetResult.Offset.RoundUpToAlignment(Align) != OffsetResult.Offset) {
5020  Result.Designator.setInvalid();
5021  APSInt Offset(64, false);
5022  Offset = OffsetResult.Offset.getQuantity();
5023 
5024  if (OffsetResult.Base)
5025  CCEDiag(E->getArg(0),
5026  diag::note_constexpr_baa_insufficient_alignment) << 1
5027  << (int) getExtValue(Offset) << (unsigned) getExtValue(Alignment);
5028  else
5029  CCEDiag(E->getArg(0),
5030  diag::note_constexpr_baa_value_insufficient_alignment)
5031  << Offset << (unsigned) getExtValue(Alignment);
5032 
5033  return false;
5034  }
5035 
5036  return true;
5037  }
5038  default:
5039  return ExprEvaluatorBaseTy::VisitCallExpr(E);
5040  }
5041 }
5042 
5043 //===----------------------------------------------------------------------===//
5044 // Member Pointer Evaluation
5045 //===----------------------------------------------------------------------===//
5046 
5047 namespace {
5048 class MemberPointerExprEvaluator
5049  : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
5050  MemberPtr &Result;
5051 
5052  bool Success(const ValueDecl *D) {
5053  Result = MemberPtr(D);
5054  return true;
5055  }
5056 public:
5057 
5058  MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5059  : ExprEvaluatorBaseTy(Info), Result(Result) {}
5060 
5061  bool Success(const APValue &V, const Expr *E) {
5062  Result.setFrom(V);
5063  return true;
5064  }
5065  bool ZeroInitialization(const Expr *E) {
5066  return Success((const ValueDecl*)nullptr);
5067  }
5068 
5069  bool VisitCastExpr(const CastExpr *E);
5070  bool VisitUnaryAddrOf(const UnaryOperator *E);
5071 };
5072 } // end anonymous namespace
5073 
5074 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5075  EvalInfo &Info) {
5076  assert(E->isRValue() && E->getType()->isMemberPointerType());
5077  return MemberPointerExprEvaluator(Info, Result).Visit(E);
5078 }
5079 
5080 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5081  switch (E->getCastKind()) {
5082  default:
5083  return ExprEvaluatorBaseTy::VisitCastExpr(E);
5084 
5086  VisitIgnoredValue(E->getSubExpr());
5087  return ZeroInitialization(E);
5088 
5090  if (!Visit(E->getSubExpr()))
5091  return false;
5092  if (E->path_empty())
5093  return true;
5094  // Base-to-derived member pointer casts store the path in derived-to-base
5095  // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5096  // the wrong end of the derived->base arc, so stagger the path by one class.
5097  typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5098  for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5099  PathI != PathE; ++PathI) {
5100  assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5101  const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5102  if (!Result.castToDerived(Derived))
5103  return Error(E);
5104  }
5105  const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5106  if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
5107  return Error(E);
5108  return true;
5109  }
5110 
5112  if (!Visit(E->getSubExpr()))
5113  return false;
5114  for (CastExpr::path_const_iterator PathI = E->path_begin(),
5115  PathE = E->path_end(); PathI != PathE; ++PathI) {
5116  assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5117  const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5118  if (!Result.castToBase(Base))
5119  return Error(E);
5120  }
5121  return true;
5122  }
5123 }
5124 
5125 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5126  // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5127  // member can be formed.
5128  return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
5129 }
5130 
5131 //===----------------------------------------------------------------------===//
5132 // Record Evaluation
5133 //===----------------------------------------------------------------------===//
5134 
5135 namespace {
5136  class RecordExprEvaluator
5137  : public ExprEvaluatorBase<RecordExprEvaluator> {
5138  const LValue &This;
5139  APValue &Result;
5140  public:
5141 
5142  RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
5143  : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
5144 
5145  bool Success(const APValue &V, const Expr *E) {
5146  Result = V;
5147  return true;
5148  }
5149  bool ZeroInitialization(const Expr *E);
5150 
5151  bool VisitCastExpr(const CastExpr *E);
5152  bool VisitInitListExpr(const InitListExpr *E);
5153  bool VisitCXXConstructExpr(const CXXConstructExpr *E);
5154  bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
5155  };
5156 }
5157 
5158 /// Perform zero-initialization on an object of non-union class type.
5159 /// C++11 [dcl.init]p5:
5160 /// To zero-initialize an object or reference of type T means:
5161 /// [...]
5162 /// -- if T is a (possibly cv-qualified) non-union class type,
5163 /// each non-static data member and each base-class subobject is
5164 /// zero-initialized
5165 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
5166  const RecordDecl *RD,
5167  const LValue &This, APValue &Result) {
5168  assert(!RD->isUnion() && "Expected non-union class type");
5169  const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
5170  Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
5171  std::distance(RD->field_begin(), RD->field_end()));
5172 
5173  if (RD->isInvalidDecl()) return false;
5174  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5175 
5176  if (CD) {
5177  unsigned Index = 0;
5178  for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
5179  End = CD->bases_end(); I != End; ++I, ++Index) {
5180  const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
5181  LValue Subobject = This;
5182  if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
5183  return false;
5184  if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
5185  Result.getStructBase(Index)))
5186  return false;
5187  }
5188  }
5189 
5190  for (const auto *I : RD->fields()) {
5191  // -- if T is a reference type, no initialization is performed.
5192  if (I->getType()->isReferenceType())
5193  continue;
5194 
5195  LValue Subobject = This;
5196  if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
5197  return false;
5198 
5199  ImplicitValueInitExpr VIE(I->getType());
5200  if (!EvaluateInPlace(
5201  Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
5202  return false;
5203  }
5204 
5205  return true;
5206 }
5207 
5208 bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
5209  const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
5210  if (RD->isInvalidDecl()) return false;
5211  if (RD->isUnion()) {
5212  // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5213  // object's first non-static named data member is zero-initialized
5215  if (I == RD->field_end()) {
5216  Result = APValue((const FieldDecl*)nullptr);
5217  return true;
5218  }
5219 
5220  LValue Subobject = This;
5221  if (!HandleLValueMember(Info, E, Subobject, *I))
5222  return false;
5223  Result = APValue(*I);
5224  ImplicitValueInitExpr VIE(I->getType());
5225  return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
5226  }
5227 
5228  if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
5229  Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
5230  return false;
5231  }
5232 
5233  return HandleClassZeroInitialization(Info, E, RD, This, Result);
5234 }
5235 
5236 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
5237  switch (E->getCastKind()) {
5238  default:
5239  return ExprEvaluatorBaseTy::VisitCastExpr(E);
5240 
5242  return Visit(E->getSubExpr());
5243 
5244  case CK_DerivedToBase:
5246  APValue DerivedObject;
5247  if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
5248  return false;
5249  if (!DerivedObject.isStruct())
5250  return Error(E->getSubExpr());
5251 
5252  // Derived-to-base rvalue conversion: just slice off the derived part.
5253  APValue *Value = &DerivedObject;
5254  const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
5255  for (CastExpr::path_const_iterator PathI = E->path_begin(),
5256  PathE = E->path_end(); PathI != PathE; ++PathI) {
5257  assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
5258  const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5259  Value = &Value->getStructBase(getBaseIndex(RD, Base));
5260  RD = Base;
5261  }
5262  Result = *Value;
5263  return true;
5264  }
5265  }
5266 }
5267 
5268 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5269  const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
5270  if (RD->isInvalidDecl()) return false;
5271  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5272 
5273  if (RD->isUnion()) {
5274  const FieldDecl *Field = E->getInitializedFieldInUnion();
5275  Result = APValue(Field);
5276  if (!Field)
5277  return true;
5278 
5279  // If the initializer list for a union does not contain any elements, the
5280  // first element of the union is value-initialized.
5281  // FIXME: The element should be initialized from an initializer list.
5282  // Is this difference ever observable for initializer lists which
5283  // we don't build?
5284  ImplicitValueInitExpr VIE(Field->getType());
5285  const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
5286 
5287  LValue Subobject = This;
5288  if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
5289  return false;
5290 
5291  // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5292  ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5293  isa<CXXDefaultInitExpr>(InitExpr));
5294 
5295  return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
5296  }
5297 
5298  assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
5299  "initializer list for class with base classes");
5300  Result = APValue(APValue::UninitStruct(), 0,
5301  std::distance(RD->field_begin(), RD->field_end()));
5302  unsigned ElementNo = 0;
5303  bool Success = true;
5304  for (const auto *Field : RD->fields()) {
5305  // Anonymous bit-fields are not considered members of the class for
5306  // purposes of aggregate initialization.
5307  if (Field->isUnnamedBitfield())
5308  continue;
5309 
5310  LValue Subobject = This;
5311 
5312  bool HaveInit = ElementNo < E->getNumInits();
5313 
5314  // FIXME: Diagnostics here should point to the end of the initializer
5315  // list, not the start.
5316  if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
5317  Subobject, Field, &Layout))
5318  return false;
5319 
5320  // Perform an implicit value-initialization for members beyond the end of
5321  // the initializer list.
5322  ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
5323  const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
5324 
5325  // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5326  ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5327  isa<CXXDefaultInitExpr>(Init));
5328 
5329  APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
5330  if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
5331  (Field->isBitField() && !truncateBitfieldValue(Info, Init,
5332  FieldVal, Field))) {
5333  if (!Info.keepEvaluatingAfterFailure())
5334  return false;
5335  Success = false;
5336  }
5337  }
5338 
5339  return Success;
5340 }
5341 
5342 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
5343  const CXXConstructorDecl *FD = E->getConstructor();
5344  if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
5345 
5346  bool ZeroInit = E->requiresZeroInitialization();
5347  if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
5348  // If we've already performed zero-initialization, we're already done.
5349  if (!Result.isUninit())
5350  return true;
5351 
5352  // We can get here in two different ways:
5353  // 1) We're performing value-initialization, and should zero-initialize
5354  // the object, or
5355  // 2) We're performing default-initialization of an object with a trivial
5356  // constexpr default constructor, in which case we should start the
5357  // lifetimes of all the base subobjects (there can be no data member
5358  // subobjects in this case) per [basic.life]p1.
5359  // Either way, ZeroInitialization is appropriate.
5360  return ZeroInitialization(E);
5361  }
5362 
5363  const FunctionDecl *Definition = nullptr;
5364  FD->getBody(Definition);
5365 
5366  if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5367  return false;
5368 
5369  // Avoid materializing a temporary for an elidable copy/move constructor.
5370  if (E->isElidable() && !ZeroInit)
5371  if (const MaterializeTemporaryExpr *ME
5372  = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
5373  return Visit(ME->GetTemporaryExpr());
5374 
5375  if (ZeroInit && !ZeroInitialization(E))
5376  return false;
5377 
5378  auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
5379  return HandleConstructorCall(E->getExprLoc(), This, Args,
5380  cast<CXXConstructorDecl>(Definition), Info,
5381  Result);
5382 }
5383 
5384 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
5385  const CXXStdInitializerListExpr *E) {
5386  const ConstantArrayType *ArrayType =
5387  Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
5388 
5389  LValue Array;
5390  if (!EvaluateLValue(E->getSubExpr(), Array, Info))
5391  return false;
5392 
5393  // Get a pointer to the first element of the array.
5394  Array.addArray(Info, E, ArrayType);
5395 
5396  // FIXME: Perform the checks on the field types in SemaInit.
5397  RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
5398  RecordDecl::field_iterator Field = Record->field_begin();
5399  if (Field == Record->field_end())
5400  return Error(E);
5401 
5402  // Start pointer.
5403  if (!Field->getType()->isPointerType() ||
5404  !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5405  ArrayType->getElementType()))
5406  return Error(E);
5407 
5408  // FIXME: What if the initializer_list type has base classes, etc?
5409  Result = APValue(APValue::UninitStruct(), 0, 2);
5410  Array.moveInto(Result.getStructField(0));
5411 
5412  if (++Field == Record->field_end())
5413  return Error(E);
5414 
5415  if (Field->getType()->isPointerType() &&
5416  Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5417  ArrayType->getElementType())) {
5418  // End pointer.
5419  if (!HandleLValueArrayAdjustment(Info, E, Array,
5420  ArrayType->getElementType(),
5421  ArrayType->getSize().getZExtValue()))
5422  return false;
5423  Array.moveInto(Result.getStructField(1));
5424  } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
5425  // Length.
5426  Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
5427  else
5428  return Error(E);
5429 
5430  if (++Field != Record->field_end())
5431  return Error(E);
5432 
5433  return true;
5434 }
5435 
5436 static bool EvaluateRecord(const Expr *E, const LValue &This,
5437  APValue &Result, EvalInfo &Info) {
5438  assert(E->isRValue() && E->getType()->isRecordType() &&
5439  "can't evaluate expression as a record rvalue");
5440  return RecordExprEvaluator(Info, This, Result).Visit(E);
5441 }
5442 
5443 //===----------------------------------------------------------------------===//
5444 // Temporary Evaluation
5445 //
5446 // Temporaries are represented in the AST as rvalues, but generally behave like
5447 // lvalues. The full-object of which the temporary is a subobject is implicitly
5448 // materialized so that a reference can bind to it.
5449 //===----------------------------------------------------------------------===//
5450 namespace {
5451 class TemporaryExprEvaluator
5452  : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
5453 public:
5454  TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
5455  LValueExprEvaluatorBaseTy(Info, Result) {}
5456 
5457  /// Visit an expression which constructs the value of this temporary.
5458  bool VisitConstructExpr(const Expr *E) {
5459  Result.set(E, Info.CurrentCall->Index);
5460  return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
5461  Info, Result, E);
5462  }
5463 
5464  bool VisitCastExpr(const CastExpr *E) {
5465  switch (E->getCastKind()) {
5466  default:
5467  return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5468 
5470  return VisitConstructExpr(E->getSubExpr());
5471  }
5472  }
5473  bool VisitInitListExpr(const InitListExpr *E) {
5474  return VisitConstructExpr(E);
5475  }
5476  bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5477  return VisitConstructExpr(E);
5478  }
5479  bool VisitCallExpr(const CallExpr *E) {
5480  return VisitConstructExpr(E);
5481  }
5482  bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
5483  return VisitConstructExpr(E);
5484  }
5485 };
5486 } // end anonymous namespace
5487 
5488 /// Evaluate an expression of record type as a temporary.
5489 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
5490  assert(E->isRValue() && E->getType()->isRecordType());
5491  return TemporaryExprEvaluator(Info, Result).Visit(E);
5492 }
5493 
5494 //===----------------------------------------------------------------------===//
5495 // Vector Evaluation
5496 //===----------------------------------------------------------------------===//
5497 
5498 namespace {
5499  class VectorExprEvaluator
5500  : public ExprEvaluatorBase<VectorExprEvaluator> {
5501  APValue &Result;
5502  public:
5503 
5504  VectorExprEvaluator(EvalInfo &info, APValue &Result)
5505  : ExprEvaluatorBaseTy(info), Result(Result) {}
5506 
5507  bool Success(const ArrayRef<APValue> &V, const Expr *E) {
5508  assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
5509  // FIXME: remove this APValue copy.
5510  Result = APValue(V.data(), V.size());
5511  return true;
5512  }
5513  bool Success(const APValue &V, const Expr *E) {
5514  assert(V.isVector());
5515  Result = V;
5516  return true;
5517  }
5518  bool ZeroInitialization(const Expr *E);
5519 
5520  bool VisitUnaryReal(const UnaryOperator *E)
5521  { return Visit(E->getSubExpr()); }
5522  bool VisitCastExpr(const CastExpr* E);
5523  bool VisitInitListExpr(const InitListExpr *E);
5524  bool VisitUnaryImag(const UnaryOperator *E);
5525  // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
5526  // binary comparisons, binary and/or/xor,
5527  // shufflevector, ExtVectorElementExpr
5528  };
5529 } // end anonymous namespace
5530 
5531 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
5532  assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
5533  return VectorExprEvaluator(Info, Result).Visit(E);
5534 }
5535 
5536 bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
5537  const VectorType *VTy = E->getType()->castAs<VectorType>();
5538  unsigned NElts = VTy->getNumElements();
5539 
5540  const Expr *SE = E->getSubExpr();
5541  QualType SETy = SE->getType();
5542 
5543  switch (E->getCastKind()) {
5544  case CK_VectorSplat: {
5545  APValue Val = APValue();
5546  if (SETy->isIntegerType()) {
5547  APSInt IntResult;
5548  if (!EvaluateInteger(SE, IntResult, Info))
5549  return false;
5550  Val = APValue(IntResult);
5551  } else if (SETy->isRealFloatingType()) {
5552  APFloat F(0.0);
5553  if (!EvaluateFloat(SE, F, Info))
5554  return false;
5555  Val = APValue(F);
5556  } else {
5557  return Error(E);
5558  }
5559 
5560  // Splat and create vector APValue.
5561  SmallVector<APValue, 4> Elts(NElts, Val);
5562  return Success(Elts, E);
5563  }
5564  case CK_BitCast: {
5565  // Evaluate the operand into an APInt we can extract from.
5566  llvm::APInt SValInt;
5567  if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
5568  return false;
5569  // Extract the elements
5570  QualType EltTy = VTy->getElementType();
5571  unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
5572  bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
5574  if (EltTy->isRealFloatingType()) {
5575  const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
5576  unsigned FloatEltSize = EltSize;
5577  if (&Sem == &APFloat::x87DoubleExtended)
5578  FloatEltSize = 80;
5579  for (unsigned i = 0; i < NElts; i++) {
5580  llvm::APInt Elt;
5581  if (BigEndian)
5582  Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
5583  else
5584  Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
5585  Elts.push_back(APValue(APFloat(Sem, Elt)));
5586  }
5587  } else if (EltTy->isIntegerType()) {
5588  for (unsigned i = 0; i < NElts; i++) {
5589  llvm::APInt Elt;
5590  if (BigEndian)
5591  Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
5592  else
5593  Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
5594  Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
5595  }
5596  } else {
5597  return Error(E);
5598  }
5599  return Success(Elts, E);
5600  }
5601  default:
5602  return ExprEvaluatorBaseTy::VisitCastExpr(E);
5603  }
5604 }
5605 
5606 bool
5607 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5608  const VectorType *VT = E->getType()->castAs<VectorType>();
5609  unsigned NumInits = E->getNumInits();
5610  unsigned NumElements = VT->getNumElements();
5611 
5612  QualType EltTy = VT->getElementType();
5613  SmallVector<APValue, 4> Elements;
5614 
5615  // The number of initializers can be less than the number of
5616  // vector elements. For OpenCL, this can be due to nested vector
5617  // initialization. For GCC compatibility, missing trailing elements
5618  // should be initialized with zeroes.
5619  unsigned CountInits = 0, CountElts = 0;
5620  while (CountElts < NumElements) {
5621  // Handle nested vector initialization.
5622  if (CountInits < NumInits
5623  && E->getInit(CountInits)->getType()->isVectorType()) {
5624  APValue v;
5625  if (!EvaluateVector(E->getInit(CountInits), v, Info))
5626  return Error(E);
5627  unsigned vlen = v.getVectorLength();
5628  for (unsigned j = 0; j < vlen; j++)
5629  Elements.push_back(v.getVectorElt(j));
5630  CountElts += vlen;
5631  } else if (EltTy->isIntegerType()) {
5632  llvm::APSInt sInt(32);
5633  if (CountInits < NumInits) {
5634  if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
5635  return false;
5636  } else // trailing integer zero.
5637  sInt = Info.Ctx.MakeIntValue(0, EltTy);
5638  Elements.push_back(APValue(sInt));
5639  CountElts++;
5640  } else {
5641  llvm::APFloat f(0.0);
5642  if (CountInits < NumInits) {
5643  if (!EvaluateFloat(E->getInit(CountInits), f, Info))
5644  return false;
5645  } else // trailing float zero.
5646  f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
5647  Elements.push_back(APValue(f));
5648  CountElts++;
5649  }
5650  CountInits++;
5651  }
5652  return Success(Elements, E);
5653 }
5654 
5655 bool
5656 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
5657  const VectorType *VT = E->getType()->getAs<VectorType>();
5658  QualType EltTy = VT->getElementType();
5659  APValue ZeroElement;
5660  if (EltTy->isIntegerType())
5661  ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
5662  else
5663  ZeroElement =
5664  APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
5665 
5666  SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
5667  return Success(Elements, E);
5668 }
5669 
5670 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5671  VisitIgnoredValue(E->getSubExpr());
5672  return ZeroInitialization(E);
5673 }
5674 
5675 //===----------------------------------------------------------------------===//
5676 // Array Evaluation
5677 //===----------------------------------------------------------------------===//
5678 
5679 namespace {
5680  class ArrayExprEvaluator
5681  : public ExprEvaluatorBase<ArrayExprEvaluator> {
5682  const LValue &This;
5683  APValue &Result;
5684  public:
5685 
5686  ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
5687  : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
5688 
5689  bool Success(const APValue &V, const Expr *E) {
5690  assert((V.isArray() || V.isLValue()) &&
5691  "expected array or string literal");
5692  Result = V;
5693  return true;
5694  }
5695 
5696  bool ZeroInitialization(const Expr *E) {
5697  const ConstantArrayType *CAT =
5698  Info.Ctx.getAsConstantArrayType(E->getType());
5699  if (!CAT)
5700  return Error(E);
5701 
5702  Result = APValue(APValue::UninitArray(), 0,
5703  CAT->getSize().getZExtValue());
5704  if (!Result.hasArrayFiller()) return true;
5705 
5706  // Zero-initialize all elements.
5707  LValue Subobject = This;
5708  Subobject.addArray(Info, E, CAT);
5710  return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
5711  }
5712 
5713  bool VisitInitListExpr(const InitListExpr *E);
5714  bool VisitCXXConstructExpr(const CXXConstructExpr *E);
5715  bool VisitCXXConstructExpr(const CXXConstructExpr *E,
5716  const LValue &Subobject,
5717  APValue *Value, QualType Type);
5718  };
5719 } // end anonymous namespace
5720 
5721 static bool EvaluateArray(const Expr *E, const LValue &This,
5722  APValue &Result, EvalInfo &Info) {
5723  assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
5724  return ArrayExprEvaluator(Info, This, Result).Visit(E);
5725 }
5726 
5727 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5728  const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
5729  if (!CAT)
5730  return Error(E);
5731 
5732  // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
5733  // an appropriately-typed string literal enclosed in braces.
5734  if (E->isStringLiteralInit()) {
5735  LValue LV;
5736  if (!EvaluateLValue(E->getInit(0), LV, Info))
5737  return false;
5738  APValue Val;
5739  LV.moveInto(Val);
5740  return Success(Val, E);
5741  }
5742 
5743  bool Success = true;
5744 
5745  assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
5746  "zero-initialized array shouldn't have any initialized elts");
5747  APValue Filler;
5748  if (Result.isArray() && Result.hasArrayFiller())
5749  Filler = Result.getArrayFiller();
5750 
5751  unsigned NumEltsToInit = E->getNumInits();
5752  unsigned NumElts = CAT->getSize().getZExtValue();
5753  const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
5754 
5755  // If the initializer might depend on the array index, run it for each
5756  // array element. For now, just whitelist non-class value-initialization.
5757  if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
5758  NumEltsToInit = NumElts;
5759 
5760  Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
5761 
5762  // If the array was previously zero-initialized, preserve the
5763  // zero-initialized values.
5764  if (!Filler.isUninit()) {
5765  for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
5766  Result.getArrayInitializedElt(I) = Filler;
5767  if (Result.hasArrayFiller())
5768  Result.getArrayFiller() = Filler;
5769  }
5770 
5771  LValue Subobject = This;
5772  Subobject.addArray(Info, E, CAT);
5773  for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
5774  const Expr *Init =
5775  Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
5776  if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
5777  Info, Subobject, Init) ||
5778  !HandleLValueArrayAdjustment(Info, Init, Subobject,
5779  CAT->getElementType(), 1)) {
5780  if (!Info.keepEvaluatingAfterFailure())
5781  return false;
5782  Success = false;
5783  }
5784  }
5785 
5786  if (!Result.hasArrayFiller())
5787  return Success;
5788 
5789  // If we get here, we have a trivial filler, which we can just evaluate
5790  // once and splat over the rest of the array elements.
5791  assert(FillerExpr && "no array filler for incomplete init list");
5792  return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
5793  FillerExpr) && Success;
5794 }
5795 
5796 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
5797  return VisitCXXConstructExpr(E, This, &Result, E->getType());
5798 }
5799 
5800 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5801  const LValue &Subobject,
5802  APValue *Value,
5803  QualType Type) {
5804  bool HadZeroInit = !Value->isUninit();
5805 
5806  if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
5807  unsigned N = CAT->getSize().getZExtValue();
5808 
5809  // Preserve the array filler if we had prior zero-initialization.
5810  APValue Filler =
5811  HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
5812  : APValue();
5813 
5814  *Value = APValue(APValue::UninitArray(), N, N);
5815 
5816  if (HadZeroInit)
5817  for (unsigned I = 0; I != N; ++I)
5818  Value->getArrayInitializedElt(I) = Filler;
5819 
5820  // Initialize the elements.
5821  LValue ArrayElt = Subobject;
5822  ArrayElt.addArray(Info, E, CAT);
5823  for (unsigned I = 0; I != N; ++I)
5824  if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
5825  CAT->getElementType()) ||
5826  !HandleLValueArrayAdjustment(Info, E, ArrayElt,
5827  CAT->getElementType(), 1))
5828  return false;
5829 
5830  return true;
5831  }
5832 
5833  if (!Type->isRecordType())
5834  return Error(E);
5835 
5836  const CXXConstructorDecl *FD = E->getConstructor();
5837 
5838  bool ZeroInit = E->requiresZeroInitialization();
5839  if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
5840  if (HadZeroInit)
5841  return true;
5842 
5843  // See RecordExprEvaluator::VisitCXXConstructExpr for explanation.
5844  ImplicitValueInitExpr VIE(Type);
5845  return EvaluateInPlace(*Value, Info, Subobject, &VIE);
5846  }
5847 
5848  const FunctionDecl *Definition = nullptr;
5849  FD->getBody(Definition);
5850 
5851  if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5852  return false;
5853 
5854  if (ZeroInit && !HadZeroInit) {
5855  ImplicitValueInitExpr VIE(Type);
5856  if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
5857  return false;
5858  }
5859 
5860  auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
5861  return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
5862  cast<CXXConstructorDecl>(Definition),
5863  Info, *Value);
5864 }
5865 
5866 //===----------------------------------------------------------------------===//
5867 // Integer Evaluation
5868 //
5869 // As a GNU extension, we support casting pointers to sufficiently-wide integer
5870 // types and back in constant folding. Integer values are thus represented
5871 // either as an integer-valued APValue, or as an lvalue-valued APValue.
5872 //===----------------------------------------------------------------------===//
5873 
5874 namespace {
5875 class IntExprEvaluator
5876  : public ExprEvaluatorBase<IntExprEvaluator> {
5877  APValue &Result;
5878 public:
5879  IntExprEvaluator(EvalInfo &info, APValue &result)
5880  : ExprEvaluatorBaseTy(info), Result(result) {}
5881 
5882  bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
5883  assert(E->getType()->isIntegralOrEnumerationType() &&
5884  "Invalid evaluation result.");
5885  assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
5886  "Invalid evaluation result.");
5887  assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
5888  "Invalid evaluation result.");
5889  Result = APValue(SI);
5890  return true;
5891  }
5892  bool Success(const llvm::APSInt &SI, const Expr *E) {
5893  return Success(SI, E, Result);
5894  }
5895 
5896  bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
5897  assert(E->getType()->isIntegralOrEnumerationType() &&
5898  "Invalid evaluation result.");
5899  assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
5900  "Invalid evaluation result.");
5901  Result = APValue(APSInt(I));
5902  Result.getInt().setIsUnsigned(
5904  return true;
5905  }
5906  bool Success(const llvm::APInt &I, const Expr *E) {
5907  return Success(I, E, Result);
5908  }
5909 
5910  bool Success(uint64_t Value, const Expr *E, APValue &Result) {
5911  assert(E->getType()->isIntegralOrEnumerationType() &&
5912  "Invalid evaluation result.");
5913  Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
5914  return true;
5915  }
5916  bool Success(uint64_t Value, const Expr *E) {
5917  return Success(Value, E, Result);
5918  }
5919 
5920  bool Success(CharUnits Size, const Expr *E) {
5921  return Success(Size.getQuantity(), E);
5922  }
5923 
5924  bool Success(const APValue &V, const Expr *E) {
5925  if (V.isLValue() || V.isAddrLabelDiff()) {
5926  Result = V;
5927  return true;
5928  }
5929  return Success(V.getInt(), E);
5930  }
5931 
5932  bool ZeroInitialization(const Expr *E) { return Success(0, E); }
5933 
5934  //===--------------------------------------------------------------------===//
5935  // Visitor Methods
5936  //===--------------------------------------------------------------------===//
5937 
5938  bool VisitIntegerLiteral(const IntegerLiteral *E) {
5939  return Success(E->getValue(), E);
5940  }
5941  bool VisitCharacterLiteral(const CharacterLiteral *E) {
5942  return Success(E->getValue(), E);
5943  }
5944 
5945  bool CheckReferencedDecl(const Expr *E, const Decl *D);
5946  bool VisitDeclRefExpr(const DeclRefExpr *E) {
5947  if (CheckReferencedDecl(E, E->getDecl()))
5948  return true;
5949 
5950  return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
5951  }
5952  bool VisitMemberExpr(const MemberExpr *E) {
5953  if (CheckReferencedDecl(E, E->getMemberDecl())) {
5954  VisitIgnoredValue(E->getBase());
5955  return true;
5956  }
5957 
5958  return ExprEvaluatorBaseTy::VisitMemberExpr(E);
5959  }
5960 
5961  bool VisitCallExpr(const CallExpr *E);
5962  bool VisitBinaryOperator(const BinaryOperator *E);
5963  bool VisitOffsetOfExpr(const OffsetOfExpr *E);
5964  bool VisitUnaryOperator(const UnaryOperator *E);
5965 
5966  bool VisitCastExpr(const CastExpr* E);
5967  bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
5968 
5969  bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
5970  return Success(E->getValue(), E);
5971  }
5972 
5973  bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
5974  return Success(E->getValue(), E);
5975  }
5976 
5977  // Note, GNU defines __null as an integer, not a pointer.
5978  bool VisitGNUNullExpr(const GNUNullExpr *E) {
5979  return ZeroInitialization(E);
5980  }
5981 
5982  bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
5983  return Success(E->getValue(), E);
5984  }
5985 
5986  bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
5987  return Success(E->getValue(), E);
5988  }
5989 
5990  bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
5991  return Success(E->getValue(), E);
5992  }
5993 
5994  bool VisitUnaryReal(const UnaryOperator *E);
5995  bool VisitUnaryImag(const UnaryOperator *E);
5996 
5997  bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
5998  bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
5999 
6000 private:
6001  static QualType GetObjectType(APValue::LValueBase B);
6002  bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
6003  // FIXME: Missing: array subscript of vector, member of vector
6004 };
6005 } // end anonymous namespace
6006 
6007 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
6008 /// produce either the integer value or a pointer.
6009 ///
6010 /// GCC has a heinous extension which folds casts between pointer types and
6011 /// pointer-sized integral types. We support this by allowing the evaluation of
6012 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
6013 /// Some simple arithmetic on such values is supported (they are treated much
6014 /// like char*).
6015 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
6016  EvalInfo &Info) {
6017  assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
6018  return IntExprEvaluator(Info, Result).Visit(E);
6019 }
6020 
6021 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
6022  APValue Val;
6023  if (!EvaluateIntegerOrLValue(E, Val, Info))
6024  return false;
6025  if (!Val.isInt()) {
6026  // FIXME: It would be better to produce the diagnostic for casting
6027  // a pointer to an integer.
6028  Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
6029  return false;
6030  }
6031  Result = Val.getInt();
6032  return true;
6033 }
6034 
6035 /// Check whether the given declaration can be directly converted to an integral
6036 /// rvalue. If not, no diagnostic is produced; there are other things we can
6037 /// try.
6038 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
6039  // Enums are integer constant exprs.
6040  if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
6041  // Check for signedness/width mismatches between E type and ECD value.
6042  bool SameSign = (ECD->getInitVal().isSigned()
6044  bool SameWidth = (ECD->getInitVal().getBitWidth()
6045  == Info.Ctx.getIntWidth(E->getType()));
6046  if (SameSign && SameWidth)
6047  return Success(ECD->getInitVal(), E);
6048  else {
6049  // Get rid of mismatch (otherwise Success assertions will fail)
6050  // by computing a new value matching the type of E.
6051  llvm::APSInt Val = ECD->getInitVal();
6052  if (!SameSign)
6053  Val.setIsSigned(!ECD->getInitVal().isSigned());
6054  if (!SameWidth)
6055  Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
6056  return Success(Val, E);
6057  }
6058  }
6059  return false;
6060 }
6061 
6062 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
6063 /// as GCC.
6065  // The following enum mimics the values returned by GCC.
6066  // FIXME: Does GCC differ between lvalue and rvalue references here?
6067  enum gcc_type_class {
6068  no_type_class = -1,
6069  void_type_class, integer_type_class, char_type_class,
6070  enumeral_type_class, boolean_type_class,
6071  pointer_type_class, reference_type_class, offset_type_class,
6072  real_type_class, complex_type_class,
6073  function_type_class, method_type_class,
6074  record_type_class, union_type_class,
6075  array_type_class, string_type_class,
6076  lang_type_class
6077  };
6078 
6079  // If no argument was supplied, default to "no_type_class". This isn't
6080  // ideal, however it is what gcc does.
6081  if (E->getNumArgs() == 0)
6082  return no_type_class;
6083 
6084  QualType ArgTy = E->getArg(0)->getType();
6085  if (ArgTy->isVoidType())
6086  return void_type_class;
6087  else if (ArgTy->isEnumeralType())
6088  return enumeral_type_class;
6089  else if (ArgTy->isBooleanType())
6090  return boolean_type_class;
6091  else if (ArgTy->isCharType())
6092  return string_type_class; // gcc doesn't appear to use char_type_class
6093  else if (ArgTy->isIntegerType())
6094  return integer_type_class;
6095  else if (ArgTy->isPointerType())
6096  return pointer_type_class;
6097  else if (ArgTy->isReferenceType())
6098  return reference_type_class;
6099  else if (ArgTy->isRealType())
6100  return real_type_class;
6101  else if (ArgTy->isComplexType())
6102  return complex_type_class;
6103  else if (ArgTy->isFunctionType())
6104  return function_type_class;
6105  else if (ArgTy->isStructureOrClassType())
6106  return record_type_class;
6107  else if (ArgTy->isUnionType())
6108  return union_type_class;
6109  else if (ArgTy->isArrayType())
6110  return array_type_class;
6111  else if (ArgTy->isUnionType())
6112  return union_type_class;
6113  else // FIXME: offset_type_class, method_type_class, & lang_type_class?
6114  llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6115 }
6116 
6117 /// EvaluateBuiltinConstantPForLValue - Determine the result of
6118 /// __builtin_constant_p when applied to the given lvalue.
6119 ///
6120 /// An lvalue is only "constant" if it is a pointer or reference to the first
6121 /// character of a string literal.
6122 template<typename LValue>
6123 static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
6124  const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
6125  return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
6126 }
6127 
6128 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
6129 /// GCC as we can manage.
6130 static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
6131  QualType ArgType = Arg->getType();
6132 
6133  // __builtin_constant_p always has one operand. The rules which gcc follows
6134  // are not precisely documented, but are as follows:
6135  //
6136  // - If the operand is of integral, floating, complex or enumeration type,
6137  // and can be folded to a known value of that type, it returns 1.
6138  // - If the operand and can be folded to a pointer to the first character
6139  // of a string literal (or such a pointer cast to an integral type), it
6140  // returns 1.
6141  //
6142  // Otherwise, it returns 0.
6143  //
6144  // FIXME: GCC also intends to return 1 for literals of aggregate types, but
6145  // its support for this does not currently work.
6146  if (ArgType->isIntegralOrEnumerationType()) {
6147  Expr::EvalResult Result;
6148  if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
6149  return false;
6150 
6151  APValue &V = Result.Val;
6152  if (V.getKind() == APValue::Int)
6153  return true;
6154 
6156  } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
6157  return Arg->isEvaluatable(Ctx);
6158  } else if (ArgType->isPointerType() || Arg->isGLValue()) {
6159  LValue LV;
6160  Expr::EvalStatus Status;
6161  EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
6162  if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
6163  : EvaluatePointer(Arg, LV, Info)) &&
6164  !Status.HasSideEffects)
6166  }
6167 
6168  // Anything else isn't considered to be sufficiently constant.
6169  return false;
6170 }
6171 
6172 /// Retrieves the "underlying object type" of the given expression,
6173 /// as used by __builtin_object_size.
6174 QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
6175  if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
6176  if (const VarDecl *VD = dyn_cast<VarDecl>(D))
6177  return VD->getType();
6178  } else if (const Expr *E = B.get<const Expr*>()) {
6179  if (isa<CompoundLiteralExpr>(E))
6180  return E->getType();
6181  }
6182 
6183  return QualType();
6184 }
6185 
6186 bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
6187  LValue Base;
6188 
6189  {
6190  // The operand of __builtin_object_size is never evaluated for side-effects.
6191  // If there are any, but we can determine the pointed-to object anyway, then
6192  // ignore the side-effects.
6193  SpeculativeEvaluationRAII SpeculativeEval(Info);
6194  if (!EvaluatePointer(E->getArg(0), Base, Info))
6195  return false;
6196  }
6197 
6198  if (!Base.getLValueBase()) {
6199  // It is not possible to determine which objects ptr points to at compile time,
6200  // __builtin_object_size should return (size_t) -1 for type 0 or 1
6201  // and (size_t) 0 for type 2 or 3.
6202  llvm::APSInt TypeIntVaue;
6203  const Expr *ExprType = E->getArg(1);
6204  if (!ExprType->EvaluateAsInt(TypeIntVaue, Info.Ctx))
6205  return false;
6206  if (TypeIntVaue == 0 || TypeIntVaue == 1)
6207  return Success(-1, E);
6208  if (TypeIntVaue == 2 || TypeIntVaue == 3)
6209  return Success(0, E);
6210  return Error(E);
6211  }
6212 
6213  QualType T = GetObjectType(Base.getLValueBase());
6214  if (T.isNull() ||
6215  T->isIncompleteType() ||
6216  T->isFunctionType() ||
6217  T->isVariablyModifiedType() ||
6218  T->isDependentType())
6219  return Error(E);
6220 
6221  CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
6222  CharUnits Offset = Base.getLValueOffset();
6223 
6224  if (!Offset.isNegative() && Offset <= Size)
6225  Size -= Offset;
6226  else
6227  Size = CharUnits::Zero();
6228  return Success(Size, E);
6229 }
6230 
6231 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
6232  switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
6233  default:
6234  return ExprEvaluatorBaseTy::VisitCallExpr(E);
6235 
6236  case Builtin::BI__builtin_object_size: {
6237  if (TryEvaluateBuiltinObjectSize(E))
6238  return true;
6239 
6240  // If evaluating the argument has side-effects, we can't determine the size
6241  // of the object, and so we lower it to unknown now. CodeGen relies on us to
6242  // handle all cases where the expression has side-effects.
6243  if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
6244  if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
6245  return Success(-1ULL, E);
6246  return Success(0, E);
6247  }
6248 
6249  // Expression had no side effects, but we couldn't statically determine the
6250  // size of the referenced object.
6251  switch (Info.EvalMode) {
6252  case EvalInfo::EM_ConstantExpression:
6253  case EvalInfo::EM_PotentialConstantExpression:
6254  case EvalInfo::EM_ConstantFold:
6255  case EvalInfo::EM_EvaluateForOverflow:
6256  case EvalInfo::EM_IgnoreSideEffects:
6257  return Error(E);
6258  case EvalInfo::EM_ConstantExpressionUnevaluated:
6259  case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
6260  return Success(-1ULL, E);
6261  }
6262  }
6263 
6264  case Builtin::BI__builtin_bswap16:
6265  case Builtin::BI__builtin_bswap32:
6266  case Builtin::BI__builtin_bswap64: {
6267  APSInt Val;
6268  if (!EvaluateInteger(E->getArg(0), Val, Info))
6269  return false;
6270 
6271  return Success(Val.byteSwap(), E);
6272  }
6273 
6274  case Builtin::BI__builtin_classify_type:
6275  return Success(EvaluateBuiltinClassifyType(E), E);
6276 
6277  // FIXME: BI__builtin_clrsb
6278  // FIXME: BI__builtin_clrsbl
6279  // FIXME: BI__builtin_clrsbll
6280 
6281  case Builtin::BI__builtin_clz:
6282  case Builtin::BI__builtin_clzl:
6283  case Builtin::BI__builtin_clzll:
6284  case Builtin::BI__builtin_clzs: {
6285  APSInt Val;
6286  if (!EvaluateInteger(E->getArg(0), Val, Info))
6287  return false;
6288  if (!Val)
6289  return Error(E);
6290 
6291  return Success(Val.countLeadingZeros(), E);
6292  }
6293 
6294  case Builtin::BI__builtin_constant_p:
6295  return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
6296 
6297  case Builtin::BI__builtin_ctz:
6298  case Builtin::BI__builtin_ctzl:
6299  case Builtin::BI__builtin_ctzll:
6300  case Builtin::BI__builtin_ctzs: {
6301  APSInt Val;
6302  if (!EvaluateInteger(E->getArg(0), Val, Info))
6303  return false;
6304  if (!Val)
6305  return Error(E);
6306 
6307  return Success(Val.countTrailingZeros(), E);
6308  }
6309 
6310  case Builtin::BI__builtin_eh_return_data_regno: {
6311  int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6312  Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
6313  return Success(Operand, E);
6314  }
6315 
6316  case Builtin::BI__builtin_expect:
6317  return Visit(E->getArg(0));
6318 
6319  case Builtin::BI__builtin_ffs:
6320  case Builtin::BI__builtin_ffsl:
6321  case Builtin::BI__builtin_ffsll: {
6322  APSInt Val;
6323  if (!EvaluateInteger(E->getArg(0), Val, Info))
6324  return false;
6325 
6326  unsigned N = Val.countTrailingZeros();
6327  return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
6328  }
6329 
6330  case Builtin::BI__builtin_fpclassify: {
6331  APFloat Val(0.0);
6332  if (!EvaluateFloat(E->getArg(5), Val, Info))
6333  return false;
6334  unsigned Arg;
6335  switch (Val.getCategory()) {
6336  case APFloat::fcNaN: Arg = 0; break;
6337  case APFloat::fcInfinity: Arg = 1; break;
6338  case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
6339  case APFloat::fcZero: Arg = 4; break;
6340  }
6341  return Visit(E->getArg(Arg));
6342  }
6343 
6344  case Builtin::BI__builtin_isinf_sign: {
6345  APFloat Val(0.0);
6346  return EvaluateFloat(E->getArg(0), Val, Info) &&
6347  Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
6348  }
6349 
6350  case Builtin::BI__builtin_isinf: {
6351  APFloat Val(0.0);
6352  return EvaluateFloat(E->getArg(0), Val, Info) &&
6353  Success(Val.isInfinity() ? 1 : 0, E);
6354  }
6355 
6356  case Builtin::BI__builtin_isfinite: {
6357  APFloat Val(0.0);
6358  return EvaluateFloat(E->getArg(0), Val, Info) &&
6359  Success(Val.isFinite() ? 1 : 0, E);
6360  }
6361 
6362  case Builtin::BI__builtin_isnan: {
6363  APFloat Val(0.0);
6364  return EvaluateFloat(E->getArg(0), Val, Info) &&
6365  Success(Val.isNaN() ? 1 : 0, E);
6366  }
6367 
6368  case Builtin::BI__builtin_isnormal: {
6369  APFloat Val(0.0);
6370  return EvaluateFloat(E->getArg(0), Val, Info) &&
6371  Success(Val.isNormal() ? 1 : 0, E);
6372  }
6373 
6374  case Builtin::BI__builtin_parity:
6375  case Builtin::BI__builtin_parityl:
6376  case Builtin::BI__builtin_parityll: {
6377  APSInt Val;
6378  if (!EvaluateInteger(E->getArg(0), Val, Info))
6379  return false;
6380 
6381  return Success(Val.countPopulation() % 2, E);
6382  }
6383 
6384  case Builtin::BI__builtin_popcount:
6385  case Builtin::BI__builtin_popcountl:
6386  case Builtin::BI__builtin_popcountll: {
6387  APSInt Val;
6388  if (!EvaluateInteger(E->getArg(0), Val, Info))
6389  return false;
6390 
6391  return Success(Val.countPopulation(), E);
6392  }
6393 
6394  case Builtin::BIstrlen:
6395  // A call to strlen is not a constant expression.
6396  if (Info.getLangOpts().CPlusPlus11)
6397  Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6398  << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
6399  else
6400  Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
6401  // Fall through.
6402  case Builtin::BI__builtin_strlen: {
6403  // As an extension, we support __builtin_strlen() as a constant expression,
6404  // and support folding strlen() to a constant.
6405  LValue String;
6406  if (!EvaluatePointer(E->getArg(0), String, Info))
6407  return false;
6408 
6409  // Fast path: if it's a string literal, search the string value.
6410  if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
6411  String.getLValueBase().dyn_cast<const Expr *>())) {
6412  // The string literal may have embedded null characters. Find the first
6413  // one and truncate there.
6414  StringRef Str = S->getBytes();
6415  int64_t Off = String.Offset.getQuantity();
6416  if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
6417  S->getCharByteWidth() == 1) {
6418  Str = Str.substr(Off);
6419 
6420  StringRef::size_type Pos = Str.find(0);
6421  if (Pos != StringRef::npos)
6422  Str = Str.substr(0, Pos);
6423 
6424  return Success(Str.size(), E);
6425  }
6426 
6427  // Fall through to slow path to issue appropriate diagnostic.
6428  }
6429 
6430  // Slow path: scan the bytes of the string looking for the terminating 0.
6431  QualType CharTy = E->getArg(0)->getType()->getPointeeType();
6432  for (uint64_t Strlen = 0; /**/; ++Strlen) {
6433  APValue Char;
6434  if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
6435  !Char.isInt())
6436  return false;
6437  if (!Char.getInt())
6438  return Success(Strlen, E);
6439  if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
6440  return false;
6441  }
6442  }
6443 
6444  case Builtin::BI__atomic_always_lock_free:
6445  case Builtin::BI__atomic_is_lock_free:
6446  case Builtin::BI__c11_atomic_is_lock_free: {
6447  APSInt SizeVal;
6448  if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
6449  return false;
6450 
6451  // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
6452  // of two less than the maximum inline atomic width, we know it is
6453  // lock-free. If the size isn't a power of two, or greater than the
6454  // maximum alignment where we promote atomics, we know it is not lock-free
6455  // (at least not in the sense of atomic_is_lock_free). Otherwise,
6456  // the answer can only be determined at runtime; for example, 16-byte
6457  // atomics have lock-free implementations on some, but not all,
6458  // x86-64 processors.
6459 
6460  // Check power-of-two.
6461  CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
6462  if (Size.isPowerOfTwo()) {
6463  // Check against inlining width.
6464  unsigned InlineWidthBits =
6465  Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
6466  if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
6467  if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
6468  Size == CharUnits::One() ||
6469  E->getArg(1)->isNullPointerConstant(Info.Ctx,
6470  Expr::NPC_NeverValueDependent))
6471  // OK, we will inline appropriately-aligned operations of this size,
6472  // and _Atomic(T) is appropriately-aligned.
6473  return Success(1, E);
6474 
6475  QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
6476  castAs<PointerType>()->getPointeeType();
6477  if (!PointeeType->isIncompleteType() &&
6478  Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
6479  // OK, we will inline operations on this object.
6480  return Success(1, E);
6481  }
6482  }
6483  }
6484 
6485  return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
6486  Success(0, E) : Error(E);
6487  }
6488  }
6489 }
6490 
6491 static bool HasSameBase(const LValue &A, const LValue &B) {
6492  if (!A.getLValueBase())
6493  return !B.getLValueBase();
6494  if (!B.getLValueBase())
6495  return false;
6496 
6497  if (A.getLValueBase().getOpaqueValue() !=
6498  B.getLValueBase().getOpaqueValue()) {
6499  const Decl *ADecl = GetLValueBaseDecl(A);
6500  if (!ADecl)
6501  return false;
6502  const Decl *BDecl = GetLValueBaseDecl(B);
6503  if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
6504  return false;
6505  }
6506 
6507  return IsGlobalLValue(A.getLValueBase()) ||
6508  A.getLValueCallIndex() == B.getLValueCallIndex();
6509 }
6510 
6511 /// \brief Determine whether this is a pointer past the end of the complete
6512 /// object referred to by the lvalue.
6514  const LValue &LV) {
6515  // A null pointer can be viewed as being "past the end" but we don't
6516  // choose to look at it that way here.
6517  if (!LV.getLValueBase())
6518  return false;
6519 
6520  // If the designator is valid and refers to a subobject, we're not pointing
6521  // past the end.
6522  if (!LV.getLValueDesignator().Invalid &&
6523  !LV.getLValueDesignator().isOnePastTheEnd())
6524  return false;
6525 
6526  // We're a past-the-end pointer if we point to the byte after the object,
6527  // no matter what our type or path is.
6528  auto Size = Ctx.getTypeSizeInChars(getType(LV.getLValueBase()));
6529  return LV.getLValueOffset() == Size;
6530 }
6531 
6532 namespace {
6533 
6534 /// \brief Data recursive integer evaluator of certain binary operators.
6535 ///
6536 /// We use a data recursive algorithm for binary operators so that we are able
6537 /// to handle extreme cases of chained binary operators without causing stack
6538 /// overflow.
6539 class DataRecursiveIntBinOpEvaluator {
6540  struct EvalResult {
6541  APValue Val;
6542  bool Failed;
6543 
6544  EvalResult() : Failed(false) { }
6545 
6546  void swap(EvalResult &RHS) {
6547  Val.swap(RHS.Val);
6548  Failed = RHS.Failed;
6549  RHS.Failed = false;
6550  }
6551  };
6552 
6553  struct Job {
6554  const Expr *E;
6555  EvalResult LHSResult; // meaningful only for binary operator expression.
6556  enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
6557 
6558  Job() : StoredInfo(nullptr) {}
6559  void startSpeculativeEval(EvalInfo &Info) {
6560  OldEvalStatus = Info.EvalStatus;
6561  Info.EvalStatus.Diag = nullptr;
6562  StoredInfo = &Info;
6563  }
6564  ~Job() {
6565  if (StoredInfo) {
6566  StoredInfo->EvalStatus = OldEvalStatus;
6567  }
6568  }
6569  private:
6570  EvalInfo *StoredInfo; // non-null if status changed.
6571  Expr::EvalStatus OldEvalStatus;
6572  };
6573 
6574  SmallVector<Job, 16> Queue;
6575 
6576  IntExprEvaluator &IntEval;
6577  EvalInfo &Info;
6578  APValue &FinalResult;
6579 
6580 public:
6581  DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
6582  : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
6583 
6584  /// \brief True if \param E is a binary operator that we are going to handle
6585  /// data recursively.
6586  /// We handle binary operators that are comma, logical, or that have operands
6587  /// with integral or enumeration type.
6588  static bool shouldEnqueue(const BinaryOperator *E) {
6589  return E->getOpcode() == BO_Comma ||
6590  E->isLogicalOp() ||
6593  }
6594 
6595  bool Traverse(const BinaryOperator *E) {
6596  enqueue(E);
6597  EvalResult PrevResult;
6598  while (!Queue.empty())
6599  process(PrevResult);
6600 
6601  if (PrevResult.Failed) return false;
6602 
6603  FinalResult.swap(PrevResult.Val);
6604  return true;
6605  }
6606 
6607 private:
6608  bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6609  return IntEval.Success(Value, E, Result);
6610  }
6611  bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
6612  return IntEval.Success(Value, E, Result);
6613  }
6614  bool Error(const Expr *E) {
6615  return IntEval.Error(E);
6616  }
6617  bool Error(const Expr *E, diag::kind D) {
6618  return IntEval.Error(E, D);
6619  }
6620 
6621  OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
6622  return Info.CCEDiag(E, D);
6623  }
6624 
6625  // \brief Returns true if visiting the RHS is necessary, false otherwise.
6626  bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
6627  bool &SuppressRHSDiags);
6628 
6629  bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6630  const BinaryOperator *E, APValue &Result);
6631 
6632  void EvaluateExpr(const Expr *E, EvalResult &Result) {
6633  Result.Failed = !Evaluate(Result.Val, Info, E);
6634  if (Result.Failed)
6635  Result.Val = APValue();
6636  }
6637 
6638  void process(EvalResult &Result);
6639 
6640  void enqueue(const Expr *E) {
6641  E = E->IgnoreParens();
6642  Queue.resize(Queue.size()+1);
6643  Queue.back().E = E;
6644  Queue.back().Kind = Job::AnyExprKind;
6645  }
6646 };
6647 
6648 }
6649 
6650 bool DataRecursiveIntBinOpEvaluator::
6651  VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
6652  bool &SuppressRHSDiags) {
6653  if (E->getOpcode() == BO_Comma) {
6654  // Ignore LHS but note if we could not evaluate it.
6655  if (LHSResult.Failed)
6656  return Info.noteSideEffect();
6657  return true;
6658  }
6659 
6660  if (E->isLogicalOp()) {
6661  bool LHSAsBool;
6662  if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
6663  // We were able to evaluate the LHS, see if we can get away with not
6664  // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
6665  if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
6666  Success(LHSAsBool, E, LHSResult.Val);
6667  return false; // Ignore RHS
6668  }
6669  } else {
6670  LHSResult.Failed = true;
6671 
6672  // Since we weren't able to evaluate the left hand side, it
6673  // must have had side effects.
6674  if (!Info.noteSideEffect())
6675  return false;
6676 
6677  // We can't evaluate the LHS; however, sometimes the result
6678  // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6679  // Don't ignore RHS and suppress diagnostics from this arm.
6680  SuppressRHSDiags = true;
6681  }
6682 
6683  return true;
6684  }
6685 
6686  assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6688 
6689  if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
6690  return false; // Ignore RHS;
6691 
6692  return true;
6693 }
6694 
6695 bool DataRecursiveIntBinOpEvaluator::
6696  VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6697  const BinaryOperator *E, APValue &Result) {
6698  if (E->getOpcode() == BO_Comma) {
6699  if (RHSResult.Failed)
6700  return false;
6701  Result = RHSResult.Val;
6702  return true;
6703  }
6704 
6705  if (E->isLogicalOp()) {
6706  bool lhsResult, rhsResult;
6707  bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
6708  bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
6709 
6710  if (LHSIsOK) {
6711  if (RHSIsOK) {
6712  if (E->getOpcode() == BO_LOr)
6713  return Success(lhsResult || rhsResult, E, Result);
6714  else
6715  return Success(lhsResult && rhsResult, E, Result);
6716  }
6717  } else {
6718  if (RHSIsOK) {
6719  // We can't evaluate the LHS; however, sometimes the result
6720  // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6721  if (rhsResult == (E->getOpcode() == BO_LOr))
6722  return Success(rhsResult, E, Result);
6723  }
6724  }
6725 
6726  return false;
6727  }
6728 
6729  assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6731 
6732  if (LHSResult.Failed || RHSResult.Failed)
6733  return false;
6734 
6735  const APValue &LHSVal = LHSResult.Val;
6736  const APValue &RHSVal = RHSResult.Val;
6737 
6738  // Handle cases like (unsigned long)&a + 4.
6739  if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
6740  Result = LHSVal;
6741  CharUnits AdditionalOffset =
6742  CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
6743  if (E->getOpcode() == BO_Add)
6744  Result.getLValueOffset() += AdditionalOffset;
6745  else
6746  Result.getLValueOffset() -= AdditionalOffset;
6747  return true;
6748  }
6749 
6750  // Handle cases like 4 + (unsigned long)&a
6751  if (E->getOpcode() == BO_Add &&
6752  RHSVal.isLValue() && LHSVal.isInt()) {
6753  Result = RHSVal;
6754  Result.getLValueOffset() +=
6755  CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
6756  return true;
6757  }
6758 
6759  if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
6760  // Handle (intptr_t)&&A - (intptr_t)&&B.
6761  if (!LHSVal.getLValueOffset().isZero() ||
6762  !RHSVal.getLValueOffset().isZero())
6763  return false;
6764  const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
6765  const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
6766  if (!LHSExpr || !RHSExpr)
6767  return false;
6768  const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6769  const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6770  if (!LHSAddrExpr || !RHSAddrExpr)
6771  return false;
6772  // Make sure both labels come from the same function.
6773  if (LHSAddrExpr->getLabel()->getDeclContext() !=
6774  RHSAddrExpr->getLabel()->getDeclContext())
6775  return false;
6776  Result = APValue(LHSAddrExpr, RHSAddrExpr);
6777  return true;
6778  }
6779 
6780  // All the remaining cases expect both operands to be an integer
6781  if (!LHSVal.isInt() || !RHSVal.isInt())
6782  return Error(E);
6783 
6784  // Set up the width and signedness manually, in case it can't be deduced
6785  // from the operation we're performing.
6786  // FIXME: Don't do this in the cases where we can deduce it.
6787  APSInt Value(Info.Ctx.getIntWidth(E->getType()),
6789  if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
6790  RHSVal.getInt(), Value))
6791  return false;
6792  return Success(Value, E, Result);
6793 }
6794 
6795 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
6796  Job &job = Queue.back();
6797 
6798  switch (job.Kind) {
6799  case Job::AnyExprKind: {
6800  if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
6801  if (shouldEnqueue(Bop)) {
6802  job.Kind = Job::BinOpKind;
6803  enqueue(Bop->getLHS());
6804  return;
6805  }
6806  }
6807 
6808  EvaluateExpr(job.E, Result);
6809  Queue.pop_back();
6810  return;
6811  }
6812 
6813  case Job::BinOpKind: {
6814  const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
6815  bool SuppressRHSDiags = false;
6816  if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
6817  Queue.pop_back();
6818  return;
6819  }
6820  if (SuppressRHSDiags)
6821  job.startSpeculativeEval(Info);
6822  job.LHSResult.swap(Result);
6823  job.Kind = Job::BinOpVisitedLHSKind;
6824  enqueue(Bop->getRHS());
6825  return;
6826  }
6827 
6828  case Job::BinOpVisitedLHSKind: {
6829  const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
6830  EvalResult RHS;
6831  RHS.swap(Result);
6832  Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
6833  Queue.pop_back();
6834  return;
6835  }
6836  }
6837 
6838  llvm_unreachable("Invalid Job::Kind!");
6839 }
6840 
6841 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
6842  if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
6843  return Error(E);
6844 
6845  if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
6846  return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
6847 
6848  QualType LHSTy = E->getLHS()->getType();
6849  QualType RHSTy = E->getRHS()->getType();
6850 
6851  if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
6852  ComplexValue LHS, RHS;
6853  bool LHSOK;
6854  if (E->isAssignmentOp()) {
6855  LValue LV;
6856  EvaluateLValue(E->getLHS(), LV, Info);
6857  LHSOK = false;
6858  } else if (LHSTy->isRealFloatingType()) {
6859  LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
6860  if (LHSOK) {
6861  LHS.makeComplexFloat();
6862  LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
6863  }
6864  } else {
6865  LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
6866  }
6867  if (!LHSOK && !Info.keepEvaluatingAfterFailure())
6868  return false;
6869 
6870  if (E->getRHS()->getType()->isRealFloatingType()) {
6871  if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
6872  return false;
6873  RHS.makeComplexFloat();
6874  RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
6875  } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
6876  return false;
6877 
6878  if (LHS.isComplexFloat()) {
6879  APFloat::cmpResult CR_r =
6880  LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
6881  APFloat::cmpResult CR_i =
6882  LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
6883 
6884  if (E->getOpcode() == BO_EQ)
6885  return Success((CR_r == APFloat::cmpEqual &&
6886  CR_i == APFloat::cmpEqual), E);
6887  else {
6888  assert(E->getOpcode() == BO_NE &&
6889  "Invalid complex comparison.");
6890  return Success(((CR_r == APFloat::cmpGreaterThan ||
6891  CR_r == APFloat::cmpLessThan ||
6892  CR_r == APFloat::cmpUnordered) ||
6893  (CR_i == APFloat::cmpGreaterThan ||
6894  CR_i == APFloat::cmpLessThan ||
6895  CR_i == APFloat::cmpUnordered)), E);
6896  }
6897  } else {
6898  if (E->getOpcode() == BO_EQ)
6899  return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
6900  LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
6901  else {
6902  assert(E->getOpcode() == BO_NE &&
6903  "Invalid compex comparison.");
6904  return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
6905  LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
6906  }
6907  }
6908  }
6909 
6910  if (LHSTy->isRealFloatingType() &&
6911  RHSTy->isRealFloatingType()) {
6912  APFloat RHS(0.0), LHS(0.0);
6913 
6914  bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
6915  if (!LHSOK && !Info.keepEvaluatingAfterFailure())
6916  return false;
6917 
6918  if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
6919  return false;
6920 
6921  APFloat::cmpResult CR = LHS.compare(RHS);
6922 
6923  switch (E->getOpcode()) {
6924  default:
6925  llvm_unreachable("Invalid binary operator!");
6926  case BO_LT:
6927  return Success(CR == APFloat::cmpLessThan, E);
6928  case BO_GT:
6929  return Success(CR == APFloat::cmpGreaterThan, E);
6930  case BO_LE:
6931  return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
6932  case BO_GE:
6933  return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
6934  E);
6935  case BO_EQ:
6936  return Success(CR == APFloat::cmpEqual, E);
6937  case BO_NE:
6938  return Success(CR == APFloat::cmpGreaterThan
6939  || CR == APFloat::cmpLessThan
6940  || CR == APFloat::cmpUnordered, E);
6941  }
6942  }
6943 
6944  if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
6945  if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
6946  LValue LHSValue, RHSValue;
6947 
6948  bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
6949  if (!LHSOK && Info.keepEvaluatingAfterFailure())
6950  return false;
6951 
6952  if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
6953  return false;
6954 
6955  // Reject differing bases from the normal codepath; we special-case
6956  // comparisons to null.
6957  if (!HasSameBase(LHSValue, RHSValue)) {
6958  if (E->getOpcode() == BO_Sub) {
6959  // Handle &&A - &&B.
6960  if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
6961  return false;
6962  const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
6963  const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
6964  if (!LHSExpr || !RHSExpr)
6965  return false;
6966  const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6967  const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6968  if (!LHSAddrExpr || !RHSAddrExpr)
6969  return false;
6970  // Make sure both labels come from the same function.
6971  if (LHSAddrExpr->getLabel()->getDeclContext() !=
6972  RHSAddrExpr->getLabel()->getDeclContext())
6973  return false;
6974  Result = APValue(LHSAddrExpr, RHSAddrExpr);
6975  return true;
6976  }
6977  // Inequalities and subtractions between unrelated pointers have
6978  // unspecified or undefined behavior.
6979  if (!E->isEqualityOp())
6980  return Error(E);
6981  // A constant address may compare equal to the address of a symbol.
6982  // The one exception is that address of an object cannot compare equal
6983  // to a null pointer constant.
6984  if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
6985  (!RHSValue.Base && !RHSValue.Offset.isZero()))
6986  return Error(E);
6987  // It's implementation-defined whether distinct literals will have
6988  // distinct addresses. In clang, the result of such a comparison is
6989  // unspecified, so it is not a constant expression. However, we do know
6990  // that the address of a literal will be non-null.
6991  if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
6992  LHSValue.Base && RHSValue.Base)
6993  return Error(E);
6994  // We can't tell whether weak symbols will end up pointing to the same
6995  // object.
6996  if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
6997  return Error(E);
6998  // We can't compare the address of the start of one object with the
6999  // past-the-end address of another object, per C++ DR1652.
7000  if ((LHSValue.Base && LHSValue.Offset.isZero() &&
7001  isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
7002  (RHSValue.Base && RHSValue.Offset.isZero() &&
7003  isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
7004  return Error(E);
7005  // We can't tell whether an object is at the same address as another
7006  // zero sized object.
7007  if ((RHSValue.Base && isZeroSized(LHSValue)) ||
7008  (LHSValue.Base && isZeroSized(RHSValue)))
7009  return Error(E);
7010  // Pointers with different bases cannot represent the same object.
7011  // (Note that clang defaults to -fmerge-all-constants, which can
7012  // lead to inconsistent results for comparisons involving the address
7013  // of a constant; this generally doesn't matter in practice.)
7014  return Success(E->getOpcode() == BO_NE, E);
7015  }
7016 
7017  const CharUnits &LHSOffset = LHSValue.getLValueOffset();
7018  const CharUnits &RHSOffset = RHSValue.getLValueOffset();
7019 
7020  SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
7021  SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
7022 
7023  if (E->getOpcode() == BO_Sub) {
7024  // C++11 [expr.add]p6:
7025  // Unless both pointers point to elements of the same array object, or
7026  // one past the last element of the array object, the behavior is
7027  // undefined.
7028  if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7029  !AreElementsOfSameArray(getType(LHSValue.Base),
7030  LHSDesignator, RHSDesignator))
7031  CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
7032 
7033  QualType Type = E->getLHS()->getType();
7034  QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
7035 
7036  CharUnits ElementSize;
7037  if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
7038  return false;
7039 
7040  // As an extension, a type may have zero size (empty struct or union in
7041  // C, array of zero length). Pointer subtraction in such cases has
7042  // undefined behavior, so is not constant.
7043  if (ElementSize.isZero()) {
7044  Info.Diag(E, diag::note_constexpr_pointer_subtraction_zero_size)
7045  << ElementType;
7046  return false;
7047  }
7048 
7049  // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
7050  // and produce incorrect results when it overflows. Such behavior
7051  // appears to be non-conforming, but is common, so perhaps we should
7052  // assume the standard intended for such cases to be undefined behavior
7053  // and check for them.
7054 
7055  // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
7056  // overflow in the final conversion to ptrdiff_t.
7057  APSInt LHS(
7058  llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
7059  APSInt RHS(
7060  llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
7061  APSInt ElemSize(
7062  llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
7063  APSInt TrueResult = (LHS - RHS) / ElemSize;
7064  APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
7065 
7066  if (Result.extend(65) != TrueResult)
7067  HandleOverflow(Info, E, TrueResult, E->getType());
7068  return Success(Result, E);
7069  }
7070 
7071  // C++11 [expr.rel]p3:
7072  // Pointers to void (after pointer conversions) can be compared, with a
7073  // result defined as follows: If both pointers represent the same
7074  // address or are both the null pointer value, the result is true if the
7075  // operator is <= or >= and false otherwise; otherwise the result is
7076  // unspecified.
7077  // We interpret this as applying to pointers to *cv* void.
7078  if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
7079  E->isRelationalOp())
7080  CCEDiag(E, diag::note_constexpr_void_comparison);
7081 
7082  // C++11 [expr.rel]p2:
7083  // - If two pointers point to non-static data members of the same object,
7084  // or to subobjects or array elements fo such members, recursively, the
7085  // pointer to the later declared member compares greater provided the
7086  // two members have the same access control and provided their class is
7087  // not a union.
7088  // [...]
7089  // - Otherwise pointer comparisons are unspecified.
7090  if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7091  E->isRelationalOp()) {
7092  bool WasArrayIndex;
7093  unsigned Mismatch =
7094  FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
7095  RHSDesignator, WasArrayIndex);
7096  // At the point where the designators diverge, the comparison has a
7097  // specified value if:
7098  // - we are comparing array indices
7099  // - we are comparing fields of a union, or fields with the same access
7100  // Otherwise, the result is unspecified and thus the comparison is not a
7101  // constant expression.
7102  if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
7103  Mismatch < RHSDesignator.Entries.size()) {
7104  const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
7105  const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
7106  if (!LF && !RF)
7107  CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
7108  else if (!LF)
7109  CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7110  << getAsBaseClass(LHSDesignator.Entries[Mismatch])
7111  << RF->getParent() << RF;
7112  else if (!RF)
7113  CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7114  << getAsBaseClass(RHSDesignator.Entries[Mismatch])
7115  << LF->getParent() << LF;
7116  else if (!LF->getParent()->isUnion() &&
7117  LF->getAccess() != RF->getAccess())
7118  CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
7119  << LF << LF->getAccess() << RF << RF->getAccess()
7120  << LF->getParent();
7121  }
7122  }
7123 
7124  // The comparison here must be unsigned, and performed with the same
7125  // width as the pointer.
7126  unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
7127  uint64_t CompareLHS = LHSOffset.getQuantity();
7128  uint64_t CompareRHS = RHSOffset.getQuantity();
7129  assert(PtrSize <= 64 && "Unexpected pointer width");
7130  uint64_t Mask = ~0ULL >> (64 - PtrSize);
7131  CompareLHS &= Mask;
7132  CompareRHS &= Mask;
7133 
7134  // If there is a base and this is a relational operator, we can only
7135  // compare pointers within the object in question; otherwise, the result
7136  // depends on where the object is located in memory.
7137  if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
7138  QualType BaseTy = getType(LHSValue.Base);
7139  if (BaseTy->isIncompleteType())
7140  return Error(E);
7141  CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
7142  uint64_t OffsetLimit = Size.getQuantity();
7143  if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
7144  return Error(E);
7145  }
7146 
7147  switch (E->getOpcode()) {
7148  default: llvm_unreachable("missing comparison operator");
7149  case BO_LT: return Success(CompareLHS < CompareRHS, E);
7150  case BO_GT: return Success(CompareLHS > CompareRHS, E);
7151  case BO_LE: return Success(CompareLHS <= CompareRHS, E);
7152  case BO_GE: return Success(CompareLHS >= CompareRHS, E);
7153  case BO_EQ: return Success(CompareLHS == CompareRHS, E);
7154  case BO_NE: return Success(CompareLHS != CompareRHS, E);
7155  }
7156  }
7157  }
7158 
7159  if (LHSTy->isMemberPointerType()) {
7160  assert(E->isEqualityOp() && "unexpected member pointer operation");
7161  assert(RHSTy->isMemberPointerType() && "invalid comparison");
7162 
7163  MemberPtr LHSValue, RHSValue;
7164 
7165  bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
7166  if (!LHSOK && Info.keepEvaluatingAfterFailure())
7167  return false;
7168 
7169  if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
7170  return false;
7171 
7172  // C++11 [expr.eq]p2:
7173  // If both operands are null, they compare equal. Otherwise if only one is
7174  // null, they compare unequal.
7175  if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
7176  bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
7177  return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
7178  }
7179 
7180  // Otherwise if either is a pointer to a virtual member function, the
7181  // result is unspecified.
7182  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
7183  if (MD->isVirtual())
7184  CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
7185  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
7186  if (MD->isVirtual())
7187  CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
7188 
7189  // Otherwise they compare equal if and only if they would refer to the
7190  // same member of the same most derived object or the same subobject if
7191  // they were dereferenced with a hypothetical object of the associated
7192  // class type.
7193  bool Equal = LHSValue == RHSValue;
7194  return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
7195  }
7196 
7197  if (LHSTy->isNullPtrType()) {
7198  assert(E->isComparisonOp() && "unexpected nullptr operation");
7199  assert(RHSTy->isNullPtrType() && "missing pointer conversion");
7200  // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
7201  // are compared, the result is true of the operator is <=, >= or ==, and
7202  // false otherwise.
7203  BinaryOperator::Opcode Opcode = E->getOpcode();
7204  return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
7205  }
7206 
7207  assert((!LHSTy->isIntegralOrEnumerationType() ||
7208  !RHSTy->isIntegralOrEnumerationType()) &&
7209  "DataRecursiveIntBinOpEvaluator should have handled integral types");
7210  // We can't continue from here for non-integral types.
7211  return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7212 }
7213 
7214 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
7215 /// a result as the expression's type.
7216 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
7217  const UnaryExprOrTypeTraitExpr *E) {
7218  switch(E->getKind()) {
7219  case UETT_AlignOf: {
7220  if (E->isArgumentType())
7221  return Success(GetAlignOfType(Info, E->getArgumentType()), E);
7222  else
7223  return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
7224  }
7225 
7226  case UETT_VecStep: {
7227  QualType Ty = E->getTypeOfArgument();
7228 
7229  if (Ty->isVectorType()) {
7230  unsigned n = Ty->castAs<VectorType>()->getNumElements();
7231 
7232  // The vec_step built-in functions that take a 3-component
7233  // vector return 4. (OpenCL 1.1 spec 6.11.12)
7234  if (n == 3)
7235  n = 4;
7236 
7237  return Success(n, E);
7238  } else
7239  return Success(1, E);
7240  }
7241 
7242  case UETT_SizeOf: {
7243  QualType SrcTy = E->getTypeOfArgument();
7244  // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
7245  // the result is the size of the referenced type."
7246  if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
7247  SrcTy = Ref->getPointeeType();
7248 
7249  CharUnits Sizeof;
7250  if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
7251  return false;
7252  return Success(Sizeof, E);
7253  }
7255  assert(E->isArgumentType());
7256  return Success(
7257  Info.Ctx.toCharUnitsFromBits(
7258  Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
7259  .getQuantity(),
7260  E);
7261  }
7262 
7263  llvm_unreachable("unknown expr/type trait");
7264 }
7265 
7266 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
7267  CharUnits Result;
7268  unsigned n = OOE->getNumComponents();
7269  if (n == 0)
7270  return Error(OOE);
7271  QualType CurrentType = OOE->getTypeSourceInfo()->getType();
7272  for (unsigned i = 0; i != n; ++i) {
7274  switch (ON.getKind()) {
7275  case OffsetOfExpr::OffsetOfNode::Array: {
7276  const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
7277  APSInt IdxResult;
7278  if (!EvaluateInteger(Idx, IdxResult, Info))
7279  return false;
7280  const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
7281  if (!AT)
7282  return Error(OOE);
7283  CurrentType = AT->getElementType();
7284  CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
7285  Result += IdxResult.getSExtValue() * ElementSize;
7286  break;
7287  }
7288 
7289  case OffsetOfExpr::OffsetOfNode::Field: {
7290  FieldDecl *MemberDecl = ON.getField();
7291  const RecordType *RT = CurrentType->getAs<RecordType>();
7292  if (!RT)
7293  return Error(OOE);
7294  RecordDecl *RD = RT->getDecl();
7295  if (RD->isInvalidDecl()) return false;
7296  const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
7297  unsigned i = MemberDecl->getFieldIndex();
7298  assert(i < RL.getFieldCount() && "offsetof field in wrong type");
7299  Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
7300  CurrentType = MemberDecl->getType().getNonReferenceType();
7301  break;
7302  }
7303 
7304  case OffsetOfExpr::OffsetOfNode::Identifier:
7305  llvm_unreachable("dependent __builtin_offsetof");
7306 
7307  case OffsetOfExpr::OffsetOfNode::Base: {
7308  CXXBaseSpecifier *BaseSpec = ON.getBase();
7309  if (BaseSpec->isVirtual())
7310  return Error(OOE);
7311 
7312  // Find the layout of the class whose base we are looking into.
7313  const RecordType *RT = CurrentType->getAs<RecordType>();
7314  if (!RT)
7315  return Error(OOE);
7316  RecordDecl *RD = RT->getDecl();
7317  if (RD->isInvalidDecl()) return false;
7318  const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
7319 
7320  // Find the base class itself.
7321  CurrentType = BaseSpec->getType();
7322  const RecordType *BaseRT = CurrentType->getAs<RecordType>();
7323  if (!BaseRT)
7324  return Error(OOE);
7325 
7326  // Add the offset to the base.
7327  Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
7328  break;
7329  }
7330  }
7331  }
7332  return Success(Result, OOE);
7333 }
7334 
7335 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
7336  switch (E->getOpcode()) {
7337  default:
7338  // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
7339  // See C99 6.6p3.
7340  return Error(E);
7341  case UO_Extension:
7342  // FIXME: Should extension allow i-c-e extension expressions in its scope?
7343  // If so, we could clear the diagnostic ID.
7344  return Visit(E->getSubExpr());
7345  case UO_Plus:
7346  // The result is just the value.
7347  return Visit(E->getSubExpr());
7348  case UO_Minus: {
7349  if (!Visit(E->getSubExpr()))
7350  return false;
7351  if (!Result.isInt()) return Error(E);
7352  const APSInt &Value = Result.getInt();
7353  if (Value.isSigned() && Value.isMinSignedValue())
7354  HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
7355  E->getType());
7356  return Success(-Value, E);
7357  }
7358  case UO_Not: {
7359  if (!Visit(E->getSubExpr()))
7360  return false;
7361  if (!Result.isInt()) return Error(E);
7362  return Success(~Result.getInt(), E);
7363  }
7364  case UO_LNot: {
7365  bool bres;
7366  if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
7367  return false;
7368  return Success(!bres, E);
7369  }
7370  }
7371 }
7372 
7373 /// HandleCast - This is used to evaluate implicit or explicit casts where the
7374 /// result type is integer.
7375 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
7376  const Expr *SubExpr = E->getSubExpr();
7377  QualType DestType = E->getType();
7378  QualType SrcType = SubExpr->getType();
7379 
7380  switch (E->getCastKind()) {
7381  case CK_BaseToDerived:
7382  case CK_DerivedToBase:
7384  case CK_Dynamic:
7385  case CK_ToUnion:
7388  case CK_NullToPointer:
7394  case CK_IntegralToPointer:
7395  case CK_ToVoid:
7396  case CK_VectorSplat:
7397  case CK_IntegralToFloating:
7398  case CK_FloatingCast:
7410  case CK_BuiltinFnToFnPtr:
7411  case CK_ZeroToOCLEvent:
7412  case CK_NonAtomicToAtomic:
7414  llvm_unreachable("invalid cast kind for integral value");
7415 
7416  case CK_BitCast:
7417  case CK_Dependent:
7418  case CK_LValueBitCast:
7419  case CK_ARCProduceObject:
7420  case CK_ARCConsumeObject:
7424  return Error(E);
7425 
7427  case CK_LValueToRValue:
7428  case CK_AtomicToNonAtomic:
7429  case CK_NoOp:
7430  return ExprEvaluatorBaseTy::VisitCastExpr(E);
7431 
7433  case CK_PointerToBoolean:
7434  case CK_IntegralToBoolean:
7435  case CK_FloatingToBoolean:
7438  bool BoolResult;
7439  if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
7440  return false;
7441  return Success(BoolResult, E);
7442  }
7443 
7444  case CK_IntegralCast: {
7445  if (!Visit(SubExpr))
7446  return false;
7447 
7448  if (!Result.isInt()) {
7449  // Allow casts of address-of-label differences if they are no-ops
7450  // or narrowing. (The narrowing case isn't actually guaranteed to
7451  // be constant-evaluatable except in some narrow cases which are hard
7452  // to detect here. We let it through on the assumption the user knows
7453  // what they are doing.)
7454  if (Result.isAddrLabelDiff())
7455  return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
7456  // Only allow casts of lvalues if they are lossless.
7457  return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
7458  }
7459 
7460  return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
7461  Result.getInt()), E);
7462  }
7463 
7464  case CK_PointerToIntegral: {
7465  CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7466 
7467  LValue LV;
7468  if (!EvaluatePointer(SubExpr, LV, Info))
7469  return false;
7470 
7471  if (LV.getLValueBase()) {
7472  // Only allow based lvalue casts if they are lossless.
7473  // FIXME: Allow a larger integer size than the pointer size, and allow
7474  // narrowing back down to pointer width in subsequent integral casts.
7475  // FIXME: Check integer type's active bits, not its type size.
7476  if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
7477  return Error(E);
7478 
7479  LV.Designator.setInvalid();
7480  LV.moveInto(Result);
7481  return true;
7482  }
7483 
7484  APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
7485  SrcType);
7486  return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
7487  }
7488 
7489  case CK_IntegralComplexToReal: {
7490  ComplexValue C;
7491  if (!EvaluateComplex(SubExpr, C, Info))
7492  return false;
7493  return Success(C.getComplexIntReal(), E);
7494  }
7495 
7496  case CK_FloatingToIntegral: {
7497  APFloat F(0.0);
7498  if (!EvaluateFloat(SubExpr, F, Info))
7499  return false;
7500 
7501  APSInt Value;
7502  if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
7503  return false;
7504  return Success(Value, E);
7505  }
7506  }
7507 
7508  llvm_unreachable("unknown cast resulting in integral value");
7509 }
7510 
7511 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7512  if (E->getSubExpr()->getType()->isAnyComplexType()) {
7513  ComplexValue LV;
7514  if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7515  return false;
7516  if (!LV.isComplexInt())
7517  return Error(E);
7518  return Success(LV.getComplexIntReal(), E);
7519  }
7520 
7521  return Visit(E->getSubExpr());
7522 }
7523 
7524 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
7525  if (E->getSubExpr()->getType()->isComplexIntegerType()) {
7526  ComplexValue LV;
7527  if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7528  return false;
7529  if (!LV.isComplexInt())
7530  return Error(E);
7531  return Success(LV.getComplexIntImag(), E);
7532  }
7533 
7534  VisitIgnoredValue(E->getSubExpr());
7535  return Success(0, E);
7536 }
7537 
7538 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
7539  return Success(E->getPackLength(), E);
7540 }
7541 
7542 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
7543  return Success(E->getValue(), E);
7544 }
7545 
7546 //===----------------------------------------------------------------------===//
7547 // Float Evaluation
7548 //===----------------------------------------------------------------------===//
7549 
7550 namespace {
7551 class FloatExprEvaluator
7552  : public ExprEvaluatorBase<FloatExprEvaluator> {
7553  APFloat &Result;
7554 public:
7555  FloatExprEvaluator(EvalInfo &info, APFloat &result)
7556  : ExprEvaluatorBaseTy(info), Result(result) {}
7557 
7558  bool Success(const APValue &V, const Expr *e) {
7559  Result = V.getFloat();
7560  return true;
7561  }
7562 
7563  bool ZeroInitialization(const Expr *E) {
7564  Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
7565  return true;
7566  }
7567 
7568  bool VisitCallExpr(const CallExpr *E);
7569 
7570  bool VisitUnaryOperator(const UnaryOperator *E);
7571  bool VisitBinaryOperator(const BinaryOperator *E);
7572  bool VisitFloatingLiteral(const FloatingLiteral *E);
7573  bool VisitCastExpr(const CastExpr *E);
7574 
7575  bool VisitUnaryReal(const UnaryOperator *E);
7576  bool VisitUnaryImag(const UnaryOperator *E);
7577 
7578  // FIXME: Missing: array subscript of vector, member of vector
7579 };
7580 } // end anonymous namespace
7581 
7582 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
7583  assert(E->isRValue() && E->getType()->isRealFloatingType());
7584  return FloatExprEvaluator(Info, Result).Visit(E);
7585 }
7586 
7588  QualType ResultTy,
7589  const Expr *Arg,
7590  bool SNaN,
7591  llvm::APFloat &Result) {
7592  const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
7593  if (!S) return false;
7594 
7595  const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
7596 
7597  llvm::APInt fill;
7598 
7599  // Treat empty strings as if they were zero.
7600  if (S->getString().empty())
7601  fill = llvm::APInt(32, 0);
7602  else if (S->getString().getAsInteger(0, fill))
7603  return false;
7604 
7605  if (Context.getTargetInfo().isNan2008()) {
7606  if (SNaN)
7607  Result = llvm::APFloat::getSNaN(Sem, false, &fill);
7608  else
7609  Result = llvm::APFloat::getQNaN(Sem, false, &fill);
7610  } else {
7611  // Prior to IEEE 754-2008, architectures were allowed to choose whether
7612  // the first bit of their significand was set for qNaN or sNaN. MIPS chose
7613  // a different encoding to what became a standard in 2008, and for pre-
7614  // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
7615  // sNaN. This is now known as "legacy NaN" encoding.
7616  if (SNaN)
7617  Result = llvm::APFloat::getQNaN(Sem, false, &fill);
7618  else
7619  Result = llvm::APFloat::getSNaN(Sem, false, &fill);
7620  }
7621 
7622  return true;
7623 }
7624 
7625 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
7626  switch (E->getBuiltinCallee()) {
7627  default:
7628  return ExprEvaluatorBaseTy::VisitCallExpr(E);
7629 
7630  case Builtin::BI__builtin_huge_val:
7631  case Builtin::BI__builtin_huge_valf:
7632  case Builtin::BI__builtin_huge_vall:
7633  case Builtin::BI__builtin_inf:
7634  case Builtin::BI__builtin_inff:
7635  case Builtin::BI__builtin_infl: {
7636  const llvm::fltSemantics &Sem =
7637  Info.Ctx.getFloatTypeSemantics(E->getType());
7638  Result = llvm::APFloat::getInf(Sem);
7639  return true;
7640  }
7641 
7642  case Builtin::BI__builtin_nans:
7643  case Builtin::BI__builtin_nansf:
7644  case Builtin::BI__builtin_nansl:
7645  if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7646  true, Result))
7647  return Error(E);
7648  return true;
7649 
7650  case Builtin::BI__builtin_nan:
7651  case Builtin::BI__builtin_nanf:
7652  case Builtin::BI__builtin_nanl:
7653  // If this is __builtin_nan() turn this into a nan, otherwise we
7654  // can't constant fold it.
7655  if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7656  false, Result))
7657  return Error(E);
7658  return true;
7659 
7660  case Builtin::BI__builtin_fabs:
7661  case Builtin::BI__builtin_fabsf:
7662  case Builtin::BI__builtin_fabsl:
7663  if (!EvaluateFloat(E->getArg(0), Result, Info))
7664  return false;
7665 
7666  if (Result.isNegative())
7667  Result.changeSign();
7668  return true;
7669 
7670  // FIXME: Builtin::BI__builtin_powi
7671  // FIXME: Builtin::BI__builtin_powif
7672  // FIXME: Builtin::BI__builtin_powil
7673 
7674  case Builtin::BI__builtin_copysign:
7675  case Builtin::BI__builtin_copysignf:
7676  case Builtin::BI__builtin_copysignl: {
7677  APFloat RHS(0.);
7678  if (!EvaluateFloat(E->getArg(0), Result, Info) ||
7679  !EvaluateFloat(E->getArg(1), RHS, Info))
7680  return false;
7681  Result.copySign(RHS);
7682  return true;
7683  }
7684  }
7685 }
7686 
7687 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7688  if (E->getSubExpr()->getType()->isAnyComplexType()) {
7689  ComplexValue CV;
7690  if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7691  return false;
7692  Result = CV.FloatReal;
7693  return true;
7694  }
7695 
7696  return Visit(E->getSubExpr());
7697 }
7698 
7699 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
7700  if (E->getSubExpr()->getType()->isAnyComplexType()) {
7701  ComplexValue CV;
7702  if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7703  return false;
7704  Result = CV.FloatImag;
7705  return true;
7706  }
7707 
7708  VisitIgnoredValue(E->getSubExpr());
7709  const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
7710  Result = llvm::APFloat::getZero(Sem);
7711  return true;
7712 }
7713 
7714 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
7715  switch (E->getOpcode()) {
7716  default: return Error(E);
7717  case UO_Plus:
7718  return EvaluateFloat(E->getSubExpr(), Result, Info);
7719  case UO_Minus:
7720  if (!EvaluateFloat(E->getSubExpr(), Result, Info))
7721  return false;
7722  Result.changeSign();
7723  return true;
7724  }
7725 }
7726 
7727 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
7728  if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
7729  return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7730 
7731  APFloat RHS(0.0);
7732  bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
7733  if (!LHSOK && !Info.keepEvaluatingAfterFailure())
7734  return false;
7735  return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
7736  handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
7737 }
7738 
7739 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
7740  Result = E->getValue();
7741  return true;
7742 }
7743 
7744 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
7745  const Expr* SubExpr = E->getSubExpr();
7746 
7747  switch (E->getCastKind()) {
7748  default:
7749  return ExprEvaluatorBaseTy::VisitCastExpr(E);
7750 
7751  case CK_IntegralToFloating: {
7752  APSInt IntResult;
7753  return EvaluateInteger(SubExpr, IntResult, Info) &&
7754  HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
7755  E->getType(), Result);
7756  }
7757 
7758  case CK_FloatingCast: {
7759  if (!Visit(SubExpr))
7760  return false;
7761  return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
7762  Result);
7763  }
7764 
7765  case CK_FloatingComplexToReal: {
7766  ComplexValue V;
7767  if (!EvaluateComplex(SubExpr, V, Info))
7768  return false;
7769  Result = V.getComplexFloatReal();
7770  return true;
7771  }
7772  }
7773 }
7774 
7775 //===----------------------------------------------------------------------===//
7776 // Complex Evaluation (for float and integer)
7777 //===----------------------------------------------------------------------===//
7778 
7779 namespace {
7780 class ComplexExprEvaluator
7781  : public ExprEvaluatorBase<ComplexExprEvaluator> {
7782  ComplexValue &Result;
7783 
7784 public:
7785  ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
7786  : ExprEvaluatorBaseTy(info), Result(Result) {}
7787 
7788  bool Success(const APValue &V, const Expr *e) {
7789  Result.setFrom(V);
7790  return true;
7791  }
7792 
7793  bool ZeroInitialization(const Expr *E);
7794 
7795  //===--------------------------------------------------------------------===//
7796  // Visitor Methods
7797  //===--------------------------------------------------------------------===//
7798 
7799  bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
7800  bool VisitCastExpr(const CastExpr *E);
7801  bool VisitBinaryOperator(const BinaryOperator *E);
7802  bool VisitUnaryOperator(const UnaryOperator *E);
7803  bool VisitInitListExpr(const InitListExpr *E);
7804 };
7805 } // end anonymous namespace
7806 
7807 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
7808  EvalInfo &Info) {
7809  assert(E->isRValue() && E->getType()->isAnyComplexType());
7810  return ComplexExprEvaluator(Info, Result).Visit(E);
7811 }
7812 
7813 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
7814  QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
7815  if (ElemTy->isRealFloatingType()) {
7816  Result.makeComplexFloat();
7817  APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
7818  Result.FloatReal = Zero;
7819  Result.FloatImag = Zero;
7820  } else {
7821  Result.makeComplexInt();
7822  APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
7823  Result.IntReal = Zero;
7824  Result.IntImag = Zero;
7825  }
7826  return true;
7827 }
7828 
7829 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
7830  const Expr* SubExpr = E->getSubExpr();
7831 
7832  if (SubExpr->getType()->isRealFloatingType()) {
7833  Result.makeComplexFloat();
7834  APFloat &Imag = Result.FloatImag;
7835  if (!EvaluateFloat(SubExpr, Imag, Info))
7836  return false;
7837 
7838  Result.FloatReal = APFloat(Imag.getSemantics());
7839  return true;
7840  } else {
7841  assert(SubExpr->getType()->isIntegerType() &&
7842  "Unexpected imaginary literal.");
7843 
7844  Result.makeComplexInt();
7845  APSInt &Imag = Result.IntImag;
7846  if (!EvaluateInteger(SubExpr, Imag, Info))
7847  return false;
7848 
7849  Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
7850  return true;
7851  }
7852 }
7853 
7854 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
7855 
7856  switch (E->getCastKind()) {
7857  case CK_BitCast:
7858  case CK_BaseToDerived:
7859  case CK_DerivedToBase:
7861  case CK_Dynamic:
7862  case CK_ToUnion:
7865  case CK_NullToPointer:
7872  case CK_IntegralToPointer:
7873  case CK_PointerToIntegral:
7874  case CK_PointerToBoolean:
7875  case CK_ToVoid:
7876  case CK_VectorSplat:
7877  case CK_IntegralCast:
7878  case CK_IntegralToBoolean:
7879  case CK_IntegralToFloating:
7880  case CK_FloatingToIntegral:
7881  case CK_FloatingToBoolean:
7882  case CK_FloatingCast:
7891  case CK_ARCProduceObject:
7892  case CK_ARCConsumeObject:
7896  case CK_BuiltinFnToFnPtr:
7897  case CK_ZeroToOCLEvent:
7898  case CK_NonAtomicToAtomic:
7900  llvm_unreachable("invalid cast kind for complex value");
7901 
7902  case CK_LValueToRValue:
7903  case CK_AtomicToNonAtomic:
7904  case CK_NoOp:
7905  return ExprEvaluatorBaseTy::VisitCastExpr(E);
7906 
7907  case CK_Dependent:
7908  case CK_LValueBitCast:
7910  return Error(E);
7911 
7912  case CK_FloatingRealToComplex: {
7913  APFloat &Real = Result.FloatReal;
7914  if (!EvaluateFloat(E->getSubExpr(), Real, Info))
7915  return false;
7916 
7917  Result.makeComplexFloat();
7918  Result.FloatImag = APFloat(Real.getSemantics());
7919  return true;
7920  }
7921 
7922  case CK_FloatingComplexCast: {
7923  if (!Visit(E->getSubExpr()))
7924  return false;
7925 
7926  QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7927  QualType From
7929 
7930  return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
7931  HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
7932  }
7933 
7935  if (!Visit(E->getSubExpr()))
7936  return false;
7937 
7938  QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7939  QualType From
7941  Result.makeComplexInt();
7942  return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
7943  To, Result.IntReal) &&
7944  HandleFloatToIntCast(Info, E, From, Result.FloatImag,
7945  To, Result.IntImag);
7946  }
7947 
7948  case CK_IntegralRealToComplex: {
7949  APSInt &Real = Result.IntReal;
7950  if (!EvaluateInteger(E->getSubExpr(), Real, Info))
7951  return false;
7952 
7953  Result.makeComplexInt();
7954  Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
7955  return true;
7956  }
7957 
7958  case CK_IntegralComplexCast: {
7959  if (!Visit(E->getSubExpr()))
7960  return false;
7961 
7962  QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7963  QualType From
7965 
7966  Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
7967  Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
7968  return true;
7969  }
7970 
7972  if (!Visit(E->getSubExpr()))
7973  return false;
7974 
7976  QualType From
7978  Result.makeComplexFloat();
7979  return HandleIntToFloatCast(Info, E, From, Result.IntReal,
7980  To, Result.FloatReal) &&
7981  HandleIntToFloatCast(Info, E, From, Result.IntImag,
7982  To, Result.FloatImag);
7983  }
7984  }
7985 
7986  llvm_unreachable("unknown cast resulting in complex value");
7987 }
7988 
7989 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
7990  if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
7991  return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7992 
7993  // Track whether the LHS or RHS is real at the type system level. When this is
7994  // the case we can simplify our evaluation strategy.
7995  bool LHSReal = false, RHSReal = false;
7996 
7997  bool LHSOK;
7998  if (E->getLHS()->getType()->isRealFloatingType()) {
7999  LHSReal = true;
8000  APFloat &Real = Result.FloatReal;
8001  LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
8002  if (LHSOK) {
8003  Result.makeComplexFloat();
8004  Result.FloatImag = APFloat(Real.getSemantics());
8005  }
8006  } else {
8007  LHSOK = Visit(E->getLHS());
8008  }
8009  if (!LHSOK && !Info.keepEvaluatingAfterFailure())
8010  return false;
8011 
8012  ComplexValue RHS;
8013  if (E->getRHS()->getType()->isRealFloatingType()) {
8014  RHSReal = true;
8015  APFloat &Real = RHS.FloatReal;
8016  if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
8017  return false;
8018  RHS.makeComplexFloat();
8019  RHS.FloatImag = APFloat(Real.getSemantics());
8020  } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
8021  return false;
8022 
8023  assert(!(LHSReal && RHSReal) &&
8024  "Cannot have both operands of a complex operation be real.");
8025  switch (E->getOpcode()) {
8026  default: return Error(E);
8027  case BO_Add:
8028  if (Result.isComplexFloat()) {
8029  Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
8030  APFloat::rmNearestTiesToEven);
8031  if (LHSReal)
8032  Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8033  else if (!RHSReal)
8034  Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
8035  APFloat::rmNearestTiesToEven);
8036  } else {
8037  Result.getComplexIntReal() += RHS.getComplexIntReal();
8038  Result.getComplexIntImag() += RHS.getComplexIntImag();
8039  }
8040  break;
8041  case BO_Sub:
8042  if (Result.isComplexFloat()) {
8043  Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
8044  APFloat::rmNearestTiesToEven);
8045  if (LHSReal) {
8046  Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8047  Result.getComplexFloatImag().changeSign();
8048  } else if (!RHSReal) {
8049  Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
8050  APFloat::rmNearestTiesToEven);
8051  }
8052  } else {
8053  Result.getComplexIntReal() -= RHS.getComplexIntReal();
8054  Result.getComplexIntImag() -= RHS.getComplexIntImag();
8055  }
8056  break;
8057  case BO_Mul:
8058  if (Result.isComplexFloat()) {
8059  // This is an implementation of complex multiplication according to the
8060  // constraints laid out in C11 Annex G. The implemantion uses the
8061  // following naming scheme:
8062  // (a + ib) * (c + id)
8063  ComplexValue LHS = Result;
8064  APFloat &A = LHS.getComplexFloatReal();
8065  APFloat &B = LHS.getComplexFloatImag();
8066  APFloat &C = RHS.getComplexFloatReal();
8067  APFloat &D = RHS.getComplexFloatImag();
8068  APFloat &ResR = Result.getComplexFloatReal();
8069  APFloat &ResI = Result.getComplexFloatImag();
8070  if (LHSReal) {
8071  assert(!RHSReal && "Cannot have two real operands for a complex op!");
8072  ResR = A * C;
8073  ResI = A * D;
8074  } else if (RHSReal) {
8075  ResR = C * A;
8076  ResI = C * B;
8077  } else {
8078  // In the fully general case, we need to handle NaNs and infinities
8079  // robustly.
8080  APFloat AC = A * C;
8081  APFloat BD = B * D;
8082  APFloat AD = A * D;
8083  APFloat BC = B * C;
8084  ResR = AC - BD;
8085  ResI = AD + BC;
8086  if (ResR.isNaN() && ResI.isNaN()) {
8087  bool Recalc = false;
8088  if (A.isInfinity() || B.isInfinity()) {
8089  A = APFloat::copySign(
8090  APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
8091  B = APFloat::copySign(
8092  APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
8093  if (C.isNaN())
8094  C = APFloat::copySign(APFloat(C.getSemantics()), C);
8095  if (D.isNaN())
8096  D = APFloat::copySign(APFloat(D.getSemantics()), D);
8097  Recalc = true;
8098  }
8099  if (C.isInfinity() || D.isInfinity()) {
8100  C = APFloat::copySign(
8101  APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
8102  D = APFloat::copySign(
8103  APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
8104  if (A.isNaN())
8105  A = APFloat::copySign(APFloat(A.getSemantics()), A);
8106  if (B.isNaN())
8107  B = APFloat::copySign(APFloat(B.getSemantics()), B);
8108  Recalc = true;
8109  }
8110  if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
8111  AD.isInfinity() || BC.isInfinity())) {
8112  if (A.isNaN())
8113  A = APFloat::copySign(APFloat(A.getSemantics()), A);
8114  if (B.isNaN())
8115  B = APFloat::copySign(APFloat(B.getSemantics()), B);
8116  if (C.isNaN())
8117  C = APFloat::copySign(APFloat(C.getSemantics()), C);
8118  if (D.isNaN())
8119  D = APFloat::copySign(APFloat(D.getSemantics()), D);
8120  Recalc = true;
8121  }
8122  if (Recalc) {
8123  ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
8124  ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
8125  }
8126  }
8127  }
8128  } else {
8129  ComplexValue LHS = Result;
8130  Result.getComplexIntReal() =
8131  (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
8132  LHS.getComplexIntImag() * RHS.getComplexIntImag());
8133  Result.getComplexIntImag() =
8134  (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
8135  LHS.getComplexIntImag() * RHS.getComplexIntReal());
8136  }
8137  break;
8138  case BO_Div:
8139  if (Result.isComplexFloat()) {
8140  // This is an implementation of complex division according to the
8141  // constraints laid out in C11 Annex G. The implemantion uses the
8142  // following naming scheme:
8143  // (a + ib) / (c + id)
8144  ComplexValue LHS = Result;
8145  APFloat &A = LHS.getComplexFloatReal();
8146  APFloat &B = LHS.getComplexFloatImag();
8147  APFloat &C = RHS.getComplexFloatReal();
8148  APFloat &D = RHS.getComplexFloatImag();
8149  APFloat &ResR = Result.getComplexFloatReal();
8150  APFloat &ResI = Result.getComplexFloatImag();
8151  if (RHSReal) {
8152  ResR = A / C;
8153  ResI = B / C;
8154  } else {
8155  if (LHSReal) {
8156  // No real optimizations we can do here, stub out with zero.
8157  B = APFloat::getZero(A.getSemantics());
8158  }
8159  int DenomLogB = 0;
8160  APFloat MaxCD = maxnum(abs(C), abs(D));
8161  if (MaxCD.isFinite()) {
8162  DenomLogB = ilogb(MaxCD);
8163  C = scalbn(C, -DenomLogB);
8164  D = scalbn(D, -DenomLogB);
8165  }
8166  APFloat Denom = C * C + D * D;
8167  ResR = scalbn((A * C + B * D) / Denom, -DenomLogB);
8168  ResI = scalbn((B * C - A * D) / Denom, -DenomLogB);
8169  if (ResR.isNaN() && ResI.isNaN()) {
8170  if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
8171  ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
8172  ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
8173  } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
8174  D.isFinite()) {
8175  A = APFloat::copySign(
8176  APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
8177  B = APFloat::copySign(
8178  APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
8179  ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
8180  ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
8181  } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
8182  C = APFloat::copySign(
8183  APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
8184  D = APFloat::copySign(
8185  APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
8186  ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
8187  ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
8188  }
8189  }
8190  }
8191  } else {
8192  if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
8193  return Error(E, diag::note_expr_divide_by_zero);
8194 
8195  ComplexValue LHS = Result;
8196  APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
8197  RHS.getComplexIntImag() * RHS.getComplexIntImag();
8198  Result.getComplexIntReal() =
8199  (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
8200  LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
8201  Result.getComplexIntImag() =
8202  (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
8203  LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
8204  }
8205  break;
8206  }
8207 
8208  return true;
8209 }
8210 
8211 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
8212  // Get the operand value into 'Result'.
8213  if (!Visit(E->getSubExpr()))
8214  return false;
8215 
8216  switch (E->getOpcode()) {
8217  default:
8218  return Error(E);
8219  case UO_Extension:
8220  return true;
8221  case UO_Plus:
8222  // The result is always just the subexpr.
8223  return true;
8224  case UO_Minus:
8225  if (Result.isComplexFloat()) {
8226  Result.getComplexFloatReal().changeSign();
8227  Result.getComplexFloatImag().changeSign();
8228  }
8229  else {
8230  Result.getComplexIntReal() = -Result.getComplexIntReal();
8231  Result.getComplexIntImag() = -Result.getComplexIntImag();
8232  }
8233  return true;
8234  case UO_Not:
8235  if (Result.isComplexFloat())
8236  Result.getComplexFloatImag().changeSign();
8237  else
8238  Result.getComplexIntImag() = -Result.getComplexIntImag();
8239  return true;
8240  }
8241 }
8242 
8243 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
8244  if (E->getNumInits() == 2) {
8245  if (E->getType()->isComplexType()) {
8246  Result.makeComplexFloat();
8247  if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
8248  return false;
8249  if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
8250  return false;
8251  } else {
8252  Result.makeComplexInt();
8253  if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
8254  return false;
8255  if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
8256  return false;
8257  }
8258  return true;
8259  }
8260  return ExprEvaluatorBaseTy::VisitInitListExpr(E);
8261 }
8262 
8263 //===----------------------------------------------------------------------===//
8264 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
8265 // implicit conversion.
8266 //===----------------------------------------------------------------------===//
8267 
8268 namespace {
8269 class AtomicExprEvaluator :
8270  public ExprEvaluatorBase<AtomicExprEvaluator> {
8271  APValue &Result;
8272 public:
8273  AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
8274  : ExprEvaluatorBaseTy(Info), Result(Result) {}
8275 
8276  bool Success(const APValue &V, const Expr *E) {
8277  Result = V;
8278  return true;
8279  }
8280 
8281  bool ZeroInitialization(const Expr *E) {
8283  E->getType()->castAs<AtomicType>()->getValueType());
8284  return Evaluate(Result, Info, &VIE);
8285  }
8286 
8287  bool VisitCastExpr(const CastExpr *E) {
8288  switch (E->getCastKind()) {
8289  default:
8290  return ExprEvaluatorBaseTy::VisitCastExpr(E);
8291  case CK_NonAtomicToAtomic:
8292  return Evaluate(Result, Info, E->getSubExpr());
8293  }
8294  }
8295 };
8296 } // end anonymous namespace
8297 
8298 static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
8299  assert(E->isRValue() && E->getType()->isAtomicType());
8300  return AtomicExprEvaluator(Info, Result).Visit(E);
8301 }
8302 
8303 //===----------------------------------------------------------------------===//
8304 // Void expression evaluation, primarily for a cast to void on the LHS of a
8305 // comma operator
8306 //===----------------------------------------------------------------------===//
8307 
8308 namespace {
8309 class VoidExprEvaluator
8310  : public ExprEvaluatorBase<VoidExprEvaluator> {
8311 public:
8312  VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
8313 
8314  bool Success(const APValue &V, const Expr *e) { return true; }
8315 
8316  bool VisitCastExpr(const CastExpr *E) {
8317  switch (E->getCastKind()) {
8318  default:
8319  return ExprEvaluatorBaseTy::VisitCastExpr(E);
8320  case CK_ToVoid:
8321  VisitIgnoredValue(E->getSubExpr());
8322  return true;
8323  }
8324  }
8325 
8326  bool VisitCallExpr(const CallExpr *E) {
8327  switch (E->getBuiltinCallee()) {
8328  default:
8329  return ExprEvaluatorBaseTy::VisitCallExpr(E);
8330  case Builtin::BI__assume:
8331  case Builtin::BI__builtin_assume:
8332  // The argument is not evaluated!
8333  return true;
8334  }
8335  }
8336 };
8337 } // end anonymous namespace
8338 
8339 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
8340  assert(E->isRValue() && E->getType()->isVoidType());
8341  return VoidExprEvaluator(Info).Visit(E);
8342 }
8343 
8344 //===----------------------------------------------------------------------===//
8345 // Top level Expr::EvaluateAsRValue method.
8346 //===----------------------------------------------------------------------===//
8347 
8348 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
8349  // In C, function designators are not lvalues, but we evaluate them as if they
8350  // are.
8351  QualType T = E->getType();
8352  if (E->isGLValue() || T->isFunctionType()) {
8353  LValue LV;
8354  if (!EvaluateLValue(E, LV, Info))
8355  return false;
8356  LV.moveInto(Result);
8357  } else if (T->isVectorType()) {
8358  if (!EvaluateVector(E, Result, Info))
8359  return false;
8360  } else if (T->isIntegralOrEnumerationType()) {
8361  if (!IntExprEvaluator(Info, Result).Visit(E))
8362  return false;
8363  } else if (T->hasPointerRepresentation()) {
8364  LValue LV;
8365  if (!EvaluatePointer(E, LV, Info))
8366  return false;
8367  LV.moveInto(Result);
8368  } else if (T->isRealFloatingType()) {
8369  llvm::APFloat F(0.0);
8370  if (!EvaluateFloat(E, F, Info))
8371  return false;
8372  Result = APValue(F);
8373  } else if (T->isAnyComplexType()) {
8374  ComplexValue C;
8375  if (!EvaluateComplex(E, C, Info))
8376  return false;
8377  C.moveInto(Result);
8378  } else if (T->isMemberPointerType()) {
8379  MemberPtr P;
8380  if (!EvaluateMemberPointer(E, P, Info))
8381  return false;
8382  P.moveInto(Result);
8383  return true;
8384  } else if (T->isArrayType()) {
8385  LValue LV;
8386  LV.set(E, Info.CurrentCall->Index);
8387  APValue &Value = Info.CurrentCall->createTemporary(E, false);
8388  if (!EvaluateArray(E, LV, Value, Info))
8389  return false;
8390  Result = Value;
8391  } else if (T->isRecordType()) {
8392  LValue LV;
8393  LV.set(E, Info.CurrentCall->Index);
8394  APValue &Value = Info.CurrentCall->createTemporary(E, false);
8395  if (!EvaluateRecord(E, LV, Value, Info))
8396  return false;
8397  Result = Value;
8398  } else if (T->isVoidType()) {
8399  if (!Info.getLangOpts().CPlusPlus11)
8400  Info.CCEDiag(E, diag::note_constexpr_nonliteral)
8401  << E->getType();
8402  if (!EvaluateVoid(E, Info))
8403  return false;
8404  } else if (T->isAtomicType()) {
8405  if (!EvaluateAtomic(E, Result, Info))
8406  return false;
8407  } else if (Info.getLangOpts().CPlusPlus11) {
8408  Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
8409  return false;
8410  } else {
8411  Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
8412  return false;
8413  }
8414 
8415  return true;
8416 }
8417 
8418 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
8419 /// cases, the in-place evaluation is essential, since later initializers for
8420 /// an object can indirectly refer to subobjects which were initialized earlier.
8421 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
8422  const Expr *E, bool AllowNonLiteralTypes) {
8423  assert(!E->isValueDependent());
8424 
8425  if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
8426  return false;
8427 
8428  if (E->isRValue()) {
8429  // Evaluate arrays and record types in-place, so that later initializers can
8430  // refer to earlier-initialized members of the object.
8431  if (E->getType()->isArrayType())
8432  return EvaluateArray(E, This, Result, Info);
8433  else if (E->getType()->isRecordType())
8434  return EvaluateRecord(E, This, Result, Info);
8435  }
8436 
8437  // For any other type, in-place evaluation is unimportant.
8438  return Evaluate(Result, Info, E);
8439 }
8440 
8441 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
8442 /// lvalue-to-rvalue cast if it is an lvalue.
8443 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
8444  if (E->getType().isNull())
8445  return false;
8446 
8447  if (!CheckLiteralType(Info, E))
8448  return false;
8449 
8450  if (!::Evaluate(Result, Info, E))
8451  return false;
8452 
8453  if (E->isGLValue()) {
8454  LValue LV;
8455  LV.setFrom(Info.Ctx, Result);
8456  if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
8457  return false;
8458  }
8459 
8460  // Check this core constant expression is a constant expression.
8461  return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
8462 }
8463 
8464 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
8465  const ASTContext &Ctx, bool &IsConst) {
8466  // Fast-path evaluations of integer literals, since we sometimes see files
8467  // containing vast quantities of these.
8468  if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
8469  Result.Val = APValue(APSInt(L->getValue(),
8470  L->getType()->isUnsignedIntegerType()));
8471  IsConst = true;
8472  return true;
8473  }
8474 
8475  // This case should be rare, but we need to check it before we check on
8476  // the type below.
8477  if (Exp->getType().isNull()) {
8478  IsConst = false;
8479  return true;
8480  }
8481 
8482  // FIXME: Evaluating values of large array and record types can cause
8483  // performance problems. Only do so in C++11 for now.
8484  if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
8485  Exp->getType()->isRecordType()) &&
8486  !Ctx.getLangOpts().CPlusPlus11) {
8487  IsConst = false;
8488  return true;
8489  }
8490  return false;
8491 }
8492 
8493 
8494 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
8495 /// any crazy technique (that has nothing to do with language standards) that
8496 /// we want to. If this function returns true, it returns the folded constant
8497 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
8498 /// will be applied to the result.
8499 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
8500  bool IsConst;
8501  if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
8502  return IsConst;
8503 
8504  EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
8505  return ::EvaluateAsRValue(Info, this, Result.Val);
8506 }
8507 
8509  const ASTContext &Ctx) const {
8510  EvalResult Scratch;
8511  return EvaluateAsRValue(Scratch, Ctx) &&
8512  HandleConversionToBool(Scratch.Val, Result);
8513 }
8514 
8515 bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
8516  SideEffectsKind AllowSideEffects) const {
8517  if (!getType()->isIntegralOrEnumerationType())
8518  return false;
8519 
8521  if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
8522  (!AllowSideEffects && ExprResult.HasSideEffects))
8523  return false;
8524 
8525  Result = ExprResult.Val.getInt();
8526  return true;
8527 }
8528 
8529 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
8530  EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
8531 
8532  LValue LV;
8533  if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
8535  Ctx.getLValueReferenceType(getType()), LV))
8536  return false;
8537 
8538  LV.moveInto(Result.Val);
8539  return true;
8540 }
8541 
8543  const VarDecl *VD,
8544  SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
8545  // FIXME: Evaluating initializers for large array and record types can cause
8546  // performance problems. Only do so in C++11 for now.
8547  if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
8548  !Ctx.getLangOpts().CPlusPlus11)
8549  return false;
8550 
8551  Expr::EvalStatus EStatus;
8552  EStatus.Diag = &Notes;
8553 
8554  EvalInfo InitInfo(Ctx, EStatus, EvalInfo::EM_ConstantFold);
8555  InitInfo.setEvaluatingDecl(VD, Value);
8556 
8557  LValue LVal;
8558  LVal.set(VD);
8559 
8560  // C++11 [basic.start.init]p2:
8561  // Variables with static storage duration or thread storage duration shall be
8562  // zero-initialized before any other initialization takes place.
8563  // This behavior is not present in C.
8564  if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
8565  !VD->getType()->isReferenceType()) {
8566  ImplicitValueInitExpr VIE(VD->getType());
8567  if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
8568  /*AllowNonLiteralTypes=*/true))
8569  return false;
8570  }
8571 
8572  if (!EvaluateInPlace(Value, InitInfo, LVal, this,
8573  /*AllowNonLiteralTypes=*/true) ||
8574  EStatus.HasSideEffects)
8575  return false;
8576 
8577  return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
8578  Value);
8579 }
8580 
8581 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
8582 /// constant folded, but discard the result.
8583 bool Expr::isEvaluatable(const ASTContext &Ctx) const {
8585  return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
8586 }
8587 
8591  EvalResult.Diag = Diag;
8592  bool Result = EvaluateAsRValue(EvalResult, Ctx);
8593  (void)Result;
8594  assert(Result && "Could not evaluate expression");
8595  assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
8596 
8597  return EvalResult.Val.getInt();
8598 }
8599 
8600 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
8601  bool IsConst;
8603  if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
8604  EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
8605  (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
8606  }
8607 }
8608 
8610  assert(Val.isLValue());
8611  return IsGlobalLValue(Val.getLValueBase());
8612 }
8613 
8614 
8615 /// isIntegerConstantExpr - this recursive routine will test if an expression is
8616 /// an integer constant expression.
8617 
8618 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
8619 /// comma, etc
8620 
8621 // CheckICE - This function does the fundamental ICE checking: the returned
8622 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
8623 // and a (possibly null) SourceLocation indicating the location of the problem.
8624 //
8625 // Note that to reduce code duplication, this helper does no evaluation
8626 // itself; the caller checks whether the expression is evaluatable, and
8627 // in the rare cases where CheckICE actually cares about the evaluated
8628 // value, it calls into Evalute.
8629 
8630 namespace {
8631 
8632 enum ICEKind {
8633  /// This expression is an ICE.
8634  IK_ICE,
8635  /// This expression is not an ICE, but if it isn't evaluated, it's
8636  /// a legal subexpression for an ICE. This return value is used to handle
8637  /// the comma operator in C99 mode, and non-constant subexpressions.
8638  IK_ICEIfUnevaluated,
8639  /// This expression is not an ICE, and is not a legal subexpression for one.
8640  IK_NotICE
8641 };
8642 
8643 struct ICEDiag {
8644  ICEKind Kind;
8645  SourceLocation Loc;
8646 
8647  ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
8648 };
8649 
8650 }
8651 
8652 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
8653 
8654 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
8655 
8656 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
8657  Expr::EvalResult EVResult;
8658  if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
8659  !EVResult.Val.isInt())
8660  return ICEDiag(IK_NotICE, E->getLocStart());
8661 
8662  return NoDiag();
8663 }
8664 
8665 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
8666  assert(!E->isValueDependent() && "Should not see value dependent exprs!");
8667  if (!E->getType()->isIntegralOrEnumerationType())
8668  return ICEDiag(IK_NotICE, E->getLocStart());
8669 
8670  switch (E->getStmtClass()) {
8671 #define ABSTRACT_STMT(Node)
8672 #define STMT(Node, Base) case Expr::Node##Class:
8673 #define EXPR(Node, Base)
8674 #include "clang/AST/StmtNodes.inc"
8675  case Expr::PredefinedExprClass:
8676  case Expr::FloatingLiteralClass:
8677  case Expr::ImaginaryLiteralClass:
8678  case Expr::StringLiteralClass:
8679  case Expr::ArraySubscriptExprClass:
8680  case Expr::MemberExprClass:
8681  case Expr::CompoundAssignOperatorClass:
8682  case Expr::CompoundLiteralExprClass:
8683  case Expr::ExtVectorElementExprClass:
8684  case Expr::DesignatedInitExprClass:
8685  case Expr::NoInitExprClass:
8686  case Expr::DesignatedInitUpdateExprClass:
8687  case Expr::ImplicitValueInitExprClass:
8688  case Expr::ParenListExprClass:
8689  case Expr::VAArgExprClass:
8690  case Expr::AddrLabelExprClass:
8691  case Expr::StmtExprClass:
8692  case Expr::CXXMemberCallExprClass:
8693  case Expr::CUDAKernelCallExprClass:
8694  case Expr::CXXDynamicCastExprClass:
8695  case Expr::CXXTypeidExprClass:
8696  case Expr::CXXUuidofExprClass:
8697  case Expr::MSPropertyRefExprClass:
8698  case Expr::CXXNullPtrLiteralExprClass:
8699  case Expr::UserDefinedLiteralClass:
8700  case Expr::CXXThisExprClass:
8701  case Expr::CXXThrowExprClass:
8702  case Expr::CXXNewExprClass:
8703  case Expr::CXXDeleteExprClass:
8704  case Expr::CXXPseudoDestructorExprClass:
8705  case Expr::UnresolvedLookupExprClass:
8706  case Expr::TypoExprClass:
8707  case Expr::DependentScopeDeclRefExprClass:
8708  case Expr::CXXConstructExprClass:
8709  case Expr::CXXStdInitializerListExprClass:
8710  case Expr::CXXBindTemporaryExprClass:
8711  case Expr::ExprWithCleanupsClass:
8712  case Expr::CXXTemporaryObjectExprClass:
8713  case Expr::CXXUnresolvedConstructExprClass:
8714  case Expr::CXXDependentScopeMemberExprClass:
8715  case Expr::UnresolvedMemberExprClass:
8716  case Expr::ObjCStringLiteralClass:
8717  case Expr::ObjCBoxedExprClass:
8718  case Expr::ObjCArrayLiteralClass:
8719  case Expr::ObjCDictionaryLiteralClass:
8720  case Expr::ObjCEncodeExprClass:
8721  case Expr::ObjCMessageExprClass:
8722  case Expr::ObjCSelectorExprClass:
8723  case Expr::ObjCProtocolExprClass:
8724  case Expr::ObjCIvarRefExprClass:
8725  case Expr::ObjCPropertyRefExprClass:
8726  case Expr::ObjCSubscriptRefExprClass:
8727  case Expr::ObjCIsaExprClass:
8728  case Expr::ShuffleVectorExprClass:
8729  case Expr::ConvertVectorExprClass:
8730  case Expr::BlockExprClass:
8731  case Expr::NoStmtClass:
8732  case Expr::OpaqueValueExprClass:
8733  case Expr::PackExpansionExprClass:
8734  case Expr::SubstNonTypeTemplateParmPackExprClass:
8735  case Expr::FunctionParmPackExprClass:
8736  case Expr::AsTypeExprClass:
8737  case Expr::ObjCIndirectCopyRestoreExprClass:
8738  case Expr::MaterializeTemporaryExprClass:
8739  case Expr::PseudoObjectExprClass:
8740  case Expr::AtomicExprClass:
8741  case Expr::LambdaExprClass:
8742  case Expr::CXXFoldExprClass:
8743  return ICEDiag(IK_NotICE, E->getLocStart());
8744 
8745  case Expr::InitListExprClass: {
8746  // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
8747  // form "T x = { a };" is equivalent to "T x = a;".
8748  // Unless we're initializing a reference, T is a scalar as it is known to be
8749  // of integral or enumeration type.
8750  if (E->isRValue())
8751  if (cast<InitListExpr>(E)->getNumInits() == 1)
8752  return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
8753  return ICEDiag(IK_NotICE, E->getLocStart());
8754  }
8755 
8756  case Expr::SizeOfPackExprClass:
8757  case Expr::GNUNullExprClass:
8758  // GCC considers the GNU __null value to be an integral constant expression.
8759  return NoDiag();
8760 
8761  case Expr::SubstNonTypeTemplateParmExprClass:
8762  return
8763  CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
8764 
8765  case Expr::ParenExprClass:
8766  return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
8767  case Expr::GenericSelectionExprClass:
8768  return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
8769  case Expr::IntegerLiteralClass:
8770  case Expr::CharacterLiteralClass:
8771  case Expr::ObjCBoolLiteralExprClass:
8772  case Expr::CXXBoolLiteralExprClass:
8773  case Expr::CXXScalarValueInitExprClass:
8774  case Expr::TypeTraitExprClass:
8775  case Expr::ArrayTypeTraitExprClass:
8776  case Expr::ExpressionTraitExprClass:
8777  case Expr::CXXNoexceptExprClass:
8778  return NoDiag();
8779  case Expr::CallExprClass:
8780  case Expr::CXXOperatorCallExprClass: {
8781  // C99 6.6/3 allows function calls within unevaluated subexpressions of
8782  // constant expressions, but they can never be ICEs because an ICE cannot
8783  // contain an operand of (pointer to) function type.
8784  const CallExpr *CE = cast<CallExpr>(E);
8785  if (CE->getBuiltinCallee())
8786  return CheckEvalInICE(E, Ctx);
8787  return ICEDiag(IK_NotICE, E->getLocStart());
8788  }
8789  case Expr::DeclRefExprClass: {
8790  if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
8791  return NoDiag();
8792  const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
8793  if (Ctx.getLangOpts().CPlusPlus &&
8794  D && IsConstNonVolatile(D->getType())) {
8795  // Parameter variables are never constants. Without this check,
8796  // getAnyInitializer() can find a default argument, which leads
8797  // to chaos.
8798  if (isa<ParmVarDecl>(D))
8799  return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
8800 
8801  // C++ 7.1.5.1p2
8802  // A variable of non-volatile const-qualified integral or enumeration
8803  // type initialized by an ICE can be used in ICEs.
8804  if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
8805  if (!Dcl->getType()->isIntegralOrEnumerationType())
8806  return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
8807 
8808  const VarDecl *VD;
8809  // Look for a declaration of this variable that has an initializer, and
8810  // check whether it is an ICE.
8811  if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
8812  return NoDiag();
8813  else
8814  return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
8815  }
8816  }
8817  return ICEDiag(IK_NotICE, E->getLocStart());
8818  }
8819  case Expr::UnaryOperatorClass: {
8820  const UnaryOperator *Exp = cast<UnaryOperator>(E);
8821  switch (Exp->getOpcode()) {
8822  case UO_PostInc:
8823  case UO_PostDec:
8824  case UO_PreInc:
8825  case UO_PreDec:
8826  case UO_AddrOf:
8827  case UO_Deref:
8828  // C99 6.6/3 allows increment and decrement within unevaluated
8829  // subexpressions of constant expressions, but they can never be ICEs
8830  // because an ICE cannot contain an lvalue operand.
8831  return ICEDiag(IK_NotICE, E->getLocStart());
8832  case UO_Extension:
8833  case UO_LNot:
8834  case UO_Plus:
8835  case UO_Minus:
8836  case UO_Not:
8837  case UO_Real:
8838  case UO_Imag:
8839  return CheckICE(Exp->getSubExpr(), Ctx);
8840  }
8841 
8842  // OffsetOf falls through here.
8843  }
8844  case Expr::OffsetOfExprClass: {
8845  // Note that per C99, offsetof must be an ICE. And AFAIK, using
8846  // EvaluateAsRValue matches the proposed gcc behavior for cases like
8847  // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
8848  // compliance: we should warn earlier for offsetof expressions with
8849  // array subscripts that aren't ICEs, and if the array subscripts
8850  // are ICEs, the value of the offsetof must be an integer constant.
8851  return CheckEvalInICE(E, Ctx);
8852  }
8853  case Expr::UnaryExprOrTypeTraitExprClass: {
8854  const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
8855  if ((Exp->getKind() == UETT_SizeOf) &&
8857  return ICEDiag(IK_NotICE, E->getLocStart());
8858  return NoDiag();
8859  }
8860  case Expr::BinaryOperatorClass: {
8861  const BinaryOperator *Exp = cast<BinaryOperator>(E);
8862  switch (Exp->getOpcode()) {
8863  case BO_PtrMemD:
8864  case BO_PtrMemI:
8865  case BO_Assign:
8866  case BO_MulAssign:
8867  case BO_DivAssign:
8868  case BO_RemAssign:
8869  case BO_AddAssign:
8870  case BO_SubAssign:
8871  case BO_ShlAssign:
8872  case BO_ShrAssign:
8873  case BO_AndAssign:
8874  case BO_XorAssign:
8875  case BO_OrAssign:
8876  // C99 6.6/3 allows assignments within unevaluated subexpressions of
8877  // constant expressions, but they can never be ICEs because an ICE cannot
8878  // contain an lvalue operand.
8879  return ICEDiag(IK_NotICE, E->getLocStart());
8880 
8881  case BO_Mul:
8882  case BO_Div:
8883  case BO_Rem:
8884  case BO_Add:
8885  case BO_Sub:
8886  case BO_Shl:
8887  case BO_Shr:
8888  case BO_LT:
8889  case BO_GT:
8890  case BO_LE:
8891  case BO_GE:
8892  case BO_EQ:
8893  case BO_NE:
8894  case BO_And:
8895  case BO_Xor:
8896  case BO_Or:
8897  case BO_Comma: {
8898  ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8899  ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
8900  if (Exp->getOpcode() == BO_Div ||
8901  Exp->getOpcode() == BO_Rem) {
8902  // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
8903  // we don't evaluate one.
8904  if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
8905  llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
8906  if (REval == 0)
8907  return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
8908  if (REval.isSigned() && REval.isAllOnesValue()) {
8909  llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
8910  if (LEval.isMinSignedValue())
8911  return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
8912  }
8913  }
8914  }
8915  if (Exp->getOpcode() == BO_Comma) {
8916  if (Ctx.getLangOpts().C99) {
8917  // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
8918  // if it isn't evaluated.
8919  if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
8920  return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
8921  } else {
8922  // In both C89 and C++, commas in ICEs are illegal.
8923  return ICEDiag(IK_NotICE, E->getLocStart());
8924  }
8925  }
8926  return Worst(LHSResult, RHSResult);
8927  }
8928  case BO_LAnd:
8929  case BO_LOr: {
8930  ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8931  ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
8932  if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
8933  // Rare case where the RHS has a comma "side-effect"; we need
8934  // to actually check the condition to see whether the side
8935  // with the comma is evaluated.
8936  if ((Exp->getOpcode() == BO_LAnd) !=
8937  (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
8938  return RHSResult;
8939  return NoDiag();
8940  }
8941 
8942  return Worst(LHSResult, RHSResult);
8943  }
8944  }
8945  }
8946  case Expr::ImplicitCastExprClass:
8947  case Expr::CStyleCastExprClass:
8948  case Expr::CXXFunctionalCastExprClass:
8949  case Expr::CXXStaticCastExprClass:
8950  case Expr::CXXReinterpretCastExprClass:
8951  case Expr::CXXConstCastExprClass:
8952  case Expr::ObjCBridgedCastExprClass: {
8953  const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
8954  if (isa<ExplicitCastExpr>(E)) {
8955  if (const FloatingLiteral *FL
8956  = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
8957  unsigned DestWidth = Ctx.getIntWidth(E->getType());
8958  bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
8959  APSInt IgnoredVal(DestWidth, !DestSigned);
8960  bool Ignored;
8961  // If the value does not fit in the destination type, the behavior is
8962  // undefined, so we are not required to treat it as a constant
8963  // expression.
8964  if (FL->getValue().convertToInteger(IgnoredVal,
8965  llvm::APFloat::rmTowardZero,
8966  &Ignored) & APFloat::opInvalidOp)
8967  return ICEDiag(IK_NotICE, E->getLocStart());
8968  return NoDiag();
8969  }
8970  }
8971  switch (cast<CastExpr>(E)->getCastKind()) {
8972  case CK_LValueToRValue:
8973  case CK_AtomicToNonAtomic:
8974  case CK_NonAtomicToAtomic:
8975  case CK_NoOp:
8976  case CK_IntegralToBoolean:
8977  case CK_IntegralCast:
8978  return CheckICE(SubExpr, Ctx);
8979  default:
8980  return ICEDiag(IK_NotICE, E->getLocStart());
8981  }
8982  }
8983  case Expr::BinaryConditionalOperatorClass: {
8984  const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
8985  ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
8986  if (CommonResult.Kind == IK_NotICE) return CommonResult;
8987  ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
8988  if (FalseResult.Kind == IK_NotICE) return FalseResult;
8989  if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
8990  if (FalseResult.Kind == IK_ICEIfUnevaluated &&
8991  Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
8992  return FalseResult;
8993  }
8994  case Expr::ConditionalOperatorClass: {
8995  const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
8996  // If the condition (ignoring parens) is a __builtin_constant_p call,
8997  // then only the true side is actually considered in an integer constant
8998  // expression, and it is fully evaluated. This is an important GNU
8999  // extension. See GCC PR38377 for discussion.
9000  if (const CallExpr *CallCE
9001  = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
9002  if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
9003  return CheckEvalInICE(E, Ctx);
9004  ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
9005  if (CondResult.Kind == IK_NotICE)
9006  return CondResult;
9007 
9008  ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
9009  ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
9010 
9011  if (TrueResult.Kind == IK_NotICE)
9012  return TrueResult;
9013  if (FalseResult.Kind == IK_NotICE)
9014  return FalseResult;
9015  if (CondResult.Kind == IK_ICEIfUnevaluated)
9016  return CondResult;
9017  if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
9018  return NoDiag();
9019  // Rare case where the diagnostics depend on which side is evaluated
9020  // Note that if we get here, CondResult is 0, and at least one of
9021  // TrueResult and FalseResult is non-zero.
9022  if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
9023  return FalseResult;
9024  return TrueResult;
9025  }
9026  case Expr::CXXDefaultArgExprClass:
9027  return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
9028  case Expr::CXXDefaultInitExprClass:
9029  return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
9030  case Expr::ChooseExprClass: {
9031  return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
9032  }
9033  }
9034 
9035  llvm_unreachable("Invalid StmtClass!");
9036 }
9037 
9038 /// Evaluate an expression as a C++11 integral constant expression.
9040  const Expr *E,
9041  llvm::APSInt *Value,
9042  SourceLocation *Loc) {
9043  if (!E->getType()->isIntegralOrEnumerationType()) {
9044  if (Loc) *Loc = E->getExprLoc();
9045  return false;
9046  }
9047 
9048  APValue Result;
9049  if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
9050  return false;
9051 
9052  if (!Result.isInt()) {
9053  if (Loc) *Loc = E->getExprLoc();
9054  return false;
9055  }
9056 
9057  if (Value) *Value = Result.getInt();
9058  return true;
9059 }
9060 
9062  SourceLocation *Loc) const {
9063  if (Ctx.getLangOpts().CPlusPlus11)
9064  return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
9065 
9066  ICEDiag D = CheckICE(this, Ctx);
9067  if (D.Kind != IK_ICE) {
9068  if (Loc) *Loc = D.Loc;
9069  return false;
9070  }
9071  return true;
9072 }
9073 
9074 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
9075  SourceLocation *Loc, bool isEvaluated) const {
9076  if (Ctx.getLangOpts().CPlusPlus11)
9077  return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
9078 
9079  if (!isIntegerConstantExpr(Ctx, Loc))
9080  return false;
9081  if (!EvaluateAsInt(Value, Ctx))
9082  llvm_unreachable("ICE cannot be evaluated!");
9083  return true;
9084 }
9085 
9087  return CheckICE(this, Ctx).Kind == IK_ICE;
9088 }
9089 
9091  SourceLocation *Loc) const {
9092  // We support this checking in C++98 mode in order to diagnose compatibility
9093  // issues.
9094  assert(Ctx.getLangOpts().CPlusPlus);
9095 
9096  // Build evaluation settings.
9097  Expr::EvalStatus Status;
9099  Status.Diag = &Diags;
9100  EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
9101 
9102  APValue Scratch;
9103  bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
9104 
9105  if (!Diags.empty()) {
9106  IsConstExpr = false;
9107  if (Loc) *Loc = Diags[0].first;
9108  } else if (!IsConstExpr) {
9109  // FIXME: This shouldn't happen.
9110  if (Loc) *Loc = getExprLoc();
9111  }
9112 
9113  return IsConstExpr;
9114 }
9115 
9117  const FunctionDecl *Callee,
9118  ArrayRef<const Expr*> Args) const {
9119  Expr::EvalStatus Status;
9120  EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
9121 
9122  ArgVector ArgValues(Args.size());
9123  for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
9124  I != E; ++I) {
9125  if ((*I)->isValueDependent() ||
9126  !Evaluate(ArgValues[I - Args.begin()], Info, *I))
9127  // If evaluation fails, throw away the argument entirely.
9128  ArgValues[I - Args.begin()] = APValue();
9129  if (Info.EvalStatus.HasSideEffects)
9130  return false;
9131  }
9132 
9133  // Build fake call to Callee.
9134  CallStackFrame Frame(Info, Callee->getLocation(), Callee, /*This*/nullptr,
9135  ArgValues.data());
9136  return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
9137 }
9138 
9141  PartialDiagnosticAt> &Diags) {
9142  // FIXME: It would be useful to check constexpr function templates, but at the
9143  // moment the constant expression evaluator cannot cope with the non-rigorous
9144  // ASTs which we build for dependent expressions.
9145  if (FD->isDependentContext())
9146  return true;
9147 
9148  Expr::EvalStatus Status;
9149  Status.Diag = &Diags;
9150 
9151  EvalInfo Info(FD->getASTContext(), Status,
9152  EvalInfo::EM_PotentialConstantExpression);
9153 
9154  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9155  const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
9156 
9157  // Fabricate an arbitrary expression on the stack and pretend that it
9158  // is a temporary being used as the 'this' pointer.
9159  LValue This;
9160  ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
9161  This.set(&VIE, Info.CurrentCall->Index);
9162 
9163  ArrayRef<const Expr*> Args;
9164 
9165  SourceLocation Loc = FD->getLocation();
9166 
9167  APValue Scratch;
9168  if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
9169  // Evaluate the call as a constant initializer, to allow the construction
9170  // of objects of non-literal types.
9171  Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
9172  HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
9173  } else
9174  HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
9175  Args, FD->getBody(), Info, Scratch);
9176 
9177  return Diags.empty();
9178 }
9179 
9181  const FunctionDecl *FD,
9183  PartialDiagnosticAt> &Diags) {
9184  Expr::EvalStatus Status;
9185  Status.Diag = &Diags;
9186 
9187  EvalInfo Info(FD->getASTContext(), Status,
9188  EvalInfo::EM_PotentialConstantExpressionUnevaluated);
9189 
9190  // Fabricate a call stack frame to give the arguments a plausible cover story.
9191  ArrayRef<const Expr*> Args;
9192  ArgVector ArgValues(0);
9193  bool Success = EvaluateArgs(Args, ArgValues, Info);
9194  (void)Success;
9195  assert(Success &&
9196  "Failed to set up arguments for potential constant evaluation");
9197  CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
9198 
9199  APValue ResultScratch;
9200  Evaluate(ResultScratch, Info, E);
9201  return Diags.empty();
9202 }
Expr * getInc()
Definition: Stmt.h:1178
bool isArray() const
Definition: APValue.h:188
unsigned getNumElements() const
Definition: Type.h:2724
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:2411
bool isNegative() const
isNegative - Test whether the quantity is less than zero.
Definition: CharUnits.h:125
Defines the clang::ASTContext interface.
unsigned getNumInits() const
Definition: Expr.h:3789
const SwitchCase * getNextSwitchCase() const
Definition: Stmt.h:667
CastKind getCastKind() const
Definition: Expr.h:2709
The null pointer literal (C++11 [lex.nullptr])
Definition: ExprCXX.h:466
Expr ** getArgs()
Retrieve the call arguments.
Definition: Expr.h:2208
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
bool isVector() const
Definition: APValue.h:187
body_iterator body_end()
Definition: Stmt.h:587
bool isNullPtrType() const
Definition: Type.h:5439
const FieldDecl * getUnionField() const
Definition: APValue.h:322
ParmVarDecl *const * param_const_iterator
Definition: Decl.h:1943
static bool IsGlobalLValue(APValue::LValueBase B)
bool isFileScope() const
Definition: Expr.h:2621
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition: Decl.cpp:2101
bool isVirtual() const
Determines whether the base class is a virtual base class (or not).
Definition: DeclCXX.h:206
Static storage duration.
Definition: Specifiers.h:242
bool isEvaluatable(const ASTContext &Ctx) const
base_class_range bases()
Definition: DeclCXX.h:713
bool isCharType() const
Definition: Type.cpp:1633
unsigned getFieldCount() const
getFieldCount - Get the number of fields in the layout.
Definition: RecordLayout.h:177
static Opcode getOpForCompoundAssignment(Opcode Opc)
Definition: Expr.h:3051
bool isSpecificBuiltinType(unsigned K) const
isSpecificBuiltinType - Test for a particular builtin type.
Definition: Type.h:5393
bool getValue() const
Definition: ExprCXX.h:446
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:2216
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:2330
bool isMemberPointerType() const
Definition: Type.h:5256
QualType getType() const
Retrieves the type of the base class.
Definition: DeclCXX.h:252
bool isElidable() const
Whether this construction is elidable.
Definition: ExprCXX.h:1144
bool operator==(CanQual< T > x, CanQual< U > y)
Expr * getCond()
Definition: Stmt.h:1066
A type trait used in the implementation of various C++11 and Library TR1 trait templates.
Definition: ExprCXX.h:2083
CompoundStmt * getSubStmt()
Definition: Expr.h:3412
static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info, const Stmt *S, const SwitchCase *SC=nullptr)
bool isArgumentType() const
Definition: Expr.h:2013
unsigned getIntWidth(QualType T) const
SourceLocation getLocStart() const LLVM_READONLY
Definition: Stmt.h:683
Expr * GetTemporaryExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue...
Definition: ExprCXX.h:3787
void addConst()
addConst - add the specified type qualifier to this QualType.
Definition: Type.h:733
ActionResult< Expr * > ExprResult
Definition: Ownership.h:252
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:163
TypeSourceInfo * getTypeSourceInfo() const
Definition: Expr.h:1918
bool isRecordType() const
Definition: Type.h:5289
unsigned getPackLength() const
Retrieve the length of the parameter pack.
Definition: ExprCXX.h:3539
chain_range chain() const
Definition: Decl.h:2510
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition: Decl.cpp:1987
bool isLiteralType(const ASTContext &Ctx) const
Definition: Type.cpp:2110
bool isPowerOfTwo() const
Definition: CharUnits.h:129
bool isVoidPointerType() const
Definition: Type.cpp:384
bool isEnumeralType() const
Definition: Type.h:5292
static bool extractSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, const SubobjectDesignator &Sub, APValue &Result)
Extract the designated sub-object of an rvalue.
const DiagnosticBuilder & operator<<(const DiagnosticBuilder &DB, const Attr *At)
Definition: Attr.h:154
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type...
bool isMemberPointer() const
Definition: APValue.h:191
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:851
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:5049
static bool IsConstNonVolatile(QualType T)
const Expr * getResultExpr() const
Definition: Expr.h:4514
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:232
bool hasLValuePath() const
Definition: APValue.cpp:568
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1075
An Embarcadero array type trait, as used in the implementation of __array_rank and __array_extent...
Definition: ExprCXX.h:2182
bool isBooleanType() const
Definition: Type.h:5489
static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, const LValue &LV)
Determine whether this is a pointer past the end of the complete object referred to by the lvalue...
llvm::DenseMap< Stmt *, Stmt * > MapTy
Definition: ParentMap.cpp:22
const Stmt * getElse() const
Definition: Stmt.h:918
VarDecl * getConditionVariable() const
Retrieve the variable declared in this "for" statement, if any.
Definition: Stmt.cpp:925
SourceLocation getLocEnd() const LLVM_READONLY
Definition: DeclBase.h:368
[ARC] Consumes a retainable object pointer that has just been produced, e.g. as the return value of a...
static const ValueDecl * HandleMemberPointerAccess(EvalInfo &Info, QualType LVType, LValue &LV, const Expr *RHS, bool IncludeMember=true)
static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, EvalInfo &Info)
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2147
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
Definition: Expr.cpp:2912
Represents a prvalue temporary that is written into memory so that a reference can bind to it...
Definition: ExprCXX.h:3746
static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, QualType Type, const LValue &LVal)
const llvm::APInt & getSize() const
Definition: Type.h:2472
Expr * getIndexExpr(unsigned Idx)
Definition: Expr.h:1939
static bool EvaluateDecl(EvalInfo &Info, const Decl *D)
const CXXBaseSpecifier *const * path_const_iterator
Definition: Expr.h:2726
bool isImplicit() const
Definition: ExprCXX.h:792
const Expr * getCallee() const
Definition: Expr.h:2188
static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E)
APFloat & getComplexFloatReal()
Definition: APValue.h:232
bool hasCaptures() const
Definition: Decl.h:3552
AccessSpecifier getAccess() const
Definition: DeclBase.h:416
field_iterator field_begin() const
Definition: Decl.cpp:3629
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:1701
CK_Dynamic - A C++ dynamic_cast.
Implicit construction of a std::initializer_list<T> object from an array temporary within list-initia...
Definition: ExprCXX.h:492
bool isRealType() const
Definition: Type.cpp:1782
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition: DeclCXX.cpp:1797
UnaryExprOrTypeTrait getKind() const
Definition: Expr.h:2008
static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E)
unsigned getValue() const
Definition: Expr.h:1349
static bool isAssignmentOp(Opcode Opc)
Definition: Expr.h:3040
bool body_empty() const
Definition: Stmt.h:579
ParmVarDecl - Represents a parameter to a function.
Definition: Decl.h:1334
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
Definition: Expr.cpp:3225
unsigned path_size() const
Definition: Expr.h:2728
bool hasMutableFields() const
Determine whether this class, or any of its class subobjects, contains a mutable field.
Definition: DeclCXX.h:1163
CompleteObject(APValue *Value, QualType Type)
bool isUnionType() const
Definition: Type.cpp:390
bool isVoidType() const
Definition: Type.h:5426
static bool HasSameBase(const LValue &A, const LValue &B)
Expr * IgnoreImpCasts() LLVM_READONLY
Definition: Expr.h:2803
Stmt * getBody()
Definition: Stmt.h:1114
static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type, CharUnits &Size)
Get the size of the given type in char units.
ArrayRef< const CXXRecordDecl * > getMemberPointerPath() const
Definition: APValue.cpp:622
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition: DeclCXX.h:1144
bool isComplexInt() const
Definition: APValue.h:184
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition: Decl.h:2435
static bool TryEvaluateBuiltinNaN(const ASTContext &Context, QualType ResultTy, const Expr *Arg, bool SNaN, llvm::APFloat &Result)
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:1742
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:89
Converts between different integral complex types. _Complex char -> _Complex long long _Complex unsig...
static bool EvaluateVector(const Expr *E, APValue &Result, EvalInfo &Info)
bool isDelegatingConstructor() const
Determine whether this constructor is a delegating constructor.
Definition: DeclCXX.h:2255
bool getValue() const
Definition: ExprCXX.h:3365
bool isReferenceType() const
Definition: Type.h:5241
QualType getReturnType() const
Definition: Decl.h:1997
bool isStructureOrClassType() const
Definition: Type.cpp:377
Converting between two Objective-C object types, which can occur when performing reference binding to...
static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info)
bool isPotentiallyEvaluated() const
Definition: ExprCXX.cpp:28
[ARC] Causes a value of block type to be copied to the heap, if it is not already there...
Expr * getSubExpr()
Definition: Expr.h:2713
static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, const RecordDecl *RD, const LValue &This, APValue &Result)
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:48
Expr * getLHS() const
Definition: Expr.h:2964
unsigned getLValueCallIndex() const
Definition: APValue.cpp:579
static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info)
static bool isRelationalOp(Opcode Opc)
Definition: Expr.h:3001
Converts a floating point complex to bool by comparing against 0+0i.
static bool IsWeakLValue(const LValue &Value)
static ICEDiag CheckEvalInICE(const Expr *E, const ASTContext &Ctx)
Describes an C or C++ initializer list.
Definition: Expr.h:3759
uint32_t getCodeUnit(size_t i) const
Definition: Expr.h:1543
Expr * getChosenSubExpr() const
Definition: Expr.h:3605
BinaryOperatorKind
SmallVectorImpl< PartialDiagnosticAt > * Diag
Definition: Expr.h:543
static bool isEqualityOp(Opcode Opc)
Definition: Expr.h:3004
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:518
static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, llvm::APInt &Res)
static void HandleOverflow(EvalInfo &Info, const Expr *E, const T &SrcValue, QualType DestType)
static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E, const APSInt &LHS, const APSInt &RHS, unsigned BitWidth, Operation Op)
const LangOptions & getLangOpts() const
Definition: ASTContext.h:533
unsigned getLength() const
Definition: Expr.h:1554
virtual bool isNan2008() const
Returns true if NaN encoding is IEEE 754-2008. Only MIPS allows a different encoding.
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:557
static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, const LValue &LVal, APValue &RVal)
Perform an lvalue-to-rvalue conversion on the given glvalue. This can also be used for 'lvalue-to-lva...
uint32_t Offset
Definition: CacheTokens.cpp:43
const ValueDecl * getMemberPointerDecl() const
Definition: APValue.cpp:608
const CXXRecordDecl * getParent() const
Definition: DeclCXX.h:1817
bool isDefaulted() const
Definition: Decl.h:1805
Expr * getExprOperand() const
Definition: ExprCXX.h:589
path_iterator path_begin()
Definition: Expr.h:2729
field_range fields() const
Definition: Decl.h:3349
Stmt * getBody()
Definition: Stmt.h:1179
static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, LValue &Result)
static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, LValue &LVal, QualType EltTy, int64_t Adjustment)
const ArrayType * getAsArrayType(QualType T) const
static bool isRecordType(QualType T)
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:2918
const Expr * skipRValueSubobjectAdjustments(SmallVectorImpl< const Expr * > &CommaLHS, SmallVectorImpl< SubobjectAdjustment > &Adjustments) const
Definition: Expr.cpp:54
Stmt * getInit()
Definition: Stmt.h:1158
bool isValueDependent() const
Definition: Expr.h:146
RecordDecl * getDecl() const
Definition: Type.h:3527
bool isUnsignedIntegerType() const
Definition: Type.cpp:1723
Expr * IgnoreParenCasts() LLVM_READONLY
Definition: Expr.cpp:2439
static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, QualType LValType, bool IsIncrement, APValue *Old)
Perform an increment or decrement on LVal.
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:651
Expr * getCond()
Definition: Stmt.h:1177
uint64_t getFieldOffset(unsigned FieldNo) const
Definition: RecordLayout.h:181
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr...
Definition: Decl.cpp:3840
static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, uint64_t Index)
Extract the value of a character from a string literal.
static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK, const LValue &LVal, QualType LValType)
Find the complete object to which an LValue refers.
base_class_iterator bases_begin()
Definition: DeclCXX.h:720
bool isIncompleteType(NamedDecl **Def=nullptr) const
Def If non-NULL, and the type refers to some kind of declaration that can be completed (such as a C s...
Definition: Type.cpp:1869
static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, LValue &LVal, QualType EltTy, bool Imag)
bool hasConst() const
Definition: Type.h:226
static void expandArray(APValue &Array, unsigned Index)
unsigned getBuiltinCallee() const
Definition: Expr.cpp:1219
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
APSInt & getComplexIntReal()
Definition: APValue.h:216
init_iterator init_begin()
Retrieve an iterator to the first initializer.
Definition: DeclCXX.h:2206
A default argument (C++ [dcl.fct.default]).
Definition: ExprCXX.h:862
static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, BinaryOperatorKind Opcode, APSInt RHS, APSInt &Result)
Perform the given binary integer operation.
QualType getType() const
Definition: Decl.h:538
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:733
bool isUnnamedBitfield() const
Determines whether this is an unnamed bitfield.
Definition: Decl.h:2336
bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result=nullptr, SourceLocation *Loc=nullptr) const
Represents the this expression in C++.
Definition: ExprCXX.h:770
DiagnosticsEngine & getDiagnostics() const
field_iterator field_end() const
Definition: Decl.h:3352
APValue & getVectorElt(unsigned I)
Definition: APValue.h:258
AnnotatingParser & P
bool isAddrLabelDiff() const
Definition: APValue.h:192
CXXBaseSpecifier * getBase() const
For a base class node, returns the base specifier.
Definition: Expr.h:1865
bool isStatic() const
Definition: DeclCXX.cpp:1402
bool isUnion() const
Definition: Decl.h:2906
const ArrayType * castAsArrayTypeUnsafe() const
Definition: Type.h:5595
Expr * getFalseExpr() const
Definition: Expr.h:3231
llvm::APInt getValue() const
Definition: Expr.h:1262
static bool handleCompoundAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, QualType LValType, QualType PromotedLValType, BinaryOperatorKind Opcode, const APValue &RVal)
Perform a compound assignment of LVal <op>= RVal.
Causes a block literal to by copied to the heap and then autoreleased.
static unsigned FindDesignatorMismatch(QualType ObjType, const SubobjectDesignator &A, const SubobjectDesignator &B, bool &WasArrayIndex)
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const
QualType Type
The type of the complete object.
APValue & getArrayFiller()
Definition: APValue.h:282
ASTContext * Context
const Expr * getExpr() const
Get the initialization expression that will be used.
Definition: ExprCXX.h:977
const SmallVectorImpl< AnnotatedLine * >::const_iterator End
Expr * getCond() const
Definition: Expr.h:3222
QualType getPointeeType() const
Definition: Type.cpp:414
bool isFunctionPointerType() const
Definition: Type.h:5250
Converts between different floating point complex types. _Complex float -> _Complex double...
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:1776
bool requiresZeroInitialization() const
Whether this construction first requires zero-initialization before the initializer is called...
Definition: ExprCXX.h:1165
unsigned getArrayInitializedElts() const
Definition: APValue.h:290
bool hasVolatile() const
Definition: Type.h:233
bool isSignedIntegerOrEnumerationType() const
Definition: Type.cpp:1699
unsigned getArrayExprIndex() const
For an array element node, returns the index into the array of expressions.
Definition: Expr.h:1849
Converts an integral complex to an integral real of the source's element type by discarding the imagi...
static bool HandleConversionToBool(const APValue &Val, bool &Result)
static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info)
Evaluate an expression of record type as a temporary.
bool isAnyComplexType() const
Definition: Type.h:5295
static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, const ASTContext &Ctx, bool &IsConst)
VarDecl * getConditionVariable() const
Retrieve the variable declared in this "while" statement, if any.
Definition: Stmt.cpp:985
bool getValue() const
Definition: ExprCXX.h:2126
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition: ExprCXX.h:3790
static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, LValue &This)
Build an lvalue for the object argument of a member function call.
bool isMemberPointerToDerivedMember() const
Definition: APValue.cpp:615
bool isComplexFloat() const
Definition: APValue.h:185
bool isAtomicType() const
Definition: Type.h:5314
bool isUnion() const
Definition: APValue.h:190
bool isVariableArrayType() const
Definition: Type.h:5280
#define bool
Definition: stdbool.h:31
Stmt * getBody()
Definition: Stmt.h:1069
DeclContext * getDeclContext()
Definition: DeclBase.h:381
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:224
Expr * getRHS()
Definition: Stmt.h:718
AccessKinds
Kinds of access we can perform on an object, for diagnostics.
bool isFloatingType() const
Definition: Type.cpp:1760
Represents an expression that computes the length of a parameter pack.
Definition: ExprCXX.h:3473
bool isStruct() const
Definition: APValue.h:189
static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, EvalInfo &Info)
void removeLocalConst()
Definition: Type.h:5110
static int EvaluateBuiltinClassifyType(const CallExpr *E)
Defines the clang::TypeLoc interface and its subclasses.
const SwitchCase * getSwitchCaseList() const
Definition: Stmt.h:987
static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, const Expr *Cond, bool &Result)
Evaluate a condition (either a variable declaration or an expression).
unsigned getConstexprBacktraceLimit() const
Retrieve the maximum number of constexpr evaluation notes to emit along with a given diagnostic...
Definition: Diagnostic.h:433
static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T)
static bool isPotentialConstantExpr(const FunctionDecl *FD, SmallVectorImpl< PartialDiagnosticAt > &Diags)
static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E, QualType T)
Expr * getSubExpr() const
Definition: Expr.h:1699
bool isDependentType() const
Definition: Type.h:1727
PartialDiagnostic::StorageAllocator & getDiagAllocator()
Definition: ASTContext.h:514
APValue & getStructField(unsigned i)
Definition: APValue.h:311
static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, const RecordDecl *TruncatedType, unsigned TruncatedElements)
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1174
bool EvaluateAsInt(llvm::APSInt &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects) const
static bool IsStringLiteralCall(const CallExpr *E)
Should this call expression be treated as a string literal?
unsigned getNumComponents() const
Definition: Expr.h:1935
Converts from an integral complex to a floating complex. _Complex unsigned -> _Complex float...
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition: ExprCXX.h:3558
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:707
ValueDecl * getDecl()
Definition: Expr.h:994
QualType getElementType() const
Definition: Type.h:2723
bool isGLValue() const
Definition: Expr.h:253
APSInt & getComplexIntImag()
Definition: APValue.h:224
QualType getComputationLHSType() const
Definition: Expr.h:3133
static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This, ArrayRef< const Expr * > Args, const CXXConstructorDecl *Definition, EvalInfo &Info, APValue &Result)
Evaluate a constructor call.
bool isComplexIntegerType() const
Definition: Type.cpp:402
The result type of a method or function.
static bool EvaluateArgs(ArrayRef< const Expr * > Args, ArgVector &ArgValues, EvalInfo &Info)
EvaluateArgs - Evaluate the arguments to a function call.
bool checkInitIsICE() const
Determine whether the value of the initializer attached to this declaration is an integral constant e...
Definition: Decl.cpp:2159
bool isUnsignedIntegerOrEnumerationType() const
Definition: Type.cpp:1739
static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, QualType DestType, QualType SrcType, APSInt &Value)
static bool HandleFunctionCall(SourceLocation CallLoc, const FunctionDecl *Callee, const LValue *This, ArrayRef< const Expr * > Args, const Stmt *Body, EvalInfo &Info, APValue &Result)
Evaluate a function call.
do v
Definition: arm_acle.h:77
void EvaluateForOverflow(const ASTContext &Ctx) const
Expr * getTrueExpr() const
Definition: Expr.h:3226
const Expr * getAnyInitializer() const
Definition: Decl.h:1056
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:1835
static EvalStmtResult EvaluateLoopBody(APValue &Result, EvalInfo &Info, const Stmt *Body, const SwitchCase *Case=nullptr)
Evaluate the body of a loop, and translate the result as appropriate.
bool isLValueOnePastTheEnd() const
Definition: APValue.cpp:558
bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx, const VarDecl *VD, SmallVectorImpl< PartialDiagnosticAt > &Notes) const
SideEffectsKind
Definition: Expr.h:578
APValue & getStructBase(unsigned i)
Definition: APValue.h:307
Stmt * getBody(const FunctionDecl *&Definition) const
Definition: Decl.cpp:2405
SourceLocation getLocStart() const LLVM_READONLY
Definition: DeclBase.h:365
A C++ dynamic_cast expression (C++ [expr.dynamic.cast]).
Definition: ExprCXX.h:269
static ICEDiag Worst(ICEDiag A, ICEDiag B)
bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx) const
APValue & getArrayInitializedElt(unsigned I)
Definition: APValue.h:271
#define false
Definition: stdbool.h:33
Kind
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:5476
bool isUninit() const
Definition: APValue.h:181
static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info)
bool getValue() const
Definition: ExprObjC.h:71
EvalStmtResult
Encodes a location in the source. The SourceManager can decode this to get at the full include stack...
body_range body()
Definition: Stmt.h:585
const Type * getTypePtr() const
Definition: Type.h:5016
static ICEDiag NoDiag()
QualType getElementType() const
Definition: Type.h:2077
ICEKind
unsigned getBitWidthValue(const ASTContext &Ctx) const
Definition: Decl.cpp:3344
Expr * getSourceExpr() const
Definition: Expr.h:869
static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, const APValue &Value)
bool isComplexType() const
Definition: Type.cpp:396
APValue & getUnionValue()
Definition: APValue.h:326
Expr * getLHS()
Definition: Stmt.h:717
bool isConstantSizeType() const
Definition: Type.cpp:1859
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:284
static bool EvalPointerValueAsBool(const APValue &Value, bool &Result)
ValueKind getKind() const
Definition: APValue.h:180
const Expr * getCond() const
Definition: Stmt.h:985
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3408
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
static bool IsLiteralLValue(const LValue &Value)
APFloat & getFloat()
Definition: APValue.h:208
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1717
static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E, APFloat &LHS, BinaryOperatorKind Opcode, const APFloat &RHS)
Perform the given binary floating-point operation, in-place, on LHS.
#define ilogb(__x)
Definition: tgmath.h:858
bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx, SourceLocation *Loc=nullptr, bool isEvaluated=true) const
bool getValue() const
Definition: ExprCXX.h:2290
static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, APValue &Value, const FieldDecl *FD)
unsigned getCharByteWidth() const
Definition: Expr.h:1555
const Type * getBaseElementTypeUnsafe() const
Definition: Type.h:5520
Converts from an integral real to an integral complex whose element type matches the source...
VarDecl * getConditionVariable() const
Retrieve the variable declared in this "switch" statement, if any.
Definition: Stmt.cpp:951
static const ValueDecl * GetLValueBaseDecl(const LValue &LVal)
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs. ...
void printPretty(raw_ostream &OS, ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:344
bool isRValue() const
Definition: Expr.h:251
const T * castAs() const
Definition: Type.h:5586
bool isVectorType() const
Definition: Type.h:5298
static bool EvaluateRecord(const Expr *E, const LValue &This, APValue &Result, EvalInfo &Info)
static bool isLogicalOp(Opcode Opc)
Definition: Expr.h:3037
An expression trait intrinsic.
Definition: ExprCXX.h:2252
static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, QualType SrcType, QualType DestType, APFloat &Result)
uint64_t getValue() const
Definition: ExprCXX.h:2231
static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E)
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:5086
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Definition: Expr.h:3840
const BlockDecl * getBlockDecl() const
Definition: Expr.h:4616
bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const
QualType getType() const
Return the type wrapped by this type source info.
Definition: Decl.h:68
Opcode getOpcode() const
Definition: Expr.h:1696
bool isGlobalLValue() const
const OffsetOfNode & getComponent(unsigned Idx) const
Definition: Expr.h:1925
SourceLocation getExprLoc() const LLVM_READONLY
Definition: Expr.cpp:193
bool isPtrMemOp() const
predicates to categorize the respective opcodes.
Definition: Expr.h:2991
Represents a C11 generic selection.
Definition: Expr.h:4446
EvalStatus is a struct with detailed info about an evaluation in progress.
Definition: Expr.h:531
bool isArrow() const
Definition: Expr.h:2548
AddrLabelExpr - The GNU address of label extension, representing &&label.
Definition: Expr.h:3357
QualType getType() const
Definition: Expr.h:125
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T-> getSizeExpr()))
static bool EvaluateVoid(const Expr *E, EvalInfo &Info)
Converts a floating point complex to floating point real of the source's element type. Just discards the imaginary component. _Complex long double -> long double.
static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base)
VarDecl * getConditionVariable() const
Retrieve the variable declared in this "if" statement, if any.
Definition: Stmt.cpp:894
Expr * getCommon() const
getCommon - Return the common expression, written to the left of the condition. The opaque value will...
Definition: Expr.h:3298
static const Type * getElementType(const Expr *BaseExpr)
static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, EvalInfo &Info)
static unsigned getBaseIndex(const CXXRecordDecl *Derived, const CXXRecordDecl *Base)
const Expr * getExpr() const
Definition: ExprCXX.h:911
[C99 6.4.2.2] - A predefined identifier such as func.
Definition: Expr.h:1174
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:555
Converts an integral complex to bool by comparing against 0+0i.
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:116
static bool isZeroSized(const LValue &Value)
return(x >> y)|(x<< (32-y))
const Stmt * getBody() const
Definition: Stmt.h:986
void swap(APValue &RHS)
Swaps the contents of this and the given APValue.
Definition: APValue.cpp:250
bool isInvalidDecl() const
Definition: DeclBase.h:498
A C++ reinterpret_cast expression (C++ [expr.reinterpret.cast]).
Definition: ExprCXX.h:306
static bool CheckLiteralType(EvalInfo &Info, const Expr *E, const LValue *This=nullptr)
Kind getKind() const
Determine what kind of offsetof node this is.
Definition: Expr.h:1843
bool isLValue() const
Definition: Expr.h:250
StringRef getString() const
Definition: Expr.h:1521
bool path_empty() const
Definition: Expr.h:2727
static int64_t getExtValue(const APSInt &Value)
unsigned getNumArgs() const
Definition: Expr.h:2205
A conversion of a floating point real to a floating point complex of the original type...
unsigned getNumArgs() const
Definition: ExprCXX.h:1198
bool field_empty() const
Definition: Decl.h:3358
body_iterator body_begin()
Definition: Stmt.h:586
bool isFloat() const
Definition: APValue.h:183
Stmt *const * const_body_iterator
Definition: Stmt.h:596
llvm::APFloat getValue() const
Definition: Expr.h:1377
Expr * IgnoreParenImpCasts() LLVM_READONLY
Definition: Expr.cpp:2526
[ARC] Reclaim a retainable object pointer object that may have been produced and autoreleased as part...
FieldDecl * getField() const
For a field offsetof node, returns the field.
Definition: Expr.h:1855
const Stmt * getThen() const
Definition: Stmt.h:916
QualType getNonReferenceType() const
Definition: Type.h:5182
path_iterator path_end()
Definition: Expr.h:2730
Represents a C++11 noexcept expression (C++ [expr.unary.noexcept]).
Definition: ExprCXX.h:3337
ArrayRef< LValuePathEntry > getLValuePath() const
Definition: APValue.cpp:573
const T * getAs() const
Definition: Type.h:5555
static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, const CXXRecordDecl *Derived, const CXXRecordDecl *Base, const ASTRecordLayout *RL=nullptr)
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2066
QualType getTypeOfArgument() const
Definition: Expr.h:2040
DeclStmt * getBeginEndStmt()
Definition: StmtCXX.h:151
static bool hasFields(const CXXRecordDecl *RD)
OpaqueValueExpr * getOpaqueValue() const
getOpaqueValue - Return the opaque value placeholder.
Definition: Expr.h:3301
llvm::PointerUnion< const ValueDecl *, const Expr * > LValueBase
Definition: APValue.h:56
static CharUnits GetAlignOfType(EvalInfo &Info, QualType T)
[ARC] Produces a retainable object pointer so that it may be consumed, e.g. by being passed to a cons...
static bool modifySubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, const SubobjectDesignator &Sub, APValue &NewVal)
Update the designated sub-object of an rvalue to the given value.
static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, QualType SrcType, const APSInt &Value, QualType DestType, APFloat &Result)
bool isFunctionType() const
Definition: Type.h:5229
Converts from T to _Atomic(T).
static bool isAdditiveOp(Opcode Opc)
Definition: Expr.h:2993
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition: ExprCXX.h:1201
CXXConstructorDecl * getConstructor() const
Definition: ExprCXX.h:1137
static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info)
decl_range decls()
Definition: Stmt.h:497
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1505
bool isTrivial() const
Definition: Decl.h:1800
Converts from a floating complex to an integral complex. _Complex float -> _Complex int...
static bool EvaluateArray(const Expr *E, const LValue &This, APValue &Result, EvalInfo &Info)
const Expr * getSubExpr() const
Definition: Expr.h:1442
static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, QualType Type, LValue &Result)
SubobjectHandler::result_type findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, const SubobjectDesignator &Sub, SubobjectHandler &handler)
Find the designated sub-object of an rvalue.
static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, const CXXRecordDecl *DerivedDecl, const CXXBaseSpecifier *Base)
SourceLocation getExprLoc() const LLVM_READONLY
Definition: Expr.h:2957
LabelDecl * getLabel() const
Definition: Expr.h:3379
Represents a base class of a C++ class.
Definition: DeclCXX.h:157
static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, const FieldDecl *FD, const ASTRecordLayout *RL=nullptr)
const Expr * getInitializer() const
Definition: Expr.h:2617
unsigned getFieldIndex() const
Definition: Decl.cpp:3350
bool isDefaultConstructor() const
Definition: DeclCXX.cpp:1777
DeclStmt * getRangeStmt()
Definition: StmtCXX.h:150
static bool isIncrementOp(Opcode Op)
Definition: Expr.h:1719
static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, const Expr *E, bool AllowNonLiteralTypes=false)
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condnition evaluates to false;...
Definition: Expr.h:3317
A use of a default initializer in a constructor or in aggregate initialization.
Definition: ExprCXX.h:952
Expr * getBase() const
Definition: Expr.h:2405
static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, LValue &LVal, const IndirectFieldDecl *IFD)
Update LVal to refer to the given indirect field.
Expr * getCond()
Definition: Stmt.h:1111
static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, const FunctionDecl *Declaration, const FunctionDecl *Definition)
static bool EvaluateBuiltinConstantPForLValue(const LValue &LV)
const Expr * getSubExpr() const
Definition: Expr.h:1638
static EvalStmtResult EvaluateSwitch(APValue &Result, EvalInfo &Info, const SwitchStmt *SS)
Evaluate a switch statement.
bool hasArrayFiller() const
Return true if this is an array initializer and its array "filler" has been set.
Definition: Expr.h:3850
APFloat & getComplexFloatImag()
Definition: APValue.h:240
const LValueBase getLValueBase() const
Definition: APValue.cpp:553
Represents a C++ struct/union/class.
Definition: DeclCXX.h:285
#define scalbn(__x, __y)
Definition: tgmath.h:1172
static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info)
Opcode getOpcode() const
Definition: Expr.h:2961
static bool isReadByLvalueToRvalueConversion(QualType T)
static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, const Expr *E, llvm::APSInt *Value, SourceLocation *Loc)
Evaluate an expression as a C++11 integral constant expression.
const Expr * getCond() const
Definition: Stmt.h:914
base_class_iterator bases_end()
Definition: DeclCXX.h:722
llvm::PointerIntPair< const Decl *, 1, bool > BaseOrMemberType
Definition: APValue.h:57
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1233
static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info)
static ICEDiag CheckICE(const Expr *E, const ASTContext &Ctx)
Converts from _Atomic(T) to T.
bool isArrayType() const
Definition: Type.h:5271
CheckSubobjectKind
Defines the clang::TargetInfo interface.
Expr * getRHS() const
Definition: Expr.h:2966
static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg)
bool isInt() const
Definition: APValue.h:182
CanQualType IntTy
Definition: ASTContext.h:825
bool isStringLiteralInit() const
Definition: Expr.cpp:1935
APValue * getEvaluatedValue() const
Return the already-evaluated value of this variable's initializer, or NULL if the value is not yet kn...
Definition: Decl.h:1127
A reference to a declared variable, function, enum, etc. [C99 6.5.1p2].
Definition: Expr.h:899
QualType getElementType() const
Definition: Type.h:2434
CXXCtorInitializer *const * init_const_iterator
Iterates through the member/base initializer list.
Definition: DeclCXX.h:2195
static bool AreElementsOfSameArray(QualType ObjType, const SubobjectDesignator &A, const SubobjectDesignator &B)
static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, const VarDecl *VD, CallStackFrame *Frame, APValue *&Result)
const Expr * getInit(unsigned Init) const
Definition: Expr.h:3794
static void expandStringLiteral(EvalInfo &Info, const Expr *Lit, APValue &Result)
FieldDecl * getInitializedFieldInUnion()
If this initializes a union, specifies which field in the union to initialize.
Definition: Expr.h:3858
static bool isPotentialConstantExprUnevaluated(Expr *E, const FunctionDecl *FD, SmallVectorImpl< PartialDiagnosticAt > &Diags)
DeclStmt * getLoopVarStmt()
Definition: StmtCXX.h:156
#define true
Definition: stdbool.h:32
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
APValue * Value
The value of the complete object.
SourceLocation getLocation() const
Definition: DeclBase.h:372
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition: DeclCXX.h:728
static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, QualType SrcType, const APFloat &Value, QualType DestType, APSInt &Result)
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition: ExprCXX.h:434
Automatic storage duration (most local variables).
Definition: Specifiers.h:240
bool isSignedIntegerType() const
Definition: Type.cpp:1683
APSInt & getInt()
Definition: APValue.h:200
unsigned getArraySize() const
Definition: APValue.h:294
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:5075
bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const
bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, const FunctionDecl *Callee, ArrayRef< const Expr * > Args) const
bool isNull() const
isNull - Return true if this QualType doesn't point to a type yet.
Definition: Type.h:633
static bool isComparisonOp(Opcode Opc)
Definition: Expr.h:3007
static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, QualType LValType, APValue &Val)
Perform an assignment of Val to LVal. Takes ownership of Val.
unsigned getVectorLength() const
Definition: APValue.h:266
Defines enum values for all the target-independent builtin functions.
Represents an implicitly-generated value initialization of an object of a given type.
Definition: Expr.h:4352
static void describeCall(CallStackFrame *Frame, raw_ostream &Out)
Produce a string describing the given constexpr call.
bool hasPointerRepresentation() const
Definition: Type.h:5511
bool isIntegerType() const
Definition: Type.h:5448
bool hasLocalStorage() const
Definition: Decl.h:887
bool hasArrayFiller() const
Definition: APValue.h:279
static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, const CXXConstructorDecl *CD, bool IsValueInitialization)
const RecordDecl * getParent() const
Definition: Decl.h:2424
Expr * IgnoreParens() LLVM_READONLY
Definition: Expr.cpp:2408
CharUnits & getLValueOffset()
Definition: APValue.cpp:563
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:5043
bool isLValue() const
Definition: APValue.h:186
bool isPointerType() const
Definition: Type.h:5232
static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result)
QualType getArgumentType() const
Definition: Expr.h:2014