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