clang  7.0.0svn
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/ASTLambda.h"
40 #include "clang/AST/CharUnits.h"
41 #include "clang/AST/Expr.h"
42 #include "clang/AST/RecordLayout.h"
43 #include "clang/AST/StmtVisitor.h"
44 #include "clang/AST/TypeLoc.h"
45 #include "clang/Basic/Builtins.h"
46 #include "clang/Basic/TargetInfo.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include <cstring>
49 #include <functional>
50 
51 #define DEBUG_TYPE "exprconstant"
52 
53 using namespace clang;
54 using llvm::APSInt;
55 using llvm::APFloat;
56 
57 static bool IsGlobalLValue(APValue::LValueBase B);
58 
59 namespace {
60  struct LValue;
61  struct CallStackFrame;
62  struct EvalInfo;
63 
64  static QualType getType(APValue::LValueBase B) {
65  if (!B) return QualType();
66  if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
67  // FIXME: It's unclear where we're supposed to take the type from, and
68  // this actually matters for arrays of unknown bound. Using the type of
69  // the most recent declaration isn't clearly correct in general. Eg:
70  //
71  // extern int arr[]; void f() { extern int arr[3]; };
72  // constexpr int *p = &arr[1]; // valid?
73  return cast<ValueDecl>(D->getMostRecentDecl())->getType();
74 
75  const Expr *Base = B.get<const Expr*>();
76 
77  // For a materialized temporary, the type of the temporary we materialized
78  // may not be the type of the expression.
79  if (const MaterializeTemporaryExpr *MTE =
80  dyn_cast<MaterializeTemporaryExpr>(Base)) {
83  const Expr *Temp = MTE->GetTemporaryExpr();
84  const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
85  Adjustments);
86  // Keep any cv-qualifiers from the reference if we generated a temporary
87  // for it directly. Otherwise use the type after adjustment.
88  if (!Adjustments.empty())
89  return Inner->getType();
90  }
91 
92  return Base->getType();
93  }
94 
95  /// Get an LValue path entry, which is known to not be an array index, as a
96  /// field or base class.
97  static
100  Value.setFromOpaqueValue(E.BaseOrMember);
101  return Value;
102  }
103 
104  /// Get an LValue path entry, which is known to not be an array index, as a
105  /// field declaration.
106  static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
107  return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
108  }
109  /// Get an LValue path entry, which is known to not be an array index, as a
110  /// base class declaration.
111  static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
112  return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
113  }
114  /// Determine whether this LValue path entry for a base class names a virtual
115  /// base class.
116  static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
117  return getAsBaseOrMember(E).getInt();
118  }
119 
120  /// Given a CallExpr, try to get the alloc_size attribute. May return null.
121  static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
122  const FunctionDecl *Callee = CE->getDirectCallee();
123  return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
124  }
125 
126  /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
127  /// This will look through a single cast.
128  ///
129  /// Returns null if we couldn't unwrap a function with alloc_size.
130  static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
131  if (!E->getType()->isPointerType())
132  return nullptr;
133 
134  E = E->IgnoreParens();
135  // If we're doing a variable assignment from e.g. malloc(N), there will
136  // probably be a cast of some kind. Ignore it.
137  if (const auto *Cast = dyn_cast<CastExpr>(E))
138  E = Cast->getSubExpr()->IgnoreParens();
139 
140  if (const auto *CE = dyn_cast<CallExpr>(E))
141  return getAllocSizeAttr(CE) ? CE : nullptr;
142  return nullptr;
143  }
144 
145  /// Determines whether or not the given Base contains a call to a function
146  /// with the alloc_size attribute.
147  static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
148  const auto *E = Base.dyn_cast<const Expr *>();
149  return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
150  }
151 
152  /// The bound to claim that an array of unknown bound has.
153  /// The value in MostDerivedArraySize is undefined in this case. So, set it
154  /// to an arbitrary value that's likely to loudly break things if it's used.
155  static const uint64_t AssumedSizeForUnsizedArray =
157 
158  /// Determines if an LValue with the given LValueBase will have an unsized
159  /// array in its designator.
160  /// Find the path length and type of the most-derived subobject in the given
161  /// path, and find the size of the containing array, if any.
162  static unsigned
163  findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
165  uint64_t &ArraySize, QualType &Type, bool &IsArray,
166  bool &FirstEntryIsUnsizedArray) {
167  // This only accepts LValueBases from APValues, and APValues don't support
168  // arrays that lack size info.
169  assert(!isBaseAnAllocSizeCall(Base) &&
170  "Unsized arrays shouldn't appear here");
171  unsigned MostDerivedLength = 0;
172  Type = getType(Base);
173 
174  for (unsigned I = 0, N = Path.size(); I != N; ++I) {
175  if (Type->isArrayType()) {
176  const ArrayType *AT = Ctx.getAsArrayType(Type);
177  Type = AT->getElementType();
178  MostDerivedLength = I + 1;
179  IsArray = true;
180 
181  if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
182  ArraySize = CAT->getSize().getZExtValue();
183  } else {
184  assert(I == 0 && "unexpected unsized array designator");
185  FirstEntryIsUnsizedArray = true;
186  ArraySize = AssumedSizeForUnsizedArray;
187  }
188  } else if (Type->isAnyComplexType()) {
189  const ComplexType *CT = Type->castAs<ComplexType>();
190  Type = CT->getElementType();
191  ArraySize = 2;
192  MostDerivedLength = I + 1;
193  IsArray = true;
194  } else if (const FieldDecl *FD = getAsField(Path[I])) {
195  Type = FD->getType();
196  ArraySize = 0;
197  MostDerivedLength = I + 1;
198  IsArray = false;
199  } else {
200  // Path[I] describes a base class.
201  ArraySize = 0;
202  IsArray = false;
203  }
204  }
205  return MostDerivedLength;
206  }
207 
208  // The order of this enum is important for diagnostics.
210  CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
211  CSK_This, CSK_Real, CSK_Imag
212  };
213 
214  /// A path from a glvalue to a subobject of that glvalue.
215  struct SubobjectDesignator {
216  /// True if the subobject was named in a manner not supported by C++11. Such
217  /// lvalues can still be folded, but they are not core constant expressions
218  /// and we cannot perform lvalue-to-rvalue conversions on them.
219  unsigned Invalid : 1;
220 
221  /// Is this a pointer one past the end of an object?
222  unsigned IsOnePastTheEnd : 1;
223 
224  /// Indicator of whether the first entry is an unsized array.
225  unsigned FirstEntryIsAnUnsizedArray : 1;
226 
227  /// Indicator of whether the most-derived object is an array element.
228  unsigned MostDerivedIsArrayElement : 1;
229 
230  /// The length of the path to the most-derived object of which this is a
231  /// subobject.
232  unsigned MostDerivedPathLength : 28;
233 
234  /// The size of the array of which the most-derived object is an element.
235  /// This will always be 0 if the most-derived object is not an array
236  /// element. 0 is not an indicator of whether or not the most-derived object
237  /// is an array, however, because 0-length arrays are allowed.
238  ///
239  /// If the current array is an unsized array, the value of this is
240  /// undefined.
241  uint64_t MostDerivedArraySize;
242 
243  /// The type of the most derived object referred to by this address.
244  QualType MostDerivedType;
245 
246  typedef APValue::LValuePathEntry PathEntry;
247 
248  /// The entries on the path from the glvalue to the designated subobject.
250 
251  SubobjectDesignator() : Invalid(true) {}
252 
253  explicit SubobjectDesignator(QualType T)
254  : Invalid(false), IsOnePastTheEnd(false),
255  FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
256  MostDerivedPathLength(0), MostDerivedArraySize(0),
257  MostDerivedType(T) {}
258 
259  SubobjectDesignator(ASTContext &Ctx, const APValue &V)
260  : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
261  FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
262  MostDerivedPathLength(0), MostDerivedArraySize(0) {
263  assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
264  if (!Invalid) {
265  IsOnePastTheEnd = V.isLValueOnePastTheEnd();
266  ArrayRef<PathEntry> VEntries = V.getLValuePath();
267  Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
268  if (V.getLValueBase()) {
269  bool IsArray = false;
270  bool FirstIsUnsizedArray = false;
271  MostDerivedPathLength = findMostDerivedSubobject(
272  Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
273  MostDerivedType, IsArray, FirstIsUnsizedArray);
274  MostDerivedIsArrayElement = IsArray;
275  FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
276  }
277  }
278  }
279 
280  void setInvalid() {
281  Invalid = true;
282  Entries.clear();
283  }
284 
285  /// Determine whether the most derived subobject is an array without a
286  /// known bound.
287  bool isMostDerivedAnUnsizedArray() const {
288  assert(!Invalid && "Calling this makes no sense on invalid designators");
289  return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
290  }
291 
292  /// Determine what the most derived array's size is. Results in an assertion
293  /// failure if the most derived array lacks a size.
294  uint64_t getMostDerivedArraySize() const {
295  assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
296  return MostDerivedArraySize;
297  }
298 
299  /// Determine whether this is a one-past-the-end pointer.
300  bool isOnePastTheEnd() const {
301  assert(!Invalid);
302  if (IsOnePastTheEnd)
303  return true;
304  if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
305  Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
306  return true;
307  return false;
308  }
309 
310  /// Check that this refers to a valid subobject.
311  bool isValidSubobject() const {
312  if (Invalid)
313  return false;
314  return !isOnePastTheEnd();
315  }
316  /// Check that this refers to a valid subobject, and if not, produce a
317  /// relevant diagnostic and set the designator as invalid.
318  bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
319 
320  /// Update this designator to refer to the first element within this array.
321  void addArrayUnchecked(const ConstantArrayType *CAT) {
322  PathEntry Entry;
323  Entry.ArrayIndex = 0;
324  Entries.push_back(Entry);
325 
326  // This is a most-derived object.
327  MostDerivedType = CAT->getElementType();
328  MostDerivedIsArrayElement = true;
329  MostDerivedArraySize = CAT->getSize().getZExtValue();
330  MostDerivedPathLength = Entries.size();
331  }
332  /// Update this designator to refer to the first element within the array of
333  /// elements of type T. This is an array of unknown size.
334  void addUnsizedArrayUnchecked(QualType ElemTy) {
335  PathEntry Entry;
336  Entry.ArrayIndex = 0;
337  Entries.push_back(Entry);
338 
339  MostDerivedType = ElemTy;
340  MostDerivedIsArrayElement = true;
341  // The value in MostDerivedArraySize is undefined in this case. So, set it
342  // to an arbitrary value that's likely to loudly break things if it's
343  // used.
344  MostDerivedArraySize = AssumedSizeForUnsizedArray;
345  MostDerivedPathLength = Entries.size();
346  }
347  /// Update this designator to refer to the given base or member of this
348  /// object.
349  void addDeclUnchecked(const Decl *D, bool Virtual = false) {
350  PathEntry Entry;
351  APValue::BaseOrMemberType Value(D, Virtual);
352  Entry.BaseOrMember = Value.getOpaqueValue();
353  Entries.push_back(Entry);
354 
355  // If this isn't a base class, it's a new most-derived object.
356  if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
357  MostDerivedType = FD->getType();
358  MostDerivedIsArrayElement = false;
359  MostDerivedArraySize = 0;
360  MostDerivedPathLength = Entries.size();
361  }
362  }
363  /// Update this designator to refer to the given complex component.
364  void addComplexUnchecked(QualType EltTy, bool Imag) {
365  PathEntry Entry;
366  Entry.ArrayIndex = Imag;
367  Entries.push_back(Entry);
368 
369  // This is technically a most-derived object, though in practice this
370  // is unlikely to matter.
371  MostDerivedType = EltTy;
372  MostDerivedIsArrayElement = true;
373  MostDerivedArraySize = 2;
374  MostDerivedPathLength = Entries.size();
375  }
376  void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
377  void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
378  const APSInt &N);
379  /// Add N to the address of this subobject.
380  void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
381  if (Invalid || !N) return;
382  uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
383  if (isMostDerivedAnUnsizedArray()) {
384  diagnoseUnsizedArrayPointerArithmetic(Info, E);
385  // Can't verify -- trust that the user is doing the right thing (or if
386  // not, trust that the caller will catch the bad behavior).
387  // FIXME: Should we reject if this overflows, at least?
388  Entries.back().ArrayIndex += TruncatedN;
389  return;
390  }
391 
392  // [expr.add]p4: For the purposes of these operators, a pointer to a
393  // nonarray object behaves the same as a pointer to the first element of
394  // an array of length one with the type of the object as its element type.
395  bool IsArray = MostDerivedPathLength == Entries.size() &&
396  MostDerivedIsArrayElement;
397  uint64_t ArrayIndex =
398  IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
399  uint64_t ArraySize =
400  IsArray ? getMostDerivedArraySize() : (uint64_t)1;
401 
402  if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
403  // Calculate the actual index in a wide enough type, so we can include
404  // it in the note.
405  N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
406  (llvm::APInt&)N += ArrayIndex;
407  assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
408  diagnosePointerArithmetic(Info, E, N);
409  setInvalid();
410  return;
411  }
412 
413  ArrayIndex += TruncatedN;
414  assert(ArrayIndex <= ArraySize &&
415  "bounds check succeeded for out-of-bounds index");
416 
417  if (IsArray)
418  Entries.back().ArrayIndex = ArrayIndex;
419  else
420  IsOnePastTheEnd = (ArrayIndex != 0);
421  }
422  };
423 
424  /// A stack frame in the constexpr call stack.
425  struct CallStackFrame {
426  EvalInfo &Info;
427 
428  /// Parent - The caller of this stack frame.
429  CallStackFrame *Caller;
430 
431  /// Callee - The function which was called.
432  const FunctionDecl *Callee;
433 
434  /// This - The binding for the this pointer in this call, if any.
435  const LValue *This;
436 
437  /// Arguments - Parameter bindings for this function call, indexed by
438  /// parameters' function scope indices.
439  APValue *Arguments;
440 
441  // Note that we intentionally use std::map here so that references to
442  // values are stable.
443  typedef std::map<const void*, APValue> MapTy;
444  typedef MapTy::const_iterator temp_iterator;
445  /// Temporaries - Temporary lvalues materialized within this stack frame.
446  MapTy Temporaries;
447 
448  /// CallLoc - The location of the call expression for this call.
449  SourceLocation CallLoc;
450 
451  /// Index - The call index of this call.
452  unsigned Index;
453 
454  // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
455  // on the overall stack usage of deeply-recursing constexpr evaluataions.
456  // (We should cache this map rather than recomputing it repeatedly.)
457  // But let's try this and see how it goes; we can look into caching the map
458  // as a later change.
459 
460  /// LambdaCaptureFields - Mapping from captured variables/this to
461  /// corresponding data members in the closure class.
462  llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
463  FieldDecl *LambdaThisCaptureField;
464 
465  CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
466  const FunctionDecl *Callee, const LValue *This,
467  APValue *Arguments);
468  ~CallStackFrame();
469 
470  APValue *getTemporary(const void *Key) {
471  MapTy::iterator I = Temporaries.find(Key);
472  return I == Temporaries.end() ? nullptr : &I->second;
473  }
474  APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
475  };
476 
477  /// Temporarily override 'this'.
478  class ThisOverrideRAII {
479  public:
480  ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
481  : Frame(Frame), OldThis(Frame.This) {
482  if (Enable)
483  Frame.This = NewThis;
484  }
485  ~ThisOverrideRAII() {
486  Frame.This = OldThis;
487  }
488  private:
489  CallStackFrame &Frame;
490  const LValue *OldThis;
491  };
492 
493  /// A partial diagnostic which we might know in advance that we are not going
494  /// to emit.
495  class OptionalDiagnostic {
497 
498  public:
499  explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
500  : Diag(Diag) {}
501 
502  template<typename T>
503  OptionalDiagnostic &operator<<(const T &v) {
504  if (Diag)
505  *Diag << v;
506  return *this;
507  }
508 
509  OptionalDiagnostic &operator<<(const APSInt &I) {
510  if (Diag) {
511  SmallVector<char, 32> Buffer;
512  I.toString(Buffer);
513  *Diag << StringRef(Buffer.data(), Buffer.size());
514  }
515  return *this;
516  }
517 
518  OptionalDiagnostic &operator<<(const APFloat &F) {
519  if (Diag) {
520  // FIXME: Force the precision of the source value down so we don't
521  // print digits which are usually useless (we don't really care here if
522  // we truncate a digit by accident in edge cases). Ideally,
523  // APFloat::toString would automatically print the shortest
524  // representation which rounds to the correct value, but it's a bit
525  // tricky to implement.
526  unsigned precision =
527  llvm::APFloat::semanticsPrecision(F.getSemantics());
528  precision = (precision * 59 + 195) / 196;
529  SmallVector<char, 32> Buffer;
530  F.toString(Buffer, precision);
531  *Diag << StringRef(Buffer.data(), Buffer.size());
532  }
533  return *this;
534  }
535  };
536 
537  /// A cleanup, and a flag indicating whether it is lifetime-extended.
538  class Cleanup {
539  llvm::PointerIntPair<APValue*, 1, bool> Value;
540 
541  public:
542  Cleanup(APValue *Val, bool IsLifetimeExtended)
543  : Value(Val, IsLifetimeExtended) {}
544 
545  bool isLifetimeExtended() const { return Value.getInt(); }
546  void endLifetime() {
547  *Value.getPointer() = APValue();
548  }
549  };
550 
551  /// EvalInfo - This is a private struct used by the evaluator to capture
552  /// information about a subexpression as it is folded. It retains information
553  /// about the AST context, but also maintains information about the folded
554  /// expression.
555  ///
556  /// If an expression could be evaluated, it is still possible it is not a C
557  /// "integer constant expression" or constant expression. If not, this struct
558  /// captures information about how and why not.
559  ///
560  /// One bit of information passed *into* the request for constant folding
561  /// indicates whether the subexpression is "evaluated" or not according to C
562  /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
563  /// evaluate the expression regardless of what the RHS is, but C only allows
564  /// certain things in certain situations.
565  struct EvalInfo {
566  ASTContext &Ctx;
567 
568  /// EvalStatus - Contains information about the evaluation.
569  Expr::EvalStatus &EvalStatus;
570 
571  /// CurrentCall - The top of the constexpr call stack.
572  CallStackFrame *CurrentCall;
573 
574  /// CallStackDepth - The number of calls in the call stack right now.
575  unsigned CallStackDepth;
576 
577  /// NextCallIndex - The next call index to assign.
578  unsigned NextCallIndex;
579 
580  /// StepsLeft - The remaining number of evaluation steps we're permitted
581  /// to perform. This is essentially a limit for the number of statements
582  /// we will evaluate.
583  unsigned StepsLeft;
584 
585  /// BottomFrame - The frame in which evaluation started. This must be
586  /// initialized after CurrentCall and CallStackDepth.
587  CallStackFrame BottomFrame;
588 
589  /// A stack of values whose lifetimes end at the end of some surrounding
590  /// evaluation frame.
591  llvm::SmallVector<Cleanup, 16> CleanupStack;
592 
593  /// EvaluatingDecl - This is the declaration whose initializer is being
594  /// evaluated, if any.
595  APValue::LValueBase EvaluatingDecl;
596 
597  /// EvaluatingDeclValue - This is the value being constructed for the
598  /// declaration whose initializer is being evaluated, if any.
599  APValue *EvaluatingDeclValue;
600 
601  /// EvaluatingObject - Pair of the AST node that an lvalue represents and
602  /// the call index that that lvalue was allocated in.
603  typedef std::pair<APValue::LValueBase, unsigned> EvaluatingObject;
604 
605  /// EvaluatingConstructors - Set of objects that are currently being
606  /// constructed.
607  llvm::DenseSet<EvaluatingObject> EvaluatingConstructors;
608 
609  struct EvaluatingConstructorRAII {
610  EvalInfo &EI;
611  EvaluatingObject Object;
612  bool DidInsert;
613  EvaluatingConstructorRAII(EvalInfo &EI, EvaluatingObject Object)
614  : EI(EI), Object(Object) {
615  DidInsert = EI.EvaluatingConstructors.insert(Object).second;
616  }
617  ~EvaluatingConstructorRAII() {
618  if (DidInsert) EI.EvaluatingConstructors.erase(Object);
619  }
620  };
621 
622  bool isEvaluatingConstructor(APValue::LValueBase Decl, unsigned CallIndex) {
623  return EvaluatingConstructors.count(EvaluatingObject(Decl, CallIndex));
624  }
625 
626  /// The current array initialization index, if we're performing array
627  /// initialization.
628  uint64_t ArrayInitIndex = -1;
629 
630  /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
631  /// notes attached to it will also be stored, otherwise they will not be.
632  bool HasActiveDiagnostic;
633 
634  /// \brief Have we emitted a diagnostic explaining why we couldn't constant
635  /// fold (not just why it's not strictly a constant expression)?
636  bool HasFoldFailureDiagnostic;
637 
638  /// \brief Whether or not we're currently speculatively evaluating.
639  bool IsSpeculativelyEvaluating;
640 
641  enum EvaluationMode {
642  /// Evaluate as a constant expression. Stop if we find that the expression
643  /// is not a constant expression.
644  EM_ConstantExpression,
645 
646  /// Evaluate as a potential constant expression. Keep going if we hit a
647  /// construct that we can't evaluate yet (because we don't yet know the
648  /// value of something) but stop if we hit something that could never be
649  /// a constant expression.
650  EM_PotentialConstantExpression,
651 
652  /// Fold the expression to a constant. Stop if we hit a side-effect that
653  /// we can't model.
654  EM_ConstantFold,
655 
656  /// Evaluate the expression looking for integer overflow and similar
657  /// issues. Don't worry about side-effects, and try to visit all
658  /// subexpressions.
659  EM_EvaluateForOverflow,
660 
661  /// Evaluate in any way we know how. Don't worry about side-effects that
662  /// can't be modeled.
663  EM_IgnoreSideEffects,
664 
665  /// Evaluate as a constant expression. Stop if we find that the expression
666  /// is not a constant expression. Some expressions can be retried in the
667  /// optimizer if we don't constant fold them here, but in an unevaluated
668  /// context we try to fold them immediately since the optimizer never
669  /// gets a chance to look at it.
670  EM_ConstantExpressionUnevaluated,
671 
672  /// Evaluate as a potential constant expression. Keep going if we hit a
673  /// construct that we can't evaluate yet (because we don't yet know the
674  /// value of something) but stop if we hit something that could never be
675  /// a constant expression. Some expressions can be retried in the
676  /// optimizer if we don't constant fold them here, but in an unevaluated
677  /// context we try to fold them immediately since the optimizer never
678  /// gets a chance to look at it.
679  EM_PotentialConstantExpressionUnevaluated,
680 
681  /// Evaluate as a constant expression. In certain scenarios, if:
682  /// - we find a MemberExpr with a base that can't be evaluated, or
683  /// - we find a variable initialized with a call to a function that has
684  /// the alloc_size attribute on it
685  /// then we may consider evaluation to have succeeded.
686  ///
687  /// In either case, the LValue returned shall have an invalid base; in the
688  /// former, the base will be the invalid MemberExpr, in the latter, the
689  /// base will be either the alloc_size CallExpr or a CastExpr wrapping
690  /// said CallExpr.
691  EM_OffsetFold,
692  } EvalMode;
693 
694  /// Are we checking whether the expression is a potential constant
695  /// expression?
696  bool checkingPotentialConstantExpression() const {
697  return EvalMode == EM_PotentialConstantExpression ||
698  EvalMode == EM_PotentialConstantExpressionUnevaluated;
699  }
700 
701  /// Are we checking an expression for overflow?
702  // FIXME: We should check for any kind of undefined or suspicious behavior
703  // in such constructs, not just overflow.
704  bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
705 
706  EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
707  : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
708  CallStackDepth(0), NextCallIndex(1),
709  StepsLeft(getLangOpts().ConstexprStepLimit),
710  BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
711  EvaluatingDecl((const ValueDecl *)nullptr),
712  EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
713  HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
714  EvalMode(Mode) {}
715 
716  void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
717  EvaluatingDecl = Base;
718  EvaluatingDeclValue = &Value;
719  EvaluatingConstructors.insert({Base, 0});
720  }
721 
722  const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
723 
724  bool CheckCallLimit(SourceLocation Loc) {
725  // Don't perform any constexpr calls (other than the call we're checking)
726  // when checking a potential constant expression.
727  if (checkingPotentialConstantExpression() && CallStackDepth > 1)
728  return false;
729  if (NextCallIndex == 0) {
730  // NextCallIndex has wrapped around.
731  FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
732  return false;
733  }
734  if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
735  return true;
736  FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
737  << getLangOpts().ConstexprCallDepth;
738  return false;
739  }
740 
741  CallStackFrame *getCallFrame(unsigned CallIndex) {
742  assert(CallIndex && "no call index in getCallFrame");
743  // We will eventually hit BottomFrame, which has Index 1, so Frame can't
744  // be null in this loop.
745  CallStackFrame *Frame = CurrentCall;
746  while (Frame->Index > CallIndex)
747  Frame = Frame->Caller;
748  return (Frame->Index == CallIndex) ? Frame : nullptr;
749  }
750 
751  bool nextStep(const Stmt *S) {
752  if (!StepsLeft) {
753  FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
754  return false;
755  }
756  --StepsLeft;
757  return true;
758  }
759 
760  private:
761  /// Add a diagnostic to the diagnostics list.
762  PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
763  PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
764  EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
765  return EvalStatus.Diag->back().second;
766  }
767 
768  /// Add notes containing a call stack to the current point of evaluation.
769  void addCallStack(unsigned Limit);
770 
771  private:
772  OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
773  unsigned ExtraNotes, bool IsCCEDiag) {
774 
775  if (EvalStatus.Diag) {
776  // If we have a prior diagnostic, it will be noting that the expression
777  // isn't a constant expression. This diagnostic is more important,
778  // unless we require this evaluation to produce a constant expression.
779  //
780  // FIXME: We might want to show both diagnostics to the user in
781  // EM_ConstantFold mode.
782  if (!EvalStatus.Diag->empty()) {
783  switch (EvalMode) {
784  case EM_ConstantFold:
785  case EM_IgnoreSideEffects:
786  case EM_EvaluateForOverflow:
787  if (!HasFoldFailureDiagnostic)
788  break;
789  // We've already failed to fold something. Keep that diagnostic.
790  LLVM_FALLTHROUGH;
791  case EM_ConstantExpression:
792  case EM_PotentialConstantExpression:
793  case EM_ConstantExpressionUnevaluated:
794  case EM_PotentialConstantExpressionUnevaluated:
795  case EM_OffsetFold:
796  HasActiveDiagnostic = false;
797  return OptionalDiagnostic();
798  }
799  }
800 
801  unsigned CallStackNotes = CallStackDepth - 1;
802  unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
803  if (Limit)
804  CallStackNotes = std::min(CallStackNotes, Limit + 1);
805  if (checkingPotentialConstantExpression())
806  CallStackNotes = 0;
807 
808  HasActiveDiagnostic = true;
809  HasFoldFailureDiagnostic = !IsCCEDiag;
810  EvalStatus.Diag->clear();
811  EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
812  addDiag(Loc, DiagId);
813  if (!checkingPotentialConstantExpression())
814  addCallStack(Limit);
815  return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
816  }
817  HasActiveDiagnostic = false;
818  return OptionalDiagnostic();
819  }
820  public:
821  // Diagnose that the evaluation could not be folded (FF => FoldFailure)
822  OptionalDiagnostic
823  FFDiag(SourceLocation Loc,
824  diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
825  unsigned ExtraNotes = 0) {
826  return Diag(Loc, DiagId, ExtraNotes, false);
827  }
828 
829  OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
830  = diag::note_invalid_subexpr_in_const_expr,
831  unsigned ExtraNotes = 0) {
832  if (EvalStatus.Diag)
833  return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
834  HasActiveDiagnostic = false;
835  return OptionalDiagnostic();
836  }
837 
838  /// Diagnose that the evaluation does not produce a C++11 core constant
839  /// expression.
840  ///
841  /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
842  /// EM_PotentialConstantExpression mode and we produce one of these.
843  OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
844  = diag::note_invalid_subexpr_in_const_expr,
845  unsigned ExtraNotes = 0) {
846  // Don't override a previous diagnostic. Don't bother collecting
847  // diagnostics if we're evaluating for overflow.
848  if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
849  HasActiveDiagnostic = false;
850  return OptionalDiagnostic();
851  }
852  return Diag(Loc, DiagId, ExtraNotes, true);
853  }
854  OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
855  = diag::note_invalid_subexpr_in_const_expr,
856  unsigned ExtraNotes = 0) {
857  return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
858  }
859  /// Add a note to a prior diagnostic.
860  OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
861  if (!HasActiveDiagnostic)
862  return OptionalDiagnostic();
863  return OptionalDiagnostic(&addDiag(Loc, DiagId));
864  }
865 
866  /// Add a stack of notes to a prior diagnostic.
867  void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
868  if (HasActiveDiagnostic) {
869  EvalStatus.Diag->insert(EvalStatus.Diag->end(),
870  Diags.begin(), Diags.end());
871  }
872  }
873 
874  /// Should we continue evaluation after encountering a side-effect that we
875  /// couldn't model?
876  bool keepEvaluatingAfterSideEffect() {
877  switch (EvalMode) {
878  case EM_PotentialConstantExpression:
879  case EM_PotentialConstantExpressionUnevaluated:
880  case EM_EvaluateForOverflow:
881  case EM_IgnoreSideEffects:
882  return true;
883 
884  case EM_ConstantExpression:
885  case EM_ConstantExpressionUnevaluated:
886  case EM_ConstantFold:
887  case EM_OffsetFold:
888  return false;
889  }
890  llvm_unreachable("Missed EvalMode case");
891  }
892 
893  /// Note that we have had a side-effect, and determine whether we should
894  /// keep evaluating.
895  bool noteSideEffect() {
896  EvalStatus.HasSideEffects = true;
897  return keepEvaluatingAfterSideEffect();
898  }
899 
900  /// Should we continue evaluation after encountering undefined behavior?
901  bool keepEvaluatingAfterUndefinedBehavior() {
902  switch (EvalMode) {
903  case EM_EvaluateForOverflow:
904  case EM_IgnoreSideEffects:
905  case EM_ConstantFold:
906  case EM_OffsetFold:
907  return true;
908 
909  case EM_PotentialConstantExpression:
910  case EM_PotentialConstantExpressionUnevaluated:
911  case EM_ConstantExpression:
912  case EM_ConstantExpressionUnevaluated:
913  return false;
914  }
915  llvm_unreachable("Missed EvalMode case");
916  }
917 
918  /// Note that we hit something that was technically undefined behavior, but
919  /// that we can evaluate past it (such as signed overflow or floating-point
920  /// division by zero.)
921  bool noteUndefinedBehavior() {
922  EvalStatus.HasUndefinedBehavior = true;
923  return keepEvaluatingAfterUndefinedBehavior();
924  }
925 
926  /// Should we continue evaluation as much as possible after encountering a
927  /// construct which can't be reduced to a value?
928  bool keepEvaluatingAfterFailure() {
929  if (!StepsLeft)
930  return false;
931 
932  switch (EvalMode) {
933  case EM_PotentialConstantExpression:
934  case EM_PotentialConstantExpressionUnevaluated:
935  case EM_EvaluateForOverflow:
936  return true;
937 
938  case EM_ConstantExpression:
939  case EM_ConstantExpressionUnevaluated:
940  case EM_ConstantFold:
941  case EM_IgnoreSideEffects:
942  case EM_OffsetFold:
943  return false;
944  }
945  llvm_unreachable("Missed EvalMode case");
946  }
947 
948  /// Notes that we failed to evaluate an expression that other expressions
949  /// directly depend on, and determine if we should keep evaluating. This
950  /// should only be called if we actually intend to keep evaluating.
951  ///
952  /// Call noteSideEffect() instead if we may be able to ignore the value that
953  /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
954  ///
955  /// (Foo(), 1) // use noteSideEffect
956  /// (Foo() || true) // use noteSideEffect
957  /// Foo() + 1 // use noteFailure
958  LLVM_NODISCARD bool noteFailure() {
959  // Failure when evaluating some expression often means there is some
960  // subexpression whose evaluation was skipped. Therefore, (because we
961  // don't track whether we skipped an expression when unwinding after an
962  // evaluation failure) every evaluation failure that bubbles up from a
963  // subexpression implies that a side-effect has potentially happened. We
964  // skip setting the HasSideEffects flag to true until we decide to
965  // continue evaluating after that point, which happens here.
966  bool KeepGoing = keepEvaluatingAfterFailure();
967  EvalStatus.HasSideEffects |= KeepGoing;
968  return KeepGoing;
969  }
970 
971  class ArrayInitLoopIndex {
972  EvalInfo &Info;
973  uint64_t OuterIndex;
974 
975  public:
976  ArrayInitLoopIndex(EvalInfo &Info)
977  : Info(Info), OuterIndex(Info.ArrayInitIndex) {
978  Info.ArrayInitIndex = 0;
979  }
980  ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
981 
982  operator uint64_t&() { return Info.ArrayInitIndex; }
983  };
984  };
985 
986  /// Object used to treat all foldable expressions as constant expressions.
987  struct FoldConstant {
988  EvalInfo &Info;
989  bool Enabled;
990  bool HadNoPriorDiags;
991  EvalInfo::EvaluationMode OldMode;
992 
993  explicit FoldConstant(EvalInfo &Info, bool Enabled)
994  : Info(Info),
995  Enabled(Enabled),
996  HadNoPriorDiags(Info.EvalStatus.Diag &&
997  Info.EvalStatus.Diag->empty() &&
998  !Info.EvalStatus.HasSideEffects),
999  OldMode(Info.EvalMode) {
1000  if (Enabled &&
1001  (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
1002  Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
1003  Info.EvalMode = EvalInfo::EM_ConstantFold;
1004  }
1005  void keepDiagnostics() { Enabled = false; }
1006  ~FoldConstant() {
1007  if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1008  !Info.EvalStatus.HasSideEffects)
1009  Info.EvalStatus.Diag->clear();
1010  Info.EvalMode = OldMode;
1011  }
1012  };
1013 
1014  /// RAII object used to treat the current evaluation as the correct pointer
1015  /// offset fold for the current EvalMode
1016  struct FoldOffsetRAII {
1017  EvalInfo &Info;
1018  EvalInfo::EvaluationMode OldMode;
1019  explicit FoldOffsetRAII(EvalInfo &Info)
1020  : Info(Info), OldMode(Info.EvalMode) {
1021  if (!Info.checkingPotentialConstantExpression())
1022  Info.EvalMode = EvalInfo::EM_OffsetFold;
1023  }
1024 
1025  ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
1026  };
1027 
1028  /// RAII object used to optionally suppress diagnostics and side-effects from
1029  /// a speculative evaluation.
1030  class SpeculativeEvaluationRAII {
1031  EvalInfo *Info = nullptr;
1032  Expr::EvalStatus OldStatus;
1033  bool OldIsSpeculativelyEvaluating;
1034 
1035  void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1036  Info = Other.Info;
1037  OldStatus = Other.OldStatus;
1038  OldIsSpeculativelyEvaluating = Other.OldIsSpeculativelyEvaluating;
1039  Other.Info = nullptr;
1040  }
1041 
1042  void maybeRestoreState() {
1043  if (!Info)
1044  return;
1045 
1046  Info->EvalStatus = OldStatus;
1047  Info->IsSpeculativelyEvaluating = OldIsSpeculativelyEvaluating;
1048  }
1049 
1050  public:
1051  SpeculativeEvaluationRAII() = default;
1052 
1053  SpeculativeEvaluationRAII(
1054  EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1055  : Info(&Info), OldStatus(Info.EvalStatus),
1056  OldIsSpeculativelyEvaluating(Info.IsSpeculativelyEvaluating) {
1057  Info.EvalStatus.Diag = NewDiag;
1058  Info.IsSpeculativelyEvaluating = true;
1059  }
1060 
1061  SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1062  SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1063  moveFromAndCancel(std::move(Other));
1064  }
1065 
1066  SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1067  maybeRestoreState();
1068  moveFromAndCancel(std::move(Other));
1069  return *this;
1070  }
1071 
1072  ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1073  };
1074 
1075  /// RAII object wrapping a full-expression or block scope, and handling
1076  /// the ending of the lifetime of temporaries created within it.
1077  template<bool IsFullExpression>
1078  class ScopeRAII {
1079  EvalInfo &Info;
1080  unsigned OldStackSize;
1081  public:
1082  ScopeRAII(EvalInfo &Info)
1083  : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
1084  ~ScopeRAII() {
1085  // Body moved to a static method to encourage the compiler to inline away
1086  // instances of this class.
1087  cleanup(Info, OldStackSize);
1088  }
1089  private:
1090  static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1091  unsigned NewEnd = OldStackSize;
1092  for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1093  I != N; ++I) {
1094  if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1095  // Full-expression cleanup of a lifetime-extended temporary: nothing
1096  // to do, just move this cleanup to the right place in the stack.
1097  std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1098  ++NewEnd;
1099  } else {
1100  // End the lifetime of the object.
1101  Info.CleanupStack[I].endLifetime();
1102  }
1103  }
1104  Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1105  Info.CleanupStack.end());
1106  }
1107  };
1108  typedef ScopeRAII<false> BlockScopeRAII;
1109  typedef ScopeRAII<true> FullExpressionRAII;
1110 }
1111 
1112 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1113  CheckSubobjectKind CSK) {
1114  if (Invalid)
1115  return false;
1116  if (isOnePastTheEnd()) {
1117  Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1118  << CSK;
1119  setInvalid();
1120  return false;
1121  }
1122  // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1123  // must actually be at least one array element; even a VLA cannot have a
1124  // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1125  return true;
1126 }
1127 
1128 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1129  const Expr *E) {
1130  Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1131  // Do not set the designator as invalid: we can represent this situation,
1132  // and correct handling of __builtin_object_size requires us to do so.
1133 }
1134 
1135 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1136  const Expr *E,
1137  const APSInt &N) {
1138  // If we're complaining, we must be able to statically determine the size of
1139  // the most derived array.
1140  if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1141  Info.CCEDiag(E, diag::note_constexpr_array_index)
1142  << N << /*array*/ 0
1143  << static_cast<unsigned>(getMostDerivedArraySize());
1144  else
1145  Info.CCEDiag(E, diag::note_constexpr_array_index)
1146  << N << /*non-array*/ 1;
1147  setInvalid();
1148 }
1149 
1150 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1151  const FunctionDecl *Callee, const LValue *This,
1152  APValue *Arguments)
1153  : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1154  Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1155  Info.CurrentCall = this;
1156  ++Info.CallStackDepth;
1157 }
1158 
1159 CallStackFrame::~CallStackFrame() {
1160  assert(Info.CurrentCall == this && "calls retired out of order");
1161  --Info.CallStackDepth;
1162  Info.CurrentCall = Caller;
1163 }
1164 
1165 APValue &CallStackFrame::createTemporary(const void *Key,
1166  bool IsLifetimeExtended) {
1167  APValue &Result = Temporaries[Key];
1168  assert(Result.isUninit() && "temporary created multiple times");
1169  Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1170  return Result;
1171 }
1172 
1173 static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
1174 
1175 void EvalInfo::addCallStack(unsigned Limit) {
1176  // Determine which calls to skip, if any.
1177  unsigned ActiveCalls = CallStackDepth - 1;
1178  unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1179  if (Limit && Limit < ActiveCalls) {
1180  SkipStart = Limit / 2 + Limit % 2;
1181  SkipEnd = ActiveCalls - Limit / 2;
1182  }
1183 
1184  // Walk the call stack and add the diagnostics.
1185  unsigned CallIdx = 0;
1186  for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1187  Frame = Frame->Caller, ++CallIdx) {
1188  // Skip this call?
1189  if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1190  if (CallIdx == SkipStart) {
1191  // Note that we're skipping calls.
1192  addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1193  << unsigned(ActiveCalls - Limit);
1194  }
1195  continue;
1196  }
1197 
1198  // Use a different note for an inheriting constructor, because from the
1199  // user's perspective it's not really a function at all.
1200  if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1201  if (CD->isInheritingConstructor()) {
1202  addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1203  << CD->getParent();
1204  continue;
1205  }
1206  }
1207 
1208  SmallVector<char, 128> Buffer;
1209  llvm::raw_svector_ostream Out(Buffer);
1210  describeCall(Frame, Out);
1211  addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1212  }
1213 }
1214 
1215 namespace {
1216  struct ComplexValue {
1217  private:
1218  bool IsInt;
1219 
1220  public:
1221  APSInt IntReal, IntImag;
1222  APFloat FloatReal, FloatImag;
1223 
1224  ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1225 
1226  void makeComplexFloat() { IsInt = false; }
1227  bool isComplexFloat() const { return !IsInt; }
1228  APFloat &getComplexFloatReal() { return FloatReal; }
1229  APFloat &getComplexFloatImag() { return FloatImag; }
1230 
1231  void makeComplexInt() { IsInt = true; }
1232  bool isComplexInt() const { return IsInt; }
1233  APSInt &getComplexIntReal() { return IntReal; }
1234  APSInt &getComplexIntImag() { return IntImag; }
1235 
1236  void moveInto(APValue &v) const {
1237  if (isComplexFloat())
1238  v = APValue(FloatReal, FloatImag);
1239  else
1240  v = APValue(IntReal, IntImag);
1241  }
1242  void setFrom(const APValue &v) {
1243  assert(v.isComplexFloat() || v.isComplexInt());
1244  if (v.isComplexFloat()) {
1245  makeComplexFloat();
1246  FloatReal = v.getComplexFloatReal();
1247  FloatImag = v.getComplexFloatImag();
1248  } else {
1249  makeComplexInt();
1250  IntReal = v.getComplexIntReal();
1251  IntImag = v.getComplexIntImag();
1252  }
1253  }
1254  };
1255 
1256  struct LValue {
1257  APValue::LValueBase Base;
1258  CharUnits Offset;
1259  unsigned InvalidBase : 1;
1260  unsigned CallIndex : 31;
1261  SubobjectDesignator Designator;
1262  bool IsNullPtr;
1263 
1264  const APValue::LValueBase getLValueBase() const { return Base; }
1265  CharUnits &getLValueOffset() { return Offset; }
1266  const CharUnits &getLValueOffset() const { return Offset; }
1267  unsigned getLValueCallIndex() const { return CallIndex; }
1268  SubobjectDesignator &getLValueDesignator() { return Designator; }
1269  const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1270  bool isNullPointer() const { return IsNullPtr;}
1271 
1272  void moveInto(APValue &V) const {
1273  if (Designator.Invalid)
1274  V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex,
1275  IsNullPtr);
1276  else {
1277  assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1278  V = APValue(Base, Offset, Designator.Entries,
1279  Designator.IsOnePastTheEnd, CallIndex, IsNullPtr);
1280  }
1281  }
1282  void setFrom(ASTContext &Ctx, const APValue &V) {
1283  assert(V.isLValue() && "Setting LValue from a non-LValue?");
1284  Base = V.getLValueBase();
1285  Offset = V.getLValueOffset();
1286  InvalidBase = false;
1287  CallIndex = V.getLValueCallIndex();
1288  Designator = SubobjectDesignator(Ctx, V);
1289  IsNullPtr = V.isNullPointer();
1290  }
1291 
1292  void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false) {
1293 #ifndef NDEBUG
1294  // We only allow a few types of invalid bases. Enforce that here.
1295  if (BInvalid) {
1296  const auto *E = B.get<const Expr *>();
1297  assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1298  "Unexpected type of invalid base");
1299  }
1300 #endif
1301 
1302  Base = B;
1303  Offset = CharUnits::fromQuantity(0);
1304  InvalidBase = BInvalid;
1305  CallIndex = I;
1306  Designator = SubobjectDesignator(getType(B));
1307  IsNullPtr = false;
1308  }
1309 
1310  void setNull(QualType PointerTy, uint64_t TargetVal) {
1311  Base = (Expr *)nullptr;
1312  Offset = CharUnits::fromQuantity(TargetVal);
1313  InvalidBase = false;
1314  CallIndex = 0;
1315  Designator = SubobjectDesignator(PointerTy->getPointeeType());
1316  IsNullPtr = true;
1317  }
1318 
1319  void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1320  set(B, I, true);
1321  }
1322 
1323  // Check that this LValue is not based on a null pointer. If it is, produce
1324  // a diagnostic and mark the designator as invalid.
1325  bool checkNullPointer(EvalInfo &Info, const Expr *E,
1326  CheckSubobjectKind CSK) {
1327  if (Designator.Invalid)
1328  return false;
1329  if (IsNullPtr) {
1330  Info.CCEDiag(E, diag::note_constexpr_null_subobject)
1331  << CSK;
1332  Designator.setInvalid();
1333  return false;
1334  }
1335  return true;
1336  }
1337 
1338  // Check this LValue refers to an object. If not, set the designator to be
1339  // invalid and emit a diagnostic.
1340  bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1341  return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1342  Designator.checkSubobject(Info, E, CSK);
1343  }
1344 
1345  void addDecl(EvalInfo &Info, const Expr *E,
1346  const Decl *D, bool Virtual = false) {
1347  if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1348  Designator.addDeclUnchecked(D, Virtual);
1349  }
1350  void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1351  if (!Designator.Entries.empty()) {
1352  Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1353  Designator.setInvalid();
1354  return;
1355  }
1356  if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1357  assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1358  Designator.FirstEntryIsAnUnsizedArray = true;
1359  Designator.addUnsizedArrayUnchecked(ElemTy);
1360  }
1361  }
1362  void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1363  if (checkSubobject(Info, E, CSK_ArrayToPointer))
1364  Designator.addArrayUnchecked(CAT);
1365  }
1366  void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1367  if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1368  Designator.addComplexUnchecked(EltTy, Imag);
1369  }
1370  void clearIsNullPointer() {
1371  IsNullPtr = false;
1372  }
1373  void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1374  const APSInt &Index, CharUnits ElementSize) {
1375  // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1376  // but we're not required to diagnose it and it's valid in C++.)
1377  if (!Index)
1378  return;
1379 
1380  // Compute the new offset in the appropriate width, wrapping at 64 bits.
1381  // FIXME: When compiling for a 32-bit target, we should use 32-bit
1382  // offsets.
1383  uint64_t Offset64 = Offset.getQuantity();
1384  uint64_t ElemSize64 = ElementSize.getQuantity();
1385  uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1386  Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1387 
1388  if (checkNullPointer(Info, E, CSK_ArrayIndex))
1389  Designator.adjustIndex(Info, E, Index);
1390  clearIsNullPointer();
1391  }
1392  void adjustOffset(CharUnits N) {
1393  Offset += N;
1394  if (N.getQuantity())
1395  clearIsNullPointer();
1396  }
1397  };
1398 
1399  struct MemberPtr {
1400  MemberPtr() {}
1401  explicit MemberPtr(const ValueDecl *Decl) :
1402  DeclAndIsDerivedMember(Decl, false), Path() {}
1403 
1404  /// The member or (direct or indirect) field referred to by this member
1405  /// pointer, or 0 if this is a null member pointer.
1406  const ValueDecl *getDecl() const {
1407  return DeclAndIsDerivedMember.getPointer();
1408  }
1409  /// Is this actually a member of some type derived from the relevant class?
1410  bool isDerivedMember() const {
1411  return DeclAndIsDerivedMember.getInt();
1412  }
1413  /// Get the class which the declaration actually lives in.
1414  const CXXRecordDecl *getContainingRecord() const {
1415  return cast<CXXRecordDecl>(
1416  DeclAndIsDerivedMember.getPointer()->getDeclContext());
1417  }
1418 
1419  void moveInto(APValue &V) const {
1420  V = APValue(getDecl(), isDerivedMember(), Path);
1421  }
1422  void setFrom(const APValue &V) {
1423  assert(V.isMemberPointer());
1424  DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1425  DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1426  Path.clear();
1428  Path.insert(Path.end(), P.begin(), P.end());
1429  }
1430 
1431  /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1432  /// whether the member is a member of some class derived from the class type
1433  /// of the member pointer.
1434  llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1435  /// Path - The path of base/derived classes from the member declaration's
1436  /// class (exclusive) to the class type of the member pointer (inclusive).
1438 
1439  /// Perform a cast towards the class of the Decl (either up or down the
1440  /// hierarchy).
1441  bool castBack(const CXXRecordDecl *Class) {
1442  assert(!Path.empty());
1443  const CXXRecordDecl *Expected;
1444  if (Path.size() >= 2)
1445  Expected = Path[Path.size() - 2];
1446  else
1447  Expected = getContainingRecord();
1448  if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1449  // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1450  // if B does not contain the original member and is not a base or
1451  // derived class of the class containing the original member, the result
1452  // of the cast is undefined.
1453  // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1454  // (D::*). We consider that to be a language defect.
1455  return false;
1456  }
1457  Path.pop_back();
1458  return true;
1459  }
1460  /// Perform a base-to-derived member pointer cast.
1461  bool castToDerived(const CXXRecordDecl *Derived) {
1462  if (!getDecl())
1463  return true;
1464  if (!isDerivedMember()) {
1465  Path.push_back(Derived);
1466  return true;
1467  }
1468  if (!castBack(Derived))
1469  return false;
1470  if (Path.empty())
1471  DeclAndIsDerivedMember.setInt(false);
1472  return true;
1473  }
1474  /// Perform a derived-to-base member pointer cast.
1475  bool castToBase(const CXXRecordDecl *Base) {
1476  if (!getDecl())
1477  return true;
1478  if (Path.empty())
1479  DeclAndIsDerivedMember.setInt(true);
1480  if (isDerivedMember()) {
1481  Path.push_back(Base);
1482  return true;
1483  }
1484  return castBack(Base);
1485  }
1486  };
1487 
1488  /// Compare two member pointers, which are assumed to be of the same type.
1489  static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1490  if (!LHS.getDecl() || !RHS.getDecl())
1491  return !LHS.getDecl() && !RHS.getDecl();
1492  if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1493  return false;
1494  return LHS.Path == RHS.Path;
1495  }
1496 }
1497 
1498 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1499 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1500  const LValue &This, const Expr *E,
1501  bool AllowNonLiteralTypes = false);
1502 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1503  bool InvalidBaseOK = false);
1504 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1505  bool InvalidBaseOK = false);
1506 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1507  EvalInfo &Info);
1508 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1509 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1510 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1511  EvalInfo &Info);
1512 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1513 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1514 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1515  EvalInfo &Info);
1516 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1517 
1518 //===----------------------------------------------------------------------===//
1519 // Misc utilities
1520 //===----------------------------------------------------------------------===//
1521 
1522 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1523 /// preserving its value (by extending by up to one bit as needed).
1524 static void negateAsSigned(APSInt &Int) {
1525  if (Int.isUnsigned() || Int.isMinSignedValue()) {
1526  Int = Int.extend(Int.getBitWidth() + 1);
1527  Int.setIsSigned(true);
1528  }
1529  Int = -Int;
1530 }
1531 
1532 /// Produce a string describing the given constexpr call.
1533 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1534  unsigned ArgIndex = 0;
1535  bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1536  !isa<CXXConstructorDecl>(Frame->Callee) &&
1537  cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1538 
1539  if (!IsMemberCall)
1540  Out << *Frame->Callee << '(';
1541 
1542  if (Frame->This && IsMemberCall) {
1543  APValue Val;
1544  Frame->This->moveInto(Val);
1545  Val.printPretty(Out, Frame->Info.Ctx,
1546  Frame->This->Designator.MostDerivedType);
1547  // FIXME: Add parens around Val if needed.
1548  Out << "->" << *Frame->Callee << '(';
1549  IsMemberCall = false;
1550  }
1551 
1552  for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1553  E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1554  if (ArgIndex > (unsigned)IsMemberCall)
1555  Out << ", ";
1556 
1557  const ParmVarDecl *Param = *I;
1558  const APValue &Arg = Frame->Arguments[ArgIndex];
1559  Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1560 
1561  if (ArgIndex == 0 && IsMemberCall)
1562  Out << "->" << *Frame->Callee << '(';
1563  }
1564 
1565  Out << ')';
1566 }
1567 
1568 /// Evaluate an expression to see if it had side-effects, and discard its
1569 /// result.
1570 /// \return \c true if the caller should keep evaluating.
1571 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1572  APValue Scratch;
1573  if (!Evaluate(Scratch, Info, E))
1574  // We don't need the value, but we might have skipped a side effect here.
1575  return Info.noteSideEffect();
1576  return true;
1577 }
1578 
1579 /// Should this call expression be treated as a string literal?
1580 static bool IsStringLiteralCall(const CallExpr *E) {
1581  unsigned Builtin = E->getBuiltinCallee();
1582  return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1583  Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1584 }
1585 
1587  // C++11 [expr.const]p3 An address constant expression is a prvalue core
1588  // constant expression of pointer type that evaluates to...
1589 
1590  // ... a null pointer value, or a prvalue core constant expression of type
1591  // std::nullptr_t.
1592  if (!B) return true;
1593 
1594  if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1595  // ... the address of an object with static storage duration,
1596  if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1597  return VD->hasGlobalStorage();
1598  // ... the address of a function,
1599  return isa<FunctionDecl>(D);
1600  }
1601 
1602  const Expr *E = B.get<const Expr*>();
1603  switch (E->getStmtClass()) {
1604  default:
1605  return false;
1606  case Expr::CompoundLiteralExprClass: {
1607  const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1608  return CLE->isFileScope() && CLE->isLValue();
1609  }
1610  case Expr::MaterializeTemporaryExprClass:
1611  // A materialized temporary might have been lifetime-extended to static
1612  // storage duration.
1613  return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1614  // A string literal has static storage duration.
1615  case Expr::StringLiteralClass:
1616  case Expr::PredefinedExprClass:
1617  case Expr::ObjCStringLiteralClass:
1618  case Expr::ObjCEncodeExprClass:
1619  case Expr::CXXTypeidExprClass:
1620  case Expr::CXXUuidofExprClass:
1621  return true;
1622  case Expr::CallExprClass:
1623  return IsStringLiteralCall(cast<CallExpr>(E));
1624  // For GCC compatibility, &&label has static storage duration.
1625  case Expr::AddrLabelExprClass:
1626  return true;
1627  // A Block literal expression may be used as the initialization value for
1628  // Block variables at global or local static scope.
1629  case Expr::BlockExprClass:
1630  return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1631  case Expr::ImplicitValueInitExprClass:
1632  // FIXME:
1633  // We can never form an lvalue with an implicit value initialization as its
1634  // base through expression evaluation, so these only appear in one case: the
1635  // implicit variable declaration we invent when checking whether a constexpr
1636  // constructor can produce a constant expression. We must assume that such
1637  // an expression might be a global lvalue.
1638  return true;
1639  }
1640 }
1641 
1642 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1643  assert(Base && "no location for a null lvalue");
1644  const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1645  if (VD)
1646  Info.Note(VD->getLocation(), diag::note_declared_at);
1647  else
1648  Info.Note(Base.get<const Expr*>()->getExprLoc(),
1649  diag::note_constexpr_temporary_here);
1650 }
1651 
1652 /// Check that this reference or pointer core constant expression is a valid
1653 /// value for an address or reference constant expression. Return true if we
1654 /// can fold this expression, whether or not it's a constant expression.
1655 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1656  QualType Type, const LValue &LVal) {
1657  bool IsReferenceType = Type->isReferenceType();
1658 
1659  APValue::LValueBase Base = LVal.getLValueBase();
1660  const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1661 
1662  // Check that the object is a global. Note that the fake 'this' object we
1663  // manufacture when checking potential constant expressions is conservatively
1664  // assumed to be global here.
1665  if (!IsGlobalLValue(Base)) {
1666  if (Info.getLangOpts().CPlusPlus11) {
1667  const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1668  Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
1669  << IsReferenceType << !Designator.Entries.empty()
1670  << !!VD << VD;
1671  NoteLValueLocation(Info, Base);
1672  } else {
1673  Info.FFDiag(Loc);
1674  }
1675  // Don't allow references to temporaries to escape.
1676  return false;
1677  }
1678  assert((Info.checkingPotentialConstantExpression() ||
1679  LVal.getLValueCallIndex() == 0) &&
1680  "have call index for global lvalue");
1681 
1682  if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1683  if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
1684  // Check if this is a thread-local variable.
1685  if (Var->getTLSKind())
1686  return false;
1687 
1688  // A dllimport variable never acts like a constant.
1689  if (Var->hasAttr<DLLImportAttr>())
1690  return false;
1691  }
1692  if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1693  // __declspec(dllimport) must be handled very carefully:
1694  // We must never initialize an expression with the thunk in C++.
1695  // Doing otherwise would allow the same id-expression to yield
1696  // different addresses for the same function in different translation
1697  // units. However, this means that we must dynamically initialize the
1698  // expression with the contents of the import address table at runtime.
1699  //
1700  // The C language has no notion of ODR; furthermore, it has no notion of
1701  // dynamic initialization. This means that we are permitted to
1702  // perform initialization with the address of the thunk.
1703  if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
1704  return false;
1705  }
1706  }
1707 
1708  // Allow address constant expressions to be past-the-end pointers. This is
1709  // an extension: the standard requires them to point to an object.
1710  if (!IsReferenceType)
1711  return true;
1712 
1713  // A reference constant expression must refer to an object.
1714  if (!Base) {
1715  // FIXME: diagnostic
1716  Info.CCEDiag(Loc);
1717  return true;
1718  }
1719 
1720  // Does this refer one past the end of some object?
1721  if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
1722  const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1723  Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
1724  << !Designator.Entries.empty() << !!VD << VD;
1725  NoteLValueLocation(Info, Base);
1726  }
1727 
1728  return true;
1729 }
1730 
1731 /// Member pointers are constant expressions unless they point to a
1732 /// non-virtual dllimport member function.
1733 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1734  SourceLocation Loc,
1735  QualType Type,
1736  const APValue &Value) {
1737  const ValueDecl *Member = Value.getMemberPointerDecl();
1738  const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1739  if (!FD)
1740  return true;
1741  return FD->isVirtual() || !FD->hasAttr<DLLImportAttr>();
1742 }
1743 
1744 /// Check that this core constant expression is of literal type, and if not,
1745 /// produce an appropriate diagnostic.
1746 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1747  const LValue *This = nullptr) {
1748  if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
1749  return true;
1750 
1751  // C++1y: A constant initializer for an object o [...] may also invoke
1752  // constexpr constructors for o and its subobjects even if those objects
1753  // are of non-literal class types.
1754  //
1755  // C++11 missed this detail for aggregates, so classes like this:
1756  // struct foo_t { union { int i; volatile int j; } u; };
1757  // are not (obviously) initializable like so:
1758  // __attribute__((__require_constant_initialization__))
1759  // static const foo_t x = {{0}};
1760  // because "i" is a subobject with non-literal initialization (due to the
1761  // volatile member of the union). See:
1762  // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1763  // Therefore, we use the C++1y behavior.
1764  if (This && Info.EvaluatingDecl == This->getLValueBase())
1765  return true;
1766 
1767  // Prvalue constant expressions must be of literal types.
1768  if (Info.getLangOpts().CPlusPlus11)
1769  Info.FFDiag(E, diag::note_constexpr_nonliteral)
1770  << E->getType();
1771  else
1772  Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
1773  return false;
1774 }
1775 
1776 /// Check that this core constant expression value is a valid value for a
1777 /// constant expression. If not, report an appropriate diagnostic. Does not
1778 /// check that the expression is of literal type.
1779 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1780  QualType Type, const APValue &Value) {
1781  if (Value.isUninit()) {
1782  Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
1783  << true << Type;
1784  return false;
1785  }
1786 
1787  // We allow _Atomic(T) to be initialized from anything that T can be
1788  // initialized from.
1789  if (const AtomicType *AT = Type->getAs<AtomicType>())
1790  Type = AT->getValueType();
1791 
1792  // Core issue 1454: For a literal constant expression of array or class type,
1793  // each subobject of its value shall have been initialized by a constant
1794  // expression.
1795  if (Value.isArray()) {
1796  QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1797  for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1798  if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1799  Value.getArrayInitializedElt(I)))
1800  return false;
1801  }
1802  if (!Value.hasArrayFiller())
1803  return true;
1804  return CheckConstantExpression(Info, DiagLoc, EltTy,
1805  Value.getArrayFiller());
1806  }
1807  if (Value.isUnion() && Value.getUnionField()) {
1808  return CheckConstantExpression(Info, DiagLoc,
1809  Value.getUnionField()->getType(),
1810  Value.getUnionValue());
1811  }
1812  if (Value.isStruct()) {
1813  RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1814  if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1815  unsigned BaseIndex = 0;
1816  for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1817  End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1818  if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1819  Value.getStructBase(BaseIndex)))
1820  return false;
1821  }
1822  }
1823  for (const auto *I : RD->fields()) {
1824  if (I->isUnnamedBitfield())
1825  continue;
1826 
1827  if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1828  Value.getStructField(I->getFieldIndex())))
1829  return false;
1830  }
1831  }
1832 
1833  if (Value.isLValue()) {
1834  LValue LVal;
1835  LVal.setFrom(Info.Ctx, Value);
1836  return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1837  }
1838 
1839  if (Value.isMemberPointer())
1840  return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value);
1841 
1842  // Everything else is fine.
1843  return true;
1844 }
1845 
1846 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1847  return LVal.Base.dyn_cast<const ValueDecl*>();
1848 }
1849 
1850 static bool IsLiteralLValue(const LValue &Value) {
1851  if (Value.CallIndex)
1852  return false;
1853  const Expr *E = Value.Base.dyn_cast<const Expr*>();
1854  return E && !isa<MaterializeTemporaryExpr>(E);
1855 }
1856 
1857 static bool IsWeakLValue(const LValue &Value) {
1858  const ValueDecl *Decl = GetLValueBaseDecl(Value);
1859  return Decl && Decl->isWeak();
1860 }
1861 
1862 static bool isZeroSized(const LValue &Value) {
1863  const ValueDecl *Decl = GetLValueBaseDecl(Value);
1864  if (Decl && isa<VarDecl>(Decl)) {
1865  QualType Ty = Decl->getType();
1866  if (Ty->isArrayType())
1867  return Ty->isIncompleteType() ||
1868  Decl->getASTContext().getTypeSize(Ty) == 0;
1869  }
1870  return false;
1871 }
1872 
1873 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
1874  // A null base expression indicates a null pointer. These are always
1875  // evaluatable, and they are false unless the offset is zero.
1876  if (!Value.getLValueBase()) {
1877  Result = !Value.getLValueOffset().isZero();
1878  return true;
1879  }
1880 
1881  // We have a non-null base. These are generally known to be true, but if it's
1882  // a weak declaration it can be null at runtime.
1883  Result = true;
1884  const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
1885  return !Decl || !Decl->isWeak();
1886 }
1887 
1888 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
1889  switch (Val.getKind()) {
1891  return false;
1892  case APValue::Int:
1893  Result = Val.getInt().getBoolValue();
1894  return true;
1895  case APValue::Float:
1896  Result = !Val.getFloat().isZero();
1897  return true;
1898  case APValue::ComplexInt:
1899  Result = Val.getComplexIntReal().getBoolValue() ||
1900  Val.getComplexIntImag().getBoolValue();
1901  return true;
1902  case APValue::ComplexFloat:
1903  Result = !Val.getComplexFloatReal().isZero() ||
1904  !Val.getComplexFloatImag().isZero();
1905  return true;
1906  case APValue::LValue:
1907  return EvalPointerValueAsBool(Val, Result);
1909  Result = Val.getMemberPointerDecl();
1910  return true;
1911  case APValue::Vector:
1912  case APValue::Array:
1913  case APValue::Struct:
1914  case APValue::Union:
1916  return false;
1917  }
1918 
1919  llvm_unreachable("unknown APValue kind");
1920 }
1921 
1922 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1923  EvalInfo &Info) {
1924  assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
1925  APValue Val;
1926  if (!Evaluate(Val, Info, E))
1927  return false;
1928  return HandleConversionToBool(Val, Result);
1929 }
1930 
1931 template<typename T>
1932 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1933  const T &SrcValue, QualType DestType) {
1934  Info.CCEDiag(E, diag::note_constexpr_overflow)
1935  << SrcValue << DestType;
1936  return Info.noteUndefinedBehavior();
1937 }
1938 
1939 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1940  QualType SrcType, const APFloat &Value,
1941  QualType DestType, APSInt &Result) {
1942  unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1943  // Determine whether we are converting to unsigned or signed.
1944  bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
1945 
1946  Result = APSInt(DestWidth, !DestSigned);
1947  bool ignored;
1948  if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1949  & APFloat::opInvalidOp)
1950  return HandleOverflow(Info, E, Value, DestType);
1951  return true;
1952 }
1953 
1954 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1955  QualType SrcType, QualType DestType,
1956  APFloat &Result) {
1957  APFloat Value = Result;
1958  bool ignored;
1959  if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1960  APFloat::rmNearestTiesToEven, &ignored)
1961  & APFloat::opOverflow)
1962  return HandleOverflow(Info, E, Value, DestType);
1963  return true;
1964 }
1965 
1966 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1967  QualType DestType, QualType SrcType,
1968  const APSInt &Value) {
1969  unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1970  APSInt Result = Value;
1971  // Figure out if this is a truncate, extend or noop cast.
1972  // If the input is signed, do a sign extend, noop, or truncate.
1973  Result = Result.extOrTrunc(DestWidth);
1974  Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
1975  return Result;
1976 }
1977 
1978 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1979  QualType SrcType, const APSInt &Value,
1980  QualType DestType, APFloat &Result) {
1981  Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1982  if (Result.convertFromAPInt(Value, Value.isSigned(),
1983  APFloat::rmNearestTiesToEven)
1984  & APFloat::opOverflow)
1985  return HandleOverflow(Info, E, Value, DestType);
1986  return true;
1987 }
1988 
1989 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1990  APValue &Value, const FieldDecl *FD) {
1991  assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1992 
1993  if (!Value.isInt()) {
1994  // Trying to store a pointer-cast-to-integer into a bitfield.
1995  // FIXME: In this case, we should provide the diagnostic for casting
1996  // a pointer to an integer.
1997  assert(Value.isLValue() && "integral value neither int nor lvalue?");
1998  Info.FFDiag(E);
1999  return false;
2000  }
2001 
2002  APSInt &Int = Value.getInt();
2003  unsigned OldBitWidth = Int.getBitWidth();
2004  unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2005  if (NewBitWidth < OldBitWidth)
2006  Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2007  return true;
2008 }
2009 
2010 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2011  llvm::APInt &Res) {
2012  APValue SVal;
2013  if (!Evaluate(SVal, Info, E))
2014  return false;
2015  if (SVal.isInt()) {
2016  Res = SVal.getInt();
2017  return true;
2018  }
2019  if (SVal.isFloat()) {
2020  Res = SVal.getFloat().bitcastToAPInt();
2021  return true;
2022  }
2023  if (SVal.isVector()) {
2024  QualType VecTy = E->getType();
2025  unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2026  QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2027  unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2028  bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2029  Res = llvm::APInt::getNullValue(VecSize);
2030  for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2031  APValue &Elt = SVal.getVectorElt(i);
2032  llvm::APInt EltAsInt;
2033  if (Elt.isInt()) {
2034  EltAsInt = Elt.getInt();
2035  } else if (Elt.isFloat()) {
2036  EltAsInt = Elt.getFloat().bitcastToAPInt();
2037  } else {
2038  // Don't try to handle vectors of anything other than int or float
2039  // (not sure if it's possible to hit this case).
2040  Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2041  return false;
2042  }
2043  unsigned BaseEltSize = EltAsInt.getBitWidth();
2044  if (BigEndian)
2045  Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2046  else
2047  Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2048  }
2049  return true;
2050  }
2051  // Give up if the input isn't an int, float, or vector. For example, we
2052  // reject "(v4i16)(intptr_t)&a".
2053  Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2054  return false;
2055 }
2056 
2057 /// Perform the given integer operation, which is known to need at most BitWidth
2058 /// bits, and check for overflow in the original type (if that type was not an
2059 /// unsigned type).
2060 template<typename Operation>
2061 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2062  const APSInt &LHS, const APSInt &RHS,
2063  unsigned BitWidth, Operation Op,
2064  APSInt &Result) {
2065  if (LHS.isUnsigned()) {
2066  Result = Op(LHS, RHS);
2067  return true;
2068  }
2069 
2070  APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2071  Result = Value.trunc(LHS.getBitWidth());
2072  if (Result.extend(BitWidth) != Value) {
2073  if (Info.checkingForOverflow())
2074  Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2075  diag::warn_integer_constant_overflow)
2076  << Result.toString(10) << E->getType();
2077  else
2078  return HandleOverflow(Info, E, Value, E->getType());
2079  }
2080  return true;
2081 }
2082 
2083 /// Perform the given binary integer operation.
2084 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2085  BinaryOperatorKind Opcode, APSInt RHS,
2086  APSInt &Result) {
2087  switch (Opcode) {
2088  default:
2089  Info.FFDiag(E);
2090  return false;
2091  case BO_Mul:
2092  return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2093  std::multiplies<APSInt>(), Result);
2094  case BO_Add:
2095  return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2096  std::plus<APSInt>(), Result);
2097  case BO_Sub:
2098  return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2099  std::minus<APSInt>(), Result);
2100  case BO_And: Result = LHS & RHS; return true;
2101  case BO_Xor: Result = LHS ^ RHS; return true;
2102  case BO_Or: Result = LHS | RHS; return true;
2103  case BO_Div:
2104  case BO_Rem:
2105  if (RHS == 0) {
2106  Info.FFDiag(E, diag::note_expr_divide_by_zero);
2107  return false;
2108  }
2109  Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2110  // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2111  // this operation and gives the two's complement result.
2112  if (RHS.isNegative() && RHS.isAllOnesValue() &&
2113  LHS.isSigned() && LHS.isMinSignedValue())
2114  return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2115  E->getType());
2116  return true;
2117  case BO_Shl: {
2118  if (Info.getLangOpts().OpenCL)
2119  // OpenCL 6.3j: shift values are effectively % word size of LHS.
2120  RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2121  static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2122  RHS.isUnsigned());
2123  else if (RHS.isSigned() && RHS.isNegative()) {
2124  // During constant-folding, a negative shift is an opposite shift. Such
2125  // a shift is not a constant expression.
2126  Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2127  RHS = -RHS;
2128  goto shift_right;
2129  }
2130  shift_left:
2131  // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2132  // the shifted type.
2133  unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2134  if (SA != RHS) {
2135  Info.CCEDiag(E, diag::note_constexpr_large_shift)
2136  << RHS << E->getType() << LHS.getBitWidth();
2137  } else if (LHS.isSigned()) {
2138  // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2139  // operand, and must not overflow the corresponding unsigned type.
2140  if (LHS.isNegative())
2141  Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2142  else if (LHS.countLeadingZeros() < SA)
2143  Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2144  }
2145  Result = LHS << SA;
2146  return true;
2147  }
2148  case BO_Shr: {
2149  if (Info.getLangOpts().OpenCL)
2150  // OpenCL 6.3j: shift values are effectively % word size of LHS.
2151  RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2152  static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2153  RHS.isUnsigned());
2154  else if (RHS.isSigned() && RHS.isNegative()) {
2155  // During constant-folding, a negative shift is an opposite shift. Such a
2156  // shift is not a constant expression.
2157  Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2158  RHS = -RHS;
2159  goto shift_left;
2160  }
2161  shift_right:
2162  // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2163  // shifted type.
2164  unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2165  if (SA != RHS)
2166  Info.CCEDiag(E, diag::note_constexpr_large_shift)
2167  << RHS << E->getType() << LHS.getBitWidth();
2168  Result = LHS >> SA;
2169  return true;
2170  }
2171 
2172  case BO_LT: Result = LHS < RHS; return true;
2173  case BO_GT: Result = LHS > RHS; return true;
2174  case BO_LE: Result = LHS <= RHS; return true;
2175  case BO_GE: Result = LHS >= RHS; return true;
2176  case BO_EQ: Result = LHS == RHS; return true;
2177  case BO_NE: Result = LHS != RHS; return true;
2178  }
2179 }
2180 
2181 /// Perform the given binary floating-point operation, in-place, on LHS.
2182 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2183  APFloat &LHS, BinaryOperatorKind Opcode,
2184  const APFloat &RHS) {
2185  switch (Opcode) {
2186  default:
2187  Info.FFDiag(E);
2188  return false;
2189  case BO_Mul:
2190  LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2191  break;
2192  case BO_Add:
2193  LHS.add(RHS, APFloat::rmNearestTiesToEven);
2194  break;
2195  case BO_Sub:
2196  LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2197  break;
2198  case BO_Div:
2199  LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2200  break;
2201  }
2202 
2203  if (LHS.isInfinity() || LHS.isNaN()) {
2204  Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2205  return Info.noteUndefinedBehavior();
2206  }
2207  return true;
2208 }
2209 
2210 /// Cast an lvalue referring to a base subobject to a derived class, by
2211 /// truncating the lvalue's path to the given length.
2212 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2213  const RecordDecl *TruncatedType,
2214  unsigned TruncatedElements) {
2215  SubobjectDesignator &D = Result.Designator;
2216 
2217  // Check we actually point to a derived class object.
2218  if (TruncatedElements == D.Entries.size())
2219  return true;
2220  assert(TruncatedElements >= D.MostDerivedPathLength &&
2221  "not casting to a derived class");
2222  if (!Result.checkSubobject(Info, E, CSK_Derived))
2223  return false;
2224 
2225  // Truncate the path to the subobject, and remove any derived-to-base offsets.
2226  const RecordDecl *RD = TruncatedType;
2227  for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
2228  if (RD->isInvalidDecl()) return false;
2229  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2230  const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
2231  if (isVirtualBaseClass(D.Entries[I]))
2232  Result.Offset -= Layout.getVBaseClassOffset(Base);
2233  else
2234  Result.Offset -= Layout.getBaseClassOffset(Base);
2235  RD = Base;
2236  }
2237  D.Entries.resize(TruncatedElements);
2238  return true;
2239 }
2240 
2241 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2242  const CXXRecordDecl *Derived,
2243  const CXXRecordDecl *Base,
2244  const ASTRecordLayout *RL = nullptr) {
2245  if (!RL) {
2246  if (Derived->isInvalidDecl()) return false;
2247  RL = &Info.Ctx.getASTRecordLayout(Derived);
2248  }
2249 
2250  Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
2251  Obj.addDecl(Info, E, Base, /*Virtual*/ false);
2252  return true;
2253 }
2254 
2255 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2256  const CXXRecordDecl *DerivedDecl,
2257  const CXXBaseSpecifier *Base) {
2258  const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2259 
2260  if (!Base->isVirtual())
2261  return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
2262 
2263  SubobjectDesignator &D = Obj.Designator;
2264  if (D.Invalid)
2265  return false;
2266 
2267  // Extract most-derived object and corresponding type.
2268  DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2269  if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2270  return false;
2271 
2272  // Find the virtual base class.
2273  if (DerivedDecl->isInvalidDecl()) return false;
2274  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2275  Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
2276  Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
2277  return true;
2278 }
2279 
2280 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2281  QualType Type, LValue &Result) {
2282  for (CastExpr::path_const_iterator PathI = E->path_begin(),
2283  PathE = E->path_end();
2284  PathI != PathE; ++PathI) {
2285  if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2286  *PathI))
2287  return false;
2288  Type = (*PathI)->getType();
2289  }
2290  return true;
2291 }
2292 
2293 /// Update LVal to refer to the given field, which must be a member of the type
2294 /// currently described by LVal.
2295 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
2296  const FieldDecl *FD,
2297  const ASTRecordLayout *RL = nullptr) {
2298  if (!RL) {
2299  if (FD->getParent()->isInvalidDecl()) return false;
2300  RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
2301  }
2302 
2303  unsigned I = FD->getFieldIndex();
2304  LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
2305  LVal.addDecl(Info, E, FD);
2306  return true;
2307 }
2308 
2309 /// Update LVal to refer to the given indirect field.
2310 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
2311  LValue &LVal,
2312  const IndirectFieldDecl *IFD) {
2313  for (const auto *C : IFD->chain())
2314  if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
2315  return false;
2316  return true;
2317 }
2318 
2319 /// Get the size of the given type in char units.
2320 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2321  QualType Type, CharUnits &Size) {
2322  // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2323  // extension.
2324  if (Type->isVoidType() || Type->isFunctionType()) {
2325  Size = CharUnits::One();
2326  return true;
2327  }
2328 
2329  if (Type->isDependentType()) {
2330  Info.FFDiag(Loc);
2331  return false;
2332  }
2333 
2334  if (!Type->isConstantSizeType()) {
2335  // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2336  // FIXME: Better diagnostic.
2337  Info.FFDiag(Loc);
2338  return false;
2339  }
2340 
2341  Size = Info.Ctx.getTypeSizeInChars(Type);
2342  return true;
2343 }
2344 
2345 /// Update a pointer value to model pointer arithmetic.
2346 /// \param Info - Information about the ongoing evaluation.
2347 /// \param E - The expression being evaluated, for diagnostic purposes.
2348 /// \param LVal - The pointer value to be updated.
2349 /// \param EltTy - The pointee type represented by LVal.
2350 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
2351 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2352  LValue &LVal, QualType EltTy,
2353  APSInt Adjustment) {
2354  CharUnits SizeOfPointee;
2355  if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
2356  return false;
2357 
2358  LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
2359  return true;
2360 }
2361 
2362 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2363  LValue &LVal, QualType EltTy,
2364  int64_t Adjustment) {
2365  return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2366  APSInt::get(Adjustment));
2367 }
2368 
2369 /// Update an lvalue to refer to a component of a complex number.
2370 /// \param Info - Information about the ongoing evaluation.
2371 /// \param LVal - The lvalue to be updated.
2372 /// \param EltTy - The complex number's component type.
2373 /// \param Imag - False for the real component, true for the imaginary.
2374 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2375  LValue &LVal, QualType EltTy,
2376  bool Imag) {
2377  if (Imag) {
2378  CharUnits SizeOfComponent;
2379  if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2380  return false;
2381  LVal.Offset += SizeOfComponent;
2382  }
2383  LVal.addComplex(Info, E, EltTy, Imag);
2384  return true;
2385 }
2386 
2387 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2388  QualType Type, const LValue &LVal,
2389  APValue &RVal);
2390 
2391 /// Try to evaluate the initializer for a variable declaration.
2392 ///
2393 /// \param Info Information about the ongoing evaluation.
2394 /// \param E An expression to be used when printing diagnostics.
2395 /// \param VD The variable whose initializer should be obtained.
2396 /// \param Frame The frame in which the variable was created. Must be null
2397 /// if this variable is not local to the evaluation.
2398 /// \param Result Filled in with a pointer to the value of the variable.
2399 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2400  const VarDecl *VD, CallStackFrame *Frame,
2401  APValue *&Result) {
2402 
2403  // If this is a parameter to an active constexpr function call, perform
2404  // argument substitution.
2405  if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
2406  // Assume arguments of a potential constant expression are unknown
2407  // constant expressions.
2408  if (Info.checkingPotentialConstantExpression())
2409  return false;
2410  if (!Frame || !Frame->Arguments) {
2411  Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2412  return false;
2413  }
2414  Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
2415  return true;
2416  }
2417 
2418  // If this is a local variable, dig out its value.
2419  if (Frame) {
2420  Result = Frame->getTemporary(VD);
2421  if (!Result) {
2422  // Assume variables referenced within a lambda's call operator that were
2423  // not declared within the call operator are captures and during checking
2424  // of a potential constant expression, assume they are unknown constant
2425  // expressions.
2426  assert(isLambdaCallOperator(Frame->Callee) &&
2427  (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2428  "missing value for local variable");
2429  if (Info.checkingPotentialConstantExpression())
2430  return false;
2431  // FIXME: implement capture evaluation during constant expr evaluation.
2432  Info.FFDiag(E->getLocStart(),
2433  diag::note_unimplemented_constexpr_lambda_feature_ast)
2434  << "captures not currently allowed";
2435  return false;
2436  }
2437  return true;
2438  }
2439 
2440  // Dig out the initializer, and use the declaration which it's attached to.
2441  const Expr *Init = VD->getAnyInitializer(VD);
2442  if (!Init || Init->isValueDependent()) {
2443  // If we're checking a potential constant expression, the variable could be
2444  // initialized later.
2445  if (!Info.checkingPotentialConstantExpression())
2446  Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2447  return false;
2448  }
2449 
2450  // If we're currently evaluating the initializer of this declaration, use that
2451  // in-flight value.
2452  if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
2453  Result = Info.EvaluatingDeclValue;
2454  return true;
2455  }
2456 
2457  // Never evaluate the initializer of a weak variable. We can't be sure that
2458  // this is the definition which will be used.
2459  if (VD->isWeak()) {
2460  Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2461  return false;
2462  }
2463 
2464  // Check that we can fold the initializer. In C++, we will have already done
2465  // this in the cases where it matters for conformance.
2467  if (!VD->evaluateValue(Notes)) {
2468  Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
2469  Notes.size() + 1) << VD;
2470  Info.Note(VD->getLocation(), diag::note_declared_at);
2471  Info.addNotes(Notes);
2472  return false;
2473  } else if (!VD->checkInitIsICE()) {
2474  Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
2475  Notes.size() + 1) << VD;
2476  Info.Note(VD->getLocation(), diag::note_declared_at);
2477  Info.addNotes(Notes);
2478  }
2479 
2480  Result = VD->getEvaluatedValue();
2481  return true;
2482 }
2483 
2485  Qualifiers Quals = T.getQualifiers();
2486  return Quals.hasConst() && !Quals.hasVolatile();
2487 }
2488 
2489 /// Get the base index of the given base class within an APValue representing
2490 /// the given derived class.
2491 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2492  const CXXRecordDecl *Base) {
2493  Base = Base->getCanonicalDecl();
2494  unsigned Index = 0;
2496  E = Derived->bases_end(); I != E; ++I, ++Index) {
2497  if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2498  return Index;
2499  }
2500 
2501  llvm_unreachable("base class missing from derived class's bases list");
2502 }
2503 
2504 /// Extract the value of a character from a string literal.
2505 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2506  uint64_t Index) {
2507  // FIXME: Support MakeStringConstant
2508  if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2509  std::string Str;
2510  Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2511  assert(Index <= Str.size() && "Index too large");
2512  return APSInt::getUnsigned(Str.c_str()[Index]);
2513  }
2514 
2515  if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2516  Lit = PE->getFunctionName();
2517  const StringLiteral *S = cast<StringLiteral>(Lit);
2518  const ConstantArrayType *CAT =
2519  Info.Ctx.getAsConstantArrayType(S->getType());
2520  assert(CAT && "string literal isn't an array");
2521  QualType CharType = CAT->getElementType();
2522  assert(CharType->isIntegerType() && "unexpected character type");
2523 
2524  APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2525  CharType->isUnsignedIntegerType());
2526  if (Index < S->getLength())
2527  Value = S->getCodeUnit(Index);
2528  return Value;
2529 }
2530 
2531 // Expand a string literal into an array of characters.
2532 static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2533  APValue &Result) {
2534  const StringLiteral *S = cast<StringLiteral>(Lit);
2535  const ConstantArrayType *CAT =
2536  Info.Ctx.getAsConstantArrayType(S->getType());
2537  assert(CAT && "string literal isn't an array");
2538  QualType CharType = CAT->getElementType();
2539  assert(CharType->isIntegerType() && "unexpected character type");
2540 
2541  unsigned Elts = CAT->getSize().getZExtValue();
2542  Result = APValue(APValue::UninitArray(),
2543  std::min(S->getLength(), Elts), Elts);
2544  APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2545  CharType->isUnsignedIntegerType());
2546  if (Result.hasArrayFiller())
2547  Result.getArrayFiller() = APValue(Value);
2548  for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2549  Value = S->getCodeUnit(I);
2550  Result.getArrayInitializedElt(I) = APValue(Value);
2551  }
2552 }
2553 
2554 // Expand an array so that it has more than Index filled elements.
2555 static void expandArray(APValue &Array, unsigned Index) {
2556  unsigned Size = Array.getArraySize();
2557  assert(Index < Size);
2558 
2559  // Always at least double the number of elements for which we store a value.
2560  unsigned OldElts = Array.getArrayInitializedElts();
2561  unsigned NewElts = std::max(Index+1, OldElts * 2);
2562  NewElts = std::min(Size, std::max(NewElts, 8u));
2563 
2564  // Copy the data across.
2565  APValue NewValue(APValue::UninitArray(), NewElts, Size);
2566  for (unsigned I = 0; I != OldElts; ++I)
2567  NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2568  for (unsigned I = OldElts; I != NewElts; ++I)
2569  NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2570  if (NewValue.hasArrayFiller())
2571  NewValue.getArrayFiller() = Array.getArrayFiller();
2572  Array.swap(NewValue);
2573 }
2574 
2575 /// Determine whether a type would actually be read by an lvalue-to-rvalue
2576 /// conversion. If it's of class type, we may assume that the copy operation
2577 /// is trivial. Note that this is never true for a union type with fields
2578 /// (because the copy always "reads" the active member) and always true for
2579 /// a non-class type.
2582  if (!RD || (RD->isUnion() && !RD->field_empty()))
2583  return true;
2584  if (RD->isEmpty())
2585  return false;
2586 
2587  for (auto *Field : RD->fields())
2588  if (isReadByLvalueToRvalueConversion(Field->getType()))
2589  return true;
2590 
2591  for (auto &BaseSpec : RD->bases())
2592  if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2593  return true;
2594 
2595  return false;
2596 }
2597 
2598 /// Diagnose an attempt to read from any unreadable field within the specified
2599 /// type, which might be a class type.
2600 static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2601  QualType T) {
2603  if (!RD)
2604  return false;
2605 
2606  if (!RD->hasMutableFields())
2607  return false;
2608 
2609  for (auto *Field : RD->fields()) {
2610  // If we're actually going to read this field in some way, then it can't
2611  // be mutable. If we're in a union, then assigning to a mutable field
2612  // (even an empty one) can change the active member, so that's not OK.
2613  // FIXME: Add core issue number for the union case.
2614  if (Field->isMutable() &&
2615  (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2616  Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2617  Info.Note(Field->getLocation(), diag::note_declared_at);
2618  return true;
2619  }
2620 
2621  if (diagnoseUnreadableFields(Info, E, Field->getType()))
2622  return true;
2623  }
2624 
2625  for (auto &BaseSpec : RD->bases())
2626  if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2627  return true;
2628 
2629  // All mutable fields were empty, and thus not actually read.
2630  return false;
2631 }
2632 
2633 /// Kinds of access we can perform on an object, for diagnostics.
2639 };
2640 
2641 namespace {
2642 /// A handle to a complete object (an object that is not a subobject of
2643 /// another object).
2644 struct CompleteObject {
2645  /// The value of the complete object.
2646  APValue *Value;
2647  /// The type of the complete object.
2648  QualType Type;
2649  bool LifetimeStartedInEvaluation;
2650 
2651  CompleteObject() : Value(nullptr) {}
2652  CompleteObject(APValue *Value, QualType Type,
2653  bool LifetimeStartedInEvaluation)
2654  : Value(Value), Type(Type),
2655  LifetimeStartedInEvaluation(LifetimeStartedInEvaluation) {
2656  assert(Value && "missing value for complete object");
2657  }
2658 
2659  explicit operator bool() const { return Value; }
2660 };
2661 } // end anonymous namespace
2662 
2663 /// Find the designated sub-object of an rvalue.
2664 template<typename SubobjectHandler>
2665 typename SubobjectHandler::result_type
2666 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
2667  const SubobjectDesignator &Sub, SubobjectHandler &handler) {
2668  if (Sub.Invalid)
2669  // A diagnostic will have already been produced.
2670  return handler.failed();
2671  if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
2672  if (Info.getLangOpts().CPlusPlus11)
2673  Info.FFDiag(E, Sub.isOnePastTheEnd()
2674  ? diag::note_constexpr_access_past_end
2675  : diag::note_constexpr_access_unsized_array)
2676  << handler.AccessKind;
2677  else
2678  Info.FFDiag(E);
2679  return handler.failed();
2680  }
2681 
2682  APValue *O = Obj.Value;
2683  QualType ObjType = Obj.Type;
2684  const FieldDecl *LastField = nullptr;
2685  const bool MayReadMutableMembers =
2686  Obj.LifetimeStartedInEvaluation && Info.getLangOpts().CPlusPlus14;
2687 
2688  // Walk the designator's path to find the subobject.
2689  for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2690  if (O->isUninit()) {
2691  if (!Info.checkingPotentialConstantExpression())
2692  Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2693  return handler.failed();
2694  }
2695 
2696  if (I == N) {
2697  // If we are reading an object of class type, there may still be more
2698  // things we need to check: if there are any mutable subobjects, we
2699  // cannot perform this read. (This only happens when performing a trivial
2700  // copy or assignment.)
2701  if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2702  !MayReadMutableMembers && diagnoseUnreadableFields(Info, E, ObjType))
2703  return handler.failed();
2704 
2705  if (!handler.found(*O, ObjType))
2706  return false;
2707 
2708  // If we modified a bit-field, truncate it to the right width.
2709  if (handler.AccessKind != AK_Read &&
2710  LastField && LastField->isBitField() &&
2711  !truncateBitfieldValue(Info, E, *O, LastField))
2712  return false;
2713 
2714  return true;
2715  }
2716 
2717  LastField = nullptr;
2718  if (ObjType->isArrayType()) {
2719  // Next subobject is an array element.
2720  const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
2721  assert(CAT && "vla in literal type?");
2722  uint64_t Index = Sub.Entries[I].ArrayIndex;
2723  if (CAT->getSize().ule(Index)) {
2724  // Note, it should not be possible to form a pointer with a valid
2725  // designator which points more than one past the end of the array.
2726  if (Info.getLangOpts().CPlusPlus11)
2727  Info.FFDiag(E, diag::note_constexpr_access_past_end)
2728  << handler.AccessKind;
2729  else
2730  Info.FFDiag(E);
2731  return handler.failed();
2732  }
2733 
2734  ObjType = CAT->getElementType();
2735 
2736  // An array object is represented as either an Array APValue or as an
2737  // LValue which refers to a string literal.
2738  if (O->isLValue()) {
2739  assert(I == N - 1 && "extracting subobject of character?");
2740  assert(!O->hasLValuePath() || O->getLValuePath().empty());
2741  if (handler.AccessKind != AK_Read)
2742  expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2743  *O);
2744  else
2745  return handler.foundString(*O, ObjType, Index);
2746  }
2747 
2748  if (O->getArrayInitializedElts() > Index)
2749  O = &O->getArrayInitializedElt(Index);
2750  else if (handler.AccessKind != AK_Read) {
2751  expandArray(*O, Index);
2752  O = &O->getArrayInitializedElt(Index);
2753  } else
2754  O = &O->getArrayFiller();
2755  } else if (ObjType->isAnyComplexType()) {
2756  // Next subobject is a complex number.
2757  uint64_t Index = Sub.Entries[I].ArrayIndex;
2758  if (Index > 1) {
2759  if (Info.getLangOpts().CPlusPlus11)
2760  Info.FFDiag(E, diag::note_constexpr_access_past_end)
2761  << handler.AccessKind;
2762  else
2763  Info.FFDiag(E);
2764  return handler.failed();
2765  }
2766 
2767  bool WasConstQualified = ObjType.isConstQualified();
2768  ObjType = ObjType->castAs<ComplexType>()->getElementType();
2769  if (WasConstQualified)
2770  ObjType.addConst();
2771 
2772  assert(I == N - 1 && "extracting subobject of scalar?");
2773  if (O->isComplexInt()) {
2774  return handler.found(Index ? O->getComplexIntImag()
2775  : O->getComplexIntReal(), ObjType);
2776  } else {
2777  assert(O->isComplexFloat());
2778  return handler.found(Index ? O->getComplexFloatImag()
2779  : O->getComplexFloatReal(), ObjType);
2780  }
2781  } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
2782  // In C++14 onwards, it is permitted to read a mutable member whose
2783  // lifetime began within the evaluation.
2784  // FIXME: Should we also allow this in C++11?
2785  if (Field->isMutable() && handler.AccessKind == AK_Read &&
2786  !MayReadMutableMembers) {
2787  Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
2788  << Field;
2789  Info.Note(Field->getLocation(), diag::note_declared_at);
2790  return handler.failed();
2791  }
2792 
2793  // Next subobject is a class, struct or union field.
2794  RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2795  if (RD->isUnion()) {
2796  const FieldDecl *UnionField = O->getUnionField();
2797  if (!UnionField ||
2798  UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
2799  Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
2800  << handler.AccessKind << Field << !UnionField << UnionField;
2801  return handler.failed();
2802  }
2803  O = &O->getUnionValue();
2804  } else
2805  O = &O->getStructField(Field->getFieldIndex());
2806 
2807  bool WasConstQualified = ObjType.isConstQualified();
2808  ObjType = Field->getType();
2809  if (WasConstQualified && !Field->isMutable())
2810  ObjType.addConst();
2811 
2812  if (ObjType.isVolatileQualified()) {
2813  if (Info.getLangOpts().CPlusPlus) {
2814  // FIXME: Include a description of the path to the volatile subobject.
2815  Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
2816  << handler.AccessKind << 2 << Field;
2817  Info.Note(Field->getLocation(), diag::note_declared_at);
2818  } else {
2819  Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2820  }
2821  return handler.failed();
2822  }
2823 
2824  LastField = Field;
2825  } else {
2826  // Next subobject is a base class.
2827  const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2828  const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2829  O = &O->getStructBase(getBaseIndex(Derived, Base));
2830 
2831  bool WasConstQualified = ObjType.isConstQualified();
2832  ObjType = Info.Ctx.getRecordType(Base);
2833  if (WasConstQualified)
2834  ObjType.addConst();
2835  }
2836  }
2837 }
2838 
2839 namespace {
2840 struct ExtractSubobjectHandler {
2841  EvalInfo &Info;
2842  APValue &Result;
2843 
2844  static const AccessKinds AccessKind = AK_Read;
2845 
2846  typedef bool result_type;
2847  bool failed() { return false; }
2848  bool found(APValue &Subobj, QualType SubobjType) {
2849  Result = Subobj;
2850  return true;
2851  }
2852  bool found(APSInt &Value, QualType SubobjType) {
2853  Result = APValue(Value);
2854  return true;
2855  }
2856  bool found(APFloat &Value, QualType SubobjType) {
2857  Result = APValue(Value);
2858  return true;
2859  }
2860  bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2862  Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2863  return true;
2864  }
2865 };
2866 } // end anonymous namespace
2867 
2869 
2870 /// Extract the designated sub-object of an rvalue.
2871 static bool extractSubobject(EvalInfo &Info, const Expr *E,
2872  const CompleteObject &Obj,
2873  const SubobjectDesignator &Sub,
2874  APValue &Result) {
2875  ExtractSubobjectHandler Handler = { Info, Result };
2876  return findSubobject(Info, E, Obj, Sub, Handler);
2877 }
2878 
2879 namespace {
2880 struct ModifySubobjectHandler {
2881  EvalInfo &Info;
2882  APValue &NewVal;
2883  const Expr *E;
2884 
2885  typedef bool result_type;
2886  static const AccessKinds AccessKind = AK_Assign;
2887 
2888  bool checkConst(QualType QT) {
2889  // Assigning to a const object has undefined behavior.
2890  if (QT.isConstQualified()) {
2891  Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
2892  return false;
2893  }
2894  return true;
2895  }
2896 
2897  bool failed() { return false; }
2898  bool found(APValue &Subobj, QualType SubobjType) {
2899  if (!checkConst(SubobjType))
2900  return false;
2901  // We've been given ownership of NewVal, so just swap it in.
2902  Subobj.swap(NewVal);
2903  return true;
2904  }
2905  bool found(APSInt &Value, QualType SubobjType) {
2906  if (!checkConst(SubobjType))
2907  return false;
2908  if (!NewVal.isInt()) {
2909  // Maybe trying to write a cast pointer value into a complex?
2910  Info.FFDiag(E);
2911  return false;
2912  }
2913  Value = NewVal.getInt();
2914  return true;
2915  }
2916  bool found(APFloat &Value, QualType SubobjType) {
2917  if (!checkConst(SubobjType))
2918  return false;
2919  Value = NewVal.getFloat();
2920  return true;
2921  }
2922  bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2923  llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2924  }
2925 };
2926 } // end anonymous namespace
2927 
2929 
2930 /// Update the designated sub-object of an rvalue to the given value.
2931 static bool modifySubobject(EvalInfo &Info, const Expr *E,
2932  const CompleteObject &Obj,
2933  const SubobjectDesignator &Sub,
2934  APValue &NewVal) {
2935  ModifySubobjectHandler Handler = { Info, NewVal, E };
2936  return findSubobject(Info, E, Obj, Sub, Handler);
2937 }
2938 
2939 /// Find the position where two subobject designators diverge, or equivalently
2940 /// the length of the common initial subsequence.
2941 static unsigned FindDesignatorMismatch(QualType ObjType,
2942  const SubobjectDesignator &A,
2943  const SubobjectDesignator &B,
2944  bool &WasArrayIndex) {
2945  unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2946  for (/**/; I != N; ++I) {
2947  if (!ObjType.isNull() &&
2948  (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
2949  // Next subobject is an array element.
2950  if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2951  WasArrayIndex = true;
2952  return I;
2953  }
2954  if (ObjType->isAnyComplexType())
2955  ObjType = ObjType->castAs<ComplexType>()->getElementType();
2956  else
2957  ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
2958  } else {
2959  if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2960  WasArrayIndex = false;
2961  return I;
2962  }
2963  if (const FieldDecl *FD = getAsField(A.Entries[I]))
2964  // Next subobject is a field.
2965  ObjType = FD->getType();
2966  else
2967  // Next subobject is a base class.
2968  ObjType = QualType();
2969  }
2970  }
2971  WasArrayIndex = false;
2972  return I;
2973 }
2974 
2975 /// Determine whether the given subobject designators refer to elements of the
2976 /// same array object.
2977 static bool AreElementsOfSameArray(QualType ObjType,
2978  const SubobjectDesignator &A,
2979  const SubobjectDesignator &B) {
2980  if (A.Entries.size() != B.Entries.size())
2981  return false;
2982 
2983  bool IsArray = A.MostDerivedIsArrayElement;
2984  if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2985  // A is a subobject of the array element.
2986  return false;
2987 
2988  // If A (and B) designates an array element, the last entry will be the array
2989  // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2990  // of length 1' case, and the entire path must match.
2991  bool WasArrayIndex;
2992  unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2993  return CommonLength >= A.Entries.size() - IsArray;
2994 }
2995 
2996 /// Find the complete object to which an LValue refers.
2997 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2998  AccessKinds AK, const LValue &LVal,
2999  QualType LValType) {
3000  if (!LVal.Base) {
3001  Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3002  return CompleteObject();
3003  }
3004 
3005  CallStackFrame *Frame = nullptr;
3006  if (LVal.CallIndex) {
3007  Frame = Info.getCallFrame(LVal.CallIndex);
3008  if (!Frame) {
3009  Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3010  << AK << LVal.Base.is<const ValueDecl*>();
3011  NoteLValueLocation(Info, LVal.Base);
3012  return CompleteObject();
3013  }
3014  }
3015 
3016  // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3017  // is not a constant expression (even if the object is non-volatile). We also
3018  // apply this rule to C++98, in order to conform to the expected 'volatile'
3019  // semantics.
3020  if (LValType.isVolatileQualified()) {
3021  if (Info.getLangOpts().CPlusPlus)
3022  Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3023  << AK << LValType;
3024  else
3025  Info.FFDiag(E);
3026  return CompleteObject();
3027  }
3028 
3029  // Compute value storage location and type of base object.
3030  APValue *BaseVal = nullptr;
3031  QualType BaseType = getType(LVal.Base);
3032  bool LifetimeStartedInEvaluation = Frame;
3033 
3034  if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3035  // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3036  // In C++11, constexpr, non-volatile variables initialized with constant
3037  // expressions are constant expressions too. Inside constexpr functions,
3038  // parameters are constant expressions even if they're non-const.
3039  // In C++1y, objects local to a constant expression (those with a Frame) are
3040  // both readable and writable inside constant expressions.
3041  // In C, such things can also be folded, although they are not ICEs.
3042  const VarDecl *VD = dyn_cast<VarDecl>(D);
3043  if (VD) {
3044  if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3045  VD = VDef;
3046  }
3047  if (!VD || VD->isInvalidDecl()) {
3048  Info.FFDiag(E);
3049  return CompleteObject();
3050  }
3051 
3052  // Accesses of volatile-qualified objects are not allowed.
3053  if (BaseType.isVolatileQualified()) {
3054  if (Info.getLangOpts().CPlusPlus) {
3055  Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3056  << AK << 1 << VD;
3057  Info.Note(VD->getLocation(), diag::note_declared_at);
3058  } else {
3059  Info.FFDiag(E);
3060  }
3061  return CompleteObject();
3062  }
3063 
3064  // Unless we're looking at a local variable or argument in a constexpr call,
3065  // the variable we're reading must be const.
3066  if (!Frame) {
3067  if (Info.getLangOpts().CPlusPlus14 &&
3068  VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
3069  // OK, we can read and modify an object if we're in the process of
3070  // evaluating its initializer, because its lifetime began in this
3071  // evaluation.
3072  } else if (AK != AK_Read) {
3073  // All the remaining cases only permit reading.
3074  Info.FFDiag(E, diag::note_constexpr_modify_global);
3075  return CompleteObject();
3076  } else if (VD->isConstexpr()) {
3077  // OK, we can read this variable.
3078  } else if (BaseType->isIntegralOrEnumerationType()) {
3079  // In OpenCL if a variable is in constant address space it is a const value.
3080  if (!(BaseType.isConstQualified() ||
3081  (Info.getLangOpts().OpenCL &&
3082  BaseType.getAddressSpace() == LangAS::opencl_constant))) {
3083  if (Info.getLangOpts().CPlusPlus) {
3084  Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
3085  Info.Note(VD->getLocation(), diag::note_declared_at);
3086  } else {
3087  Info.FFDiag(E);
3088  }
3089  return CompleteObject();
3090  }
3091  } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3092  // We support folding of const floating-point types, in order to make
3093  // static const data members of such types (supported as an extension)
3094  // more useful.
3095  if (Info.getLangOpts().CPlusPlus11) {
3096  Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3097  Info.Note(VD->getLocation(), diag::note_declared_at);
3098  } else {
3099  Info.CCEDiag(E);
3100  }
3101  } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3102  Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3103  // Keep evaluating to see what we can do.
3104  } else {
3105  // FIXME: Allow folding of values of any literal type in all languages.
3106  if (Info.checkingPotentialConstantExpression() &&
3107  VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3108  // The definition of this variable could be constexpr. We can't
3109  // access it right now, but may be able to in future.
3110  } else if (Info.getLangOpts().CPlusPlus11) {
3111  Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3112  Info.Note(VD->getLocation(), diag::note_declared_at);
3113  } else {
3114  Info.FFDiag(E);
3115  }
3116  return CompleteObject();
3117  }
3118  }
3119 
3120  if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
3121  return CompleteObject();
3122  } else {
3123  const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3124 
3125  if (!Frame) {
3126  if (const MaterializeTemporaryExpr *MTE =
3127  dyn_cast<MaterializeTemporaryExpr>(Base)) {
3128  assert(MTE->getStorageDuration() == SD_Static &&
3129  "should have a frame for a non-global materialized temporary");
3130 
3131  // Per C++1y [expr.const]p2:
3132  // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3133  // - a [...] glvalue of integral or enumeration type that refers to
3134  // a non-volatile const object [...]
3135  // [...]
3136  // - a [...] glvalue of literal type that refers to a non-volatile
3137  // object whose lifetime began within the evaluation of e.
3138  //
3139  // C++11 misses the 'began within the evaluation of e' check and
3140  // instead allows all temporaries, including things like:
3141  // int &&r = 1;
3142  // int x = ++r;
3143  // constexpr int k = r;
3144  // Therefore we use the C++14 rules in C++11 too.
3145  const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3146  const ValueDecl *ED = MTE->getExtendingDecl();
3147  if (!(BaseType.isConstQualified() &&
3148  BaseType->isIntegralOrEnumerationType()) &&
3149  !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
3150  Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
3151  Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3152  return CompleteObject();
3153  }
3154 
3155  BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3156  assert(BaseVal && "got reference to unevaluated temporary");
3157  LifetimeStartedInEvaluation = true;
3158  } else {
3159  Info.FFDiag(E);
3160  return CompleteObject();
3161  }
3162  } else {
3163  BaseVal = Frame->getTemporary(Base);
3164  assert(BaseVal && "missing value for temporary");
3165  }
3166 
3167  // Volatile temporary objects cannot be accessed in constant expressions.
3168  if (BaseType.isVolatileQualified()) {
3169  if (Info.getLangOpts().CPlusPlus) {
3170  Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3171  << AK << 0;
3172  Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3173  } else {
3174  Info.FFDiag(E);
3175  }
3176  return CompleteObject();
3177  }
3178  }
3179 
3180  // During the construction of an object, it is not yet 'const'.
3181  // FIXME: This doesn't do quite the right thing for const subobjects of the
3182  // object under construction.
3183  if (Info.isEvaluatingConstructor(LVal.getLValueBase(), LVal.CallIndex)) {
3184  BaseType = Info.Ctx.getCanonicalType(BaseType);
3185  BaseType.removeLocalConst();
3186  LifetimeStartedInEvaluation = true;
3187  }
3188 
3189  // In C++14, we can't safely access any mutable state when we might be
3190  // evaluating after an unmodeled side effect.
3191  //
3192  // FIXME: Not all local state is mutable. Allow local constant subobjects
3193  // to be read here (but take care with 'mutable' fields).
3194  if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3195  Info.EvalStatus.HasSideEffects) ||
3196  (AK != AK_Read && Info.IsSpeculativelyEvaluating))
3197  return CompleteObject();
3198 
3199  return CompleteObject(BaseVal, BaseType, LifetimeStartedInEvaluation);
3200 }
3201 
3202 /// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
3203 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3204 /// glvalue referred to by an entity of reference type.
3205 ///
3206 /// \param Info - Information about the ongoing evaluation.
3207 /// \param Conv - The expression for which we are performing the conversion.
3208 /// Used for diagnostics.
3209 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3210 /// case of a non-class type).
3211 /// \param LVal - The glvalue on which we are attempting to perform this action.
3212 /// \param RVal - The produced value will be placed here.
3213 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
3214  QualType Type,
3215  const LValue &LVal, APValue &RVal) {
3216  if (LVal.Designator.Invalid)
3217  return false;
3218 
3219  // Check for special cases where there is no existing APValue to look at.
3220  const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3221  if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
3222  if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3223  // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3224  // initializer until now for such expressions. Such an expression can't be
3225  // an ICE in C, so this only matters for fold.
3226  if (Type.isVolatileQualified()) {
3227  Info.FFDiag(Conv);
3228  return false;
3229  }
3230  APValue Lit;
3231  if (!Evaluate(Lit, Info, CLE->getInitializer()))
3232  return false;
3233  CompleteObject LitObj(&Lit, Base->getType(), false);
3234  return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
3235  } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
3236  // We represent a string literal array as an lvalue pointing at the
3237  // corresponding expression, rather than building an array of chars.
3238  // FIXME: Support ObjCEncodeExpr, MakeStringConstant
3239  APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
3240  CompleteObject StrObj(&Str, Base->getType(), false);
3241  return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
3242  }
3243  }
3244 
3245  CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3246  return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
3247 }
3248 
3249 /// Perform an assignment of Val to LVal. Takes ownership of Val.
3250 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
3251  QualType LValType, APValue &Val) {
3252  if (LVal.Designator.Invalid)
3253  return false;
3254 
3255  if (!Info.getLangOpts().CPlusPlus14) {
3256  Info.FFDiag(E);
3257  return false;
3258  }
3259 
3260  CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3261  return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3262 }
3263 
3264 namespace {
3265 struct CompoundAssignSubobjectHandler {
3266  EvalInfo &Info;
3267  const Expr *E;
3268  QualType PromotedLHSType;
3269  BinaryOperatorKind Opcode;
3270  const APValue &RHS;
3271 
3272  static const AccessKinds AccessKind = AK_Assign;
3273 
3274  typedef bool result_type;
3275 
3276  bool checkConst(QualType QT) {
3277  // Assigning to a const object has undefined behavior.
3278  if (QT.isConstQualified()) {
3279  Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3280  return false;
3281  }
3282  return true;
3283  }
3284 
3285  bool failed() { return false; }
3286  bool found(APValue &Subobj, QualType SubobjType) {
3287  switch (Subobj.getKind()) {
3288  case APValue::Int:
3289  return found(Subobj.getInt(), SubobjType);
3290  case APValue::Float:
3291  return found(Subobj.getFloat(), SubobjType);
3292  case APValue::ComplexInt:
3293  case APValue::ComplexFloat:
3294  // FIXME: Implement complex compound assignment.
3295  Info.FFDiag(E);
3296  return false;
3297  case APValue::LValue:
3298  return foundPointer(Subobj, SubobjType);
3299  default:
3300  // FIXME: can this happen?
3301  Info.FFDiag(E);
3302  return false;
3303  }
3304  }
3305  bool found(APSInt &Value, QualType SubobjType) {
3306  if (!checkConst(SubobjType))
3307  return false;
3308 
3309  if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3310  // We don't support compound assignment on integer-cast-to-pointer
3311  // values.
3312  Info.FFDiag(E);
3313  return false;
3314  }
3315 
3316  APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3317  SubobjType, Value);
3318  if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3319  return false;
3320  Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3321  return true;
3322  }
3323  bool found(APFloat &Value, QualType SubobjType) {
3324  return checkConst(SubobjType) &&
3325  HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3326  Value) &&
3327  handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3328  HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
3329  }
3330  bool foundPointer(APValue &Subobj, QualType SubobjType) {
3331  if (!checkConst(SubobjType))
3332  return false;
3333 
3334  QualType PointeeType;
3335  if (const PointerType *PT = SubobjType->getAs<PointerType>())
3336  PointeeType = PT->getPointeeType();
3337 
3338  if (PointeeType.isNull() || !RHS.isInt() ||
3339  (Opcode != BO_Add && Opcode != BO_Sub)) {
3340  Info.FFDiag(E);
3341  return false;
3342  }
3343 
3344  APSInt Offset = RHS.getInt();
3345  if (Opcode == BO_Sub)
3346  negateAsSigned(Offset);
3347 
3348  LValue LVal;
3349  LVal.setFrom(Info.Ctx, Subobj);
3350  if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3351  return false;
3352  LVal.moveInto(Subobj);
3353  return true;
3354  }
3355  bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3356  llvm_unreachable("shouldn't encounter string elements here");
3357  }
3358 };
3359 } // end anonymous namespace
3360 
3362 
3363 /// Perform a compound assignment of LVal <op>= RVal.
3365  EvalInfo &Info, const Expr *E,
3366  const LValue &LVal, QualType LValType, QualType PromotedLValType,
3367  BinaryOperatorKind Opcode, const APValue &RVal) {
3368  if (LVal.Designator.Invalid)
3369  return false;
3370 
3371  if (!Info.getLangOpts().CPlusPlus14) {
3372  Info.FFDiag(E);
3373  return false;
3374  }
3375 
3376  CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3377  CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3378  RVal };
3379  return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3380 }
3381 
3382 namespace {
3383 struct IncDecSubobjectHandler {
3384  EvalInfo &Info;
3385  const UnaryOperator *E;
3387  APValue *Old;
3388 
3389  typedef bool result_type;
3390 
3391  bool checkConst(QualType QT) {
3392  // Assigning to a const object has undefined behavior.
3393  if (QT.isConstQualified()) {
3394  Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3395  return false;
3396  }
3397  return true;
3398  }
3399 
3400  bool failed() { return false; }
3401  bool found(APValue &Subobj, QualType SubobjType) {
3402  // Stash the old value. Also clear Old, so we don't clobber it later
3403  // if we're post-incrementing a complex.
3404  if (Old) {
3405  *Old = Subobj;
3406  Old = nullptr;
3407  }
3408 
3409  switch (Subobj.getKind()) {
3410  case APValue::Int:
3411  return found(Subobj.getInt(), SubobjType);
3412  case APValue::Float:
3413  return found(Subobj.getFloat(), SubobjType);
3414  case APValue::ComplexInt:
3415  return found(Subobj.getComplexIntReal(),
3416  SubobjType->castAs<ComplexType>()->getElementType()
3417  .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3418  case APValue::ComplexFloat:
3419  return found(Subobj.getComplexFloatReal(),
3420  SubobjType->castAs<ComplexType>()->getElementType()
3421  .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3422  case APValue::LValue:
3423  return foundPointer(Subobj, SubobjType);
3424  default:
3425  // FIXME: can this happen?
3426  Info.FFDiag(E);
3427  return false;
3428  }
3429  }
3430  bool found(APSInt &Value, QualType SubobjType) {
3431  if (!checkConst(SubobjType))
3432  return false;
3433 
3434  if (!SubobjType->isIntegerType()) {
3435  // We don't support increment / decrement on integer-cast-to-pointer
3436  // values.
3437  Info.FFDiag(E);
3438  return false;
3439  }
3440 
3441  if (Old) *Old = APValue(Value);
3442 
3443  // bool arithmetic promotes to int, and the conversion back to bool
3444  // doesn't reduce mod 2^n, so special-case it.
3445  if (SubobjType->isBooleanType()) {
3446  if (AccessKind == AK_Increment)
3447  Value = 1;
3448  else
3449  Value = !Value;
3450  return true;
3451  }
3452 
3453  bool WasNegative = Value.isNegative();
3454  if (AccessKind == AK_Increment) {
3455  ++Value;
3456 
3457  if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3458  APSInt ActualValue(Value, /*IsUnsigned*/true);
3459  return HandleOverflow(Info, E, ActualValue, SubobjType);
3460  }
3461  } else {
3462  --Value;
3463 
3464  if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3465  unsigned BitWidth = Value.getBitWidth();
3466  APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3467  ActualValue.setBit(BitWidth);
3468  return HandleOverflow(Info, E, ActualValue, SubobjType);
3469  }
3470  }
3471  return true;
3472  }
3473  bool found(APFloat &Value, QualType SubobjType) {
3474  if (!checkConst(SubobjType))
3475  return false;
3476 
3477  if (Old) *Old = APValue(Value);
3478 
3479  APFloat One(Value.getSemantics(), 1);
3480  if (AccessKind == AK_Increment)
3481  Value.add(One, APFloat::rmNearestTiesToEven);
3482  else
3483  Value.subtract(One, APFloat::rmNearestTiesToEven);
3484  return true;
3485  }
3486  bool foundPointer(APValue &Subobj, QualType SubobjType) {
3487  if (!checkConst(SubobjType))
3488  return false;
3489 
3490  QualType PointeeType;
3491  if (const PointerType *PT = SubobjType->getAs<PointerType>())
3492  PointeeType = PT->getPointeeType();
3493  else {
3494  Info.FFDiag(E);
3495  return false;
3496  }
3497 
3498  LValue LVal;
3499  LVal.setFrom(Info.Ctx, Subobj);
3500  if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3501  AccessKind == AK_Increment ? 1 : -1))
3502  return false;
3503  LVal.moveInto(Subobj);
3504  return true;
3505  }
3506  bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3507  llvm_unreachable("shouldn't encounter string elements here");
3508  }
3509 };
3510 } // end anonymous namespace
3511 
3512 /// Perform an increment or decrement on LVal.
3513 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3514  QualType LValType, bool IsIncrement, APValue *Old) {
3515  if (LVal.Designator.Invalid)
3516  return false;
3517 
3518  if (!Info.getLangOpts().CPlusPlus14) {
3519  Info.FFDiag(E);
3520  return false;
3521  }
3522 
3523  AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3524  CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3525  IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3526  return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3527 }
3528 
3529 /// Build an lvalue for the object argument of a member function call.
3530 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3531  LValue &This) {
3532  if (Object->getType()->isPointerType())
3533  return EvaluatePointer(Object, This, Info);
3534 
3535  if (Object->isGLValue())
3536  return EvaluateLValue(Object, This, Info);
3537 
3538  if (Object->getType()->isLiteralType(Info.Ctx))
3539  return EvaluateTemporary(Object, This, Info);
3540 
3541  Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
3542  return false;
3543 }
3544 
3545 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
3546 /// lvalue referring to the result.
3547 ///
3548 /// \param Info - Information about the ongoing evaluation.
3549 /// \param LV - An lvalue referring to the base of the member pointer.
3550 /// \param RHS - The member pointer expression.
3551 /// \param IncludeMember - Specifies whether the member itself is included in
3552 /// the resulting LValue subobject designator. This is not possible when
3553 /// creating a bound member function.
3554 /// \return The field or method declaration to which the member pointer refers,
3555 /// or 0 if evaluation fails.
3556 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3557  QualType LVType,
3558  LValue &LV,
3559  const Expr *RHS,
3560  bool IncludeMember = true) {
3561  MemberPtr MemPtr;
3562  if (!EvaluateMemberPointer(RHS, MemPtr, Info))
3563  return nullptr;
3564 
3565  // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3566  // member value, the behavior is undefined.
3567  if (!MemPtr.getDecl()) {
3568  // FIXME: Specific diagnostic.
3569  Info.FFDiag(RHS);
3570  return nullptr;
3571  }
3572 
3573  if (MemPtr.isDerivedMember()) {
3574  // This is a member of some derived class. Truncate LV appropriately.
3575  // The end of the derived-to-base path for the base object must match the
3576  // derived-to-base path for the member pointer.
3577  if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
3578  LV.Designator.Entries.size()) {
3579  Info.FFDiag(RHS);
3580  return nullptr;
3581  }
3582  unsigned PathLengthToMember =
3583  LV.Designator.Entries.size() - MemPtr.Path.size();
3584  for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3585  const CXXRecordDecl *LVDecl = getAsBaseClass(
3586  LV.Designator.Entries[PathLengthToMember + I]);
3587  const CXXRecordDecl *MPDecl = MemPtr.Path[I];
3588  if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3589  Info.FFDiag(RHS);
3590  return nullptr;
3591  }
3592  }
3593 
3594  // Truncate the lvalue to the appropriate derived class.
3595  if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
3596  PathLengthToMember))
3597  return nullptr;
3598  } else if (!MemPtr.Path.empty()) {
3599  // Extend the LValue path with the member pointer's path.
3600  LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3601  MemPtr.Path.size() + IncludeMember);
3602 
3603  // Walk down to the appropriate base class.
3604  if (const PointerType *PT = LVType->getAs<PointerType>())
3605  LVType = PT->getPointeeType();
3606  const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3607  assert(RD && "member pointer access on non-class-type expression");
3608  // The first class in the path is that of the lvalue.
3609  for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3610  const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
3611  if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
3612  return nullptr;
3613  RD = Base;
3614  }
3615  // Finally cast to the class containing the member.
3616  if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3617  MemPtr.getContainingRecord()))
3618  return nullptr;
3619  }
3620 
3621  // Add the member. Note that we cannot build bound member functions here.
3622  if (IncludeMember) {
3623  if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
3624  if (!HandleLValueMember(Info, RHS, LV, FD))
3625  return nullptr;
3626  } else if (const IndirectFieldDecl *IFD =
3627  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
3628  if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
3629  return nullptr;
3630  } else {
3631  llvm_unreachable("can't construct reference to bound member function");
3632  }
3633  }
3634 
3635  return MemPtr.getDecl();
3636 }
3637 
3638 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3639  const BinaryOperator *BO,
3640  LValue &LV,
3641  bool IncludeMember = true) {
3642  assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3643 
3644  if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3645  if (Info.noteFailure()) {
3646  MemberPtr MemPtr;
3647  EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3648  }
3649  return nullptr;
3650  }
3651 
3652  return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3653  BO->getRHS(), IncludeMember);
3654 }
3655 
3656 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3657 /// the provided lvalue, which currently refers to the base object.
3658 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3659  LValue &Result) {
3660  SubobjectDesignator &D = Result.Designator;
3661  if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
3662  return false;
3663 
3664  QualType TargetQT = E->getType();
3665  if (const PointerType *PT = TargetQT->getAs<PointerType>())
3666  TargetQT = PT->getPointeeType();
3667 
3668  // Check this cast lands within the final derived-to-base subobject path.
3669  if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
3670  Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3671  << D.MostDerivedType << TargetQT;
3672  return false;
3673  }
3674 
3675  // Check the type of the final cast. We don't need to check the path,
3676  // since a cast can only be formed if the path is unique.
3677  unsigned NewEntriesSize = D.Entries.size() - E->path_size();
3678  const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3679  const CXXRecordDecl *FinalType;
3680  if (NewEntriesSize == D.MostDerivedPathLength)
3681  FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3682  else
3683  FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
3684  if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
3685  Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3686  << D.MostDerivedType << TargetQT;
3687  return false;
3688  }
3689 
3690  // Truncate the lvalue to the appropriate derived class.
3691  return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
3692 }
3693 
3694 namespace {
3696  /// Evaluation failed.
3697  ESR_Failed,
3698  /// Hit a 'return' statement.
3699  ESR_Returned,
3700  /// Evaluation succeeded.
3701  ESR_Succeeded,
3702  /// Hit a 'continue' statement.
3703  ESR_Continue,
3704  /// Hit a 'break' statement.
3705  ESR_Break,
3706  /// Still scanning for 'case' or 'default' statement.
3707  ESR_CaseNotFound
3708 };
3709 }
3710 
3711 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3712  // We don't need to evaluate the initializer for a static local.
3713  if (!VD->hasLocalStorage())
3714  return true;
3715 
3716  LValue Result;
3717  Result.set(VD, Info.CurrentCall->Index);
3718  APValue &Val = Info.CurrentCall->createTemporary(VD, true);
3719 
3720  const Expr *InitE = VD->getInit();
3721  if (!InitE) {
3722  Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3723  << false << VD->getType();
3724  Val = APValue();
3725  return false;
3726  }
3727 
3728  if (InitE->isValueDependent())
3729  return false;
3730 
3731  if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3732  // Wipe out any partially-computed value, to allow tracking that this
3733  // evaluation failed.
3734  Val = APValue();
3735  return false;
3736  }
3737 
3738  return true;
3739 }
3740 
3741 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3742  bool OK = true;
3743 
3744  if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3745  OK &= EvaluateVarDecl(Info, VD);
3746 
3747  if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3748  for (auto *BD : DD->bindings())
3749  if (auto *VD = BD->getHoldingVar())
3750  OK &= EvaluateDecl(Info, VD);
3751 
3752  return OK;
3753 }
3754 
3755 
3756 /// Evaluate a condition (either a variable declaration or an expression).
3757 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3758  const Expr *Cond, bool &Result) {
3759  FullExpressionRAII Scope(Info);
3760  if (CondDecl && !EvaluateDecl(Info, CondDecl))
3761  return false;
3762  return EvaluateAsBooleanCondition(Cond, Result, Info);
3763 }
3764 
3765 namespace {
3766 /// \brief A location where the result (returned value) of evaluating a
3767 /// statement should be stored.
3768 struct StmtResult {
3769  /// The APValue that should be filled in with the returned value.
3770  APValue &Value;
3771  /// The location containing the result, if any (used to support RVO).
3772  const LValue *Slot;
3773 };
3774 }
3775 
3776 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
3777  const Stmt *S,
3778  const SwitchCase *SC = nullptr);
3779 
3780 /// Evaluate the body of a loop, and translate the result as appropriate.
3781 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
3782  const Stmt *Body,
3783  const SwitchCase *Case = nullptr) {
3784  BlockScopeRAII Scope(Info);
3785  switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
3786  case ESR_Break:
3787  return ESR_Succeeded;
3788  case ESR_Succeeded:
3789  case ESR_Continue:
3790  return ESR_Continue;
3791  case ESR_Failed:
3792  case ESR_Returned:
3793  case ESR_CaseNotFound:
3794  return ESR;
3795  }
3796  llvm_unreachable("Invalid EvalStmtResult!");
3797 }
3798 
3799 /// Evaluate a switch statement.
3800 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
3801  const SwitchStmt *SS) {
3802  BlockScopeRAII Scope(Info);
3803 
3804  // Evaluate the switch condition.
3805  APSInt Value;
3806  {
3807  FullExpressionRAII Scope(Info);
3808  if (const Stmt *Init = SS->getInit()) {
3809  EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3810  if (ESR != ESR_Succeeded)
3811  return ESR;
3812  }
3813  if (SS->getConditionVariable() &&
3814  !EvaluateDecl(Info, SS->getConditionVariable()))
3815  return ESR_Failed;
3816  if (!EvaluateInteger(SS->getCond(), Value, Info))
3817  return ESR_Failed;
3818  }
3819 
3820  // Find the switch case corresponding to the value of the condition.
3821  // FIXME: Cache this lookup.
3822  const SwitchCase *Found = nullptr;
3823  for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3824  SC = SC->getNextSwitchCase()) {
3825  if (isa<DefaultStmt>(SC)) {
3826  Found = SC;
3827  continue;
3828  }
3829 
3830  const CaseStmt *CS = cast<CaseStmt>(SC);
3831  APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3832  APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3833  : LHS;
3834  if (LHS <= Value && Value <= RHS) {
3835  Found = SC;
3836  break;
3837  }
3838  }
3839 
3840  if (!Found)
3841  return ESR_Succeeded;
3842 
3843  // Search the switch body for the switch case and evaluate it from there.
3844  switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3845  case ESR_Break:
3846  return ESR_Succeeded;
3847  case ESR_Succeeded:
3848  case ESR_Continue:
3849  case ESR_Failed:
3850  case ESR_Returned:
3851  return ESR;
3852  case ESR_CaseNotFound:
3853  // This can only happen if the switch case is nested within a statement
3854  // expression. We have no intention of supporting that.
3855  Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3856  return ESR_Failed;
3857  }
3858  llvm_unreachable("Invalid EvalStmtResult!");
3859 }
3860 
3861 // Evaluate a statement.
3862 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
3863  const Stmt *S, const SwitchCase *Case) {
3864  if (!Info.nextStep(S))
3865  return ESR_Failed;
3866 
3867  // If we're hunting down a 'case' or 'default' label, recurse through
3868  // substatements until we hit the label.
3869  if (Case) {
3870  // FIXME: We don't start the lifetime of objects whose initialization we
3871  // jump over. However, such objects must be of class type with a trivial
3872  // default constructor that initialize all subobjects, so must be empty,
3873  // so this almost never matters.
3874  switch (S->getStmtClass()) {
3875  case Stmt::CompoundStmtClass:
3876  // FIXME: Precompute which substatement of a compound statement we
3877  // would jump to, and go straight there rather than performing a
3878  // linear scan each time.
3879  case Stmt::LabelStmtClass:
3880  case Stmt::AttributedStmtClass:
3881  case Stmt::DoStmtClass:
3882  break;
3883 
3884  case Stmt::CaseStmtClass:
3885  case Stmt::DefaultStmtClass:
3886  if (Case == S)
3887  Case = nullptr;
3888  break;
3889 
3890  case Stmt::IfStmtClass: {
3891  // FIXME: Precompute which side of an 'if' we would jump to, and go
3892  // straight there rather than scanning both sides.
3893  const IfStmt *IS = cast<IfStmt>(S);
3894 
3895  // Wrap the evaluation in a block scope, in case it's a DeclStmt
3896  // preceded by our switch label.
3897  BlockScopeRAII Scope(Info);
3898 
3899  EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3900  if (ESR != ESR_CaseNotFound || !IS->getElse())
3901  return ESR;
3902  return EvaluateStmt(Result, Info, IS->getElse(), Case);
3903  }
3904 
3905  case Stmt::WhileStmtClass: {
3906  EvalStmtResult ESR =
3907  EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3908  if (ESR != ESR_Continue)
3909  return ESR;
3910  break;
3911  }
3912 
3913  case Stmt::ForStmtClass: {
3914  const ForStmt *FS = cast<ForStmt>(S);
3915  EvalStmtResult ESR =
3916  EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3917  if (ESR != ESR_Continue)
3918  return ESR;
3919  if (FS->getInc()) {
3920  FullExpressionRAII IncScope(Info);
3921  if (!EvaluateIgnoredValue(Info, FS->getInc()))
3922  return ESR_Failed;
3923  }
3924  break;
3925  }
3926 
3927  case Stmt::DeclStmtClass:
3928  // FIXME: If the variable has initialization that can't be jumped over,
3929  // bail out of any immediately-surrounding compound-statement too.
3930  default:
3931  return ESR_CaseNotFound;
3932  }
3933  }
3934 
3935  switch (S->getStmtClass()) {
3936  default:
3937  if (const Expr *E = dyn_cast<Expr>(S)) {
3938  // Don't bother evaluating beyond an expression-statement which couldn't
3939  // be evaluated.
3940  FullExpressionRAII Scope(Info);
3941  if (!EvaluateIgnoredValue(Info, E))
3942  return ESR_Failed;
3943  return ESR_Succeeded;
3944  }
3945 
3946  Info.FFDiag(S->getLocStart());
3947  return ESR_Failed;
3948 
3949  case Stmt::NullStmtClass:
3950  return ESR_Succeeded;
3951 
3952  case Stmt::DeclStmtClass: {
3953  const DeclStmt *DS = cast<DeclStmt>(S);
3954  for (const auto *DclIt : DS->decls()) {
3955  // Each declaration initialization is its own full-expression.
3956  // FIXME: This isn't quite right; if we're performing aggregate
3957  // initialization, each braced subexpression is its own full-expression.
3958  FullExpressionRAII Scope(Info);
3959  if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
3960  return ESR_Failed;
3961  }
3962  return ESR_Succeeded;
3963  }
3964 
3965  case Stmt::ReturnStmtClass: {
3966  const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
3967  FullExpressionRAII Scope(Info);
3968  if (RetExpr &&
3969  !(Result.Slot
3970  ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3971  : Evaluate(Result.Value, Info, RetExpr)))
3972  return ESR_Failed;
3973  return ESR_Returned;
3974  }
3975 
3976  case Stmt::CompoundStmtClass: {
3977  BlockScopeRAII Scope(Info);
3978 
3979  const CompoundStmt *CS = cast<CompoundStmt>(S);
3980  for (const auto *BI : CS->body()) {
3981  EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
3982  if (ESR == ESR_Succeeded)
3983  Case = nullptr;
3984  else if (ESR != ESR_CaseNotFound)
3985  return ESR;
3986  }
3987  return Case ? ESR_CaseNotFound : ESR_Succeeded;
3988  }
3989 
3990  case Stmt::IfStmtClass: {
3991  const IfStmt *IS = cast<IfStmt>(S);
3992 
3993  // Evaluate the condition, as either a var decl or as an expression.
3994  BlockScopeRAII Scope(Info);
3995  if (const Stmt *Init = IS->getInit()) {
3996  EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3997  if (ESR != ESR_Succeeded)
3998  return ESR;
3999  }
4000  bool Cond;
4001  if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
4002  return ESR_Failed;
4003 
4004  if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4005  EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4006  if (ESR != ESR_Succeeded)
4007  return ESR;
4008  }
4009  return ESR_Succeeded;
4010  }
4011 
4012  case Stmt::WhileStmtClass: {
4013  const WhileStmt *WS = cast<WhileStmt>(S);
4014  while (true) {
4015  BlockScopeRAII Scope(Info);
4016  bool Continue;
4017  if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4018  Continue))
4019  return ESR_Failed;
4020  if (!Continue)
4021  break;
4022 
4023  EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4024  if (ESR != ESR_Continue)
4025  return ESR;
4026  }
4027  return ESR_Succeeded;
4028  }
4029 
4030  case Stmt::DoStmtClass: {
4031  const DoStmt *DS = cast<DoStmt>(S);
4032  bool Continue;
4033  do {
4034  EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
4035  if (ESR != ESR_Continue)
4036  return ESR;
4037  Case = nullptr;
4038 
4039  FullExpressionRAII CondScope(Info);
4040  if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4041  return ESR_Failed;
4042  } while (Continue);
4043  return ESR_Succeeded;
4044  }
4045 
4046  case Stmt::ForStmtClass: {
4047  const ForStmt *FS = cast<ForStmt>(S);
4048  BlockScopeRAII Scope(Info);
4049  if (FS->getInit()) {
4050  EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4051  if (ESR != ESR_Succeeded)
4052  return ESR;
4053  }
4054  while (true) {
4055  BlockScopeRAII Scope(Info);
4056  bool Continue = true;
4057  if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4058  FS->getCond(), Continue))
4059  return ESR_Failed;
4060  if (!Continue)
4061  break;
4062 
4063  EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4064  if (ESR != ESR_Continue)
4065  return ESR;
4066 
4067  if (FS->getInc()) {
4068  FullExpressionRAII IncScope(Info);
4069  if (!EvaluateIgnoredValue(Info, FS->getInc()))
4070  return ESR_Failed;
4071  }
4072  }
4073  return ESR_Succeeded;
4074  }
4075 
4076  case Stmt::CXXForRangeStmtClass: {
4077  const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
4078  BlockScopeRAII Scope(Info);
4079 
4080  // Initialize the __range variable.
4081  EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4082  if (ESR != ESR_Succeeded)
4083  return ESR;
4084 
4085  // Create the __begin and __end iterators.
4086  ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4087  if (ESR != ESR_Succeeded)
4088  return ESR;
4089  ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
4090  if (ESR != ESR_Succeeded)
4091  return ESR;
4092 
4093  while (true) {
4094  // Condition: __begin != __end.
4095  {
4096  bool Continue = true;
4097  FullExpressionRAII CondExpr(Info);
4098  if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4099  return ESR_Failed;
4100  if (!Continue)
4101  break;
4102  }
4103 
4104  // User's variable declaration, initialized by *__begin.
4105  BlockScopeRAII InnerScope(Info);
4106  ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4107  if (ESR != ESR_Succeeded)
4108  return ESR;
4109 
4110  // Loop body.
4111  ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4112  if (ESR != ESR_Continue)
4113  return ESR;
4114 
4115  // Increment: ++__begin
4116  if (!EvaluateIgnoredValue(Info, FS->getInc()))
4117  return ESR_Failed;
4118  }
4119 
4120  return ESR_Succeeded;
4121  }
4122 
4123  case Stmt::SwitchStmtClass:
4124  return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4125 
4126  case Stmt::ContinueStmtClass:
4127  return ESR_Continue;
4128 
4129  case Stmt::BreakStmtClass:
4130  return ESR_Break;
4131 
4132  case Stmt::LabelStmtClass:
4133  return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4134 
4135  case Stmt::AttributedStmtClass:
4136  // As a general principle, C++11 attributes can be ignored without
4137  // any semantic impact.
4138  return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4139  Case);
4140 
4141  case Stmt::CaseStmtClass:
4142  case Stmt::DefaultStmtClass:
4143  return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
4144  }
4145 }
4146 
4147 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4148 /// default constructor. If so, we'll fold it whether or not it's marked as
4149 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
4150 /// so we need special handling.
4151 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
4152  const CXXConstructorDecl *CD,
4153  bool IsValueInitialization) {
4154  if (!CD->isTrivial() || !CD->isDefaultConstructor())
4155  return false;
4156 
4157  // Value-initialization does not call a trivial default constructor, so such a
4158  // call is a core constant expression whether or not the constructor is
4159  // constexpr.
4160  if (!CD->isConstexpr() && !IsValueInitialization) {
4161  if (Info.getLangOpts().CPlusPlus11) {
4162  // FIXME: If DiagDecl is an implicitly-declared special member function,
4163  // we should be much more explicit about why it's not constexpr.
4164  Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4165  << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4166  Info.Note(CD->getLocation(), diag::note_declared_at);
4167  } else {
4168  Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4169  }
4170  }
4171  return true;
4172 }
4173 
4174 /// CheckConstexprFunction - Check that a function can be called in a constant
4175 /// expression.
4176 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4177  const FunctionDecl *Declaration,
4178  const FunctionDecl *Definition,
4179  const Stmt *Body) {
4180  // Potential constant expressions can contain calls to declared, but not yet
4181  // defined, constexpr functions.
4182  if (Info.checkingPotentialConstantExpression() && !Definition &&
4183  Declaration->isConstexpr())
4184  return false;
4185 
4186  // Bail out with no diagnostic if the function declaration itself is invalid.
4187  // We will have produced a relevant diagnostic while parsing it.
4188  if (Declaration->isInvalidDecl())
4189  return false;
4190 
4191  // Can we evaluate this function call?
4192  if (Definition && Definition->isConstexpr() &&
4193  !Definition->isInvalidDecl() && Body)
4194  return true;
4195 
4196  if (Info.getLangOpts().CPlusPlus11) {
4197  const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
4198 
4199  // If this function is not constexpr because it is an inherited
4200  // non-constexpr constructor, diagnose that directly.
4201  auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4202  if (CD && CD->isInheritingConstructor()) {
4203  auto *Inherited = CD->getInheritedConstructor().getConstructor();
4204  if (!Inherited->isConstexpr())
4205  DiagDecl = CD = Inherited;
4206  }
4207 
4208  // FIXME: If DiagDecl is an implicitly-declared special member function
4209  // or an inheriting constructor, we should be much more explicit about why
4210  // it's not constexpr.
4211  if (CD && CD->isInheritingConstructor())
4212  Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
4213  << CD->getInheritedConstructor().getConstructor()->getParent();
4214  else
4215  Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
4216  << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
4217  Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4218  } else {
4219  Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4220  }
4221  return false;
4222 }
4223 
4224 /// Determine if a class has any fields that might need to be copied by a
4225 /// trivial copy or move operation.
4226 static bool hasFields(const CXXRecordDecl *RD) {
4227  if (!RD || RD->isEmpty())
4228  return false;
4229  for (auto *FD : RD->fields()) {
4230  if (FD->isUnnamedBitfield())
4231  continue;
4232  return true;
4233  }
4234  for (auto &Base : RD->bases())
4235  if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4236  return true;
4237  return false;
4238 }
4239 
4240 namespace {
4241 typedef SmallVector<APValue, 8> ArgVector;
4242 }
4243 
4244 /// EvaluateArgs - Evaluate the arguments to a function call.
4245 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4246  EvalInfo &Info) {
4247  bool Success = true;
4248  for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
4249  I != E; ++I) {
4250  if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4251  // If we're checking for a potential constant expression, evaluate all
4252  // initializers even if some of them fail.
4253  if (!Info.noteFailure())
4254  return false;
4255  Success = false;
4256  }
4257  }
4258  return Success;
4259 }
4260 
4261 /// Evaluate a function call.
4263  const FunctionDecl *Callee, const LValue *This,
4264  ArrayRef<const Expr*> Args, const Stmt *Body,
4265  EvalInfo &Info, APValue &Result,
4266  const LValue *ResultSlot) {
4267  ArgVector ArgValues(Args.size());
4268  if (!EvaluateArgs(Args, ArgValues, Info))
4269  return false;
4270 
4271  if (!Info.CheckCallLimit(CallLoc))
4272  return false;
4273 
4274  CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
4275 
4276  // For a trivial copy or move assignment, perform an APValue copy. This is
4277  // essential for unions, where the operations performed by the assignment
4278  // operator cannot be represented as statements.
4279  //
4280  // Skip this for non-union classes with no fields; in that case, the defaulted
4281  // copy/move does not actually read the object.
4282  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
4283  if (MD && MD->isDefaulted() &&
4284  (MD->getParent()->isUnion() ||
4285  (MD->isTrivial() && hasFields(MD->getParent())))) {
4286  assert(This &&
4287  (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4288  LValue RHS;
4289  RHS.setFrom(Info.Ctx, ArgValues[0]);
4290  APValue RHSValue;
4291  if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4292  RHS, RHSValue))
4293  return false;
4294  if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4295  RHSValue))
4296  return false;
4297  This->moveInto(Result);
4298  return true;
4299  } else if (MD && isLambdaCallOperator(MD)) {
4300  // We're in a lambda; determine the lambda capture field maps.
4301  MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4302  Frame.LambdaThisCaptureField);
4303  }
4304 
4305  StmtResult Ret = {Result, ResultSlot};
4306  EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
4307  if (ESR == ESR_Succeeded) {
4308  if (Callee->getReturnType()->isVoidType())
4309  return true;
4310  Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
4311  }
4312  return ESR == ESR_Returned;
4313 }
4314 
4315 /// Evaluate a constructor call.
4316 static bool HandleConstructorCall(const Expr *E, const LValue &This,
4317  APValue *ArgValues,
4318  const CXXConstructorDecl *Definition,
4319  EvalInfo &Info, APValue &Result) {
4320  SourceLocation CallLoc = E->getExprLoc();
4321  if (!Info.CheckCallLimit(CallLoc))
4322  return false;
4323 
4324  const CXXRecordDecl *RD = Definition->getParent();
4325  if (RD->getNumVBases()) {
4326  Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
4327  return false;
4328  }
4329 
4330  EvalInfo::EvaluatingConstructorRAII EvalObj(
4331  Info, {This.getLValueBase(), This.CallIndex});
4332  CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
4333 
4334  // FIXME: Creating an APValue just to hold a nonexistent return value is
4335  // wasteful.
4336  APValue RetVal;
4337  StmtResult Ret = {RetVal, nullptr};
4338 
4339  // If it's a delegating constructor, delegate.
4340  if (Definition->isDelegatingConstructor()) {
4342  {
4343  FullExpressionRAII InitScope(Info);
4344  if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4345  return false;
4346  }
4347  return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4348  }
4349 
4350  // For a trivial copy or move constructor, perform an APValue copy. This is
4351  // essential for unions (or classes with anonymous union members), where the
4352  // operations performed by the constructor cannot be represented by
4353  // ctor-initializers.
4354  //
4355  // Skip this for empty non-union classes; we should not perform an
4356  // lvalue-to-rvalue conversion on them because their copy constructor does not
4357  // actually read them.
4358  if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
4359  (Definition->getParent()->isUnion() ||
4360  (Definition->isTrivial() && hasFields(Definition->getParent())))) {
4361  LValue RHS;
4362  RHS.setFrom(Info.Ctx, ArgValues[0]);
4364  Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4365  RHS, Result);
4366  }
4367 
4368  // Reserve space for the struct members.
4369  if (!RD->isUnion() && Result.isUninit())
4370  Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4371  std::distance(RD->field_begin(), RD->field_end()));
4372 
4373  if (RD->isInvalidDecl()) return false;
4374  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4375 
4376  // A scope for temporaries lifetime-extended by reference members.
4377  BlockScopeRAII LifetimeExtendedScope(Info);
4378 
4379  bool Success = true;
4380  unsigned BasesSeen = 0;
4381 #ifndef NDEBUG
4383 #endif
4384  for (const auto *I : Definition->inits()) {
4385  LValue Subobject = This;
4386  APValue *Value = &Result;
4387 
4388  // Determine the subobject to initialize.
4389  FieldDecl *FD = nullptr;
4390  if (I->isBaseInitializer()) {
4391  QualType BaseType(I->getBaseClass(), 0);
4392 #ifndef NDEBUG
4393  // Non-virtual base classes are initialized in the order in the class
4394  // definition. We have already checked for virtual base classes.
4395  assert(!BaseIt->isVirtual() && "virtual base for literal type");
4396  assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4397  "base class initializers not in expected order");
4398  ++BaseIt;
4399 #endif
4400  if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
4401  BaseType->getAsCXXRecordDecl(), &Layout))
4402  return false;
4403  Value = &Result.getStructBase(BasesSeen++);
4404  } else if ((FD = I->getMember())) {
4405  if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
4406  return false;
4407  if (RD->isUnion()) {
4408  Result = APValue(FD);
4409  Value = &Result.getUnionValue();
4410  } else {
4411  Value = &Result.getStructField(FD->getFieldIndex());
4412  }
4413  } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
4414  // Walk the indirect field decl's chain to find the object to initialize,
4415  // and make sure we've initialized every step along it.
4416  for (auto *C : IFD->chain()) {
4417  FD = cast<FieldDecl>(C);
4418  CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4419  // Switch the union field if it differs. This happens if we had
4420  // preceding zero-initialization, and we're now initializing a union
4421  // subobject other than the first.
4422  // FIXME: In this case, the values of the other subobjects are
4423  // specified, since zero-initialization sets all padding bits to zero.
4424  if (Value->isUninit() ||
4425  (Value->isUnion() && Value->getUnionField() != FD)) {
4426  if (CD->isUnion())
4427  *Value = APValue(FD);
4428  else
4429  *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
4430  std::distance(CD->field_begin(), CD->field_end()));
4431  }
4432  if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
4433  return false;
4434  if (CD->isUnion())
4435  Value = &Value->getUnionValue();
4436  else
4437  Value = &Value->getStructField(FD->getFieldIndex());
4438  }
4439  } else {
4440  llvm_unreachable("unknown base initializer kind");
4441  }
4442 
4443  FullExpressionRAII InitScope(Info);
4444  if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
4445  (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
4446  *Value, FD))) {
4447  // If we're checking for a potential constant expression, evaluate all
4448  // initializers even if some of them fail.
4449  if (!Info.noteFailure())
4450  return false;
4451  Success = false;
4452  }
4453  }
4454 
4455  return Success &&
4456  EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4457 }
4458 
4459 static bool HandleConstructorCall(const Expr *E, const LValue &This,
4460  ArrayRef<const Expr*> Args,
4461  const CXXConstructorDecl *Definition,
4462  EvalInfo &Info, APValue &Result) {
4463  ArgVector ArgValues(Args.size());
4464  if (!EvaluateArgs(Args, ArgValues, Info))
4465  return false;
4466 
4467  return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4468  Info, Result);
4469 }
4470 
4471 //===----------------------------------------------------------------------===//
4472 // Generic Evaluation
4473 //===----------------------------------------------------------------------===//
4474 namespace {
4475 
4476 template <class Derived>
4477 class ExprEvaluatorBase
4478  : public ConstStmtVisitor<Derived, bool> {
4479 private:
4480  Derived &getDerived() { return static_cast<Derived&>(*this); }
4481  bool DerivedSuccess(const APValue &V, const Expr *E) {
4482  return getDerived().Success(V, E);
4483  }
4484  bool DerivedZeroInitialization(const Expr *E) {
4485  return getDerived().ZeroInitialization(E);
4486  }
4487 
4488  // Check whether a conditional operator with a non-constant condition is a
4489  // potential constant expression. If neither arm is a potential constant
4490  // expression, then the conditional operator is not either.
4491  template<typename ConditionalOperator>
4492  void CheckPotentialConstantConditional(const ConditionalOperator *E) {
4493  assert(Info.checkingPotentialConstantExpression());
4494 
4495  // Speculatively evaluate both arms.
4497  {
4498  SpeculativeEvaluationRAII Speculate(Info, &Diag);
4499  StmtVisitorTy::Visit(E->getFalseExpr());
4500  if (Diag.empty())
4501  return;
4502  }
4503 
4504  {
4505  SpeculativeEvaluationRAII Speculate(Info, &Diag);
4506  Diag.clear();
4507  StmtVisitorTy::Visit(E->getTrueExpr());
4508  if (Diag.empty())
4509  return;
4510  }
4511 
4512  Error(E, diag::note_constexpr_conditional_never_const);
4513  }
4514 
4515 
4516  template<typename ConditionalOperator>
4517  bool HandleConditionalOperator(const ConditionalOperator *E) {
4518  bool BoolResult;
4519  if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
4520  if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
4521  CheckPotentialConstantConditional(E);
4522  return false;
4523  }
4524  if (Info.noteFailure()) {
4525  StmtVisitorTy::Visit(E->getTrueExpr());
4526  StmtVisitorTy::Visit(E->getFalseExpr());
4527  }
4528  return false;
4529  }
4530 
4531  Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4532  return StmtVisitorTy::Visit(EvalExpr);
4533  }
4534 
4535 protected:
4536  EvalInfo &Info;
4537  typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
4538  typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4539 
4540  OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4541  return Info.CCEDiag(E, D);
4542  }
4543 
4544  bool ZeroInitialization(const Expr *E) { return Error(E); }
4545 
4546 public:
4547  ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4548 
4549  EvalInfo &getEvalInfo() { return Info; }
4550 
4551  /// Report an evaluation error. This should only be called when an error is
4552  /// first discovered. When propagating an error, just return false.
4553  bool Error(const Expr *E, diag::kind D) {
4554  Info.FFDiag(E, D);
4555  return false;
4556  }
4557  bool Error(const Expr *E) {
4558  return Error(E, diag::note_invalid_subexpr_in_const_expr);
4559  }
4560 
4561  bool VisitStmt(const Stmt *) {
4562  llvm_unreachable("Expression evaluator should not be called on stmts");
4563  }
4564  bool VisitExpr(const Expr *E) {
4565  return Error(E);
4566  }
4567 
4568  bool VisitParenExpr(const ParenExpr *E)
4569  { return StmtVisitorTy::Visit(E->getSubExpr()); }
4570  bool VisitUnaryExtension(const UnaryOperator *E)
4571  { return StmtVisitorTy::Visit(E->getSubExpr()); }
4572  bool VisitUnaryPlus(const UnaryOperator *E)
4573  { return StmtVisitorTy::Visit(E->getSubExpr()); }
4574  bool VisitChooseExpr(const ChooseExpr *E)
4575  { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
4576  bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
4577  { return StmtVisitorTy::Visit(E->getResultExpr()); }
4578  bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
4579  { return StmtVisitorTy::Visit(E->getReplacement()); }
4580  bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
4581  { return StmtVisitorTy::Visit(E->getExpr()); }
4582  bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
4583  // The initializer may not have been parsed yet, or might be erroneous.
4584  if (!E->getExpr())
4585  return Error(E);
4586  return StmtVisitorTy::Visit(E->getExpr());
4587  }
4588  // We cannot create any objects for which cleanups are required, so there is
4589  // nothing to do here; all cleanups must come from unevaluated subexpressions.
4590  bool VisitExprWithCleanups(const ExprWithCleanups *E)
4591  { return StmtVisitorTy::Visit(E->getSubExpr()); }
4592 
4593  bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
4594  CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4595  return static_cast<Derived*>(this)->VisitCastExpr(E);
4596  }
4597  bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
4598  CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4599  return static_cast<Derived*>(this)->VisitCastExpr(E);
4600  }
4601 
4602  bool VisitBinaryOperator(const BinaryOperator *E) {
4603  switch (E->getOpcode()) {
4604  default:
4605  return Error(E);
4606 
4607  case BO_Comma:
4608  VisitIgnoredValue(E->getLHS());
4609  return StmtVisitorTy::Visit(E->getRHS());
4610 
4611  case BO_PtrMemD:
4612  case BO_PtrMemI: {
4613  LValue Obj;
4614  if (!HandleMemberPointerAccess(Info, E, Obj))
4615  return false;
4616  APValue Result;
4617  if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
4618  return false;
4619  return DerivedSuccess(Result, E);
4620  }
4621  }
4622  }
4623 
4624  bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
4625  // Evaluate and cache the common expression. We treat it as a temporary,
4626  // even though it's not quite the same thing.
4627  if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
4628  Info, E->getCommon()))
4629  return false;
4630 
4631  return HandleConditionalOperator(E);
4632  }
4633 
4634  bool VisitConditionalOperator(const ConditionalOperator *E) {
4635  bool IsBcpCall = false;
4636  // If the condition (ignoring parens) is a __builtin_constant_p call,
4637  // the result is a constant expression if it can be folded without
4638  // side-effects. This is an important GNU extension. See GCC PR38377
4639  // for discussion.
4640  if (const CallExpr *CallCE =
4641  dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
4642  if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
4643  IsBcpCall = true;
4644 
4645  // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4646  // constant expression; we can't check whether it's potentially foldable.
4647  if (Info.checkingPotentialConstantExpression() && IsBcpCall)
4648  return false;
4649 
4650  FoldConstant Fold(Info, IsBcpCall);
4651  if (!HandleConditionalOperator(E)) {
4652  Fold.keepDiagnostics();
4653  return false;
4654  }
4655 
4656  return true;
4657  }
4658 
4659  bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
4660  if (APValue *Value = Info.CurrentCall->getTemporary(E))
4661  return DerivedSuccess(*Value, E);
4662 
4663  const Expr *Source = E->getSourceExpr();
4664  if (!Source)
4665  return Error(E);
4666  if (Source == E) { // sanity checking.
4667  assert(0 && "OpaqueValueExpr recursively refers to itself");
4668  return Error(E);
4669  }
4670  return StmtVisitorTy::Visit(Source);
4671  }
4672 
4673  bool VisitCallExpr(const CallExpr *E) {
4674  APValue Result;
4675  if (!handleCallExpr(E, Result, nullptr))
4676  return false;
4677  return DerivedSuccess(Result, E);
4678  }
4679 
4680  bool handleCallExpr(const CallExpr *E, APValue &Result,
4681  const LValue *ResultSlot) {
4682  const Expr *Callee = E->getCallee()->IgnoreParens();
4683  QualType CalleeType = Callee->getType();
4684 
4685  const FunctionDecl *FD = nullptr;
4686  LValue *This = nullptr, ThisVal;
4687  auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
4688  bool HasQualifier = false;
4689 
4690  // Extract function decl and 'this' pointer from the callee.
4691  if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
4692  const ValueDecl *Member = nullptr;
4693  if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4694  // Explicit bound member calls, such as x.f() or p->g();
4695  if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
4696  return false;
4697  Member = ME->getMemberDecl();
4698  This = &ThisVal;
4699  HasQualifier = ME->hasQualifier();
4700  } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4701  // Indirect bound member calls ('.*' or '->*').
4702  Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4703  if (!Member) return false;
4704  This = &ThisVal;
4705  } else
4706  return Error(Callee);
4707 
4708  FD = dyn_cast<FunctionDecl>(Member);
4709  if (!FD)
4710  return Error(Callee);
4711  } else if (CalleeType->isFunctionPointerType()) {
4712  LValue Call;
4713  if (!EvaluatePointer(Callee, Call, Info))
4714  return false;
4715 
4716  if (!Call.getLValueOffset().isZero())
4717  return Error(Callee);
4718  FD = dyn_cast_or_null<FunctionDecl>(
4719  Call.getLValueBase().dyn_cast<const ValueDecl*>());
4720  if (!FD)
4721  return Error(Callee);
4722  // Don't call function pointers which have been cast to some other type.
4723  // Per DR (no number yet), the caller and callee can differ in noexcept.
4724  if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4725  CalleeType->getPointeeType(), FD->getType())) {
4726  return Error(E);
4727  }
4728 
4729  // Overloaded operator calls to member functions are represented as normal
4730  // calls with '*this' as the first argument.
4731  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4732  if (MD && !MD->isStatic()) {
4733  // FIXME: When selecting an implicit conversion for an overloaded
4734  // operator delete, we sometimes try to evaluate calls to conversion
4735  // operators without a 'this' parameter!
4736  if (Args.empty())
4737  return Error(E);
4738 
4739  if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4740  return false;
4741  This = &ThisVal;
4742  Args = Args.slice(1);
4743  } else if (MD && MD->isLambdaStaticInvoker()) {
4744  // Map the static invoker for the lambda back to the call operator.
4745  // Conveniently, we don't have to slice out the 'this' argument (as is
4746  // being done for the non-static case), since a static member function
4747  // doesn't have an implicit argument passed in.
4748  const CXXRecordDecl *ClosureClass = MD->getParent();
4749  assert(
4750  ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4751  "Number of captures must be zero for conversion to function-ptr");
4752 
4753  const CXXMethodDecl *LambdaCallOp =
4754  ClosureClass->getLambdaCallOperator();
4755 
4756  // Set 'FD', the function that will be called below, to the call
4757  // operator. If the closure object represents a generic lambda, find
4758  // the corresponding specialization of the call operator.
4759 
4760  if (ClosureClass->isGenericLambda()) {
4761  assert(MD->isFunctionTemplateSpecialization() &&
4762  "A generic lambda's static-invoker function must be a "
4763  "template specialization");
4765  FunctionTemplateDecl *CallOpTemplate =
4766  LambdaCallOp->getDescribedFunctionTemplate();
4767  void *InsertPos = nullptr;
4768  FunctionDecl *CorrespondingCallOpSpecialization =
4769  CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4770  assert(CorrespondingCallOpSpecialization &&
4771  "We must always have a function call operator specialization "
4772  "that corresponds to our static invoker specialization");
4773  FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4774  } else
4775  FD = LambdaCallOp;
4776  }
4777 
4778 
4779  } else
4780  return Error(E);
4781 
4782  if (This && !This->checkSubobject(Info, E, CSK_This))
4783  return false;
4784 
4785  // DR1358 allows virtual constexpr functions in some cases. Don't allow
4786  // calls to such functions in constant expressions.
4787  if (This && !HasQualifier &&
4788  isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4789  return Error(E, diag::note_constexpr_virtual_call);
4790 
4791  const FunctionDecl *Definition = nullptr;
4792  Stmt *Body = FD->getBody(Definition);
4793 
4794  if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
4795  !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4796  Result, ResultSlot))
4797  return false;
4798 
4799  return true;
4800  }
4801 
4802  bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
4803  return StmtVisitorTy::Visit(E->getInitializer());
4804  }
4805  bool VisitInitListExpr(const InitListExpr *E) {
4806  if (E->getNumInits() == 0)
4807  return DerivedZeroInitialization(E);
4808  if (E->getNumInits() == 1)
4809  return StmtVisitorTy::Visit(E->getInit(0));
4810  return Error(E);
4811  }
4812  bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
4813  return DerivedZeroInitialization(E);
4814  }
4815  bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
4816  return DerivedZeroInitialization(E);
4817  }
4818  bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
4819  return DerivedZeroInitialization(E);
4820  }
4821 
4822  /// A member expression where the object is a prvalue is itself a prvalue.
4823  bool VisitMemberExpr(const MemberExpr *E) {
4824  assert(!E->isArrow() && "missing call to bound member function?");
4825 
4826  APValue Val;
4827  if (!Evaluate(Val, Info, E->getBase()))
4828  return false;
4829 
4830  QualType BaseTy = E->getBase()->getType();
4831 
4832  const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
4833  if (!FD) return Error(E);
4834  assert(!FD->getType()->isReferenceType() && "prvalue reference?");
4835  assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4836  FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4837 
4838  CompleteObject Obj(&Val, BaseTy, true);
4839  SubobjectDesignator Designator(BaseTy);
4840  Designator.addDeclUnchecked(FD);
4841 
4842  APValue Result;
4843  return extractSubobject(Info, E, Obj, Designator, Result) &&
4844  DerivedSuccess(Result, E);
4845  }
4846 
4847  bool VisitCastExpr(const CastExpr *E) {
4848  switch (E->getCastKind()) {
4849  default:
4850  break;
4851 
4852  case CK_AtomicToNonAtomic: {
4853  APValue AtomicVal;
4854  // This does not need to be done in place even for class/array types:
4855  // atomic-to-non-atomic conversion implies copying the object
4856  // representation.
4857  if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
4858  return false;
4859  return DerivedSuccess(AtomicVal, E);
4860  }
4861 
4862  case CK_NoOp:
4863  case CK_UserDefinedConversion:
4864  return StmtVisitorTy::Visit(E->getSubExpr());
4865 
4866  case CK_LValueToRValue: {
4867  LValue LVal;
4868  if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4869  return false;
4870  APValue RVal;
4871  // Note, we use the subexpression's type in order to retain cv-qualifiers.
4872  if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
4873  LVal, RVal))
4874  return false;
4875  return DerivedSuccess(RVal, E);
4876  }
4877  }
4878 
4879  return Error(E);
4880  }
4881 
4882  bool VisitUnaryPostInc(const UnaryOperator *UO) {
4883  return VisitUnaryPostIncDec(UO);
4884  }
4885  bool VisitUnaryPostDec(const UnaryOperator *UO) {
4886  return VisitUnaryPostIncDec(UO);
4887  }
4888  bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
4889  if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
4890  return Error(UO);
4891 
4892  LValue LVal;
4893  if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4894  return false;
4895  APValue RVal;
4896  if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4897  UO->isIncrementOp(), &RVal))
4898  return false;
4899  return DerivedSuccess(RVal, UO);
4900  }
4901 
4902  bool VisitStmtExpr(const StmtExpr *E) {
4903  // We will have checked the full-expressions inside the statement expression
4904  // when they were completed, and don't need to check them again now.
4905  if (Info.checkingForOverflow())
4906  return Error(E);
4907 
4908  BlockScopeRAII Scope(Info);
4909  const CompoundStmt *CS = E->getSubStmt();
4910  if (CS->body_empty())
4911  return true;
4912 
4914  BE = CS->body_end();
4915  /**/; ++BI) {
4916  if (BI + 1 == BE) {
4917  const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4918  if (!FinalExpr) {
4919  Info.FFDiag((*BI)->getLocStart(),
4920  diag::note_constexpr_stmt_expr_unsupported);
4921  return false;
4922  }
4923  return this->Visit(FinalExpr);
4924  }
4925 
4926  APValue ReturnValue;
4927  StmtResult Result = { ReturnValue, nullptr };
4928  EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
4929  if (ESR != ESR_Succeeded) {
4930  // FIXME: If the statement-expression terminated due to 'return',
4931  // 'break', or 'continue', it would be nice to propagate that to
4932  // the outer statement evaluation rather than bailing out.
4933  if (ESR != ESR_Failed)
4934  Info.FFDiag((*BI)->getLocStart(),
4935  diag::note_constexpr_stmt_expr_unsupported);
4936  return false;
4937  }
4938  }
4939 
4940  llvm_unreachable("Return from function from the loop above.");
4941  }
4942 
4943  /// Visit a value which is evaluated, but whose value is ignored.
4944  void VisitIgnoredValue(const Expr *E) {
4945  EvaluateIgnoredValue(Info, E);
4946  }
4947 
4948  /// Potentially visit a MemberExpr's base expression.
4949  void VisitIgnoredBaseExpression(const Expr *E) {
4950  // While MSVC doesn't evaluate the base expression, it does diagnose the
4951  // presence of side-effecting behavior.
4952  if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4953  return;
4954  VisitIgnoredValue(E);
4955  }
4956 };
4957 
4958 }
4959 
4960 //===----------------------------------------------------------------------===//
4961 // Common base class for lvalue and temporary evaluation.
4962 //===----------------------------------------------------------------------===//
4963 namespace {
4964 template<class Derived>
4965 class LValueExprEvaluatorBase
4966  : public ExprEvaluatorBase<Derived> {
4967 protected:
4968  LValue &Result;
4969  bool InvalidBaseOK;
4970  typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
4971  typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
4972 
4973  bool Success(APValue::LValueBase B) {
4974  Result.set(B);
4975  return true;
4976  }
4977 
4978  bool evaluatePointer(const Expr *E, LValue &Result) {
4979  return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
4980  }
4981 
4982 public:
4983  LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
4984  : ExprEvaluatorBaseTy(Info), Result(Result),
4985  InvalidBaseOK(InvalidBaseOK) {}
4986 
4987  bool Success(const APValue &V, const Expr *E) {
4988  Result.setFrom(this->Info.Ctx, V);
4989  return true;
4990  }
4991 
4992  bool VisitMemberExpr(const MemberExpr *E) {
4993  // Handle non-static data members.
4994  QualType BaseTy;
4995  bool EvalOK;
4996  if (E->isArrow()) {
4997  EvalOK = evaluatePointer(E->getBase(), Result);
4998  BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
4999  } else if (E->getBase()->isRValue()) {
5000  assert(E->getBase()->getType()->isRecordType());
5001  EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
5002  BaseTy = E->getBase()->getType();
5003  } else {
5004  EvalOK = this->Visit(E->getBase());
5005  BaseTy = E->getBase()->getType();
5006  }
5007  if (!EvalOK) {
5008  if (!InvalidBaseOK)
5009  return false;
5010  Result.setInvalid(E);
5011  return true;
5012  }
5013 
5014  const ValueDecl *MD = E->getMemberDecl();
5015  if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
5016  assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
5017  FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5018  (void)BaseTy;
5019  if (!HandleLValueMember(this->Info, E, Result, FD))
5020  return false;
5021  } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
5022  if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
5023  return false;
5024  } else
5025  return this->Error(E);
5026 
5027  if (MD->getType()->isReferenceType()) {
5028  APValue RefValue;
5029  if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
5030  RefValue))
5031  return false;
5032  return Success(RefValue, E);
5033  }
5034  return true;
5035  }
5036 
5037  bool VisitBinaryOperator(const BinaryOperator *E) {
5038  switch (E->getOpcode()) {
5039  default:
5040  return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5041 
5042  case BO_PtrMemD:
5043  case BO_PtrMemI:
5044  return HandleMemberPointerAccess(this->Info, E, Result);
5045  }
5046  }
5047 
5048  bool VisitCastExpr(const CastExpr *E) {
5049  switch (E->getCastKind()) {
5050  default:
5051  return ExprEvaluatorBaseTy::VisitCastExpr(E);
5052 
5053  case CK_DerivedToBase:
5054  case CK_UncheckedDerivedToBase:
5055  if (!this->Visit(E->getSubExpr()))
5056  return false;
5057 
5058  // Now figure out the necessary offset to add to the base LV to get from
5059  // the derived class to the base class.
5060  return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
5061  Result);
5062  }
5063  }
5064 };
5065 }
5066 
5067 //===----------------------------------------------------------------------===//
5068 // LValue Evaluation
5069 //
5070 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
5071 // function designators (in C), decl references to void objects (in C), and
5072 // temporaries (if building with -Wno-address-of-temporary).
5073 //
5074 // LValue evaluation produces values comprising a base expression of one of the
5075 // following types:
5076 // - Declarations
5077 // * VarDecl
5078 // * FunctionDecl
5079 // - Literals
5080 // * CompoundLiteralExpr in C (and in global scope in C++)
5081 // * StringLiteral
5082 // * CXXTypeidExpr
5083 // * PredefinedExpr
5084 // * ObjCStringLiteralExpr
5085 // * ObjCEncodeExpr
5086 // * AddrLabelExpr
5087 // * BlockExpr
5088 // * CallExpr for a MakeStringConstant builtin
5089 // - Locals and temporaries
5090 // * MaterializeTemporaryExpr
5091 // * Any Expr, with a CallIndex indicating the function in which the temporary
5092 // was evaluated, for cases where the MaterializeTemporaryExpr is missing
5093 // from the AST (FIXME).
5094 // * A MaterializeTemporaryExpr that has static storage duration, with no
5095 // CallIndex, for a lifetime-extended temporary.
5096 // plus an offset in bytes.
5097 //===----------------------------------------------------------------------===//
5098 namespace {
5099 class LValueExprEvaluator
5100  : public LValueExprEvaluatorBase<LValueExprEvaluator> {
5101 public:
5102  LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
5103  LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
5104 
5105  bool VisitVarDecl(const Expr *E, const VarDecl *VD);
5106  bool VisitUnaryPreIncDec(const UnaryOperator *UO);
5107 
5108  bool VisitDeclRefExpr(const DeclRefExpr *E);
5109  bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
5110  bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
5111  bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5112  bool VisitMemberExpr(const MemberExpr *E);
5113  bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5114  bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
5115  bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
5116  bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
5117  bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5118  bool VisitUnaryDeref(const UnaryOperator *E);
5119  bool VisitUnaryReal(const UnaryOperator *E);
5120  bool VisitUnaryImag(const UnaryOperator *E);
5121  bool VisitUnaryPreInc(const UnaryOperator *UO) {
5122  return VisitUnaryPreIncDec(UO);
5123  }
5124  bool VisitUnaryPreDec(const UnaryOperator *UO) {
5125  return VisitUnaryPreIncDec(UO);
5126  }
5127  bool VisitBinAssign(const BinaryOperator *BO);
5128  bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
5129 
5130  bool VisitCastExpr(const CastExpr *E) {
5131  switch (E->getCastKind()) {
5132  default:
5133  return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5134 
5135  case CK_LValueBitCast:
5136  this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5137  if (!Visit(E->getSubExpr()))
5138  return false;
5139  Result.Designator.setInvalid();
5140  return true;
5141 
5142  case CK_BaseToDerived:
5143  if (!Visit(E->getSubExpr()))
5144  return false;
5145  return HandleBaseToDerivedCast(Info, E, Result);
5146  }
5147  }
5148 };
5149 } // end anonymous namespace
5150 
5151 /// Evaluate an expression as an lvalue. This can be legitimately called on
5152 /// expressions which are not glvalues, in three cases:
5153 /// * function designators in C, and
5154 /// * "extern void" objects
5155 /// * @selector() expressions in Objective-C
5156 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5157  bool InvalidBaseOK) {
5158  assert(E->isGLValue() || E->getType()->isFunctionType() ||
5159  E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
5160  return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
5161 }
5162 
5163 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
5164  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
5165  return Success(FD);
5166  if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
5167  return VisitVarDecl(E, VD);
5168  if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
5169  return Visit(BD->getBinding());
5170  return Error(E);
5171 }
5172 
5173 
5174 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
5175 
5176  // If we are within a lambda's call operator, check whether the 'VD' referred
5177  // to within 'E' actually represents a lambda-capture that maps to a
5178  // data-member/field within the closure object, and if so, evaluate to the
5179  // field or what the field refers to.
5180  if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee)) {
5181  if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
5182  if (Info.checkingPotentialConstantExpression())
5183  return false;
5184  // Start with 'Result' referring to the complete closure object...
5185  Result = *Info.CurrentCall->This;
5186  // ... then update it to refer to the field of the closure object
5187  // that represents the capture.
5188  if (!HandleLValueMember(Info, E, Result, FD))
5189  return false;
5190  // And if the field is of reference type, update 'Result' to refer to what
5191  // the field refers to.
5192  if (FD->getType()->isReferenceType()) {
5193  APValue RVal;
5194  if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5195  RVal))
5196  return false;
5197  Result.setFrom(Info.Ctx, RVal);
5198  }
5199  return true;
5200  }
5201  }
5202  CallStackFrame *Frame = nullptr;
5203  if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5204  // Only if a local variable was declared in the function currently being
5205  // evaluated, do we expect to be able to find its value in the current
5206  // frame. (Otherwise it was likely declared in an enclosing context and
5207  // could either have a valid evaluatable value (for e.g. a constexpr
5208  // variable) or be ill-formed (and trigger an appropriate evaluation
5209  // diagnostic)).
5210  if (Info.CurrentCall->Callee &&
5211  Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5212  Frame = Info.CurrentCall;
5213  }
5214  }
5215 
5216  if (!VD->getType()->isReferenceType()) {
5217  if (Frame) {
5218  Result.set(VD, Frame->Index);
5219  return true;
5220  }
5221  return Success(VD);
5222  }
5223 
5224  APValue *V;
5225  if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
5226  return false;
5227  if (V->isUninit()) {
5228  if (!Info.checkingPotentialConstantExpression())
5229  Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
5230  return false;
5231  }
5232  return Success(*V, E);
5233 }
5234 
5235 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5236  const MaterializeTemporaryExpr *E) {
5237  // Walk through the expression to find the materialized temporary itself.
5238  SmallVector<const Expr *, 2> CommaLHSs;
5240  const Expr *Inner = E->GetTemporaryExpr()->
5241  skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
5242 
5243  // If we passed any comma operators, evaluate their LHSs.
5244  for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5245  if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5246  return false;
5247 
5248  // A materialized temporary with static storage duration can appear within the
5249  // result of a constant expression evaluation, so we need to preserve its
5250  // value for use outside this evaluation.
5251  APValue *Value;
5252  if (E->getStorageDuration() == SD_Static) {
5253  Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
5254  *Value = APValue();
5255  Result.set(E);
5256  } else {
5257  Value = &Info.CurrentCall->
5258  createTemporary(E, E->getStorageDuration() == SD_Automatic);
5259  Result.set(E, Info.CurrentCall->Index);
5260  }
5261 
5262  QualType Type = Inner->getType();
5263 
5264  // Materialize the temporary itself.
5265  if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5266  (E->getStorageDuration() == SD_Static &&
5267  !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5268  *Value = APValue();
5269  return false;
5270  }
5271 
5272  // Adjust our lvalue to refer to the desired subobject.
5273  for (unsigned I = Adjustments.size(); I != 0; /**/) {
5274  --I;
5275  switch (Adjustments[I].Kind) {
5277  if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5278  Type, Result))
5279  return false;
5280  Type = Adjustments[I].DerivedToBase.BasePath->getType();
5281  break;
5282 
5284  if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5285  return false;
5286  Type = Adjustments[I].Field->getType();
5287  break;
5288 
5290  if (!HandleMemberPointerAccess(this->Info, Type, Result,
5291  Adjustments[I].Ptr.RHS))
5292  return false;
5293  Type = Adjustments[I].Ptr.MPT->getPointeeType();
5294  break;
5295  }
5296  }
5297 
5298  return true;
5299 }
5300 
5301 bool
5302 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
5303  assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5304  "lvalue compound literal in c++?");
5305  // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5306  // only see this when folding in C, so there's no standard to follow here.
5307  return Success(E);
5308 }
5309 
5310 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
5311  if (!E->isPotentiallyEvaluated())
5312  return Success(E);
5313 
5314  Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
5315  << E->getExprOperand()->getType()
5316  << E->getExprOperand()->getSourceRange();
5317  return false;
5318 }
5319 
5320 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5321  return Success(E);
5322 }
5323 
5324 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
5325  // Handle static data members.
5326  if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
5327  VisitIgnoredBaseExpression(E->getBase());
5328  return VisitVarDecl(E, VD);
5329  }
5330 
5331  // Handle static member functions.
5332  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5333  if (MD->isStatic()) {
5334  VisitIgnoredBaseExpression(E->getBase());
5335  return Success(MD);
5336  }
5337  }
5338 
5339  // Handle non-static data members.
5340  return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
5341 }
5342 
5343 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
5344  // FIXME: Deal with vectors as array subscript bases.
5345  if (E->getBase()->getType()->isVectorType())
5346  return Error(E);
5347 
5348  bool Success = true;
5349  if (!evaluatePointer(E->getBase(), Result)) {
5350  if (!Info.noteFailure())
5351  return false;
5352  Success = false;
5353  }
5354 
5355  APSInt Index;
5356  if (!EvaluateInteger(E->getIdx(), Index, Info))
5357  return false;
5358 
5359  return Success &&
5360  HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
5361 }
5362 
5363 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
5364  return evaluatePointer(E->getSubExpr(), Result);
5365 }
5366 
5367 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5368  if (!Visit(E->getSubExpr()))
5369  return false;
5370  // __real is a no-op on scalar lvalues.
5371  if (E->getSubExpr()->getType()->isAnyComplexType())
5372  HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5373  return true;
5374 }
5375 
5376 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5377  assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5378  "lvalue __imag__ on scalar?");
5379  if (!Visit(E->getSubExpr()))
5380  return false;
5381  HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5382  return true;
5383 }
5384 
5385 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
5386  if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5387  return Error(UO);
5388 
5389  if (!this->Visit(UO->getSubExpr()))
5390  return false;
5391 
5392  return handleIncDec(
5393  this->Info, UO, Result, UO->getSubExpr()->getType(),
5394  UO->isIncrementOp(), nullptr);
5395 }
5396 
5397 bool LValueExprEvaluator::VisitCompoundAssignOperator(
5398  const CompoundAssignOperator *CAO) {
5399  if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5400  return Error(CAO);
5401 
5402  APValue RHS;
5403 
5404  // The overall lvalue result is the result of evaluating the LHS.
5405  if (!this->Visit(CAO->getLHS())) {
5406  if (Info.noteFailure())
5407  Evaluate(RHS, this->Info, CAO->getRHS());
5408  return false;
5409  }
5410 
5411  if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5412  return false;
5413 
5414  return handleCompoundAssignment(
5415  this->Info, CAO,
5416  Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5417  CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
5418 }
5419 
5420 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
5421  if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5422  return Error(E);
5423 
5424  APValue NewVal;
5425 
5426  if (!this->Visit(E->getLHS())) {
5427  if (Info.noteFailure())
5428  Evaluate(NewVal, this->Info, E->getRHS());
5429  return false;
5430  }
5431 
5432  if (!Evaluate(NewVal, this->Info, E->getRHS()))
5433  return false;
5434 
5435  return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
5436  NewVal);
5437 }
5438 
5439 //===----------------------------------------------------------------------===//
5440 // Pointer Evaluation
5441 //===----------------------------------------------------------------------===//
5442 
5443 /// \brief Attempts to compute the number of bytes available at the pointer
5444 /// returned by a function with the alloc_size attribute. Returns true if we
5445 /// were successful. Places an unsigned number into `Result`.
5446 ///
5447 /// This expects the given CallExpr to be a call to a function with an
5448 /// alloc_size attribute.
5450  const CallExpr *Call,
5451  llvm::APInt &Result) {
5452  const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5453 
5454  // alloc_size args are 1-indexed, 0 means not present.
5455  assert(AllocSize && AllocSize->getElemSizeParam() != 0);
5456  unsigned SizeArgNo = AllocSize->getElemSizeParam() - 1;
5457  unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5458  if (Call->getNumArgs() <= SizeArgNo)
5459  return false;
5460 
5461  auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5462  if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5463  return false;
5464  if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5465  return false;
5466  Into = Into.zextOrSelf(BitsInSizeT);
5467  return true;
5468  };
5469 
5470  APSInt SizeOfElem;
5471  if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5472  return false;
5473 
5474  if (!AllocSize->getNumElemsParam()) {
5475  Result = std::move(SizeOfElem);
5476  return true;
5477  }
5478 
5479  APSInt NumberOfElems;
5480  // Argument numbers start at 1
5481  unsigned NumArgNo = AllocSize->getNumElemsParam() - 1;
5482  if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5483  return false;
5484 
5485  bool Overflow;
5486  llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5487  if (Overflow)
5488  return false;
5489 
5490  Result = std::move(BytesAvailable);
5491  return true;
5492 }
5493 
5494 /// \brief Convenience function. LVal's base must be a call to an alloc_size
5495 /// function.
5497  const LValue &LVal,
5498  llvm::APInt &Result) {
5499  assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5500  "Can't get the size of a non alloc_size function");
5501  const auto *Base = LVal.getLValueBase().get<const Expr *>();
5502  const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5503  return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5504 }
5505 
5506 /// \brief Attempts to evaluate the given LValueBase as the result of a call to
5507 /// a function with the alloc_size attribute. If it was possible to do so, this
5508 /// function will return true, make Result's Base point to said function call,
5509 /// and mark Result's Base as invalid.
5510 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5511  LValue &Result) {
5512  if (Base.isNull())
5513  return false;
5514 
5515  // Because we do no form of static analysis, we only support const variables.
5516  //
5517  // Additionally, we can't support parameters, nor can we support static
5518  // variables (in the latter case, use-before-assign isn't UB; in the former,
5519  // we have no clue what they'll be assigned to).
5520  const auto *VD =
5521  dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5522  if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5523  return false;
5524 
5525  const Expr *Init = VD->getAnyInitializer();
5526  if (!Init)
5527  return false;
5528 
5529  const Expr *E = Init->IgnoreParens();
5530  if (!tryUnwrapAllocSizeCall(E))
5531  return false;
5532 
5533  // Store E instead of E unwrapped so that the type of the LValue's base is
5534  // what the user wanted.
5535  Result.setInvalid(E);
5536 
5537  QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
5538  Result.addUnsizedArray(Info, E, Pointee);
5539  return true;
5540 }
5541 
5542 namespace {
5543 class PointerExprEvaluator
5544  : public ExprEvaluatorBase<PointerExprEvaluator> {
5545  LValue &Result;
5546  bool InvalidBaseOK;
5547 
5548  bool Success(const Expr *E) {
5549  Result.set(E);
5550  return true;
5551  }
5552 
5553  bool evaluateLValue(const Expr *E, LValue &Result) {
5554  return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5555  }
5556 
5557  bool evaluatePointer(const Expr *E, LValue &Result) {
5558  return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5559  }
5560 
5561  bool visitNonBuiltinCallExpr(const CallExpr *E);
5562 public:
5563 
5564  PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5565  : ExprEvaluatorBaseTy(info), Result(Result),
5566  InvalidBaseOK(InvalidBaseOK) {}
5567 
5568  bool Success(const APValue &V, const Expr *E) {
5569  Result.setFrom(Info.Ctx, V);
5570  return true;
5571  }
5572  bool ZeroInitialization(const Expr *E) {
5573  auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
5574  Result.setNull(E->getType(), TargetVal);
5575  return true;
5576  }
5577 
5578  bool VisitBinaryOperator(const BinaryOperator *E);
5579  bool VisitCastExpr(const CastExpr* E);
5580  bool VisitUnaryAddrOf(const UnaryOperator *E);
5581  bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
5582  { return Success(E); }
5583  bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
5584  if (Info.noteFailure())
5585  EvaluateIgnoredValue(Info, E->getSubExpr());
5586  return Error(E);
5587  }
5588  bool VisitAddrLabelExpr(const AddrLabelExpr *E)
5589  { return Success(E); }
5590  bool VisitCallExpr(const CallExpr *E);
5591  bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
5592  bool VisitBlockExpr(const BlockExpr *E) {
5593  if (!E->getBlockDecl()->hasCaptures())
5594  return Success(E);
5595  return Error(E);
5596  }
5597  bool VisitCXXThisExpr(const CXXThisExpr *E) {
5598  // Can't look at 'this' when checking a potential constant expression.
5599  if (Info.checkingPotentialConstantExpression())
5600  return false;
5601  if (!Info.CurrentCall->This) {
5602  if (Info.getLangOpts().CPlusPlus11)
5603  Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
5604  else
5605  Info.FFDiag(E);
5606  return false;
5607  }
5608  Result = *Info.CurrentCall->This;
5609  // If we are inside a lambda's call operator, the 'this' expression refers
5610  // to the enclosing '*this' object (either by value or reference) which is
5611  // either copied into the closure object's field that represents the '*this'
5612  // or refers to '*this'.
5613  if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5614  // Update 'Result' to refer to the data member/field of the closure object
5615  // that represents the '*this' capture.
5616  if (!HandleLValueMember(Info, E, Result,
5617  Info.CurrentCall->LambdaThisCaptureField))
5618  return false;
5619  // If we captured '*this' by reference, replace the field with its referent.
5620  if (Info.CurrentCall->LambdaThisCaptureField->getType()
5621  ->isPointerType()) {
5622  APValue RVal;
5623  if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5624  RVal))
5625  return false;
5626 
5627  Result.setFrom(Info.Ctx, RVal);
5628  }
5629  }
5630  return true;
5631  }
5632 
5633  // FIXME: Missing: @protocol, @selector
5634 };
5635 } // end anonymous namespace
5636 
5637 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5638  bool InvalidBaseOK) {
5639  assert(E->isRValue() && E->getType()->hasPointerRepresentation());
5640  return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
5641 }
5642 
5643 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5644  if (E->getOpcode() != BO_Add &&
5645  E->getOpcode() != BO_Sub)
5646  return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5647 
5648  const Expr *PExp = E->getLHS();
5649  const Expr *IExp = E->getRHS();
5650  if (IExp->getType()->isPointerType())
5651  std::swap(PExp, IExp);
5652 
5653  bool EvalPtrOK = evaluatePointer(PExp, Result);
5654  if (!EvalPtrOK && !Info.noteFailure())
5655  return false;
5656 
5657  llvm::APSInt Offset;
5658  if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
5659  return false;
5660 
5661  if (E->getOpcode() == BO_Sub)
5662  negateAsSigned(Offset);
5663 
5664  QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
5665  return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
5666 }
5667 
5668 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5669  return evaluateLValue(E->getSubExpr(), Result);
5670 }
5671 
5672 bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5673  const Expr* SubExpr = E->getSubExpr();
5674 
5675  switch (E->getCastKind()) {
5676  default:
5677  break;
5678 
5679  case CK_BitCast:
5680  case CK_CPointerToObjCPointerCast:
5681  case CK_BlockPointerToObjCPointerCast:
5682  case CK_AnyPointerToBlockPointerCast:
5683  case CK_AddressSpaceConversion:
5684  if (!Visit(SubExpr))
5685  return false;
5686  // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5687  // permitted in constant expressions in C++11. Bitcasts from cv void* are
5688  // also static_casts, but we disallow them as a resolution to DR1312.
5689  if (!E->getType()->isVoidPointerType()) {
5690  Result.Designator.setInvalid();
5691  if (SubExpr->getType()->isVoidPointerType())
5692  CCEDiag(E, diag::note_constexpr_invalid_cast)
5693  << 3 << SubExpr->getType();
5694  else
5695  CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5696  }
5697  if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5698  ZeroInitialization(E);
5699  return true;
5700 
5701  case CK_DerivedToBase:
5702  case CK_UncheckedDerivedToBase:
5703  if (!evaluatePointer(E->getSubExpr(), Result))
5704  return false;
5705  if (!Result.Base && Result.Offset.isZero())
5706  return true;
5707 
5708  // Now figure out the necessary offset to add to the base LV to get from
5709  // the derived class to the base class.
5710  return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5711  castAs<PointerType>()->getPointeeType(),
5712  Result);
5713 
5714  case CK_BaseToDerived:
5715  if (!Visit(E->getSubExpr()))
5716  return false;
5717  if (!Result.Base && Result.Offset.isZero())
5718  return true;
5719  return HandleBaseToDerivedCast(Info, E, Result);
5720 
5721  case CK_NullToPointer:
5722  VisitIgnoredValue(E->getSubExpr());
5723  return ZeroInitialization(E);
5724 
5725  case CK_IntegralToPointer: {
5726  CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5727 
5728  APValue Value;
5729  if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
5730  break;
5731 
5732  if (Value.isInt()) {
5733  unsigned Size = Info.Ctx.getTypeSize(E->getType());
5734  uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
5735  Result.Base = (Expr*)nullptr;
5736  Result.InvalidBase = false;
5737  Result.Offset = CharUnits::fromQuantity(N);
5738  Result.CallIndex = 0;
5739  Result.Designator.setInvalid();
5740  Result.IsNullPtr = false;
5741  return true;
5742  } else {
5743  // Cast is of an lvalue, no need to change value.
5744  Result.setFrom(Info.Ctx, Value);
5745  return true;
5746  }
5747  }
5748 
5749  case CK_ArrayToPointerDecay: {
5750  if (SubExpr->isGLValue()) {
5751  if (!evaluateLValue(SubExpr, Result))
5752  return false;
5753  } else {
5754  Result.set(SubExpr, Info.CurrentCall->Index);
5755  if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
5756  Info, Result, SubExpr))
5757  return false;
5758  }
5759  // The result is a pointer to the first element of the array.
5760  auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
5761  if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
5762  Result.addArray(Info, E, CAT);
5763  else
5764  Result.addUnsizedArray(Info, E, AT->getElementType());
5765  return true;
5766  }
5767 
5768  case CK_FunctionToPointerDecay:
5769  return evaluateLValue(SubExpr, Result);
5770 
5771  case CK_LValueToRValue: {
5772  LValue LVal;
5773  if (!evaluateLValue(E->getSubExpr(), LVal))
5774  return false;
5775 
5776  APValue RVal;
5777  // Note, we use the subexpression's type in order to retain cv-qualifiers.
5778  if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5779  LVal, RVal))
5780  return InvalidBaseOK &&
5781  evaluateLValueAsAllocSize(Info, LVal.Base, Result);
5782  return Success(RVal, E);
5783  }
5784  }
5785 
5786  return ExprEvaluatorBaseTy::VisitCastExpr(E);
5787 }
5788 
5789 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5790  // C++ [expr.alignof]p3:
5791  // When alignof is applied to a reference type, the result is the
5792  // alignment of the referenced type.
5793  if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5794  T = Ref->getPointeeType();
5795 
5796  // __alignof is defined to return the preferred alignment.
5797  if (T.getQualifiers().hasUnaligned())
5798  return CharUnits::One();
5799  return Info.Ctx.toCharUnitsFromBits(
5800  Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5801 }
5802 
5803 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5804  E = E->IgnoreParens();
5805 
5806  // The kinds of expressions that we have special-case logic here for
5807  // should be kept up to date with the special checks for those
5808  // expressions in Sema.
5809 
5810  // alignof decl is always accepted, even if it doesn't make sense: we default
5811  // to 1 in those cases.
5812  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5813  return Info.Ctx.getDeclAlign(DRE->getDecl(),
5814  /*RefAsPointee*/true);
5815 
5816  if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5817  return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5818  /*RefAsPointee*/true);
5819 
5820  return GetAlignOfType(Info, E->getType());
5821 }
5822 
5823 // To be clear: this happily visits unsupported builtins. Better name welcomed.
5824 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
5825  if (ExprEvaluatorBaseTy::VisitCallExpr(E))
5826  return true;
5827 
5828  if (!(InvalidBaseOK && getAllocSizeAttr(E)))
5829  return false;
5830 
5831  Result.setInvalid(E);
5832  QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
5833  Result.addUnsizedArray(Info, E, PointeeTy);
5834  return true;
5835 }
5836 
5837 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
5838  if (IsStringLiteralCall(E))
5839  return Success(E);
5840 
5841  if (unsigned BuiltinOp = E->getBuiltinCallee())
5842  return VisitBuiltinCallExpr(E, BuiltinOp);
5843 
5844  return visitNonBuiltinCallExpr(E);
5845 }
5846 
5847 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5848  unsigned BuiltinOp) {
5849  switch (BuiltinOp) {
5850  case Builtin::BI__builtin_addressof:
5851  return evaluateLValue(E->getArg(0), Result);
5852  case Builtin::BI__builtin_assume_aligned: {
5853  // We need to be very careful here because: if the pointer does not have the
5854  // asserted alignment, then the behavior is undefined, and undefined
5855  // behavior is non-constant.
5856  if (!evaluatePointer(E->getArg(0), Result))
5857  return false;
5858 
5859  LValue OffsetResult(Result);
5860  APSInt Alignment;
5861  if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5862  return false;
5863  CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
5864 
5865  if (E->getNumArgs() > 2) {
5866  APSInt Offset;
5867  if (!EvaluateInteger(E->getArg(2), Offset, Info))
5868  return false;
5869 
5870  int64_t AdditionalOffset = -Offset.getZExtValue();
5871  OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5872  }
5873 
5874  // If there is a base object, then it must have the correct alignment.
5875  if (OffsetResult.Base) {
5876  CharUnits BaseAlignment;
5877  if (const ValueDecl *VD =
5878  OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5879  BaseAlignment = Info.Ctx.getDeclAlign(VD);
5880  } else {
5881  BaseAlignment =
5882  GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5883  }
5884 
5885  if (BaseAlignment < Align) {
5886  Result.Designator.setInvalid();
5887  // FIXME: Add support to Diagnostic for long / long long.
5888  CCEDiag(E->getArg(0),
5889  diag::note_constexpr_baa_insufficient_alignment) << 0
5890  << (unsigned)BaseAlignment.getQuantity()
5891  << (unsigned)Align.getQuantity();
5892  return false;
5893  }
5894  }
5895 
5896  // The offset must also have the correct alignment.
5897  if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
5898  Result.Designator.setInvalid();
5899 
5900  (OffsetResult.Base
5901  ? CCEDiag(E->getArg(0),
5902  diag::note_constexpr_baa_insufficient_alignment) << 1
5903  : CCEDiag(E->getArg(0),
5904  diag::note_constexpr_baa_value_insufficient_alignment))
5905  << (int)OffsetResult.Offset.getQuantity()
5906  << (unsigned)Align.getQuantity();
5907  return false;
5908  }
5909 
5910  return true;
5911  }
5912 
5913  case Builtin::BIstrchr:
5914  case Builtin::BIwcschr:
5915  case Builtin::BImemchr:
5916  case Builtin::BIwmemchr:
5917  if (Info.getLangOpts().CPlusPlus11)
5918  Info.CCEDiag(E, diag::note_constexpr_invalid_function)
5919  << /*isConstexpr*/0 << /*isConstructor*/0
5920  << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
5921  else
5922  Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
5923  LLVM_FALLTHROUGH;
5924  case Builtin::BI__builtin_strchr:
5925  case Builtin::BI__builtin_wcschr:
5926  case Builtin::BI__builtin_memchr:
5927  case Builtin::BI__builtin_char_memchr:
5928  case Builtin::BI__builtin_wmemchr: {
5929  if (!Visit(E->getArg(0)))
5930  return false;
5931  APSInt Desired;
5932  if (!EvaluateInteger(E->getArg(1), Desired, Info))
5933  return false;
5934  uint64_t MaxLength = uint64_t(-1);
5935  if (BuiltinOp != Builtin::BIstrchr &&
5936  BuiltinOp != Builtin::BIwcschr &&
5937  BuiltinOp != Builtin::BI__builtin_strchr &&
5938  BuiltinOp != Builtin::BI__builtin_wcschr) {
5939  APSInt N;
5940  if (!EvaluateInteger(E->getArg(2), N, Info))
5941  return false;
5942  MaxLength = N.getExtValue();
5943  }
5944 
5945  QualType CharTy = E->getArg(0)->getType()->getPointeeType();
5946 
5947  // Figure out what value we're actually looking for (after converting to
5948  // the corresponding unsigned type if necessary).
5949  uint64_t DesiredVal;
5950  bool StopAtNull = false;
5951  switch (BuiltinOp) {
5952  case Builtin::BIstrchr:
5953  case Builtin::BI__builtin_strchr:
5954  // strchr compares directly to the passed integer, and therefore
5955  // always fails if given an int that is not a char.
5956  if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
5957  E->getArg(1)->getType(),
5958  Desired),
5959  Desired))
5960  return ZeroInitialization(E);
5961  StopAtNull = true;
5962  LLVM_FALLTHROUGH;
5963  case Builtin::BImemchr:
5964  case Builtin::BI__builtin_memchr:
5965  case Builtin::BI__builtin_char_memchr:
5966  // memchr compares by converting both sides to unsigned char. That's also
5967  // correct for strchr if we get this far (to cope with plain char being
5968  // unsigned in the strchr case).
5969  DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
5970  break;
5971 
5972  case Builtin::BIwcschr:
5973  case Builtin::BI__builtin_wcschr:
5974  StopAtNull = true;
5975  LLVM_FALLTHROUGH;
5976  case Builtin::BIwmemchr:
5977  case Builtin::BI__builtin_wmemchr:
5978  // wcschr and wmemchr are given a wchar_t to look for. Just use it.
5979  DesiredVal = Desired.getZExtValue();
5980  break;
5981  }
5982 
5983  for (; MaxLength; --MaxLength) {
5984  APValue Char;
5985  if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
5986  !Char.isInt())
5987  return false;
5988  if (Char.getInt().getZExtValue() == DesiredVal)
5989  return true;