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