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