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