1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Expr constant evaluator.
10 //
11 // Constant expression evaluation produces four main results:
12 //
13 //  * A success/failure flag indicating whether constant folding was successful.
14 //    This is the 'bool' return value used by most of the code in this file. A
15 //    'false' return value indicates that constant folding has failed, and any
16 //    appropriate diagnostic has already been produced.
17 //
18 //  * An evaluated result, valid only if constant folding has not failed.
19 //
20 //  * A flag indicating if evaluation encountered (unevaluated) side-effects.
21 //    These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
22 //    where it is possible to determine the evaluated result regardless.
23 //
24 //  * A set of notes indicating why the evaluation was not a constant expression
25 //    (under the C++11 / C++1y rules only, at the moment), or, if folding failed
26 //    too, why the expression could not be folded.
27 //
28 // If we are checking for a potential constant expression, failure to constant
29 // fold a potential constant sub-expression will be indicated by a 'false'
30 // return value (the expression could not be folded) and no diagnostic (the
31 // expression is not necessarily non-constant).
32 //
33 //===----------------------------------------------------------------------===//
34 
35 #include "Interp/Context.h"
36 #include "Interp/Frame.h"
37 #include "Interp/State.h"
38 #include "clang/AST/APValue.h"
39 #include "clang/AST/ASTContext.h"
40 #include "clang/AST/ASTDiagnostic.h"
41 #include "clang/AST/ASTLambda.h"
42 #include "clang/AST/Attr.h"
43 #include "clang/AST/CXXInheritance.h"
44 #include "clang/AST/CharUnits.h"
45 #include "clang/AST/CurrentSourceLocExprScope.h"
46 #include "clang/AST/Expr.h"
47 #include "clang/AST/OSLog.h"
48 #include "clang/AST/OptionalDiagnostic.h"
49 #include "clang/AST/RecordLayout.h"
50 #include "clang/AST/StmtVisitor.h"
51 #include "clang/AST/TypeLoc.h"
52 #include "clang/Basic/Builtins.h"
53 #include "clang/Basic/FixedPoint.h"
54 #include "clang/Basic/TargetInfo.h"
55 #include "llvm/ADT/Optional.h"
56 #include "llvm/ADT/SmallBitVector.h"
57 #include "llvm/Support/SaveAndRestore.h"
58 #include "llvm/Support/raw_ostream.h"
59 #include <cstring>
60 #include <functional>
61 
62 #define DEBUG_TYPE "exprconstant"
63 
64 using namespace clang;
65 using llvm::APInt;
66 using llvm::APSInt;
67 using llvm::APFloat;
68 using llvm::Optional;
69 
70 namespace {
71   struct LValue;
72   class CallStackFrame;
73   class EvalInfo;
74 
75   using SourceLocExprScopeGuard =
76       CurrentSourceLocExprScope::SourceLocExprScopeGuard;
77 
78   static QualType getType(APValue::LValueBase B) {
79     if (!B) return QualType();
80     if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
81       // FIXME: It's unclear where we're supposed to take the type from, and
82       // this actually matters for arrays of unknown bound. Eg:
83       //
84       // extern int arr[]; void f() { extern int arr[3]; };
85       // constexpr int *p = &arr[1]; // valid?
86       //
87       // For now, we take the array bound from the most recent declaration.
88       for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
89            Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
90         QualType T = Redecl->getType();
91         if (!T->isIncompleteArrayType())
92           return T;
93       }
94       return D->getType();
95     }
96 
97     if (B.is<TypeInfoLValue>())
98       return B.getTypeInfoType();
99 
100     if (B.is<DynamicAllocLValue>())
101       return B.getDynamicAllocType();
102 
103     const Expr *Base = B.get<const Expr*>();
104 
105     // For a materialized temporary, the type of the temporary we materialized
106     // may not be the type of the expression.
107     if (const MaterializeTemporaryExpr *MTE =
108             dyn_cast<MaterializeTemporaryExpr>(Base)) {
109       SmallVector<const Expr *, 2> CommaLHSs;
110       SmallVector<SubobjectAdjustment, 2> Adjustments;
111       const Expr *Temp = MTE->getSubExpr();
112       const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
113                                                                Adjustments);
114       // Keep any cv-qualifiers from the reference if we generated a temporary
115       // for it directly. Otherwise use the type after adjustment.
116       if (!Adjustments.empty())
117         return Inner->getType();
118     }
119 
120     return Base->getType();
121   }
122 
123   /// Get an LValue path entry, which is known to not be an array index, as a
124   /// field declaration.
125   static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
126     return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
127   }
128   /// Get an LValue path entry, which is known to not be an array index, as a
129   /// base class declaration.
130   static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
131     return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
132   }
133   /// Determine whether this LValue path entry for a base class names a virtual
134   /// base class.
135   static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
136     return E.getAsBaseOrMember().getInt();
137   }
138 
139   /// Given an expression, determine the type used to store the result of
140   /// evaluating that expression.
141   static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
142     if (E->isRValue())
143       return E->getType();
144     return Ctx.getLValueReferenceType(E->getType());
145   }
146 
147   /// Given a CallExpr, try to get the alloc_size attribute. May return null.
148   static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
149     const FunctionDecl *Callee = CE->getDirectCallee();
150     return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
151   }
152 
153   /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
154   /// This will look through a single cast.
155   ///
156   /// Returns null if we couldn't unwrap a function with alloc_size.
157   static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
158     if (!E->getType()->isPointerType())
159       return nullptr;
160 
161     E = E->IgnoreParens();
162     // If we're doing a variable assignment from e.g. malloc(N), there will
163     // probably be a cast of some kind. In exotic cases, we might also see a
164     // top-level ExprWithCleanups. Ignore them either way.
165     if (const auto *FE = dyn_cast<FullExpr>(E))
166       E = FE->getSubExpr()->IgnoreParens();
167 
168     if (const auto *Cast = dyn_cast<CastExpr>(E))
169       E = Cast->getSubExpr()->IgnoreParens();
170 
171     if (const auto *CE = dyn_cast<CallExpr>(E))
172       return getAllocSizeAttr(CE) ? CE : nullptr;
173     return nullptr;
174   }
175 
176   /// Determines whether or not the given Base contains a call to a function
177   /// with the alloc_size attribute.
178   static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
179     const auto *E = Base.dyn_cast<const Expr *>();
180     return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
181   }
182 
183   /// The bound to claim that an array of unknown bound has.
184   /// The value in MostDerivedArraySize is undefined in this case. So, set it
185   /// to an arbitrary value that's likely to loudly break things if it's used.
186   static const uint64_t AssumedSizeForUnsizedArray =
187       std::numeric_limits<uint64_t>::max() / 2;
188 
189   /// Determines if an LValue with the given LValueBase will have an unsized
190   /// array in its designator.
191   /// Find the path length and type of the most-derived subobject in the given
192   /// path, and find the size of the containing array, if any.
193   static unsigned
194   findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
195                            ArrayRef<APValue::LValuePathEntry> Path,
196                            uint64_t &ArraySize, QualType &Type, bool &IsArray,
197                            bool &FirstEntryIsUnsizedArray) {
198     // This only accepts LValueBases from APValues, and APValues don't support
199     // arrays that lack size info.
200     assert(!isBaseAnAllocSizeCall(Base) &&
201            "Unsized arrays shouldn't appear here");
202     unsigned MostDerivedLength = 0;
203     Type = getType(Base);
204 
205     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
206       if (Type->isArrayType()) {
207         const ArrayType *AT = Ctx.getAsArrayType(Type);
208         Type = AT->getElementType();
209         MostDerivedLength = I + 1;
210         IsArray = true;
211 
212         if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
213           ArraySize = CAT->getSize().getZExtValue();
214         } else {
215           assert(I == 0 && "unexpected unsized array designator");
216           FirstEntryIsUnsizedArray = true;
217           ArraySize = AssumedSizeForUnsizedArray;
218         }
219       } else if (Type->isAnyComplexType()) {
220         const ComplexType *CT = Type->castAs<ComplexType>();
221         Type = CT->getElementType();
222         ArraySize = 2;
223         MostDerivedLength = I + 1;
224         IsArray = true;
225       } else if (const FieldDecl *FD = getAsField(Path[I])) {
226         Type = FD->getType();
227         ArraySize = 0;
228         MostDerivedLength = I + 1;
229         IsArray = false;
230       } else {
231         // Path[I] describes a base class.
232         ArraySize = 0;
233         IsArray = false;
234       }
235     }
236     return MostDerivedLength;
237   }
238 
239   /// A path from a glvalue to a subobject of that glvalue.
240   struct SubobjectDesignator {
241     /// True if the subobject was named in a manner not supported by C++11. Such
242     /// lvalues can still be folded, but they are not core constant expressions
243     /// and we cannot perform lvalue-to-rvalue conversions on them.
244     unsigned Invalid : 1;
245 
246     /// Is this a pointer one past the end of an object?
247     unsigned IsOnePastTheEnd : 1;
248 
249     /// Indicator of whether the first entry is an unsized array.
250     unsigned FirstEntryIsAnUnsizedArray : 1;
251 
252     /// Indicator of whether the most-derived object is an array element.
253     unsigned MostDerivedIsArrayElement : 1;
254 
255     /// The length of the path to the most-derived object of which this is a
256     /// subobject.
257     unsigned MostDerivedPathLength : 28;
258 
259     /// The size of the array of which the most-derived object is an element.
260     /// This will always be 0 if the most-derived object is not an array
261     /// element. 0 is not an indicator of whether or not the most-derived object
262     /// is an array, however, because 0-length arrays are allowed.
263     ///
264     /// If the current array is an unsized array, the value of this is
265     /// undefined.
266     uint64_t MostDerivedArraySize;
267 
268     /// The type of the most derived object referred to by this address.
269     QualType MostDerivedType;
270 
271     typedef APValue::LValuePathEntry PathEntry;
272 
273     /// The entries on the path from the glvalue to the designated subobject.
274     SmallVector<PathEntry, 8> Entries;
275 
276     SubobjectDesignator() : Invalid(true) {}
277 
278     explicit SubobjectDesignator(QualType T)
279         : Invalid(false), IsOnePastTheEnd(false),
280           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
281           MostDerivedPathLength(0), MostDerivedArraySize(0),
282           MostDerivedType(T) {}
283 
284     SubobjectDesignator(ASTContext &Ctx, const APValue &V)
285         : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
286           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
287           MostDerivedPathLength(0), MostDerivedArraySize(0) {
288       assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
289       if (!Invalid) {
290         IsOnePastTheEnd = V.isLValueOnePastTheEnd();
291         ArrayRef<PathEntry> VEntries = V.getLValuePath();
292         Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
293         if (V.getLValueBase()) {
294           bool IsArray = false;
295           bool FirstIsUnsizedArray = false;
296           MostDerivedPathLength = findMostDerivedSubobject(
297               Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
298               MostDerivedType, IsArray, FirstIsUnsizedArray);
299           MostDerivedIsArrayElement = IsArray;
300           FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
301         }
302       }
303     }
304 
305     void truncate(ASTContext &Ctx, APValue::LValueBase Base,
306                   unsigned NewLength) {
307       if (Invalid)
308         return;
309 
310       assert(Base && "cannot truncate path for null pointer");
311       assert(NewLength <= Entries.size() && "not a truncation");
312 
313       if (NewLength == Entries.size())
314         return;
315       Entries.resize(NewLength);
316 
317       bool IsArray = false;
318       bool FirstIsUnsizedArray = false;
319       MostDerivedPathLength = findMostDerivedSubobject(
320           Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
321           FirstIsUnsizedArray);
322       MostDerivedIsArrayElement = IsArray;
323       FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
324     }
325 
326     void setInvalid() {
327       Invalid = true;
328       Entries.clear();
329     }
330 
331     /// Determine whether the most derived subobject is an array without a
332     /// known bound.
333     bool isMostDerivedAnUnsizedArray() const {
334       assert(!Invalid && "Calling this makes no sense on invalid designators");
335       return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
336     }
337 
338     /// Determine what the most derived array's size is. Results in an assertion
339     /// failure if the most derived array lacks a size.
340     uint64_t getMostDerivedArraySize() const {
341       assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
342       return MostDerivedArraySize;
343     }
344 
345     /// Determine whether this is a one-past-the-end pointer.
346     bool isOnePastTheEnd() const {
347       assert(!Invalid);
348       if (IsOnePastTheEnd)
349         return true;
350       if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
351           Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
352               MostDerivedArraySize)
353         return true;
354       return false;
355     }
356 
357     /// Get the range of valid index adjustments in the form
358     ///   {maximum value that can be subtracted from this pointer,
359     ///    maximum value that can be added to this pointer}
360     std::pair<uint64_t, uint64_t> validIndexAdjustments() {
361       if (Invalid || isMostDerivedAnUnsizedArray())
362         return {0, 0};
363 
364       // [expr.add]p4: For the purposes of these operators, a pointer to a
365       // nonarray object behaves the same as a pointer to the first element of
366       // an array of length one with the type of the object as its element type.
367       bool IsArray = MostDerivedPathLength == Entries.size() &&
368                      MostDerivedIsArrayElement;
369       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
370                                     : (uint64_t)IsOnePastTheEnd;
371       uint64_t ArraySize =
372           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
373       return {ArrayIndex, ArraySize - ArrayIndex};
374     }
375 
376     /// Check that this refers to a valid subobject.
377     bool isValidSubobject() const {
378       if (Invalid)
379         return false;
380       return !isOnePastTheEnd();
381     }
382     /// Check that this refers to a valid subobject, and if not, produce a
383     /// relevant diagnostic and set the designator as invalid.
384     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
385 
386     /// Get the type of the designated object.
387     QualType getType(ASTContext &Ctx) const {
388       assert(!Invalid && "invalid designator has no subobject type");
389       return MostDerivedPathLength == Entries.size()
390                  ? MostDerivedType
391                  : Ctx.getRecordType(getAsBaseClass(Entries.back()));
392     }
393 
394     /// Update this designator to refer to the first element within this array.
395     void addArrayUnchecked(const ConstantArrayType *CAT) {
396       Entries.push_back(PathEntry::ArrayIndex(0));
397 
398       // This is a most-derived object.
399       MostDerivedType = CAT->getElementType();
400       MostDerivedIsArrayElement = true;
401       MostDerivedArraySize = CAT->getSize().getZExtValue();
402       MostDerivedPathLength = Entries.size();
403     }
404     /// Update this designator to refer to the first element within the array of
405     /// elements of type T. This is an array of unknown size.
406     void addUnsizedArrayUnchecked(QualType ElemTy) {
407       Entries.push_back(PathEntry::ArrayIndex(0));
408 
409       MostDerivedType = ElemTy;
410       MostDerivedIsArrayElement = true;
411       // The value in MostDerivedArraySize is undefined in this case. So, set it
412       // to an arbitrary value that's likely to loudly break things if it's
413       // used.
414       MostDerivedArraySize = AssumedSizeForUnsizedArray;
415       MostDerivedPathLength = Entries.size();
416     }
417     /// Update this designator to refer to the given base or member of this
418     /// object.
419     void addDeclUnchecked(const Decl *D, bool Virtual = false) {
420       Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
421 
422       // If this isn't a base class, it's a new most-derived object.
423       if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
424         MostDerivedType = FD->getType();
425         MostDerivedIsArrayElement = false;
426         MostDerivedArraySize = 0;
427         MostDerivedPathLength = Entries.size();
428       }
429     }
430     /// Update this designator to refer to the given complex component.
431     void addComplexUnchecked(QualType EltTy, bool Imag) {
432       Entries.push_back(PathEntry::ArrayIndex(Imag));
433 
434       // This is technically a most-derived object, though in practice this
435       // is unlikely to matter.
436       MostDerivedType = EltTy;
437       MostDerivedIsArrayElement = true;
438       MostDerivedArraySize = 2;
439       MostDerivedPathLength = Entries.size();
440     }
441     void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
442     void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
443                                    const APSInt &N);
444     /// Add N to the address of this subobject.
445     void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
446       if (Invalid || !N) return;
447       uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
448       if (isMostDerivedAnUnsizedArray()) {
449         diagnoseUnsizedArrayPointerArithmetic(Info, E);
450         // Can't verify -- trust that the user is doing the right thing (or if
451         // not, trust that the caller will catch the bad behavior).
452         // FIXME: Should we reject if this overflows, at least?
453         Entries.back() = PathEntry::ArrayIndex(
454             Entries.back().getAsArrayIndex() + TruncatedN);
455         return;
456       }
457 
458       // [expr.add]p4: For the purposes of these operators, a pointer to a
459       // nonarray object behaves the same as a pointer to the first element of
460       // an array of length one with the type of the object as its element type.
461       bool IsArray = MostDerivedPathLength == Entries.size() &&
462                      MostDerivedIsArrayElement;
463       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
464                                     : (uint64_t)IsOnePastTheEnd;
465       uint64_t ArraySize =
466           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
467 
468       if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
469         // Calculate the actual index in a wide enough type, so we can include
470         // it in the note.
471         N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
472         (llvm::APInt&)N += ArrayIndex;
473         assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
474         diagnosePointerArithmetic(Info, E, N);
475         setInvalid();
476         return;
477       }
478 
479       ArrayIndex += TruncatedN;
480       assert(ArrayIndex <= ArraySize &&
481              "bounds check succeeded for out-of-bounds index");
482 
483       if (IsArray)
484         Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
485       else
486         IsOnePastTheEnd = (ArrayIndex != 0);
487     }
488   };
489 
490   /// A stack frame in the constexpr call stack.
491   class CallStackFrame : public interp::Frame {
492   public:
493     EvalInfo &Info;
494 
495     /// Parent - The caller of this stack frame.
496     CallStackFrame *Caller;
497 
498     /// Callee - The function which was called.
499     const FunctionDecl *Callee;
500 
501     /// This - The binding for the this pointer in this call, if any.
502     const LValue *This;
503 
504     /// Arguments - Parameter bindings for this function call, indexed by
505     /// parameters' function scope indices.
506     APValue *Arguments;
507 
508     /// Source location information about the default argument or default
509     /// initializer expression we're evaluating, if any.
510     CurrentSourceLocExprScope CurSourceLocExprScope;
511 
512     // Note that we intentionally use std::map here so that references to
513     // values are stable.
514     typedef std::pair<const void *, unsigned> MapKeyTy;
515     typedef std::map<MapKeyTy, APValue> MapTy;
516     /// Temporaries - Temporary lvalues materialized within this stack frame.
517     MapTy Temporaries;
518 
519     /// CallLoc - The location of the call expression for this call.
520     SourceLocation CallLoc;
521 
522     /// Index - The call index of this call.
523     unsigned Index;
524 
525     /// The stack of integers for tracking version numbers for temporaries.
526     SmallVector<unsigned, 2> TempVersionStack = {1};
527     unsigned CurTempVersion = TempVersionStack.back();
528 
529     unsigned getTempVersion() const { return TempVersionStack.back(); }
530 
531     void pushTempVersion() {
532       TempVersionStack.push_back(++CurTempVersion);
533     }
534 
535     void popTempVersion() {
536       TempVersionStack.pop_back();
537     }
538 
539     // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
540     // on the overall stack usage of deeply-recursing constexpr evaluations.
541     // (We should cache this map rather than recomputing it repeatedly.)
542     // But let's try this and see how it goes; we can look into caching the map
543     // as a later change.
544 
545     /// LambdaCaptureFields - Mapping from captured variables/this to
546     /// corresponding data members in the closure class.
547     llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
548     FieldDecl *LambdaThisCaptureField;
549 
550     CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
551                    const FunctionDecl *Callee, const LValue *This,
552                    APValue *Arguments);
553     ~CallStackFrame();
554 
555     // Return the temporary for Key whose version number is Version.
556     APValue *getTemporary(const void *Key, unsigned Version) {
557       MapKeyTy KV(Key, Version);
558       auto LB = Temporaries.lower_bound(KV);
559       if (LB != Temporaries.end() && LB->first == KV)
560         return &LB->second;
561       // Pair (Key,Version) wasn't found in the map. Check that no elements
562       // in the map have 'Key' as their key.
563       assert((LB == Temporaries.end() || LB->first.first != Key) &&
564              (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
565              "Element with key 'Key' found in map");
566       return nullptr;
567     }
568 
569     // Return the current temporary for Key in the map.
570     APValue *getCurrentTemporary(const void *Key) {
571       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
572       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
573         return &std::prev(UB)->second;
574       return nullptr;
575     }
576 
577     // Return the version number of the current temporary for Key.
578     unsigned getCurrentTemporaryVersion(const void *Key) const {
579       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
580       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
581         return std::prev(UB)->first.second;
582       return 0;
583     }
584 
585     /// Allocate storage for an object of type T in this stack frame.
586     /// Populates LV with a handle to the created object. Key identifies
587     /// the temporary within the stack frame, and must not be reused without
588     /// bumping the temporary version number.
589     template<typename KeyT>
590     APValue &createTemporary(const KeyT *Key, QualType T,
591                              bool IsLifetimeExtended, LValue &LV);
592 
593     void describe(llvm::raw_ostream &OS) override;
594 
595     Frame *getCaller() const override { return Caller; }
596     SourceLocation getCallLocation() const override { return CallLoc; }
597     const FunctionDecl *getCallee() const override { return Callee; }
598 
599     bool isStdFunction() const {
600       for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
601         if (DC->isStdNamespace())
602           return true;
603       return false;
604     }
605   };
606 
607   /// Temporarily override 'this'.
608   class ThisOverrideRAII {
609   public:
610     ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
611         : Frame(Frame), OldThis(Frame.This) {
612       if (Enable)
613         Frame.This = NewThis;
614     }
615     ~ThisOverrideRAII() {
616       Frame.This = OldThis;
617     }
618   private:
619     CallStackFrame &Frame;
620     const LValue *OldThis;
621   };
622 }
623 
624 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
625                               const LValue &This, QualType ThisType);
626 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
627                               APValue::LValueBase LVBase, APValue &Value,
628                               QualType T);
629 
630 namespace {
631   /// A cleanup, and a flag indicating whether it is lifetime-extended.
632   class Cleanup {
633     llvm::PointerIntPair<APValue*, 1, bool> Value;
634     APValue::LValueBase Base;
635     QualType T;
636 
637   public:
638     Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
639             bool IsLifetimeExtended)
640         : Value(Val, IsLifetimeExtended), Base(Base), T(T) {}
641 
642     bool isLifetimeExtended() const { return Value.getInt(); }
643     bool endLifetime(EvalInfo &Info, bool RunDestructors) {
644       if (RunDestructors) {
645         SourceLocation Loc;
646         if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
647           Loc = VD->getLocation();
648         else if (const Expr *E = Base.dyn_cast<const Expr*>())
649           Loc = E->getExprLoc();
650         return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
651       }
652       *Value.getPointer() = APValue();
653       return true;
654     }
655 
656     bool hasSideEffect() {
657       return T.isDestructedType();
658     }
659   };
660 
661   /// A reference to an object whose construction we are currently evaluating.
662   struct ObjectUnderConstruction {
663     APValue::LValueBase Base;
664     ArrayRef<APValue::LValuePathEntry> Path;
665     friend bool operator==(const ObjectUnderConstruction &LHS,
666                            const ObjectUnderConstruction &RHS) {
667       return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
668     }
669     friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
670       return llvm::hash_combine(Obj.Base, Obj.Path);
671     }
672   };
673   enum class ConstructionPhase {
674     None,
675     Bases,
676     AfterBases,
677     Destroying,
678     DestroyingBases
679   };
680 }
681 
682 namespace llvm {
683 template<> struct DenseMapInfo<ObjectUnderConstruction> {
684   using Base = DenseMapInfo<APValue::LValueBase>;
685   static ObjectUnderConstruction getEmptyKey() {
686     return {Base::getEmptyKey(), {}}; }
687   static ObjectUnderConstruction getTombstoneKey() {
688     return {Base::getTombstoneKey(), {}};
689   }
690   static unsigned getHashValue(const ObjectUnderConstruction &Object) {
691     return hash_value(Object);
692   }
693   static bool isEqual(const ObjectUnderConstruction &LHS,
694                       const ObjectUnderConstruction &RHS) {
695     return LHS == RHS;
696   }
697 };
698 }
699 
700 namespace {
701   /// A dynamically-allocated heap object.
702   struct DynAlloc {
703     /// The value of this heap-allocated object.
704     APValue Value;
705     /// The allocating expression; used for diagnostics. Either a CXXNewExpr
706     /// or a CallExpr (the latter is for direct calls to operator new inside
707     /// std::allocator<T>::allocate).
708     const Expr *AllocExpr = nullptr;
709 
710     enum Kind {
711       New,
712       ArrayNew,
713       StdAllocator
714     };
715 
716     /// Get the kind of the allocation. This must match between allocation
717     /// and deallocation.
718     Kind getKind() const {
719       if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
720         return NE->isArray() ? ArrayNew : New;
721       assert(isa<CallExpr>(AllocExpr));
722       return StdAllocator;
723     }
724   };
725 
726   struct DynAllocOrder {
727     bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
728       return L.getIndex() < R.getIndex();
729     }
730   };
731 
732   /// EvalInfo - This is a private struct used by the evaluator to capture
733   /// information about a subexpression as it is folded.  It retains information
734   /// about the AST context, but also maintains information about the folded
735   /// expression.
736   ///
737   /// If an expression could be evaluated, it is still possible it is not a C
738   /// "integer constant expression" or constant expression.  If not, this struct
739   /// captures information about how and why not.
740   ///
741   /// One bit of information passed *into* the request for constant folding
742   /// indicates whether the subexpression is "evaluated" or not according to C
743   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
744   /// evaluate the expression regardless of what the RHS is, but C only allows
745   /// certain things in certain situations.
746   class EvalInfo : public interp::State {
747   public:
748     ASTContext &Ctx;
749 
750     /// EvalStatus - Contains information about the evaluation.
751     Expr::EvalStatus &EvalStatus;
752 
753     /// CurrentCall - The top of the constexpr call stack.
754     CallStackFrame *CurrentCall;
755 
756     /// CallStackDepth - The number of calls in the call stack right now.
757     unsigned CallStackDepth;
758 
759     /// NextCallIndex - The next call index to assign.
760     unsigned NextCallIndex;
761 
762     /// StepsLeft - The remaining number of evaluation steps we're permitted
763     /// to perform. This is essentially a limit for the number of statements
764     /// we will evaluate.
765     unsigned StepsLeft;
766 
767     /// Enable the experimental new constant interpreter. If an expression is
768     /// not supported by the interpreter, an error is triggered.
769     bool EnableNewConstInterp;
770 
771     /// BottomFrame - The frame in which evaluation started. This must be
772     /// initialized after CurrentCall and CallStackDepth.
773     CallStackFrame BottomFrame;
774 
775     /// A stack of values whose lifetimes end at the end of some surrounding
776     /// evaluation frame.
777     llvm::SmallVector<Cleanup, 16> CleanupStack;
778 
779     /// EvaluatingDecl - This is the declaration whose initializer is being
780     /// evaluated, if any.
781     APValue::LValueBase EvaluatingDecl;
782 
783     enum class EvaluatingDeclKind {
784       None,
785       /// We're evaluating the construction of EvaluatingDecl.
786       Ctor,
787       /// We're evaluating the destruction of EvaluatingDecl.
788       Dtor,
789     };
790     EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
791 
792     /// EvaluatingDeclValue - This is the value being constructed for the
793     /// declaration whose initializer is being evaluated, if any.
794     APValue *EvaluatingDeclValue;
795 
796     /// Set of objects that are currently being constructed.
797     llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
798         ObjectsUnderConstruction;
799 
800     /// Current heap allocations, along with the location where each was
801     /// allocated. We use std::map here because we need stable addresses
802     /// for the stored APValues.
803     std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
804 
805     /// The number of heap allocations performed so far in this evaluation.
806     unsigned NumHeapAllocs = 0;
807 
808     struct EvaluatingConstructorRAII {
809       EvalInfo &EI;
810       ObjectUnderConstruction Object;
811       bool DidInsert;
812       EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
813                                 bool HasBases)
814           : EI(EI), Object(Object) {
815         DidInsert =
816             EI.ObjectsUnderConstruction
817                 .insert({Object, HasBases ? ConstructionPhase::Bases
818                                           : ConstructionPhase::AfterBases})
819                 .second;
820       }
821       void finishedConstructingBases() {
822         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
823       }
824       ~EvaluatingConstructorRAII() {
825         if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
826       }
827     };
828 
829     struct EvaluatingDestructorRAII {
830       EvalInfo &EI;
831       ObjectUnderConstruction Object;
832       bool DidInsert;
833       EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
834           : EI(EI), Object(Object) {
835         DidInsert = EI.ObjectsUnderConstruction
836                         .insert({Object, ConstructionPhase::Destroying})
837                         .second;
838       }
839       void startedDestroyingBases() {
840         EI.ObjectsUnderConstruction[Object] =
841             ConstructionPhase::DestroyingBases;
842       }
843       ~EvaluatingDestructorRAII() {
844         if (DidInsert)
845           EI.ObjectsUnderConstruction.erase(Object);
846       }
847     };
848 
849     ConstructionPhase
850     isEvaluatingCtorDtor(APValue::LValueBase Base,
851                          ArrayRef<APValue::LValuePathEntry> Path) {
852       return ObjectsUnderConstruction.lookup({Base, Path});
853     }
854 
855     /// If we're currently speculatively evaluating, the outermost call stack
856     /// depth at which we can mutate state, otherwise 0.
857     unsigned SpeculativeEvaluationDepth = 0;
858 
859     /// The current array initialization index, if we're performing array
860     /// initialization.
861     uint64_t ArrayInitIndex = -1;
862 
863     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
864     /// notes attached to it will also be stored, otherwise they will not be.
865     bool HasActiveDiagnostic;
866 
867     /// Have we emitted a diagnostic explaining why we couldn't constant
868     /// fold (not just why it's not strictly a constant expression)?
869     bool HasFoldFailureDiagnostic;
870 
871     /// Whether or not we're in a context where the front end requires a
872     /// constant value.
873     bool InConstantContext;
874 
875     /// Whether we're checking that an expression is a potential constant
876     /// expression. If so, do not fail on constructs that could become constant
877     /// later on (such as a use of an undefined global).
878     bool CheckingPotentialConstantExpression = false;
879 
880     /// Whether we're checking for an expression that has undefined behavior.
881     /// If so, we will produce warnings if we encounter an operation that is
882     /// always undefined.
883     bool CheckingForUndefinedBehavior = false;
884 
885     enum EvaluationMode {
886       /// Evaluate as a constant expression. Stop if we find that the expression
887       /// is not a constant expression.
888       EM_ConstantExpression,
889 
890       /// Evaluate as a constant expression. Stop if we find that the expression
891       /// is not a constant expression. Some expressions can be retried in the
892       /// optimizer if we don't constant fold them here, but in an unevaluated
893       /// context we try to fold them immediately since the optimizer never
894       /// gets a chance to look at it.
895       EM_ConstantExpressionUnevaluated,
896 
897       /// Fold the expression to a constant. Stop if we hit a side-effect that
898       /// we can't model.
899       EM_ConstantFold,
900 
901       /// Evaluate in any way we know how. Don't worry about side-effects that
902       /// can't be modeled.
903       EM_IgnoreSideEffects,
904     } EvalMode;
905 
906     /// Are we checking whether the expression is a potential constant
907     /// expression?
908     bool checkingPotentialConstantExpression() const override  {
909       return CheckingPotentialConstantExpression;
910     }
911 
912     /// Are we checking an expression for overflow?
913     // FIXME: We should check for any kind of undefined or suspicious behavior
914     // in such constructs, not just overflow.
915     bool checkingForUndefinedBehavior() const override {
916       return CheckingForUndefinedBehavior;
917     }
918 
919     EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
920         : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
921           CallStackDepth(0), NextCallIndex(1),
922           StepsLeft(C.getLangOpts().ConstexprStepLimit),
923           EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
924           BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
925           EvaluatingDecl((const ValueDecl *)nullptr),
926           EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
927           HasFoldFailureDiagnostic(false), InConstantContext(false),
928           EvalMode(Mode) {}
929 
930     ~EvalInfo() {
931       discardCleanups();
932     }
933 
934     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
935                            EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
936       EvaluatingDecl = Base;
937       IsEvaluatingDecl = EDK;
938       EvaluatingDeclValue = &Value;
939     }
940 
941     bool CheckCallLimit(SourceLocation Loc) {
942       // Don't perform any constexpr calls (other than the call we're checking)
943       // when checking a potential constant expression.
944       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
945         return false;
946       if (NextCallIndex == 0) {
947         // NextCallIndex has wrapped around.
948         FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
949         return false;
950       }
951       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
952         return true;
953       FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
954         << getLangOpts().ConstexprCallDepth;
955       return false;
956     }
957 
958     std::pair<CallStackFrame *, unsigned>
959     getCallFrameAndDepth(unsigned CallIndex) {
960       assert(CallIndex && "no call index in getCallFrameAndDepth");
961       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
962       // be null in this loop.
963       unsigned Depth = CallStackDepth;
964       CallStackFrame *Frame = CurrentCall;
965       while (Frame->Index > CallIndex) {
966         Frame = Frame->Caller;
967         --Depth;
968       }
969       if (Frame->Index == CallIndex)
970         return {Frame, Depth};
971       return {nullptr, 0};
972     }
973 
974     bool nextStep(const Stmt *S) {
975       if (!StepsLeft) {
976         FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
977         return false;
978       }
979       --StepsLeft;
980       return true;
981     }
982 
983     APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
984 
985     Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) {
986       Optional<DynAlloc*> Result;
987       auto It = HeapAllocs.find(DA);
988       if (It != HeapAllocs.end())
989         Result = &It->second;
990       return Result;
991     }
992 
993     /// Information about a stack frame for std::allocator<T>::[de]allocate.
994     struct StdAllocatorCaller {
995       unsigned FrameIndex;
996       QualType ElemType;
997       explicit operator bool() const { return FrameIndex != 0; };
998     };
999 
1000     StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1001       for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1002            Call = Call->Caller) {
1003         const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1004         if (!MD)
1005           continue;
1006         const IdentifierInfo *FnII = MD->getIdentifier();
1007         if (!FnII || !FnII->isStr(FnName))
1008           continue;
1009 
1010         const auto *CTSD =
1011             dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1012         if (!CTSD)
1013           continue;
1014 
1015         const IdentifierInfo *ClassII = CTSD->getIdentifier();
1016         const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1017         if (CTSD->isInStdNamespace() && ClassII &&
1018             ClassII->isStr("allocator") && TAL.size() >= 1 &&
1019             TAL[0].getKind() == TemplateArgument::Type)
1020           return {Call->Index, TAL[0].getAsType()};
1021       }
1022 
1023       return {};
1024     }
1025 
1026     void performLifetimeExtension() {
1027       // Disable the cleanups for lifetime-extended temporaries.
1028       CleanupStack.erase(
1029           std::remove_if(CleanupStack.begin(), CleanupStack.end(),
1030                          [](Cleanup &C) { return C.isLifetimeExtended(); }),
1031           CleanupStack.end());
1032      }
1033 
1034     /// Throw away any remaining cleanups at the end of evaluation. If any
1035     /// cleanups would have had a side-effect, note that as an unmodeled
1036     /// side-effect and return false. Otherwise, return true.
1037     bool discardCleanups() {
1038       for (Cleanup &C : CleanupStack) {
1039         if (C.hasSideEffect() && !noteSideEffect()) {
1040           CleanupStack.clear();
1041           return false;
1042         }
1043       }
1044       CleanupStack.clear();
1045       return true;
1046     }
1047 
1048   private:
1049     interp::Frame *getCurrentFrame() override { return CurrentCall; }
1050     const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1051 
1052     bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1053     void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1054 
1055     void setFoldFailureDiagnostic(bool Flag) override {
1056       HasFoldFailureDiagnostic = Flag;
1057     }
1058 
1059     Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1060 
1061     ASTContext &getCtx() const override { return Ctx; }
1062 
1063     // If we have a prior diagnostic, it will be noting that the expression
1064     // isn't a constant expression. This diagnostic is more important,
1065     // unless we require this evaluation to produce a constant expression.
1066     //
1067     // FIXME: We might want to show both diagnostics to the user in
1068     // EM_ConstantFold mode.
1069     bool hasPriorDiagnostic() override {
1070       if (!EvalStatus.Diag->empty()) {
1071         switch (EvalMode) {
1072         case EM_ConstantFold:
1073         case EM_IgnoreSideEffects:
1074           if (!HasFoldFailureDiagnostic)
1075             break;
1076           // We've already failed to fold something. Keep that diagnostic.
1077           LLVM_FALLTHROUGH;
1078         case EM_ConstantExpression:
1079         case EM_ConstantExpressionUnevaluated:
1080           setActiveDiagnostic(false);
1081           return true;
1082         }
1083       }
1084       return false;
1085     }
1086 
1087     unsigned getCallStackDepth() override { return CallStackDepth; }
1088 
1089   public:
1090     /// Should we continue evaluation after encountering a side-effect that we
1091     /// couldn't model?
1092     bool keepEvaluatingAfterSideEffect() {
1093       switch (EvalMode) {
1094       case EM_IgnoreSideEffects:
1095         return true;
1096 
1097       case EM_ConstantExpression:
1098       case EM_ConstantExpressionUnevaluated:
1099       case EM_ConstantFold:
1100         // By default, assume any side effect might be valid in some other
1101         // evaluation of this expression from a different context.
1102         return checkingPotentialConstantExpression() ||
1103                checkingForUndefinedBehavior();
1104       }
1105       llvm_unreachable("Missed EvalMode case");
1106     }
1107 
1108     /// Note that we have had a side-effect, and determine whether we should
1109     /// keep evaluating.
1110     bool noteSideEffect() {
1111       EvalStatus.HasSideEffects = true;
1112       return keepEvaluatingAfterSideEffect();
1113     }
1114 
1115     /// Should we continue evaluation after encountering undefined behavior?
1116     bool keepEvaluatingAfterUndefinedBehavior() {
1117       switch (EvalMode) {
1118       case EM_IgnoreSideEffects:
1119       case EM_ConstantFold:
1120         return true;
1121 
1122       case EM_ConstantExpression:
1123       case EM_ConstantExpressionUnevaluated:
1124         return checkingForUndefinedBehavior();
1125       }
1126       llvm_unreachable("Missed EvalMode case");
1127     }
1128 
1129     /// Note that we hit something that was technically undefined behavior, but
1130     /// that we can evaluate past it (such as signed overflow or floating-point
1131     /// division by zero.)
1132     bool noteUndefinedBehavior() override {
1133       EvalStatus.HasUndefinedBehavior = true;
1134       return keepEvaluatingAfterUndefinedBehavior();
1135     }
1136 
1137     /// Should we continue evaluation as much as possible after encountering a
1138     /// construct which can't be reduced to a value?
1139     bool keepEvaluatingAfterFailure() const override {
1140       if (!StepsLeft)
1141         return false;
1142 
1143       switch (EvalMode) {
1144       case EM_ConstantExpression:
1145       case EM_ConstantExpressionUnevaluated:
1146       case EM_ConstantFold:
1147       case EM_IgnoreSideEffects:
1148         return checkingPotentialConstantExpression() ||
1149                checkingForUndefinedBehavior();
1150       }
1151       llvm_unreachable("Missed EvalMode case");
1152     }
1153 
1154     /// Notes that we failed to evaluate an expression that other expressions
1155     /// directly depend on, and determine if we should keep evaluating. This
1156     /// should only be called if we actually intend to keep evaluating.
1157     ///
1158     /// Call noteSideEffect() instead if we may be able to ignore the value that
1159     /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1160     ///
1161     /// (Foo(), 1)      // use noteSideEffect
1162     /// (Foo() || true) // use noteSideEffect
1163     /// Foo() + 1       // use noteFailure
1164     LLVM_NODISCARD bool noteFailure() {
1165       // Failure when evaluating some expression often means there is some
1166       // subexpression whose evaluation was skipped. Therefore, (because we
1167       // don't track whether we skipped an expression when unwinding after an
1168       // evaluation failure) every evaluation failure that bubbles up from a
1169       // subexpression implies that a side-effect has potentially happened. We
1170       // skip setting the HasSideEffects flag to true until we decide to
1171       // continue evaluating after that point, which happens here.
1172       bool KeepGoing = keepEvaluatingAfterFailure();
1173       EvalStatus.HasSideEffects |= KeepGoing;
1174       return KeepGoing;
1175     }
1176 
1177     class ArrayInitLoopIndex {
1178       EvalInfo &Info;
1179       uint64_t OuterIndex;
1180 
1181     public:
1182       ArrayInitLoopIndex(EvalInfo &Info)
1183           : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1184         Info.ArrayInitIndex = 0;
1185       }
1186       ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1187 
1188       operator uint64_t&() { return Info.ArrayInitIndex; }
1189     };
1190   };
1191 
1192   /// Object used to treat all foldable expressions as constant expressions.
1193   struct FoldConstant {
1194     EvalInfo &Info;
1195     bool Enabled;
1196     bool HadNoPriorDiags;
1197     EvalInfo::EvaluationMode OldMode;
1198 
1199     explicit FoldConstant(EvalInfo &Info, bool Enabled)
1200       : Info(Info),
1201         Enabled(Enabled),
1202         HadNoPriorDiags(Info.EvalStatus.Diag &&
1203                         Info.EvalStatus.Diag->empty() &&
1204                         !Info.EvalStatus.HasSideEffects),
1205         OldMode(Info.EvalMode) {
1206       if (Enabled)
1207         Info.EvalMode = EvalInfo::EM_ConstantFold;
1208     }
1209     void keepDiagnostics() { Enabled = false; }
1210     ~FoldConstant() {
1211       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1212           !Info.EvalStatus.HasSideEffects)
1213         Info.EvalStatus.Diag->clear();
1214       Info.EvalMode = OldMode;
1215     }
1216   };
1217 
1218   /// RAII object used to set the current evaluation mode to ignore
1219   /// side-effects.
1220   struct IgnoreSideEffectsRAII {
1221     EvalInfo &Info;
1222     EvalInfo::EvaluationMode OldMode;
1223     explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1224         : Info(Info), OldMode(Info.EvalMode) {
1225       Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1226     }
1227 
1228     ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1229   };
1230 
1231   /// RAII object used to optionally suppress diagnostics and side-effects from
1232   /// a speculative evaluation.
1233   class SpeculativeEvaluationRAII {
1234     EvalInfo *Info = nullptr;
1235     Expr::EvalStatus OldStatus;
1236     unsigned OldSpeculativeEvaluationDepth;
1237 
1238     void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1239       Info = Other.Info;
1240       OldStatus = Other.OldStatus;
1241       OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1242       Other.Info = nullptr;
1243     }
1244 
1245     void maybeRestoreState() {
1246       if (!Info)
1247         return;
1248 
1249       Info->EvalStatus = OldStatus;
1250       Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1251     }
1252 
1253   public:
1254     SpeculativeEvaluationRAII() = default;
1255 
1256     SpeculativeEvaluationRAII(
1257         EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1258         : Info(&Info), OldStatus(Info.EvalStatus),
1259           OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1260       Info.EvalStatus.Diag = NewDiag;
1261       Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1262     }
1263 
1264     SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1265     SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1266       moveFromAndCancel(std::move(Other));
1267     }
1268 
1269     SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1270       maybeRestoreState();
1271       moveFromAndCancel(std::move(Other));
1272       return *this;
1273     }
1274 
1275     ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1276   };
1277 
1278   /// RAII object wrapping a full-expression or block scope, and handling
1279   /// the ending of the lifetime of temporaries created within it.
1280   template<bool IsFullExpression>
1281   class ScopeRAII {
1282     EvalInfo &Info;
1283     unsigned OldStackSize;
1284   public:
1285     ScopeRAII(EvalInfo &Info)
1286         : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1287       // Push a new temporary version. This is needed to distinguish between
1288       // temporaries created in different iterations of a loop.
1289       Info.CurrentCall->pushTempVersion();
1290     }
1291     bool destroy(bool RunDestructors = true) {
1292       bool OK = cleanup(Info, RunDestructors, OldStackSize);
1293       OldStackSize = -1U;
1294       return OK;
1295     }
1296     ~ScopeRAII() {
1297       if (OldStackSize != -1U)
1298         destroy(false);
1299       // Body moved to a static method to encourage the compiler to inline away
1300       // instances of this class.
1301       Info.CurrentCall->popTempVersion();
1302     }
1303   private:
1304     static bool cleanup(EvalInfo &Info, bool RunDestructors,
1305                         unsigned OldStackSize) {
1306       assert(OldStackSize <= Info.CleanupStack.size() &&
1307              "running cleanups out of order?");
1308 
1309       // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1310       // for a full-expression scope.
1311       bool Success = true;
1312       for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1313         if (!(IsFullExpression &&
1314               Info.CleanupStack[I - 1].isLifetimeExtended())) {
1315           if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1316             Success = false;
1317             break;
1318           }
1319         }
1320       }
1321 
1322       // Compact lifetime-extended cleanups.
1323       auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1324       if (IsFullExpression)
1325         NewEnd =
1326             std::remove_if(NewEnd, Info.CleanupStack.end(),
1327                            [](Cleanup &C) { return !C.isLifetimeExtended(); });
1328       Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1329       return Success;
1330     }
1331   };
1332   typedef ScopeRAII<false> BlockScopeRAII;
1333   typedef ScopeRAII<true> FullExpressionRAII;
1334 }
1335 
1336 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1337                                          CheckSubobjectKind CSK) {
1338   if (Invalid)
1339     return false;
1340   if (isOnePastTheEnd()) {
1341     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1342       << CSK;
1343     setInvalid();
1344     return false;
1345   }
1346   // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1347   // must actually be at least one array element; even a VLA cannot have a
1348   // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1349   return true;
1350 }
1351 
1352 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1353                                                                 const Expr *E) {
1354   Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1355   // Do not set the designator as invalid: we can represent this situation,
1356   // and correct handling of __builtin_object_size requires us to do so.
1357 }
1358 
1359 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1360                                                     const Expr *E,
1361                                                     const APSInt &N) {
1362   // If we're complaining, we must be able to statically determine the size of
1363   // the most derived array.
1364   if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1365     Info.CCEDiag(E, diag::note_constexpr_array_index)
1366       << N << /*array*/ 0
1367       << static_cast<unsigned>(getMostDerivedArraySize());
1368   else
1369     Info.CCEDiag(E, diag::note_constexpr_array_index)
1370       << N << /*non-array*/ 1;
1371   setInvalid();
1372 }
1373 
1374 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1375                                const FunctionDecl *Callee, const LValue *This,
1376                                APValue *Arguments)
1377     : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1378       Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1379   Info.CurrentCall = this;
1380   ++Info.CallStackDepth;
1381 }
1382 
1383 CallStackFrame::~CallStackFrame() {
1384   assert(Info.CurrentCall == this && "calls retired out of order");
1385   --Info.CallStackDepth;
1386   Info.CurrentCall = Caller;
1387 }
1388 
1389 static bool isRead(AccessKinds AK) {
1390   return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1391 }
1392 
1393 static bool isModification(AccessKinds AK) {
1394   switch (AK) {
1395   case AK_Read:
1396   case AK_ReadObjectRepresentation:
1397   case AK_MemberCall:
1398   case AK_DynamicCast:
1399   case AK_TypeId:
1400     return false;
1401   case AK_Assign:
1402   case AK_Increment:
1403   case AK_Decrement:
1404   case AK_Construct:
1405   case AK_Destroy:
1406     return true;
1407   }
1408   llvm_unreachable("unknown access kind");
1409 }
1410 
1411 static bool isAnyAccess(AccessKinds AK) {
1412   return isRead(AK) || isModification(AK);
1413 }
1414 
1415 /// Is this an access per the C++ definition?
1416 static bool isFormalAccess(AccessKinds AK) {
1417   return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
1418 }
1419 
1420 namespace {
1421   struct ComplexValue {
1422   private:
1423     bool IsInt;
1424 
1425   public:
1426     APSInt IntReal, IntImag;
1427     APFloat FloatReal, FloatImag;
1428 
1429     ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1430 
1431     void makeComplexFloat() { IsInt = false; }
1432     bool isComplexFloat() const { return !IsInt; }
1433     APFloat &getComplexFloatReal() { return FloatReal; }
1434     APFloat &getComplexFloatImag() { return FloatImag; }
1435 
1436     void makeComplexInt() { IsInt = true; }
1437     bool isComplexInt() const { return IsInt; }
1438     APSInt &getComplexIntReal() { return IntReal; }
1439     APSInt &getComplexIntImag() { return IntImag; }
1440 
1441     void moveInto(APValue &v) const {
1442       if (isComplexFloat())
1443         v = APValue(FloatReal, FloatImag);
1444       else
1445         v = APValue(IntReal, IntImag);
1446     }
1447     void setFrom(const APValue &v) {
1448       assert(v.isComplexFloat() || v.isComplexInt());
1449       if (v.isComplexFloat()) {
1450         makeComplexFloat();
1451         FloatReal = v.getComplexFloatReal();
1452         FloatImag = v.getComplexFloatImag();
1453       } else {
1454         makeComplexInt();
1455         IntReal = v.getComplexIntReal();
1456         IntImag = v.getComplexIntImag();
1457       }
1458     }
1459   };
1460 
1461   struct LValue {
1462     APValue::LValueBase Base;
1463     CharUnits Offset;
1464     SubobjectDesignator Designator;
1465     bool IsNullPtr : 1;
1466     bool InvalidBase : 1;
1467 
1468     const APValue::LValueBase getLValueBase() const { return Base; }
1469     CharUnits &getLValueOffset() { return Offset; }
1470     const CharUnits &getLValueOffset() const { return Offset; }
1471     SubobjectDesignator &getLValueDesignator() { return Designator; }
1472     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1473     bool isNullPointer() const { return IsNullPtr;}
1474 
1475     unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1476     unsigned getLValueVersion() const { return Base.getVersion(); }
1477 
1478     void moveInto(APValue &V) const {
1479       if (Designator.Invalid)
1480         V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1481       else {
1482         assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1483         V = APValue(Base, Offset, Designator.Entries,
1484                     Designator.IsOnePastTheEnd, IsNullPtr);
1485       }
1486     }
1487     void setFrom(ASTContext &Ctx, const APValue &V) {
1488       assert(V.isLValue() && "Setting LValue from a non-LValue?");
1489       Base = V.getLValueBase();
1490       Offset = V.getLValueOffset();
1491       InvalidBase = false;
1492       Designator = SubobjectDesignator(Ctx, V);
1493       IsNullPtr = V.isNullPointer();
1494     }
1495 
1496     void set(APValue::LValueBase B, bool BInvalid = false) {
1497 #ifndef NDEBUG
1498       // We only allow a few types of invalid bases. Enforce that here.
1499       if (BInvalid) {
1500         const auto *E = B.get<const Expr *>();
1501         assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1502                "Unexpected type of invalid base");
1503       }
1504 #endif
1505 
1506       Base = B;
1507       Offset = CharUnits::fromQuantity(0);
1508       InvalidBase = BInvalid;
1509       Designator = SubobjectDesignator(getType(B));
1510       IsNullPtr = false;
1511     }
1512 
1513     void setNull(ASTContext &Ctx, QualType PointerTy) {
1514       Base = (Expr *)nullptr;
1515       Offset =
1516           CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
1517       InvalidBase = false;
1518       Designator = SubobjectDesignator(PointerTy->getPointeeType());
1519       IsNullPtr = true;
1520     }
1521 
1522     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1523       set(B, true);
1524     }
1525 
1526     std::string toString(ASTContext &Ctx, QualType T) const {
1527       APValue Printable;
1528       moveInto(Printable);
1529       return Printable.getAsString(Ctx, T);
1530     }
1531 
1532   private:
1533     // Check that this LValue is not based on a null pointer. If it is, produce
1534     // a diagnostic and mark the designator as invalid.
1535     template <typename GenDiagType>
1536     bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1537       if (Designator.Invalid)
1538         return false;
1539       if (IsNullPtr) {
1540         GenDiag();
1541         Designator.setInvalid();
1542         return false;
1543       }
1544       return true;
1545     }
1546 
1547   public:
1548     bool checkNullPointer(EvalInfo &Info, const Expr *E,
1549                           CheckSubobjectKind CSK) {
1550       return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1551         Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1552       });
1553     }
1554 
1555     bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1556                                        AccessKinds AK) {
1557       return checkNullPointerDiagnosingWith([&Info, E, AK] {
1558         Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1559       });
1560     }
1561 
1562     // Check this LValue refers to an object. If not, set the designator to be
1563     // invalid and emit a diagnostic.
1564     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1565       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1566              Designator.checkSubobject(Info, E, CSK);
1567     }
1568 
1569     void addDecl(EvalInfo &Info, const Expr *E,
1570                  const Decl *D, bool Virtual = false) {
1571       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1572         Designator.addDeclUnchecked(D, Virtual);
1573     }
1574     void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1575       if (!Designator.Entries.empty()) {
1576         Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1577         Designator.setInvalid();
1578         return;
1579       }
1580       if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1581         assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1582         Designator.FirstEntryIsAnUnsizedArray = true;
1583         Designator.addUnsizedArrayUnchecked(ElemTy);
1584       }
1585     }
1586     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1587       if (checkSubobject(Info, E, CSK_ArrayToPointer))
1588         Designator.addArrayUnchecked(CAT);
1589     }
1590     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1591       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1592         Designator.addComplexUnchecked(EltTy, Imag);
1593     }
1594     void clearIsNullPointer() {
1595       IsNullPtr = false;
1596     }
1597     void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1598                               const APSInt &Index, CharUnits ElementSize) {
1599       // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1600       // but we're not required to diagnose it and it's valid in C++.)
1601       if (!Index)
1602         return;
1603 
1604       // Compute the new offset in the appropriate width, wrapping at 64 bits.
1605       // FIXME: When compiling for a 32-bit target, we should use 32-bit
1606       // offsets.
1607       uint64_t Offset64 = Offset.getQuantity();
1608       uint64_t ElemSize64 = ElementSize.getQuantity();
1609       uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1610       Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1611 
1612       if (checkNullPointer(Info, E, CSK_ArrayIndex))
1613         Designator.adjustIndex(Info, E, Index);
1614       clearIsNullPointer();
1615     }
1616     void adjustOffset(CharUnits N) {
1617       Offset += N;
1618       if (N.getQuantity())
1619         clearIsNullPointer();
1620     }
1621   };
1622 
1623   struct MemberPtr {
1624     MemberPtr() {}
1625     explicit MemberPtr(const ValueDecl *Decl) :
1626       DeclAndIsDerivedMember(Decl, false), Path() {}
1627 
1628     /// The member or (direct or indirect) field referred to by this member
1629     /// pointer, or 0 if this is a null member pointer.
1630     const ValueDecl *getDecl() const {
1631       return DeclAndIsDerivedMember.getPointer();
1632     }
1633     /// Is this actually a member of some type derived from the relevant class?
1634     bool isDerivedMember() const {
1635       return DeclAndIsDerivedMember.getInt();
1636     }
1637     /// Get the class which the declaration actually lives in.
1638     const CXXRecordDecl *getContainingRecord() const {
1639       return cast<CXXRecordDecl>(
1640           DeclAndIsDerivedMember.getPointer()->getDeclContext());
1641     }
1642 
1643     void moveInto(APValue &V) const {
1644       V = APValue(getDecl(), isDerivedMember(), Path);
1645     }
1646     void setFrom(const APValue &V) {
1647       assert(V.isMemberPointer());
1648       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1649       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1650       Path.clear();
1651       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1652       Path.insert(Path.end(), P.begin(), P.end());
1653     }
1654 
1655     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1656     /// whether the member is a member of some class derived from the class type
1657     /// of the member pointer.
1658     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1659     /// Path - The path of base/derived classes from the member declaration's
1660     /// class (exclusive) to the class type of the member pointer (inclusive).
1661     SmallVector<const CXXRecordDecl*, 4> Path;
1662 
1663     /// Perform a cast towards the class of the Decl (either up or down the
1664     /// hierarchy).
1665     bool castBack(const CXXRecordDecl *Class) {
1666       assert(!Path.empty());
1667       const CXXRecordDecl *Expected;
1668       if (Path.size() >= 2)
1669         Expected = Path[Path.size() - 2];
1670       else
1671         Expected = getContainingRecord();
1672       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1673         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1674         // if B does not contain the original member and is not a base or
1675         // derived class of the class containing the original member, the result
1676         // of the cast is undefined.
1677         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1678         // (D::*). We consider that to be a language defect.
1679         return false;
1680       }
1681       Path.pop_back();
1682       return true;
1683     }
1684     /// Perform a base-to-derived member pointer cast.
1685     bool castToDerived(const CXXRecordDecl *Derived) {
1686       if (!getDecl())
1687         return true;
1688       if (!isDerivedMember()) {
1689         Path.push_back(Derived);
1690         return true;
1691       }
1692       if (!castBack(Derived))
1693         return false;
1694       if (Path.empty())
1695         DeclAndIsDerivedMember.setInt(false);
1696       return true;
1697     }
1698     /// Perform a derived-to-base member pointer cast.
1699     bool castToBase(const CXXRecordDecl *Base) {
1700       if (!getDecl())
1701         return true;
1702       if (Path.empty())
1703         DeclAndIsDerivedMember.setInt(true);
1704       if (isDerivedMember()) {
1705         Path.push_back(Base);
1706         return true;
1707       }
1708       return castBack(Base);
1709     }
1710   };
1711 
1712   /// Compare two member pointers, which are assumed to be of the same type.
1713   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1714     if (!LHS.getDecl() || !RHS.getDecl())
1715       return !LHS.getDecl() && !RHS.getDecl();
1716     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1717       return false;
1718     return LHS.Path == RHS.Path;
1719   }
1720 }
1721 
1722 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1723 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1724                             const LValue &This, const Expr *E,
1725                             bool AllowNonLiteralTypes = false);
1726 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1727                            bool InvalidBaseOK = false);
1728 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1729                             bool InvalidBaseOK = false);
1730 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1731                                   EvalInfo &Info);
1732 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1733 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1734 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1735                                     EvalInfo &Info);
1736 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1737 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1738 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1739                            EvalInfo &Info);
1740 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1741 
1742 /// Evaluate an integer or fixed point expression into an APResult.
1743 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1744                                         EvalInfo &Info);
1745 
1746 /// Evaluate only a fixed point expression into an APResult.
1747 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1748                                EvalInfo &Info);
1749 
1750 //===----------------------------------------------------------------------===//
1751 // Misc utilities
1752 //===----------------------------------------------------------------------===//
1753 
1754 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1755 /// preserving its value (by extending by up to one bit as needed).
1756 static void negateAsSigned(APSInt &Int) {
1757   if (Int.isUnsigned() || Int.isMinSignedValue()) {
1758     Int = Int.extend(Int.getBitWidth() + 1);
1759     Int.setIsSigned(true);
1760   }
1761   Int = -Int;
1762 }
1763 
1764 template<typename KeyT>
1765 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1766                                          bool IsLifetimeExtended, LValue &LV) {
1767   unsigned Version = getTempVersion();
1768   APValue::LValueBase Base(Key, Index, Version);
1769   LV.set(Base);
1770   APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1771   assert(Result.isAbsent() && "temporary created multiple times");
1772 
1773   // If we're creating a temporary immediately in the operand of a speculative
1774   // evaluation, don't register a cleanup to be run outside the speculative
1775   // evaluation context, since we won't actually be able to initialize this
1776   // object.
1777   if (Index <= Info.SpeculativeEvaluationDepth) {
1778     if (T.isDestructedType())
1779       Info.noteSideEffect();
1780   } else {
1781     Info.CleanupStack.push_back(Cleanup(&Result, Base, T, IsLifetimeExtended));
1782   }
1783   return Result;
1784 }
1785 
1786 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1787   if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1788     FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1789     return nullptr;
1790   }
1791 
1792   DynamicAllocLValue DA(NumHeapAllocs++);
1793   LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1794   auto Result = HeapAllocs.emplace(std::piecewise_construct,
1795                                    std::forward_as_tuple(DA), std::tuple<>());
1796   assert(Result.second && "reused a heap alloc index?");
1797   Result.first->second.AllocExpr = E;
1798   return &Result.first->second.Value;
1799 }
1800 
1801 /// Produce a string describing the given constexpr call.
1802 void CallStackFrame::describe(raw_ostream &Out) {
1803   unsigned ArgIndex = 0;
1804   bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1805                       !isa<CXXConstructorDecl>(Callee) &&
1806                       cast<CXXMethodDecl>(Callee)->isInstance();
1807 
1808   if (!IsMemberCall)
1809     Out << *Callee << '(';
1810 
1811   if (This && IsMemberCall) {
1812     APValue Val;
1813     This->moveInto(Val);
1814     Val.printPretty(Out, Info.Ctx,
1815                     This->Designator.MostDerivedType);
1816     // FIXME: Add parens around Val if needed.
1817     Out << "->" << *Callee << '(';
1818     IsMemberCall = false;
1819   }
1820 
1821   for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1822        E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
1823     if (ArgIndex > (unsigned)IsMemberCall)
1824       Out << ", ";
1825 
1826     const ParmVarDecl *Param = *I;
1827     const APValue &Arg = Arguments[ArgIndex];
1828     Arg.printPretty(Out, Info.Ctx, Param->getType());
1829 
1830     if (ArgIndex == 0 && IsMemberCall)
1831       Out << "->" << *Callee << '(';
1832   }
1833 
1834   Out << ')';
1835 }
1836 
1837 /// Evaluate an expression to see if it had side-effects, and discard its
1838 /// result.
1839 /// \return \c true if the caller should keep evaluating.
1840 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1841   APValue Scratch;
1842   if (!Evaluate(Scratch, Info, E))
1843     // We don't need the value, but we might have skipped a side effect here.
1844     return Info.noteSideEffect();
1845   return true;
1846 }
1847 
1848 /// Should this call expression be treated as a string literal?
1849 static bool IsStringLiteralCall(const CallExpr *E) {
1850   unsigned Builtin = E->getBuiltinCallee();
1851   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1852           Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1853 }
1854 
1855 static bool IsGlobalLValue(APValue::LValueBase B) {
1856   // C++11 [expr.const]p3 An address constant expression is a prvalue core
1857   // constant expression of pointer type that evaluates to...
1858 
1859   // ... a null pointer value, or a prvalue core constant expression of type
1860   // std::nullptr_t.
1861   if (!B) return true;
1862 
1863   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1864     // ... the address of an object with static storage duration,
1865     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1866       return VD->hasGlobalStorage();
1867     // ... the address of a function,
1868     return isa<FunctionDecl>(D);
1869   }
1870 
1871   if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
1872     return true;
1873 
1874   const Expr *E = B.get<const Expr*>();
1875   switch (E->getStmtClass()) {
1876   default:
1877     return false;
1878   case Expr::CompoundLiteralExprClass: {
1879     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1880     return CLE->isFileScope() && CLE->isLValue();
1881   }
1882   case Expr::MaterializeTemporaryExprClass:
1883     // A materialized temporary might have been lifetime-extended to static
1884     // storage duration.
1885     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1886   // A string literal has static storage duration.
1887   case Expr::StringLiteralClass:
1888   case Expr::PredefinedExprClass:
1889   case Expr::ObjCStringLiteralClass:
1890   case Expr::ObjCEncodeExprClass:
1891   case Expr::CXXUuidofExprClass:
1892     return true;
1893   case Expr::ObjCBoxedExprClass:
1894     return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
1895   case Expr::CallExprClass:
1896     return IsStringLiteralCall(cast<CallExpr>(E));
1897   // For GCC compatibility, &&label has static storage duration.
1898   case Expr::AddrLabelExprClass:
1899     return true;
1900   // A Block literal expression may be used as the initialization value for
1901   // Block variables at global or local static scope.
1902   case Expr::BlockExprClass:
1903     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1904   case Expr::ImplicitValueInitExprClass:
1905     // FIXME:
1906     // We can never form an lvalue with an implicit value initialization as its
1907     // base through expression evaluation, so these only appear in one case: the
1908     // implicit variable declaration we invent when checking whether a constexpr
1909     // constructor can produce a constant expression. We must assume that such
1910     // an expression might be a global lvalue.
1911     return true;
1912   }
1913 }
1914 
1915 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1916   return LVal.Base.dyn_cast<const ValueDecl*>();
1917 }
1918 
1919 static bool IsLiteralLValue(const LValue &Value) {
1920   if (Value.getLValueCallIndex())
1921     return false;
1922   const Expr *E = Value.Base.dyn_cast<const Expr*>();
1923   return E && !isa<MaterializeTemporaryExpr>(E);
1924 }
1925 
1926 static bool IsWeakLValue(const LValue &Value) {
1927   const ValueDecl *Decl = GetLValueBaseDecl(Value);
1928   return Decl && Decl->isWeak();
1929 }
1930 
1931 static bool isZeroSized(const LValue &Value) {
1932   const ValueDecl *Decl = GetLValueBaseDecl(Value);
1933   if (Decl && isa<VarDecl>(Decl)) {
1934     QualType Ty = Decl->getType();
1935     if (Ty->isArrayType())
1936       return Ty->isIncompleteType() ||
1937              Decl->getASTContext().getTypeSize(Ty) == 0;
1938   }
1939   return false;
1940 }
1941 
1942 static bool HasSameBase(const LValue &A, const LValue &B) {
1943   if (!A.getLValueBase())
1944     return !B.getLValueBase();
1945   if (!B.getLValueBase())
1946     return false;
1947 
1948   if (A.getLValueBase().getOpaqueValue() !=
1949       B.getLValueBase().getOpaqueValue()) {
1950     const Decl *ADecl = GetLValueBaseDecl(A);
1951     if (!ADecl)
1952       return false;
1953     const Decl *BDecl = GetLValueBaseDecl(B);
1954     if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
1955       return false;
1956   }
1957 
1958   return IsGlobalLValue(A.getLValueBase()) ||
1959          (A.getLValueCallIndex() == B.getLValueCallIndex() &&
1960           A.getLValueVersion() == B.getLValueVersion());
1961 }
1962 
1963 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1964   assert(Base && "no location for a null lvalue");
1965   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1966   if (VD)
1967     Info.Note(VD->getLocation(), diag::note_declared_at);
1968   else if (const Expr *E = Base.dyn_cast<const Expr*>())
1969     Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
1970   else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
1971     // FIXME: Produce a note for dangling pointers too.
1972     if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA))
1973       Info.Note((*Alloc)->AllocExpr->getExprLoc(),
1974                 diag::note_constexpr_dynamic_alloc_here);
1975   }
1976   // We have no information to show for a typeid(T) object.
1977 }
1978 
1979 enum class CheckEvaluationResultKind {
1980   ConstantExpression,
1981   FullyInitialized,
1982 };
1983 
1984 /// Materialized temporaries that we've already checked to determine if they're
1985 /// initializsed by a constant expression.
1986 using CheckedTemporaries =
1987     llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
1988 
1989 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
1990                                   EvalInfo &Info, SourceLocation DiagLoc,
1991                                   QualType Type, const APValue &Value,
1992                                   Expr::ConstExprUsage Usage,
1993                                   SourceLocation SubobjectLoc,
1994                                   CheckedTemporaries &CheckedTemps);
1995 
1996 /// Check that this reference or pointer core constant expression is a valid
1997 /// value for an address or reference constant expression. Return true if we
1998 /// can fold this expression, whether or not it's a constant expression.
1999 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2000                                           QualType Type, const LValue &LVal,
2001                                           Expr::ConstExprUsage Usage,
2002                                           CheckedTemporaries &CheckedTemps) {
2003   bool IsReferenceType = Type->isReferenceType();
2004 
2005   APValue::LValueBase Base = LVal.getLValueBase();
2006   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2007 
2008   if (auto *VD = LVal.getLValueBase().dyn_cast<const ValueDecl *>()) {
2009     if (auto *FD = dyn_cast<FunctionDecl>(VD)) {
2010       if (FD->isConsteval()) {
2011         Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2012             << !Type->isAnyPointerType();
2013         Info.Note(FD->getLocation(), diag::note_declared_at);
2014         return false;
2015       }
2016     }
2017   }
2018 
2019   // Check that the object is a global. Note that the fake 'this' object we
2020   // manufacture when checking potential constant expressions is conservatively
2021   // assumed to be global here.
2022   if (!IsGlobalLValue(Base)) {
2023     if (Info.getLangOpts().CPlusPlus11) {
2024       const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2025       Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2026         << IsReferenceType << !Designator.Entries.empty()
2027         << !!VD << VD;
2028       NoteLValueLocation(Info, Base);
2029     } else {
2030       Info.FFDiag(Loc);
2031     }
2032     // Don't allow references to temporaries to escape.
2033     return false;
2034   }
2035   assert((Info.checkingPotentialConstantExpression() ||
2036           LVal.getLValueCallIndex() == 0) &&
2037          "have call index for global lvalue");
2038 
2039   if (Base.is<DynamicAllocLValue>()) {
2040     Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2041         << IsReferenceType << !Designator.Entries.empty();
2042     NoteLValueLocation(Info, Base);
2043     return false;
2044   }
2045 
2046   if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
2047     if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
2048       // Check if this is a thread-local variable.
2049       if (Var->getTLSKind())
2050         // FIXME: Diagnostic!
2051         return false;
2052 
2053       // A dllimport variable never acts like a constant.
2054       if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
2055         // FIXME: Diagnostic!
2056         return false;
2057     }
2058     if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
2059       // __declspec(dllimport) must be handled very carefully:
2060       // We must never initialize an expression with the thunk in C++.
2061       // Doing otherwise would allow the same id-expression to yield
2062       // different addresses for the same function in different translation
2063       // units.  However, this means that we must dynamically initialize the
2064       // expression with the contents of the import address table at runtime.
2065       //
2066       // The C language has no notion of ODR; furthermore, it has no notion of
2067       // dynamic initialization.  This means that we are permitted to
2068       // perform initialization with the address of the thunk.
2069       if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
2070           FD->hasAttr<DLLImportAttr>())
2071         // FIXME: Diagnostic!
2072         return false;
2073     }
2074   } else if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(
2075                  Base.dyn_cast<const Expr *>())) {
2076     if (CheckedTemps.insert(MTE).second) {
2077       QualType TempType = getType(Base);
2078       if (TempType.isDestructedType()) {
2079         Info.FFDiag(MTE->getExprLoc(),
2080                     diag::note_constexpr_unsupported_tempoarary_nontrivial_dtor)
2081             << TempType;
2082         return false;
2083       }
2084 
2085       APValue *V = MTE->getOrCreateValue(false);
2086       assert(V && "evasluation result refers to uninitialised temporary");
2087       if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2088                                  Info, MTE->getExprLoc(), TempType, *V,
2089                                  Usage, SourceLocation(), CheckedTemps))
2090         return false;
2091     }
2092   }
2093 
2094   // Allow address constant expressions to be past-the-end pointers. This is
2095   // an extension: the standard requires them to point to an object.
2096   if (!IsReferenceType)
2097     return true;
2098 
2099   // A reference constant expression must refer to an object.
2100   if (!Base) {
2101     // FIXME: diagnostic
2102     Info.CCEDiag(Loc);
2103     return true;
2104   }
2105 
2106   // Does this refer one past the end of some object?
2107   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2108     const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2109     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2110       << !Designator.Entries.empty() << !!VD << VD;
2111     NoteLValueLocation(Info, Base);
2112   }
2113 
2114   return true;
2115 }
2116 
2117 /// Member pointers are constant expressions unless they point to a
2118 /// non-virtual dllimport member function.
2119 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2120                                                  SourceLocation Loc,
2121                                                  QualType Type,
2122                                                  const APValue &Value,
2123                                                  Expr::ConstExprUsage Usage) {
2124   const ValueDecl *Member = Value.getMemberPointerDecl();
2125   const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2126   if (!FD)
2127     return true;
2128   if (FD->isConsteval()) {
2129     Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2130     Info.Note(FD->getLocation(), diag::note_declared_at);
2131     return false;
2132   }
2133   return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
2134          !FD->hasAttr<DLLImportAttr>();
2135 }
2136 
2137 /// Check that this core constant expression is of literal type, and if not,
2138 /// produce an appropriate diagnostic.
2139 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2140                              const LValue *This = nullptr) {
2141   if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
2142     return true;
2143 
2144   // C++1y: A constant initializer for an object o [...] may also invoke
2145   // constexpr constructors for o and its subobjects even if those objects
2146   // are of non-literal class types.
2147   //
2148   // C++11 missed this detail for aggregates, so classes like this:
2149   //   struct foo_t { union { int i; volatile int j; } u; };
2150   // are not (obviously) initializable like so:
2151   //   __attribute__((__require_constant_initialization__))
2152   //   static const foo_t x = {{0}};
2153   // because "i" is a subobject with non-literal initialization (due to the
2154   // volatile member of the union). See:
2155   //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2156   // Therefore, we use the C++1y behavior.
2157   if (This && Info.EvaluatingDecl == This->getLValueBase())
2158     return true;
2159 
2160   // Prvalue constant expressions must be of literal types.
2161   if (Info.getLangOpts().CPlusPlus11)
2162     Info.FFDiag(E, diag::note_constexpr_nonliteral)
2163       << E->getType();
2164   else
2165     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2166   return false;
2167 }
2168 
2169 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2170                                   EvalInfo &Info, SourceLocation DiagLoc,
2171                                   QualType Type, const APValue &Value,
2172                                   Expr::ConstExprUsage Usage,
2173                                   SourceLocation SubobjectLoc,
2174                                   CheckedTemporaries &CheckedTemps) {
2175   if (!Value.hasValue()) {
2176     Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2177       << true << Type;
2178     if (SubobjectLoc.isValid())
2179       Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2180     return false;
2181   }
2182 
2183   // We allow _Atomic(T) to be initialized from anything that T can be
2184   // initialized from.
2185   if (const AtomicType *AT = Type->getAs<AtomicType>())
2186     Type = AT->getValueType();
2187 
2188   // Core issue 1454: For a literal constant expression of array or class type,
2189   // each subobject of its value shall have been initialized by a constant
2190   // expression.
2191   if (Value.isArray()) {
2192     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2193     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2194       if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2195                                  Value.getArrayInitializedElt(I), Usage,
2196                                  SubobjectLoc, CheckedTemps))
2197         return false;
2198     }
2199     if (!Value.hasArrayFiller())
2200       return true;
2201     return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2202                                  Value.getArrayFiller(), Usage, SubobjectLoc,
2203                                  CheckedTemps);
2204   }
2205   if (Value.isUnion() && Value.getUnionField()) {
2206     return CheckEvaluationResult(
2207         CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2208         Value.getUnionValue(), Usage, Value.getUnionField()->getLocation(),
2209         CheckedTemps);
2210   }
2211   if (Value.isStruct()) {
2212     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2213     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2214       unsigned BaseIndex = 0;
2215       for (const CXXBaseSpecifier &BS : CD->bases()) {
2216         if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2217                                    Value.getStructBase(BaseIndex), Usage,
2218                                    BS.getBeginLoc(), CheckedTemps))
2219           return false;
2220         ++BaseIndex;
2221       }
2222     }
2223     for (const auto *I : RD->fields()) {
2224       if (I->isUnnamedBitfield())
2225         continue;
2226 
2227       if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2228                                  Value.getStructField(I->getFieldIndex()),
2229                                  Usage, I->getLocation(), CheckedTemps))
2230         return false;
2231     }
2232   }
2233 
2234   if (Value.isLValue() &&
2235       CERK == CheckEvaluationResultKind::ConstantExpression) {
2236     LValue LVal;
2237     LVal.setFrom(Info.Ctx, Value);
2238     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage,
2239                                          CheckedTemps);
2240   }
2241 
2242   if (Value.isMemberPointer() &&
2243       CERK == CheckEvaluationResultKind::ConstantExpression)
2244     return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
2245 
2246   // Everything else is fine.
2247   return true;
2248 }
2249 
2250 /// Check that this core constant expression value is a valid value for a
2251 /// constant expression. If not, report an appropriate diagnostic. Does not
2252 /// check that the expression is of literal type.
2253 static bool
2254 CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
2255                         const APValue &Value,
2256                         Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
2257   CheckedTemporaries CheckedTemps;
2258   return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2259                                Info, DiagLoc, Type, Value, Usage,
2260                                SourceLocation(), CheckedTemps);
2261 }
2262 
2263 /// Check that this evaluated value is fully-initialized and can be loaded by
2264 /// an lvalue-to-rvalue conversion.
2265 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2266                                   QualType Type, const APValue &Value) {
2267   CheckedTemporaries CheckedTemps;
2268   return CheckEvaluationResult(
2269       CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2270       Expr::EvaluateForCodeGen, SourceLocation(), CheckedTemps);
2271 }
2272 
2273 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2274 /// "the allocated storage is deallocated within the evaluation".
2275 static bool CheckMemoryLeaks(EvalInfo &Info) {
2276   if (!Info.HeapAllocs.empty()) {
2277     // We can still fold to a constant despite a compile-time memory leak,
2278     // so long as the heap allocation isn't referenced in the result (we check
2279     // that in CheckConstantExpression).
2280     Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2281                  diag::note_constexpr_memory_leak)
2282         << unsigned(Info.HeapAllocs.size() - 1);
2283   }
2284   return true;
2285 }
2286 
2287 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2288   // A null base expression indicates a null pointer.  These are always
2289   // evaluatable, and they are false unless the offset is zero.
2290   if (!Value.getLValueBase()) {
2291     Result = !Value.getLValueOffset().isZero();
2292     return true;
2293   }
2294 
2295   // We have a non-null base.  These are generally known to be true, but if it's
2296   // a weak declaration it can be null at runtime.
2297   Result = true;
2298   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2299   return !Decl || !Decl->isWeak();
2300 }
2301 
2302 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2303   switch (Val.getKind()) {
2304   case APValue::None:
2305   case APValue::Indeterminate:
2306     return false;
2307   case APValue::Int:
2308     Result = Val.getInt().getBoolValue();
2309     return true;
2310   case APValue::FixedPoint:
2311     Result = Val.getFixedPoint().getBoolValue();
2312     return true;
2313   case APValue::Float:
2314     Result = !Val.getFloat().isZero();
2315     return true;
2316   case APValue::ComplexInt:
2317     Result = Val.getComplexIntReal().getBoolValue() ||
2318              Val.getComplexIntImag().getBoolValue();
2319     return true;
2320   case APValue::ComplexFloat:
2321     Result = !Val.getComplexFloatReal().isZero() ||
2322              !Val.getComplexFloatImag().isZero();
2323     return true;
2324   case APValue::LValue:
2325     return EvalPointerValueAsBool(Val, Result);
2326   case APValue::MemberPointer:
2327     Result = Val.getMemberPointerDecl();
2328     return true;
2329   case APValue::Vector:
2330   case APValue::Array:
2331   case APValue::Struct:
2332   case APValue::Union:
2333   case APValue::AddrLabelDiff:
2334     return false;
2335   }
2336 
2337   llvm_unreachable("unknown APValue kind");
2338 }
2339 
2340 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2341                                        EvalInfo &Info) {
2342   assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
2343   APValue Val;
2344   if (!Evaluate(Val, Info, E))
2345     return false;
2346   return HandleConversionToBool(Val, Result);
2347 }
2348 
2349 template<typename T>
2350 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2351                            const T &SrcValue, QualType DestType) {
2352   Info.CCEDiag(E, diag::note_constexpr_overflow)
2353     << SrcValue << DestType;
2354   return Info.noteUndefinedBehavior();
2355 }
2356 
2357 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2358                                  QualType SrcType, const APFloat &Value,
2359                                  QualType DestType, APSInt &Result) {
2360   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2361   // Determine whether we are converting to unsigned or signed.
2362   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2363 
2364   Result = APSInt(DestWidth, !DestSigned);
2365   bool ignored;
2366   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2367       & APFloat::opInvalidOp)
2368     return HandleOverflow(Info, E, Value, DestType);
2369   return true;
2370 }
2371 
2372 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2373                                    QualType SrcType, QualType DestType,
2374                                    APFloat &Result) {
2375   APFloat Value = Result;
2376   bool ignored;
2377   Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2378                  APFloat::rmNearestTiesToEven, &ignored);
2379   return true;
2380 }
2381 
2382 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2383                                  QualType DestType, QualType SrcType,
2384                                  const APSInt &Value) {
2385   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2386   // Figure out if this is a truncate, extend or noop cast.
2387   // If the input is signed, do a sign extend, noop, or truncate.
2388   APSInt Result = Value.extOrTrunc(DestWidth);
2389   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2390   if (DestType->isBooleanType())
2391     Result = Value.getBoolValue();
2392   return Result;
2393 }
2394 
2395 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2396                                  QualType SrcType, const APSInt &Value,
2397                                  QualType DestType, APFloat &Result) {
2398   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2399   Result.convertFromAPInt(Value, Value.isSigned(),
2400                           APFloat::rmNearestTiesToEven);
2401   return true;
2402 }
2403 
2404 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2405                                   APValue &Value, const FieldDecl *FD) {
2406   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2407 
2408   if (!Value.isInt()) {
2409     // Trying to store a pointer-cast-to-integer into a bitfield.
2410     // FIXME: In this case, we should provide the diagnostic for casting
2411     // a pointer to an integer.
2412     assert(Value.isLValue() && "integral value neither int nor lvalue?");
2413     Info.FFDiag(E);
2414     return false;
2415   }
2416 
2417   APSInt &Int = Value.getInt();
2418   unsigned OldBitWidth = Int.getBitWidth();
2419   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2420   if (NewBitWidth < OldBitWidth)
2421     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2422   return true;
2423 }
2424 
2425 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2426                                   llvm::APInt &Res) {
2427   APValue SVal;
2428   if (!Evaluate(SVal, Info, E))
2429     return false;
2430   if (SVal.isInt()) {
2431     Res = SVal.getInt();
2432     return true;
2433   }
2434   if (SVal.isFloat()) {
2435     Res = SVal.getFloat().bitcastToAPInt();
2436     return true;
2437   }
2438   if (SVal.isVector()) {
2439     QualType VecTy = E->getType();
2440     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2441     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2442     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2443     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2444     Res = llvm::APInt::getNullValue(VecSize);
2445     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2446       APValue &Elt = SVal.getVectorElt(i);
2447       llvm::APInt EltAsInt;
2448       if (Elt.isInt()) {
2449         EltAsInt = Elt.getInt();
2450       } else if (Elt.isFloat()) {
2451         EltAsInt = Elt.getFloat().bitcastToAPInt();
2452       } else {
2453         // Don't try to handle vectors of anything other than int or float
2454         // (not sure if it's possible to hit this case).
2455         Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2456         return false;
2457       }
2458       unsigned BaseEltSize = EltAsInt.getBitWidth();
2459       if (BigEndian)
2460         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2461       else
2462         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2463     }
2464     return true;
2465   }
2466   // Give up if the input isn't an int, float, or vector.  For example, we
2467   // reject "(v4i16)(intptr_t)&a".
2468   Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2469   return false;
2470 }
2471 
2472 /// Perform the given integer operation, which is known to need at most BitWidth
2473 /// bits, and check for overflow in the original type (if that type was not an
2474 /// unsigned type).
2475 template<typename Operation>
2476 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2477                                  const APSInt &LHS, const APSInt &RHS,
2478                                  unsigned BitWidth, Operation Op,
2479                                  APSInt &Result) {
2480   if (LHS.isUnsigned()) {
2481     Result = Op(LHS, RHS);
2482     return true;
2483   }
2484 
2485   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2486   Result = Value.trunc(LHS.getBitWidth());
2487   if (Result.extend(BitWidth) != Value) {
2488     if (Info.checkingForUndefinedBehavior())
2489       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2490                                        diag::warn_integer_constant_overflow)
2491           << Result.toString(10) << E->getType();
2492     else
2493       return HandleOverflow(Info, E, Value, E->getType());
2494   }
2495   return true;
2496 }
2497 
2498 /// Perform the given binary integer operation.
2499 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2500                               BinaryOperatorKind Opcode, APSInt RHS,
2501                               APSInt &Result) {
2502   switch (Opcode) {
2503   default:
2504     Info.FFDiag(E);
2505     return false;
2506   case BO_Mul:
2507     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2508                                 std::multiplies<APSInt>(), Result);
2509   case BO_Add:
2510     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2511                                 std::plus<APSInt>(), Result);
2512   case BO_Sub:
2513     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2514                                 std::minus<APSInt>(), Result);
2515   case BO_And: Result = LHS & RHS; return true;
2516   case BO_Xor: Result = LHS ^ RHS; return true;
2517   case BO_Or:  Result = LHS | RHS; return true;
2518   case BO_Div:
2519   case BO_Rem:
2520     if (RHS == 0) {
2521       Info.FFDiag(E, diag::note_expr_divide_by_zero);
2522       return false;
2523     }
2524     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2525     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2526     // this operation and gives the two's complement result.
2527     if (RHS.isNegative() && RHS.isAllOnesValue() &&
2528         LHS.isSigned() && LHS.isMinSignedValue())
2529       return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2530                             E->getType());
2531     return true;
2532   case BO_Shl: {
2533     if (Info.getLangOpts().OpenCL)
2534       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2535       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2536                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2537                     RHS.isUnsigned());
2538     else if (RHS.isSigned() && RHS.isNegative()) {
2539       // During constant-folding, a negative shift is an opposite shift. Such
2540       // a shift is not a constant expression.
2541       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2542       RHS = -RHS;
2543       goto shift_right;
2544     }
2545   shift_left:
2546     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2547     // the shifted type.
2548     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2549     if (SA != RHS) {
2550       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2551         << RHS << E->getType() << LHS.getBitWidth();
2552     } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus2a) {
2553       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2554       // operand, and must not overflow the corresponding unsigned type.
2555       // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2556       // E1 x 2^E2 module 2^N.
2557       if (LHS.isNegative())
2558         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2559       else if (LHS.countLeadingZeros() < SA)
2560         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2561     }
2562     Result = LHS << SA;
2563     return true;
2564   }
2565   case BO_Shr: {
2566     if (Info.getLangOpts().OpenCL)
2567       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2568       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2569                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2570                     RHS.isUnsigned());
2571     else if (RHS.isSigned() && RHS.isNegative()) {
2572       // During constant-folding, a negative shift is an opposite shift. Such a
2573       // shift is not a constant expression.
2574       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2575       RHS = -RHS;
2576       goto shift_left;
2577     }
2578   shift_right:
2579     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2580     // shifted type.
2581     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2582     if (SA != RHS)
2583       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2584         << RHS << E->getType() << LHS.getBitWidth();
2585     Result = LHS >> SA;
2586     return true;
2587   }
2588 
2589   case BO_LT: Result = LHS < RHS; return true;
2590   case BO_GT: Result = LHS > RHS; return true;
2591   case BO_LE: Result = LHS <= RHS; return true;
2592   case BO_GE: Result = LHS >= RHS; return true;
2593   case BO_EQ: Result = LHS == RHS; return true;
2594   case BO_NE: Result = LHS != RHS; return true;
2595   case BO_Cmp:
2596     llvm_unreachable("BO_Cmp should be handled elsewhere");
2597   }
2598 }
2599 
2600 /// Perform the given binary floating-point operation, in-place, on LHS.
2601 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2602                                   APFloat &LHS, BinaryOperatorKind Opcode,
2603                                   const APFloat &RHS) {
2604   switch (Opcode) {
2605   default:
2606     Info.FFDiag(E);
2607     return false;
2608   case BO_Mul:
2609     LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2610     break;
2611   case BO_Add:
2612     LHS.add(RHS, APFloat::rmNearestTiesToEven);
2613     break;
2614   case BO_Sub:
2615     LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2616     break;
2617   case BO_Div:
2618     // [expr.mul]p4:
2619     //   If the second operand of / or % is zero the behavior is undefined.
2620     if (RHS.isZero())
2621       Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2622     LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2623     break;
2624   }
2625 
2626   // [expr.pre]p4:
2627   //   If during the evaluation of an expression, the result is not
2628   //   mathematically defined [...], the behavior is undefined.
2629   // FIXME: C++ rules require us to not conform to IEEE 754 here.
2630   if (LHS.isNaN()) {
2631     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2632     return Info.noteUndefinedBehavior();
2633   }
2634   return true;
2635 }
2636 
2637 /// Cast an lvalue referring to a base subobject to a derived class, by
2638 /// truncating the lvalue's path to the given length.
2639 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2640                                const RecordDecl *TruncatedType,
2641                                unsigned TruncatedElements) {
2642   SubobjectDesignator &D = Result.Designator;
2643 
2644   // Check we actually point to a derived class object.
2645   if (TruncatedElements == D.Entries.size())
2646     return true;
2647   assert(TruncatedElements >= D.MostDerivedPathLength &&
2648          "not casting to a derived class");
2649   if (!Result.checkSubobject(Info, E, CSK_Derived))
2650     return false;
2651 
2652   // Truncate the path to the subobject, and remove any derived-to-base offsets.
2653   const RecordDecl *RD = TruncatedType;
2654   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
2655     if (RD->isInvalidDecl()) return false;
2656     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2657     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
2658     if (isVirtualBaseClass(D.Entries[I]))
2659       Result.Offset -= Layout.getVBaseClassOffset(Base);
2660     else
2661       Result.Offset -= Layout.getBaseClassOffset(Base);
2662     RD = Base;
2663   }
2664   D.Entries.resize(TruncatedElements);
2665   return true;
2666 }
2667 
2668 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2669                                    const CXXRecordDecl *Derived,
2670                                    const CXXRecordDecl *Base,
2671                                    const ASTRecordLayout *RL = nullptr) {
2672   if (!RL) {
2673     if (Derived->isInvalidDecl()) return false;
2674     RL = &Info.Ctx.getASTRecordLayout(Derived);
2675   }
2676 
2677   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
2678   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
2679   return true;
2680 }
2681 
2682 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2683                              const CXXRecordDecl *DerivedDecl,
2684                              const CXXBaseSpecifier *Base) {
2685   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2686 
2687   if (!Base->isVirtual())
2688     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
2689 
2690   SubobjectDesignator &D = Obj.Designator;
2691   if (D.Invalid)
2692     return false;
2693 
2694   // Extract most-derived object and corresponding type.
2695   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2696   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2697     return false;
2698 
2699   // Find the virtual base class.
2700   if (DerivedDecl->isInvalidDecl()) return false;
2701   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2702   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
2703   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
2704   return true;
2705 }
2706 
2707 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2708                                  QualType Type, LValue &Result) {
2709   for (CastExpr::path_const_iterator PathI = E->path_begin(),
2710                                      PathE = E->path_end();
2711        PathI != PathE; ++PathI) {
2712     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2713                           *PathI))
2714       return false;
2715     Type = (*PathI)->getType();
2716   }
2717   return true;
2718 }
2719 
2720 /// Cast an lvalue referring to a derived class to a known base subobject.
2721 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
2722                             const CXXRecordDecl *DerivedRD,
2723                             const CXXRecordDecl *BaseRD) {
2724   CXXBasePaths Paths(/*FindAmbiguities=*/false,
2725                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
2726   if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
2727     llvm_unreachable("Class must be derived from the passed in base class!");
2728 
2729   for (CXXBasePathElement &Elem : Paths.front())
2730     if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
2731       return false;
2732   return true;
2733 }
2734 
2735 /// Update LVal to refer to the given field, which must be a member of the type
2736 /// currently described by LVal.
2737 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
2738                                const FieldDecl *FD,
2739                                const ASTRecordLayout *RL = nullptr) {
2740   if (!RL) {
2741     if (FD->getParent()->isInvalidDecl()) return false;
2742     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
2743   }
2744 
2745   unsigned I = FD->getFieldIndex();
2746   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
2747   LVal.addDecl(Info, E, FD);
2748   return true;
2749 }
2750 
2751 /// Update LVal to refer to the given indirect field.
2752 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
2753                                        LValue &LVal,
2754                                        const IndirectFieldDecl *IFD) {
2755   for (const auto *C : IFD->chain())
2756     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
2757       return false;
2758   return true;
2759 }
2760 
2761 /// Get the size of the given type in char units.
2762 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2763                          QualType Type, CharUnits &Size) {
2764   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2765   // extension.
2766   if (Type->isVoidType() || Type->isFunctionType()) {
2767     Size = CharUnits::One();
2768     return true;
2769   }
2770 
2771   if (Type->isDependentType()) {
2772     Info.FFDiag(Loc);
2773     return false;
2774   }
2775 
2776   if (!Type->isConstantSizeType()) {
2777     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2778     // FIXME: Better diagnostic.
2779     Info.FFDiag(Loc);
2780     return false;
2781   }
2782 
2783   Size = Info.Ctx.getTypeSizeInChars(Type);
2784   return true;
2785 }
2786 
2787 /// Update a pointer value to model pointer arithmetic.
2788 /// \param Info - Information about the ongoing evaluation.
2789 /// \param E - The expression being evaluated, for diagnostic purposes.
2790 /// \param LVal - The pointer value to be updated.
2791 /// \param EltTy - The pointee type represented by LVal.
2792 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
2793 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2794                                         LValue &LVal, QualType EltTy,
2795                                         APSInt Adjustment) {
2796   CharUnits SizeOfPointee;
2797   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
2798     return false;
2799 
2800   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
2801   return true;
2802 }
2803 
2804 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2805                                         LValue &LVal, QualType EltTy,
2806                                         int64_t Adjustment) {
2807   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2808                                      APSInt::get(Adjustment));
2809 }
2810 
2811 /// Update an lvalue to refer to a component of a complex number.
2812 /// \param Info - Information about the ongoing evaluation.
2813 /// \param LVal - The lvalue to be updated.
2814 /// \param EltTy - The complex number's component type.
2815 /// \param Imag - False for the real component, true for the imaginary.
2816 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2817                                        LValue &LVal, QualType EltTy,
2818                                        bool Imag) {
2819   if (Imag) {
2820     CharUnits SizeOfComponent;
2821     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2822       return false;
2823     LVal.Offset += SizeOfComponent;
2824   }
2825   LVal.addComplex(Info, E, EltTy, Imag);
2826   return true;
2827 }
2828 
2829 /// Try to evaluate the initializer for a variable declaration.
2830 ///
2831 /// \param Info   Information about the ongoing evaluation.
2832 /// \param E      An expression to be used when printing diagnostics.
2833 /// \param VD     The variable whose initializer should be obtained.
2834 /// \param Frame  The frame in which the variable was created. Must be null
2835 ///               if this variable is not local to the evaluation.
2836 /// \param Result Filled in with a pointer to the value of the variable.
2837 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2838                                 const VarDecl *VD, CallStackFrame *Frame,
2839                                 APValue *&Result, const LValue *LVal) {
2840 
2841   // If this is a parameter to an active constexpr function call, perform
2842   // argument substitution.
2843   if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
2844     // Assume arguments of a potential constant expression are unknown
2845     // constant expressions.
2846     if (Info.checkingPotentialConstantExpression())
2847       return false;
2848     if (!Frame || !Frame->Arguments) {
2849       Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2850       return false;
2851     }
2852     Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
2853     return true;
2854   }
2855 
2856   // If this is a local variable, dig out its value.
2857   if (Frame) {
2858     Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2859                   : Frame->getCurrentTemporary(VD);
2860     if (!Result) {
2861       // Assume variables referenced within a lambda's call operator that were
2862       // not declared within the call operator are captures and during checking
2863       // of a potential constant expression, assume they are unknown constant
2864       // expressions.
2865       assert(isLambdaCallOperator(Frame->Callee) &&
2866              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2867              "missing value for local variable");
2868       if (Info.checkingPotentialConstantExpression())
2869         return false;
2870       // FIXME: implement capture evaluation during constant expr evaluation.
2871       Info.FFDiag(E->getBeginLoc(),
2872                   diag::note_unimplemented_constexpr_lambda_feature_ast)
2873           << "captures not currently allowed";
2874       return false;
2875     }
2876     return true;
2877   }
2878 
2879   // Dig out the initializer, and use the declaration which it's attached to.
2880   const Expr *Init = VD->getAnyInitializer(VD);
2881   if (!Init || Init->isValueDependent()) {
2882     // If we're checking a potential constant expression, the variable could be
2883     // initialized later.
2884     if (!Info.checkingPotentialConstantExpression())
2885       Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2886     return false;
2887   }
2888 
2889   // If we're currently evaluating the initializer of this declaration, use that
2890   // in-flight value.
2891   if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
2892     Result = Info.EvaluatingDeclValue;
2893     return true;
2894   }
2895 
2896   // Never evaluate the initializer of a weak variable. We can't be sure that
2897   // this is the definition which will be used.
2898   if (VD->isWeak()) {
2899     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2900     return false;
2901   }
2902 
2903   // Check that we can fold the initializer. In C++, we will have already done
2904   // this in the cases where it matters for conformance.
2905   SmallVector<PartialDiagnosticAt, 8> Notes;
2906   if (!VD->evaluateValue(Notes)) {
2907     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
2908               Notes.size() + 1) << VD;
2909     Info.Note(VD->getLocation(), diag::note_declared_at);
2910     Info.addNotes(Notes);
2911     return false;
2912   } else if (!VD->checkInitIsICE()) {
2913     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
2914                  Notes.size() + 1) << VD;
2915     Info.Note(VD->getLocation(), diag::note_declared_at);
2916     Info.addNotes(Notes);
2917   }
2918 
2919   Result = VD->getEvaluatedValue();
2920   return true;
2921 }
2922 
2923 static bool IsConstNonVolatile(QualType T) {
2924   Qualifiers Quals = T.getQualifiers();
2925   return Quals.hasConst() && !Quals.hasVolatile();
2926 }
2927 
2928 /// Get the base index of the given base class within an APValue representing
2929 /// the given derived class.
2930 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2931                              const CXXRecordDecl *Base) {
2932   Base = Base->getCanonicalDecl();
2933   unsigned Index = 0;
2934   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2935          E = Derived->bases_end(); I != E; ++I, ++Index) {
2936     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2937       return Index;
2938   }
2939 
2940   llvm_unreachable("base class missing from derived class's bases list");
2941 }
2942 
2943 /// Extract the value of a character from a string literal.
2944 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2945                                             uint64_t Index) {
2946   assert(!isa<SourceLocExpr>(Lit) &&
2947          "SourceLocExpr should have already been converted to a StringLiteral");
2948 
2949   // FIXME: Support MakeStringConstant
2950   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2951     std::string Str;
2952     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2953     assert(Index <= Str.size() && "Index too large");
2954     return APSInt::getUnsigned(Str.c_str()[Index]);
2955   }
2956 
2957   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2958     Lit = PE->getFunctionName();
2959   const StringLiteral *S = cast<StringLiteral>(Lit);
2960   const ConstantArrayType *CAT =
2961       Info.Ctx.getAsConstantArrayType(S->getType());
2962   assert(CAT && "string literal isn't an array");
2963   QualType CharType = CAT->getElementType();
2964   assert(CharType->isIntegerType() && "unexpected character type");
2965 
2966   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2967                CharType->isUnsignedIntegerType());
2968   if (Index < S->getLength())
2969     Value = S->getCodeUnit(Index);
2970   return Value;
2971 }
2972 
2973 // Expand a string literal into an array of characters.
2974 //
2975 // FIXME: This is inefficient; we should probably introduce something similar
2976 // to the LLVM ConstantDataArray to make this cheaper.
2977 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
2978                                 APValue &Result,
2979                                 QualType AllocType = QualType()) {
2980   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
2981       AllocType.isNull() ? S->getType() : AllocType);
2982   assert(CAT && "string literal isn't an array");
2983   QualType CharType = CAT->getElementType();
2984   assert(CharType->isIntegerType() && "unexpected character type");
2985 
2986   unsigned Elts = CAT->getSize().getZExtValue();
2987   Result = APValue(APValue::UninitArray(),
2988                    std::min(S->getLength(), Elts), Elts);
2989   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2990                CharType->isUnsignedIntegerType());
2991   if (Result.hasArrayFiller())
2992     Result.getArrayFiller() = APValue(Value);
2993   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2994     Value = S->getCodeUnit(I);
2995     Result.getArrayInitializedElt(I) = APValue(Value);
2996   }
2997 }
2998 
2999 // Expand an array so that it has more than Index filled elements.
3000 static void expandArray(APValue &Array, unsigned Index) {
3001   unsigned Size = Array.getArraySize();
3002   assert(Index < Size);
3003 
3004   // Always at least double the number of elements for which we store a value.
3005   unsigned OldElts = Array.getArrayInitializedElts();
3006   unsigned NewElts = std::max(Index+1, OldElts * 2);
3007   NewElts = std::min(Size, std::max(NewElts, 8u));
3008 
3009   // Copy the data across.
3010   APValue NewValue(APValue::UninitArray(), NewElts, Size);
3011   for (unsigned I = 0; I != OldElts; ++I)
3012     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3013   for (unsigned I = OldElts; I != NewElts; ++I)
3014     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3015   if (NewValue.hasArrayFiller())
3016     NewValue.getArrayFiller() = Array.getArrayFiller();
3017   Array.swap(NewValue);
3018 }
3019 
3020 /// Determine whether a type would actually be read by an lvalue-to-rvalue
3021 /// conversion. If it's of class type, we may assume that the copy operation
3022 /// is trivial. Note that this is never true for a union type with fields
3023 /// (because the copy always "reads" the active member) and always true for
3024 /// a non-class type.
3025 static bool isReadByLvalueToRvalueConversion(QualType T) {
3026   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3027   if (!RD || (RD->isUnion() && !RD->field_empty()))
3028     return true;
3029   if (RD->isEmpty())
3030     return false;
3031 
3032   for (auto *Field : RD->fields())
3033     if (isReadByLvalueToRvalueConversion(Field->getType()))
3034       return true;
3035 
3036   for (auto &BaseSpec : RD->bases())
3037     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3038       return true;
3039 
3040   return false;
3041 }
3042 
3043 /// Diagnose an attempt to read from any unreadable field within the specified
3044 /// type, which might be a class type.
3045 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3046                                   QualType T) {
3047   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3048   if (!RD)
3049     return false;
3050 
3051   if (!RD->hasMutableFields())
3052     return false;
3053 
3054   for (auto *Field : RD->fields()) {
3055     // If we're actually going to read this field in some way, then it can't
3056     // be mutable. If we're in a union, then assigning to a mutable field
3057     // (even an empty one) can change the active member, so that's not OK.
3058     // FIXME: Add core issue number for the union case.
3059     if (Field->isMutable() &&
3060         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3061       Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3062       Info.Note(Field->getLocation(), diag::note_declared_at);
3063       return true;
3064     }
3065 
3066     if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3067       return true;
3068   }
3069 
3070   for (auto &BaseSpec : RD->bases())
3071     if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3072       return true;
3073 
3074   // All mutable fields were empty, and thus not actually read.
3075   return false;
3076 }
3077 
3078 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3079                                         APValue::LValueBase Base,
3080                                         bool MutableSubobject = false) {
3081   // A temporary we created.
3082   if (Base.getCallIndex())
3083     return true;
3084 
3085   auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3086   if (!Evaluating)
3087     return false;
3088 
3089   auto *BaseD = Base.dyn_cast<const ValueDecl*>();
3090 
3091   switch (Info.IsEvaluatingDecl) {
3092   case EvalInfo::EvaluatingDeclKind::None:
3093     return false;
3094 
3095   case EvalInfo::EvaluatingDeclKind::Ctor:
3096     // The variable whose initializer we're evaluating.
3097     if (BaseD)
3098       return declaresSameEntity(Evaluating, BaseD);
3099 
3100     // A temporary lifetime-extended by the variable whose initializer we're
3101     // evaluating.
3102     if (auto *BaseE = Base.dyn_cast<const Expr *>())
3103       if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3104         return declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating);
3105     return false;
3106 
3107   case EvalInfo::EvaluatingDeclKind::Dtor:
3108     // C++2a [expr.const]p6:
3109     //   [during constant destruction] the lifetime of a and its non-mutable
3110     //   subobjects (but not its mutable subobjects) [are] considered to start
3111     //   within e.
3112     //
3113     // FIXME: We can meaningfully extend this to cover non-const objects, but
3114     // we will need special handling: we should be able to access only
3115     // subobjects of such objects that are themselves declared const.
3116     if (!BaseD ||
3117         !(BaseD->getType().isConstQualified() ||
3118           BaseD->getType()->isReferenceType()) ||
3119         MutableSubobject)
3120       return false;
3121     return declaresSameEntity(Evaluating, BaseD);
3122   }
3123 
3124   llvm_unreachable("unknown evaluating decl kind");
3125 }
3126 
3127 namespace {
3128 /// A handle to a complete object (an object that is not a subobject of
3129 /// another object).
3130 struct CompleteObject {
3131   /// The identity of the object.
3132   APValue::LValueBase Base;
3133   /// The value of the complete object.
3134   APValue *Value;
3135   /// The type of the complete object.
3136   QualType Type;
3137 
3138   CompleteObject() : Value(nullptr) {}
3139   CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3140       : Base(Base), Value(Value), Type(Type) {}
3141 
3142   bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3143     // In C++14 onwards, it is permitted to read a mutable member whose
3144     // lifetime began within the evaluation.
3145     // FIXME: Should we also allow this in C++11?
3146     if (!Info.getLangOpts().CPlusPlus14)
3147       return false;
3148     return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3149   }
3150 
3151   explicit operator bool() const { return !Type.isNull(); }
3152 };
3153 } // end anonymous namespace
3154 
3155 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3156                                  bool IsMutable = false) {
3157   // C++ [basic.type.qualifier]p1:
3158   // - A const object is an object of type const T or a non-mutable subobject
3159   //   of a const object.
3160   if (ObjType.isConstQualified() && !IsMutable)
3161     SubobjType.addConst();
3162   // - A volatile object is an object of type const T or a subobject of a
3163   //   volatile object.
3164   if (ObjType.isVolatileQualified())
3165     SubobjType.addVolatile();
3166   return SubobjType;
3167 }
3168 
3169 /// Find the designated sub-object of an rvalue.
3170 template<typename SubobjectHandler>
3171 typename SubobjectHandler::result_type
3172 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3173               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3174   if (Sub.Invalid)
3175     // A diagnostic will have already been produced.
3176     return handler.failed();
3177   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3178     if (Info.getLangOpts().CPlusPlus11)
3179       Info.FFDiag(E, Sub.isOnePastTheEnd()
3180                          ? diag::note_constexpr_access_past_end
3181                          : diag::note_constexpr_access_unsized_array)
3182           << handler.AccessKind;
3183     else
3184       Info.FFDiag(E);
3185     return handler.failed();
3186   }
3187 
3188   APValue *O = Obj.Value;
3189   QualType ObjType = Obj.Type;
3190   const FieldDecl *LastField = nullptr;
3191   const FieldDecl *VolatileField = nullptr;
3192 
3193   // Walk the designator's path to find the subobject.
3194   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3195     // Reading an indeterminate value is undefined, but assigning over one is OK.
3196     if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3197         (O->isIndeterminate() && handler.AccessKind != AK_Construct &&
3198          handler.AccessKind != AK_Assign &&
3199          handler.AccessKind != AK_ReadObjectRepresentation)) {
3200       if (!Info.checkingPotentialConstantExpression())
3201         Info.FFDiag(E, diag::note_constexpr_access_uninit)
3202             << handler.AccessKind << O->isIndeterminate();
3203       return handler.failed();
3204     }
3205 
3206     // C++ [class.ctor]p5, C++ [class.dtor]p5:
3207     //    const and volatile semantics are not applied on an object under
3208     //    {con,de}struction.
3209     if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3210         ObjType->isRecordType() &&
3211         Info.isEvaluatingCtorDtor(
3212             Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3213                                          Sub.Entries.begin() + I)) !=
3214                           ConstructionPhase::None) {
3215       ObjType = Info.Ctx.getCanonicalType(ObjType);
3216       ObjType.removeLocalConst();
3217       ObjType.removeLocalVolatile();
3218     }
3219 
3220     // If this is our last pass, check that the final object type is OK.
3221     if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3222       // Accesses to volatile objects are prohibited.
3223       if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3224         if (Info.getLangOpts().CPlusPlus) {
3225           int DiagKind;
3226           SourceLocation Loc;
3227           const NamedDecl *Decl = nullptr;
3228           if (VolatileField) {
3229             DiagKind = 2;
3230             Loc = VolatileField->getLocation();
3231             Decl = VolatileField;
3232           } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3233             DiagKind = 1;
3234             Loc = VD->getLocation();
3235             Decl = VD;
3236           } else {
3237             DiagKind = 0;
3238             if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3239               Loc = E->getExprLoc();
3240           }
3241           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3242               << handler.AccessKind << DiagKind << Decl;
3243           Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3244         } else {
3245           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3246         }
3247         return handler.failed();
3248       }
3249 
3250       // If we are reading an object of class type, there may still be more
3251       // things we need to check: if there are any mutable subobjects, we
3252       // cannot perform this read. (This only happens when performing a trivial
3253       // copy or assignment.)
3254       if (ObjType->isRecordType() &&
3255           !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3256           diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3257         return handler.failed();
3258     }
3259 
3260     if (I == N) {
3261       if (!handler.found(*O, ObjType))
3262         return false;
3263 
3264       // If we modified a bit-field, truncate it to the right width.
3265       if (isModification(handler.AccessKind) &&
3266           LastField && LastField->isBitField() &&
3267           !truncateBitfieldValue(Info, E, *O, LastField))
3268         return false;
3269 
3270       return true;
3271     }
3272 
3273     LastField = nullptr;
3274     if (ObjType->isArrayType()) {
3275       // Next subobject is an array element.
3276       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3277       assert(CAT && "vla in literal type?");
3278       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3279       if (CAT->getSize().ule(Index)) {
3280         // Note, it should not be possible to form a pointer with a valid
3281         // designator which points more than one past the end of the array.
3282         if (Info.getLangOpts().CPlusPlus11)
3283           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3284             << handler.AccessKind;
3285         else
3286           Info.FFDiag(E);
3287         return handler.failed();
3288       }
3289 
3290       ObjType = CAT->getElementType();
3291 
3292       if (O->getArrayInitializedElts() > Index)
3293         O = &O->getArrayInitializedElt(Index);
3294       else if (!isRead(handler.AccessKind)) {
3295         expandArray(*O, Index);
3296         O = &O->getArrayInitializedElt(Index);
3297       } else
3298         O = &O->getArrayFiller();
3299     } else if (ObjType->isAnyComplexType()) {
3300       // Next subobject is a complex number.
3301       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3302       if (Index > 1) {
3303         if (Info.getLangOpts().CPlusPlus11)
3304           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3305             << handler.AccessKind;
3306         else
3307           Info.FFDiag(E);
3308         return handler.failed();
3309       }
3310 
3311       ObjType = getSubobjectType(
3312           ObjType, ObjType->castAs<ComplexType>()->getElementType());
3313 
3314       assert(I == N - 1 && "extracting subobject of scalar?");
3315       if (O->isComplexInt()) {
3316         return handler.found(Index ? O->getComplexIntImag()
3317                                    : O->getComplexIntReal(), ObjType);
3318       } else {
3319         assert(O->isComplexFloat());
3320         return handler.found(Index ? O->getComplexFloatImag()
3321                                    : O->getComplexFloatReal(), ObjType);
3322       }
3323     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3324       if (Field->isMutable() &&
3325           !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3326         Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3327           << handler.AccessKind << Field;
3328         Info.Note(Field->getLocation(), diag::note_declared_at);
3329         return handler.failed();
3330       }
3331 
3332       // Next subobject is a class, struct or union field.
3333       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3334       if (RD->isUnion()) {
3335         const FieldDecl *UnionField = O->getUnionField();
3336         if (!UnionField ||
3337             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3338           if (I == N - 1 && handler.AccessKind == AK_Construct) {
3339             // Placement new onto an inactive union member makes it active.
3340             O->setUnion(Field, APValue());
3341           } else {
3342             // FIXME: If O->getUnionValue() is absent, report that there's no
3343             // active union member rather than reporting the prior active union
3344             // member. We'll need to fix nullptr_t to not use APValue() as its
3345             // representation first.
3346             Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3347                 << handler.AccessKind << Field << !UnionField << UnionField;
3348             return handler.failed();
3349           }
3350         }
3351         O = &O->getUnionValue();
3352       } else
3353         O = &O->getStructField(Field->getFieldIndex());
3354 
3355       ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3356       LastField = Field;
3357       if (Field->getType().isVolatileQualified())
3358         VolatileField = Field;
3359     } else {
3360       // Next subobject is a base class.
3361       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3362       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3363       O = &O->getStructBase(getBaseIndex(Derived, Base));
3364 
3365       ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3366     }
3367   }
3368 }
3369 
3370 namespace {
3371 struct ExtractSubobjectHandler {
3372   EvalInfo &Info;
3373   const Expr *E;
3374   APValue &Result;
3375   const AccessKinds AccessKind;
3376 
3377   typedef bool result_type;
3378   bool failed() { return false; }
3379   bool found(APValue &Subobj, QualType SubobjType) {
3380     Result = Subobj;
3381     if (AccessKind == AK_ReadObjectRepresentation)
3382       return true;
3383     return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3384   }
3385   bool found(APSInt &Value, QualType SubobjType) {
3386     Result = APValue(Value);
3387     return true;
3388   }
3389   bool found(APFloat &Value, QualType SubobjType) {
3390     Result = APValue(Value);
3391     return true;
3392   }
3393 };
3394 } // end anonymous namespace
3395 
3396 /// Extract the designated sub-object of an rvalue.
3397 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3398                              const CompleteObject &Obj,
3399                              const SubobjectDesignator &Sub, APValue &Result,
3400                              AccessKinds AK = AK_Read) {
3401   assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3402   ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3403   return findSubobject(Info, E, Obj, Sub, Handler);
3404 }
3405 
3406 namespace {
3407 struct ModifySubobjectHandler {
3408   EvalInfo &Info;
3409   APValue &NewVal;
3410   const Expr *E;
3411 
3412   typedef bool result_type;
3413   static const AccessKinds AccessKind = AK_Assign;
3414 
3415   bool checkConst(QualType QT) {
3416     // Assigning to a const object has undefined behavior.
3417     if (QT.isConstQualified()) {
3418       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3419       return false;
3420     }
3421     return true;
3422   }
3423 
3424   bool failed() { return false; }
3425   bool found(APValue &Subobj, QualType SubobjType) {
3426     if (!checkConst(SubobjType))
3427       return false;
3428     // We've been given ownership of NewVal, so just swap it in.
3429     Subobj.swap(NewVal);
3430     return true;
3431   }
3432   bool found(APSInt &Value, QualType SubobjType) {
3433     if (!checkConst(SubobjType))
3434       return false;
3435     if (!NewVal.isInt()) {
3436       // Maybe trying to write a cast pointer value into a complex?
3437       Info.FFDiag(E);
3438       return false;
3439     }
3440     Value = NewVal.getInt();
3441     return true;
3442   }
3443   bool found(APFloat &Value, QualType SubobjType) {
3444     if (!checkConst(SubobjType))
3445       return false;
3446     Value = NewVal.getFloat();
3447     return true;
3448   }
3449 };
3450 } // end anonymous namespace
3451 
3452 const AccessKinds ModifySubobjectHandler::AccessKind;
3453 
3454 /// Update the designated sub-object of an rvalue to the given value.
3455 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3456                             const CompleteObject &Obj,
3457                             const SubobjectDesignator &Sub,
3458                             APValue &NewVal) {
3459   ModifySubobjectHandler Handler = { Info, NewVal, E };
3460   return findSubobject(Info, E, Obj, Sub, Handler);
3461 }
3462 
3463 /// Find the position where two subobject designators diverge, or equivalently
3464 /// the length of the common initial subsequence.
3465 static unsigned FindDesignatorMismatch(QualType ObjType,
3466                                        const SubobjectDesignator &A,
3467                                        const SubobjectDesignator &B,
3468                                        bool &WasArrayIndex) {
3469   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3470   for (/**/; I != N; ++I) {
3471     if (!ObjType.isNull() &&
3472         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3473       // Next subobject is an array element.
3474       if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3475         WasArrayIndex = true;
3476         return I;
3477       }
3478       if (ObjType->isAnyComplexType())
3479         ObjType = ObjType->castAs<ComplexType>()->getElementType();
3480       else
3481         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3482     } else {
3483       if (A.Entries[I].getAsBaseOrMember() !=
3484           B.Entries[I].getAsBaseOrMember()) {
3485         WasArrayIndex = false;
3486         return I;
3487       }
3488       if (const FieldDecl *FD = getAsField(A.Entries[I]))
3489         // Next subobject is a field.
3490         ObjType = FD->getType();
3491       else
3492         // Next subobject is a base class.
3493         ObjType = QualType();
3494     }
3495   }
3496   WasArrayIndex = false;
3497   return I;
3498 }
3499 
3500 /// Determine whether the given subobject designators refer to elements of the
3501 /// same array object.
3502 static bool AreElementsOfSameArray(QualType ObjType,
3503                                    const SubobjectDesignator &A,
3504                                    const SubobjectDesignator &B) {
3505   if (A.Entries.size() != B.Entries.size())
3506     return false;
3507 
3508   bool IsArray = A.MostDerivedIsArrayElement;
3509   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3510     // A is a subobject of the array element.
3511     return false;
3512 
3513   // If A (and B) designates an array element, the last entry will be the array
3514   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3515   // of length 1' case, and the entire path must match.
3516   bool WasArrayIndex;
3517   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3518   return CommonLength >= A.Entries.size() - IsArray;
3519 }
3520 
3521 /// Find the complete object to which an LValue refers.
3522 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3523                                          AccessKinds AK, const LValue &LVal,
3524                                          QualType LValType) {
3525   if (LVal.InvalidBase) {
3526     Info.FFDiag(E);
3527     return CompleteObject();
3528   }
3529 
3530   if (!LVal.Base) {
3531     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3532     return CompleteObject();
3533   }
3534 
3535   CallStackFrame *Frame = nullptr;
3536   unsigned Depth = 0;
3537   if (LVal.getLValueCallIndex()) {
3538     std::tie(Frame, Depth) =
3539         Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3540     if (!Frame) {
3541       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3542         << AK << LVal.Base.is<const ValueDecl*>();
3543       NoteLValueLocation(Info, LVal.Base);
3544       return CompleteObject();
3545     }
3546   }
3547 
3548   bool IsAccess = isAnyAccess(AK);
3549 
3550   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3551   // is not a constant expression (even if the object is non-volatile). We also
3552   // apply this rule to C++98, in order to conform to the expected 'volatile'
3553   // semantics.
3554   if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
3555     if (Info.getLangOpts().CPlusPlus)
3556       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3557         << AK << LValType;
3558     else
3559       Info.FFDiag(E);
3560     return CompleteObject();
3561   }
3562 
3563   // Compute value storage location and type of base object.
3564   APValue *BaseVal = nullptr;
3565   QualType BaseType = getType(LVal.Base);
3566 
3567   if (const ConstantExpr *CE =
3568           dyn_cast_or_null<ConstantExpr>(LVal.Base.dyn_cast<const Expr *>())) {
3569     /// Nested immediate invocation have been previously removed so if we found
3570     /// a ConstantExpr it can only be the EvaluatingDecl.
3571     assert(CE->isImmediateInvocation() && CE == Info.EvaluatingDecl);
3572     BaseVal = Info.EvaluatingDeclValue;
3573   } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
3574     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3575     // In C++11, constexpr, non-volatile variables initialized with constant
3576     // expressions are constant expressions too. Inside constexpr functions,
3577     // parameters are constant expressions even if they're non-const.
3578     // In C++1y, objects local to a constant expression (those with a Frame) are
3579     // both readable and writable inside constant expressions.
3580     // In C, such things can also be folded, although they are not ICEs.
3581     const VarDecl *VD = dyn_cast<VarDecl>(D);
3582     if (VD) {
3583       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3584         VD = VDef;
3585     }
3586     if (!VD || VD->isInvalidDecl()) {
3587       Info.FFDiag(E);
3588       return CompleteObject();
3589     }
3590 
3591     // Unless we're looking at a local variable or argument in a constexpr call,
3592     // the variable we're reading must be const.
3593     if (!Frame) {
3594       if (Info.getLangOpts().CPlusPlus14 &&
3595           lifetimeStartedInEvaluation(Info, LVal.Base)) {
3596         // OK, we can read and modify an object if we're in the process of
3597         // evaluating its initializer, because its lifetime began in this
3598         // evaluation.
3599       } else if (isModification(AK)) {
3600         // All the remaining cases do not permit modification of the object.
3601         Info.FFDiag(E, diag::note_constexpr_modify_global);
3602         return CompleteObject();
3603       } else if (VD->isConstexpr()) {
3604         // OK, we can read this variable.
3605       } else if (BaseType->isIntegralOrEnumerationType()) {
3606         // In OpenCL if a variable is in constant address space it is a const
3607         // value.
3608         if (!(BaseType.isConstQualified() ||
3609               (Info.getLangOpts().OpenCL &&
3610                BaseType.getAddressSpace() == LangAS::opencl_constant))) {
3611           if (!IsAccess)
3612             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3613           if (Info.getLangOpts().CPlusPlus) {
3614             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
3615             Info.Note(VD->getLocation(), diag::note_declared_at);
3616           } else {
3617             Info.FFDiag(E);
3618           }
3619           return CompleteObject();
3620         }
3621       } else if (!IsAccess) {
3622         return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3623       } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3624         // We support folding of const floating-point types, in order to make
3625         // static const data members of such types (supported as an extension)
3626         // more useful.
3627         if (Info.getLangOpts().CPlusPlus11) {
3628           Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3629           Info.Note(VD->getLocation(), diag::note_declared_at);
3630         } else {
3631           Info.CCEDiag(E);
3632         }
3633       } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3634         Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3635         // Keep evaluating to see what we can do.
3636       } else {
3637         // FIXME: Allow folding of values of any literal type in all languages.
3638         if (Info.checkingPotentialConstantExpression() &&
3639             VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3640           // The definition of this variable could be constexpr. We can't
3641           // access it right now, but may be able to in future.
3642         } else if (Info.getLangOpts().CPlusPlus11) {
3643           Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3644           Info.Note(VD->getLocation(), diag::note_declared_at);
3645         } else {
3646           Info.FFDiag(E);
3647         }
3648         return CompleteObject();
3649       }
3650     }
3651 
3652     if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
3653       return CompleteObject();
3654   } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
3655     Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
3656     if (!Alloc) {
3657       Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
3658       return CompleteObject();
3659     }
3660     return CompleteObject(LVal.Base, &(*Alloc)->Value,
3661                           LVal.Base.getDynamicAllocType());
3662   } else {
3663     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3664 
3665     if (!Frame) {
3666       if (const MaterializeTemporaryExpr *MTE =
3667               dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
3668         assert(MTE->getStorageDuration() == SD_Static &&
3669                "should have a frame for a non-global materialized temporary");
3670 
3671         // Per C++1y [expr.const]p2:
3672         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3673         //   - a [...] glvalue of integral or enumeration type that refers to
3674         //     a non-volatile const object [...]
3675         //   [...]
3676         //   - a [...] glvalue of literal type that refers to a non-volatile
3677         //     object whose lifetime began within the evaluation of e.
3678         //
3679         // C++11 misses the 'began within the evaluation of e' check and
3680         // instead allows all temporaries, including things like:
3681         //   int &&r = 1;
3682         //   int x = ++r;
3683         //   constexpr int k = r;
3684         // Therefore we use the C++14 rules in C++11 too.
3685         //
3686         // Note that temporaries whose lifetimes began while evaluating a
3687         // variable's constructor are not usable while evaluating the
3688         // corresponding destructor, not even if they're of const-qualified
3689         // types.
3690         if (!(BaseType.isConstQualified() &&
3691               BaseType->isIntegralOrEnumerationType()) &&
3692             !lifetimeStartedInEvaluation(Info, LVal.Base)) {
3693           if (!IsAccess)
3694             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3695           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
3696           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3697           return CompleteObject();
3698         }
3699 
3700         BaseVal = MTE->getOrCreateValue(false);
3701         assert(BaseVal && "got reference to unevaluated temporary");
3702       } else {
3703         if (!IsAccess)
3704           return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3705         APValue Val;
3706         LVal.moveInto(Val);
3707         Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
3708             << AK
3709             << Val.getAsString(Info.Ctx,
3710                                Info.Ctx.getLValueReferenceType(LValType));
3711         NoteLValueLocation(Info, LVal.Base);
3712         return CompleteObject();
3713       }
3714     } else {
3715       BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
3716       assert(BaseVal && "missing value for temporary");
3717     }
3718   }
3719 
3720   // In C++14, we can't safely access any mutable state when we might be
3721   // evaluating after an unmodeled side effect.
3722   //
3723   // FIXME: Not all local state is mutable. Allow local constant subobjects
3724   // to be read here (but take care with 'mutable' fields).
3725   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3726        Info.EvalStatus.HasSideEffects) ||
3727       (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth))
3728     return CompleteObject();
3729 
3730   return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
3731 }
3732 
3733 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
3734 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3735 /// glvalue referred to by an entity of reference type.
3736 ///
3737 /// \param Info - Information about the ongoing evaluation.
3738 /// \param Conv - The expression for which we are performing the conversion.
3739 ///               Used for diagnostics.
3740 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3741 ///               case of a non-class type).
3742 /// \param LVal - The glvalue on which we are attempting to perform this action.
3743 /// \param RVal - The produced value will be placed here.
3744 /// \param WantObjectRepresentation - If true, we're looking for the object
3745 ///               representation rather than the value, and in particular,
3746 ///               there is no requirement that the result be fully initialized.
3747 static bool
3748 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
3749                                const LValue &LVal, APValue &RVal,
3750                                bool WantObjectRepresentation = false) {
3751   if (LVal.Designator.Invalid)
3752     return false;
3753 
3754   // Check for special cases where there is no existing APValue to look at.
3755   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3756 
3757   AccessKinds AK =
3758       WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
3759 
3760   if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
3761     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3762       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3763       // initializer until now for such expressions. Such an expression can't be
3764       // an ICE in C, so this only matters for fold.
3765       if (Type.isVolatileQualified()) {
3766         Info.FFDiag(Conv);
3767         return false;
3768       }
3769       APValue Lit;
3770       if (!Evaluate(Lit, Info, CLE->getInitializer()))
3771         return false;
3772       CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
3773       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
3774     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
3775       // Special-case character extraction so we don't have to construct an
3776       // APValue for the whole string.
3777       assert(LVal.Designator.Entries.size() <= 1 &&
3778              "Can only read characters from string literals");
3779       if (LVal.Designator.Entries.empty()) {
3780         // Fail for now for LValue to RValue conversion of an array.
3781         // (This shouldn't show up in C/C++, but it could be triggered by a
3782         // weird EvaluateAsRValue call from a tool.)
3783         Info.FFDiag(Conv);
3784         return false;
3785       }
3786       if (LVal.Designator.isOnePastTheEnd()) {
3787         if (Info.getLangOpts().CPlusPlus11)
3788           Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
3789         else
3790           Info.FFDiag(Conv);
3791         return false;
3792       }
3793       uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
3794       RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
3795       return true;
3796     }
3797   }
3798 
3799   CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
3800   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
3801 }
3802 
3803 /// Perform an assignment of Val to LVal. Takes ownership of Val.
3804 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
3805                              QualType LValType, APValue &Val) {
3806   if (LVal.Designator.Invalid)
3807     return false;
3808 
3809   if (!Info.getLangOpts().CPlusPlus14) {
3810     Info.FFDiag(E);
3811     return false;
3812   }
3813 
3814   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3815   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3816 }
3817 
3818 namespace {
3819 struct CompoundAssignSubobjectHandler {
3820   EvalInfo &Info;
3821   const Expr *E;
3822   QualType PromotedLHSType;
3823   BinaryOperatorKind Opcode;
3824   const APValue &RHS;
3825 
3826   static const AccessKinds AccessKind = AK_Assign;
3827 
3828   typedef bool result_type;
3829 
3830   bool checkConst(QualType QT) {
3831     // Assigning to a const object has undefined behavior.
3832     if (QT.isConstQualified()) {
3833       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3834       return false;
3835     }
3836     return true;
3837   }
3838 
3839   bool failed() { return false; }
3840   bool found(APValue &Subobj, QualType SubobjType) {
3841     switch (Subobj.getKind()) {
3842     case APValue::Int:
3843       return found(Subobj.getInt(), SubobjType);
3844     case APValue::Float:
3845       return found(Subobj.getFloat(), SubobjType);
3846     case APValue::ComplexInt:
3847     case APValue::ComplexFloat:
3848       // FIXME: Implement complex compound assignment.
3849       Info.FFDiag(E);
3850       return false;
3851     case APValue::LValue:
3852       return foundPointer(Subobj, SubobjType);
3853     default:
3854       // FIXME: can this happen?
3855       Info.FFDiag(E);
3856       return false;
3857     }
3858   }
3859   bool found(APSInt &Value, QualType SubobjType) {
3860     if (!checkConst(SubobjType))
3861       return false;
3862 
3863     if (!SubobjType->isIntegerType()) {
3864       // We don't support compound assignment on integer-cast-to-pointer
3865       // values.
3866       Info.FFDiag(E);
3867       return false;
3868     }
3869 
3870     if (RHS.isInt()) {
3871       APSInt LHS =
3872           HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
3873       if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3874         return false;
3875       Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3876       return true;
3877     } else if (RHS.isFloat()) {
3878       APFloat FValue(0.0);
3879       return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
3880                                   FValue) &&
3881              handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
3882              HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
3883                                   Value);
3884     }
3885 
3886     Info.FFDiag(E);
3887     return false;
3888   }
3889   bool found(APFloat &Value, QualType SubobjType) {
3890     return checkConst(SubobjType) &&
3891            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3892                                   Value) &&
3893            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3894            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
3895   }
3896   bool foundPointer(APValue &Subobj, QualType SubobjType) {
3897     if (!checkConst(SubobjType))
3898       return false;
3899 
3900     QualType PointeeType;
3901     if (const PointerType *PT = SubobjType->getAs<PointerType>())
3902       PointeeType = PT->getPointeeType();
3903 
3904     if (PointeeType.isNull() || !RHS.isInt() ||
3905         (Opcode != BO_Add && Opcode != BO_Sub)) {
3906       Info.FFDiag(E);
3907       return false;
3908     }
3909 
3910     APSInt Offset = RHS.getInt();
3911     if (Opcode == BO_Sub)
3912       negateAsSigned(Offset);
3913 
3914     LValue LVal;
3915     LVal.setFrom(Info.Ctx, Subobj);
3916     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3917       return false;
3918     LVal.moveInto(Subobj);
3919     return true;
3920   }
3921 };
3922 } // end anonymous namespace
3923 
3924 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3925 
3926 /// Perform a compound assignment of LVal <op>= RVal.
3927 static bool handleCompoundAssignment(
3928     EvalInfo &Info, const Expr *E,
3929     const LValue &LVal, QualType LValType, QualType PromotedLValType,
3930     BinaryOperatorKind Opcode, const APValue &RVal) {
3931   if (LVal.Designator.Invalid)
3932     return false;
3933 
3934   if (!Info.getLangOpts().CPlusPlus14) {
3935     Info.FFDiag(E);
3936     return false;
3937   }
3938 
3939   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3940   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3941                                              RVal };
3942   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3943 }
3944 
3945 namespace {
3946 struct IncDecSubobjectHandler {
3947   EvalInfo &Info;
3948   const UnaryOperator *E;
3949   AccessKinds AccessKind;
3950   APValue *Old;
3951 
3952   typedef bool result_type;
3953 
3954   bool checkConst(QualType QT) {
3955     // Assigning to a const object has undefined behavior.
3956     if (QT.isConstQualified()) {
3957       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3958       return false;
3959     }
3960     return true;
3961   }
3962 
3963   bool failed() { return false; }
3964   bool found(APValue &Subobj, QualType SubobjType) {
3965     // Stash the old value. Also clear Old, so we don't clobber it later
3966     // if we're post-incrementing a complex.
3967     if (Old) {
3968       *Old = Subobj;
3969       Old = nullptr;
3970     }
3971 
3972     switch (Subobj.getKind()) {
3973     case APValue::Int:
3974       return found(Subobj.getInt(), SubobjType);
3975     case APValue::Float:
3976       return found(Subobj.getFloat(), SubobjType);
3977     case APValue::ComplexInt:
3978       return found(Subobj.getComplexIntReal(),
3979                    SubobjType->castAs<ComplexType>()->getElementType()
3980                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3981     case APValue::ComplexFloat:
3982       return found(Subobj.getComplexFloatReal(),
3983                    SubobjType->castAs<ComplexType>()->getElementType()
3984                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3985     case APValue::LValue:
3986       return foundPointer(Subobj, SubobjType);
3987     default:
3988       // FIXME: can this happen?
3989       Info.FFDiag(E);
3990       return false;
3991     }
3992   }
3993   bool found(APSInt &Value, QualType SubobjType) {
3994     if (!checkConst(SubobjType))
3995       return false;
3996 
3997     if (!SubobjType->isIntegerType()) {
3998       // We don't support increment / decrement on integer-cast-to-pointer
3999       // values.
4000       Info.FFDiag(E);
4001       return false;
4002     }
4003 
4004     if (Old) *Old = APValue(Value);
4005 
4006     // bool arithmetic promotes to int, and the conversion back to bool
4007     // doesn't reduce mod 2^n, so special-case it.
4008     if (SubobjType->isBooleanType()) {
4009       if (AccessKind == AK_Increment)
4010         Value = 1;
4011       else
4012         Value = !Value;
4013       return true;
4014     }
4015 
4016     bool WasNegative = Value.isNegative();
4017     if (AccessKind == AK_Increment) {
4018       ++Value;
4019 
4020       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4021         APSInt ActualValue(Value, /*IsUnsigned*/true);
4022         return HandleOverflow(Info, E, ActualValue, SubobjType);
4023       }
4024     } else {
4025       --Value;
4026 
4027       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4028         unsigned BitWidth = Value.getBitWidth();
4029         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4030         ActualValue.setBit(BitWidth);
4031         return HandleOverflow(Info, E, ActualValue, SubobjType);
4032       }
4033     }
4034     return true;
4035   }
4036   bool found(APFloat &Value, QualType SubobjType) {
4037     if (!checkConst(SubobjType))
4038       return false;
4039 
4040     if (Old) *Old = APValue(Value);
4041 
4042     APFloat One(Value.getSemantics(), 1);
4043     if (AccessKind == AK_Increment)
4044       Value.add(One, APFloat::rmNearestTiesToEven);
4045     else
4046       Value.subtract(One, APFloat::rmNearestTiesToEven);
4047     return true;
4048   }
4049   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4050     if (!checkConst(SubobjType))
4051       return false;
4052 
4053     QualType PointeeType;
4054     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4055       PointeeType = PT->getPointeeType();
4056     else {
4057       Info.FFDiag(E);
4058       return false;
4059     }
4060 
4061     LValue LVal;
4062     LVal.setFrom(Info.Ctx, Subobj);
4063     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4064                                      AccessKind == AK_Increment ? 1 : -1))
4065       return false;
4066     LVal.moveInto(Subobj);
4067     return true;
4068   }
4069 };
4070 } // end anonymous namespace
4071 
4072 /// Perform an increment or decrement on LVal.
4073 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4074                          QualType LValType, bool IsIncrement, APValue *Old) {
4075   if (LVal.Designator.Invalid)
4076     return false;
4077 
4078   if (!Info.getLangOpts().CPlusPlus14) {
4079     Info.FFDiag(E);
4080     return false;
4081   }
4082 
4083   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4084   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4085   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4086   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4087 }
4088 
4089 /// Build an lvalue for the object argument of a member function call.
4090 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4091                                    LValue &This) {
4092   if (Object->getType()->isPointerType() && Object->isRValue())
4093     return EvaluatePointer(Object, This, Info);
4094 
4095   if (Object->isGLValue())
4096     return EvaluateLValue(Object, This, Info);
4097 
4098   if (Object->getType()->isLiteralType(Info.Ctx))
4099     return EvaluateTemporary(Object, This, Info);
4100 
4101   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4102   return false;
4103 }
4104 
4105 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
4106 /// lvalue referring to the result.
4107 ///
4108 /// \param Info - Information about the ongoing evaluation.
4109 /// \param LV - An lvalue referring to the base of the member pointer.
4110 /// \param RHS - The member pointer expression.
4111 /// \param IncludeMember - Specifies whether the member itself is included in
4112 ///        the resulting LValue subobject designator. This is not possible when
4113 ///        creating a bound member function.
4114 /// \return The field or method declaration to which the member pointer refers,
4115 ///         or 0 if evaluation fails.
4116 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4117                                                   QualType LVType,
4118                                                   LValue &LV,
4119                                                   const Expr *RHS,
4120                                                   bool IncludeMember = true) {
4121   MemberPtr MemPtr;
4122   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4123     return nullptr;
4124 
4125   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4126   // member value, the behavior is undefined.
4127   if (!MemPtr.getDecl()) {
4128     // FIXME: Specific diagnostic.
4129     Info.FFDiag(RHS);
4130     return nullptr;
4131   }
4132 
4133   if (MemPtr.isDerivedMember()) {
4134     // This is a member of some derived class. Truncate LV appropriately.
4135     // The end of the derived-to-base path for the base object must match the
4136     // derived-to-base path for the member pointer.
4137     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4138         LV.Designator.Entries.size()) {
4139       Info.FFDiag(RHS);
4140       return nullptr;
4141     }
4142     unsigned PathLengthToMember =
4143         LV.Designator.Entries.size() - MemPtr.Path.size();
4144     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4145       const CXXRecordDecl *LVDecl = getAsBaseClass(
4146           LV.Designator.Entries[PathLengthToMember + I]);
4147       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4148       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4149         Info.FFDiag(RHS);
4150         return nullptr;
4151       }
4152     }
4153 
4154     // Truncate the lvalue to the appropriate derived class.
4155     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4156                             PathLengthToMember))
4157       return nullptr;
4158   } else if (!MemPtr.Path.empty()) {
4159     // Extend the LValue path with the member pointer's path.
4160     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4161                                   MemPtr.Path.size() + IncludeMember);
4162 
4163     // Walk down to the appropriate base class.
4164     if (const PointerType *PT = LVType->getAs<PointerType>())
4165       LVType = PT->getPointeeType();
4166     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4167     assert(RD && "member pointer access on non-class-type expression");
4168     // The first class in the path is that of the lvalue.
4169     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4170       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4171       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4172         return nullptr;
4173       RD = Base;
4174     }
4175     // Finally cast to the class containing the member.
4176     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4177                                 MemPtr.getContainingRecord()))
4178       return nullptr;
4179   }
4180 
4181   // Add the member. Note that we cannot build bound member functions here.
4182   if (IncludeMember) {
4183     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4184       if (!HandleLValueMember(Info, RHS, LV, FD))
4185         return nullptr;
4186     } else if (const IndirectFieldDecl *IFD =
4187                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4188       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4189         return nullptr;
4190     } else {
4191       llvm_unreachable("can't construct reference to bound member function");
4192     }
4193   }
4194 
4195   return MemPtr.getDecl();
4196 }
4197 
4198 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4199                                                   const BinaryOperator *BO,
4200                                                   LValue &LV,
4201                                                   bool IncludeMember = true) {
4202   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4203 
4204   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4205     if (Info.noteFailure()) {
4206       MemberPtr MemPtr;
4207       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4208     }
4209     return nullptr;
4210   }
4211 
4212   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4213                                    BO->getRHS(), IncludeMember);
4214 }
4215 
4216 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4217 /// the provided lvalue, which currently refers to the base object.
4218 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4219                                     LValue &Result) {
4220   SubobjectDesignator &D = Result.Designator;
4221   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4222     return false;
4223 
4224   QualType TargetQT = E->getType();
4225   if (const PointerType *PT = TargetQT->getAs<PointerType>())
4226     TargetQT = PT->getPointeeType();
4227 
4228   // Check this cast lands within the final derived-to-base subobject path.
4229   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4230     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4231       << D.MostDerivedType << TargetQT;
4232     return false;
4233   }
4234 
4235   // Check the type of the final cast. We don't need to check the path,
4236   // since a cast can only be formed if the path is unique.
4237   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4238   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4239   const CXXRecordDecl *FinalType;
4240   if (NewEntriesSize == D.MostDerivedPathLength)
4241     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4242   else
4243     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4244   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4245     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4246       << D.MostDerivedType << TargetQT;
4247     return false;
4248   }
4249 
4250   // Truncate the lvalue to the appropriate derived class.
4251   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4252 }
4253 
4254 /// Get the value to use for a default-initialized object of type T.
4255 static APValue getDefaultInitValue(QualType T) {
4256   if (auto *RD = T->getAsCXXRecordDecl()) {
4257     if (RD->isUnion())
4258       return APValue((const FieldDecl*)nullptr);
4259 
4260     APValue Struct(APValue::UninitStruct(), RD->getNumBases(),
4261                    std::distance(RD->field_begin(), RD->field_end()));
4262 
4263     unsigned Index = 0;
4264     for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4265            End = RD->bases_end(); I != End; ++I, ++Index)
4266       Struct.getStructBase(Index) = getDefaultInitValue(I->getType());
4267 
4268     for (const auto *I : RD->fields()) {
4269       if (I->isUnnamedBitfield())
4270         continue;
4271       Struct.getStructField(I->getFieldIndex()) =
4272           getDefaultInitValue(I->getType());
4273     }
4274     return Struct;
4275   }
4276 
4277   if (auto *AT =
4278           dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4279     APValue Array(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4280     if (Array.hasArrayFiller())
4281       Array.getArrayFiller() = getDefaultInitValue(AT->getElementType());
4282     return Array;
4283   }
4284 
4285   return APValue::IndeterminateValue();
4286 }
4287 
4288 namespace {
4289 enum EvalStmtResult {
4290   /// Evaluation failed.
4291   ESR_Failed,
4292   /// Hit a 'return' statement.
4293   ESR_Returned,
4294   /// Evaluation succeeded.
4295   ESR_Succeeded,
4296   /// Hit a 'continue' statement.
4297   ESR_Continue,
4298   /// Hit a 'break' statement.
4299   ESR_Break,
4300   /// Still scanning for 'case' or 'default' statement.
4301   ESR_CaseNotFound
4302 };
4303 }
4304 
4305 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4306   // We don't need to evaluate the initializer for a static local.
4307   if (!VD->hasLocalStorage())
4308     return true;
4309 
4310   LValue Result;
4311   APValue &Val =
4312       Info.CurrentCall->createTemporary(VD, VD->getType(), true, Result);
4313 
4314   const Expr *InitE = VD->getInit();
4315   if (!InitE) {
4316     Val = getDefaultInitValue(VD->getType());
4317     return true;
4318   }
4319 
4320   if (InitE->isValueDependent())
4321     return false;
4322 
4323   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4324     // Wipe out any partially-computed value, to allow tracking that this
4325     // evaluation failed.
4326     Val = APValue();
4327     return false;
4328   }
4329 
4330   return true;
4331 }
4332 
4333 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4334   bool OK = true;
4335 
4336   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4337     OK &= EvaluateVarDecl(Info, VD);
4338 
4339   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4340     for (auto *BD : DD->bindings())
4341       if (auto *VD = BD->getHoldingVar())
4342         OK &= EvaluateDecl(Info, VD);
4343 
4344   return OK;
4345 }
4346 
4347 
4348 /// Evaluate a condition (either a variable declaration or an expression).
4349 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4350                          const Expr *Cond, bool &Result) {
4351   FullExpressionRAII Scope(Info);
4352   if (CondDecl && !EvaluateDecl(Info, CondDecl))
4353     return false;
4354   if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4355     return false;
4356   return Scope.destroy();
4357 }
4358 
4359 namespace {
4360 /// A location where the result (returned value) of evaluating a
4361 /// statement should be stored.
4362 struct StmtResult {
4363   /// The APValue that should be filled in with the returned value.
4364   APValue &Value;
4365   /// The location containing the result, if any (used to support RVO).
4366   const LValue *Slot;
4367 };
4368 
4369 struct TempVersionRAII {
4370   CallStackFrame &Frame;
4371 
4372   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4373     Frame.pushTempVersion();
4374   }
4375 
4376   ~TempVersionRAII() {
4377     Frame.popTempVersion();
4378   }
4379 };
4380 
4381 }
4382 
4383 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4384                                    const Stmt *S,
4385                                    const SwitchCase *SC = nullptr);
4386 
4387 /// Evaluate the body of a loop, and translate the result as appropriate.
4388 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4389                                        const Stmt *Body,
4390                                        const SwitchCase *Case = nullptr) {
4391   BlockScopeRAII Scope(Info);
4392 
4393   EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4394   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4395     ESR = ESR_Failed;
4396 
4397   switch (ESR) {
4398   case ESR_Break:
4399     return ESR_Succeeded;
4400   case ESR_Succeeded:
4401   case ESR_Continue:
4402     return ESR_Continue;
4403   case ESR_Failed:
4404   case ESR_Returned:
4405   case ESR_CaseNotFound:
4406     return ESR;
4407   }
4408   llvm_unreachable("Invalid EvalStmtResult!");
4409 }
4410 
4411 /// Evaluate a switch statement.
4412 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4413                                      const SwitchStmt *SS) {
4414   BlockScopeRAII Scope(Info);
4415 
4416   // Evaluate the switch condition.
4417   APSInt Value;
4418   {
4419     if (const Stmt *Init = SS->getInit()) {
4420       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4421       if (ESR != ESR_Succeeded) {
4422         if (ESR != ESR_Failed && !Scope.destroy())
4423           ESR = ESR_Failed;
4424         return ESR;
4425       }
4426     }
4427 
4428     FullExpressionRAII CondScope(Info);
4429     if (SS->getConditionVariable() &&
4430         !EvaluateDecl(Info, SS->getConditionVariable()))
4431       return ESR_Failed;
4432     if (!EvaluateInteger(SS->getCond(), Value, Info))
4433       return ESR_Failed;
4434     if (!CondScope.destroy())
4435       return ESR_Failed;
4436   }
4437 
4438   // Find the switch case corresponding to the value of the condition.
4439   // FIXME: Cache this lookup.
4440   const SwitchCase *Found = nullptr;
4441   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4442        SC = SC->getNextSwitchCase()) {
4443     if (isa<DefaultStmt>(SC)) {
4444       Found = SC;
4445       continue;
4446     }
4447 
4448     const CaseStmt *CS = cast<CaseStmt>(SC);
4449     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4450     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4451                               : LHS;
4452     if (LHS <= Value && Value <= RHS) {
4453       Found = SC;
4454       break;
4455     }
4456   }
4457 
4458   if (!Found)
4459     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4460 
4461   // Search the switch body for the switch case and evaluate it from there.
4462   EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
4463   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4464     return ESR_Failed;
4465 
4466   switch (ESR) {
4467   case ESR_Break:
4468     return ESR_Succeeded;
4469   case ESR_Succeeded:
4470   case ESR_Continue:
4471   case ESR_Failed:
4472   case ESR_Returned:
4473     return ESR;
4474   case ESR_CaseNotFound:
4475     // This can only happen if the switch case is nested within a statement
4476     // expression. We have no intention of supporting that.
4477     Info.FFDiag(Found->getBeginLoc(),
4478                 diag::note_constexpr_stmt_expr_unsupported);
4479     return ESR_Failed;
4480   }
4481   llvm_unreachable("Invalid EvalStmtResult!");
4482 }
4483 
4484 // Evaluate a statement.
4485 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4486                                    const Stmt *S, const SwitchCase *Case) {
4487   if (!Info.nextStep(S))
4488     return ESR_Failed;
4489 
4490   // If we're hunting down a 'case' or 'default' label, recurse through
4491   // substatements until we hit the label.
4492   if (Case) {
4493     switch (S->getStmtClass()) {
4494     case Stmt::CompoundStmtClass:
4495       // FIXME: Precompute which substatement of a compound statement we
4496       // would jump to, and go straight there rather than performing a
4497       // linear scan each time.
4498     case Stmt::LabelStmtClass:
4499     case Stmt::AttributedStmtClass:
4500     case Stmt::DoStmtClass:
4501       break;
4502 
4503     case Stmt::CaseStmtClass:
4504     case Stmt::DefaultStmtClass:
4505       if (Case == S)
4506         Case = nullptr;
4507       break;
4508 
4509     case Stmt::IfStmtClass: {
4510       // FIXME: Precompute which side of an 'if' we would jump to, and go
4511       // straight there rather than scanning both sides.
4512       const IfStmt *IS = cast<IfStmt>(S);
4513 
4514       // Wrap the evaluation in a block scope, in case it's a DeclStmt
4515       // preceded by our switch label.
4516       BlockScopeRAII Scope(Info);
4517 
4518       // Step into the init statement in case it brings an (uninitialized)
4519       // variable into scope.
4520       if (const Stmt *Init = IS->getInit()) {
4521         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
4522         if (ESR != ESR_CaseNotFound) {
4523           assert(ESR != ESR_Succeeded);
4524           return ESR;
4525         }
4526       }
4527 
4528       // Condition variable must be initialized if it exists.
4529       // FIXME: We can skip evaluating the body if there's a condition
4530       // variable, as there can't be any case labels within it.
4531       // (The same is true for 'for' statements.)
4532 
4533       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
4534       if (ESR == ESR_Failed)
4535         return ESR;
4536       if (ESR != ESR_CaseNotFound)
4537         return Scope.destroy() ? ESR : ESR_Failed;
4538       if (!IS->getElse())
4539         return ESR_CaseNotFound;
4540 
4541       ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
4542       if (ESR == ESR_Failed)
4543         return ESR;
4544       if (ESR != ESR_CaseNotFound)
4545         return Scope.destroy() ? ESR : ESR_Failed;
4546       return ESR_CaseNotFound;
4547     }
4548 
4549     case Stmt::WhileStmtClass: {
4550       EvalStmtResult ESR =
4551           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4552       if (ESR != ESR_Continue)
4553         return ESR;
4554       break;
4555     }
4556 
4557     case Stmt::ForStmtClass: {
4558       const ForStmt *FS = cast<ForStmt>(S);
4559       BlockScopeRAII Scope(Info);
4560 
4561       // Step into the init statement in case it brings an (uninitialized)
4562       // variable into scope.
4563       if (const Stmt *Init = FS->getInit()) {
4564         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
4565         if (ESR != ESR_CaseNotFound) {
4566           assert(ESR != ESR_Succeeded);
4567           return ESR;
4568         }
4569       }
4570 
4571       EvalStmtResult ESR =
4572           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4573       if (ESR != ESR_Continue)
4574         return ESR;
4575       if (FS->getInc()) {
4576         FullExpressionRAII IncScope(Info);
4577         if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
4578           return ESR_Failed;
4579       }
4580       break;
4581     }
4582 
4583     case Stmt::DeclStmtClass: {
4584       // Start the lifetime of any uninitialized variables we encounter. They
4585       // might be used by the selected branch of the switch.
4586       const DeclStmt *DS = cast<DeclStmt>(S);
4587       for (const auto *D : DS->decls()) {
4588         if (const auto *VD = dyn_cast<VarDecl>(D)) {
4589           if (VD->hasLocalStorage() && !VD->getInit())
4590             if (!EvaluateVarDecl(Info, VD))
4591               return ESR_Failed;
4592           // FIXME: If the variable has initialization that can't be jumped
4593           // over, bail out of any immediately-surrounding compound-statement
4594           // too. There can't be any case labels here.
4595         }
4596       }
4597       return ESR_CaseNotFound;
4598     }
4599 
4600     default:
4601       return ESR_CaseNotFound;
4602     }
4603   }
4604 
4605   switch (S->getStmtClass()) {
4606   default:
4607     if (const Expr *E = dyn_cast<Expr>(S)) {
4608       // Don't bother evaluating beyond an expression-statement which couldn't
4609       // be evaluated.
4610       // FIXME: Do we need the FullExpressionRAII object here?
4611       // VisitExprWithCleanups should create one when necessary.
4612       FullExpressionRAII Scope(Info);
4613       if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
4614         return ESR_Failed;
4615       return ESR_Succeeded;
4616     }
4617 
4618     Info.FFDiag(S->getBeginLoc());
4619     return ESR_Failed;
4620 
4621   case Stmt::NullStmtClass:
4622     return ESR_Succeeded;
4623 
4624   case Stmt::DeclStmtClass: {
4625     const DeclStmt *DS = cast<DeclStmt>(S);
4626     for (const auto *D : DS->decls()) {
4627       // Each declaration initialization is its own full-expression.
4628       FullExpressionRAII Scope(Info);
4629       if (!EvaluateDecl(Info, D) && !Info.noteFailure())
4630         return ESR_Failed;
4631       if (!Scope.destroy())
4632         return ESR_Failed;
4633     }
4634     return ESR_Succeeded;
4635   }
4636 
4637   case Stmt::ReturnStmtClass: {
4638     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
4639     FullExpressionRAII Scope(Info);
4640     if (RetExpr &&
4641         !(Result.Slot
4642               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4643               : Evaluate(Result.Value, Info, RetExpr)))
4644       return ESR_Failed;
4645     return Scope.destroy() ? ESR_Returned : ESR_Failed;
4646   }
4647 
4648   case Stmt::CompoundStmtClass: {
4649     BlockScopeRAII Scope(Info);
4650 
4651     const CompoundStmt *CS = cast<CompoundStmt>(S);
4652     for (const auto *BI : CS->body()) {
4653       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
4654       if (ESR == ESR_Succeeded)
4655         Case = nullptr;
4656       else if (ESR != ESR_CaseNotFound) {
4657         if (ESR != ESR_Failed && !Scope.destroy())
4658           return ESR_Failed;
4659         return ESR;
4660       }
4661     }
4662     if (Case)
4663       return ESR_CaseNotFound;
4664     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4665   }
4666 
4667   case Stmt::IfStmtClass: {
4668     const IfStmt *IS = cast<IfStmt>(S);
4669 
4670     // Evaluate the condition, as either a var decl or as an expression.
4671     BlockScopeRAII Scope(Info);
4672     if (const Stmt *Init = IS->getInit()) {
4673       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4674       if (ESR != ESR_Succeeded) {
4675         if (ESR != ESR_Failed && !Scope.destroy())
4676           return ESR_Failed;
4677         return ESR;
4678       }
4679     }
4680     bool Cond;
4681     if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
4682       return ESR_Failed;
4683 
4684     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4685       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4686       if (ESR != ESR_Succeeded) {
4687         if (ESR != ESR_Failed && !Scope.destroy())
4688           return ESR_Failed;
4689         return ESR;
4690       }
4691     }
4692     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4693   }
4694 
4695   case Stmt::WhileStmtClass: {
4696     const WhileStmt *WS = cast<WhileStmt>(S);
4697     while (true) {
4698       BlockScopeRAII Scope(Info);
4699       bool Continue;
4700       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4701                         Continue))
4702         return ESR_Failed;
4703       if (!Continue)
4704         break;
4705 
4706       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4707       if (ESR != ESR_Continue) {
4708         if (ESR != ESR_Failed && !Scope.destroy())
4709           return ESR_Failed;
4710         return ESR;
4711       }
4712       if (!Scope.destroy())
4713         return ESR_Failed;
4714     }
4715     return ESR_Succeeded;
4716   }
4717 
4718   case Stmt::DoStmtClass: {
4719     const DoStmt *DS = cast<DoStmt>(S);
4720     bool Continue;
4721     do {
4722       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
4723       if (ESR != ESR_Continue)
4724         return ESR;
4725       Case = nullptr;
4726 
4727       FullExpressionRAII CondScope(Info);
4728       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
4729           !CondScope.destroy())
4730         return ESR_Failed;
4731     } while (Continue);
4732     return ESR_Succeeded;
4733   }
4734 
4735   case Stmt::ForStmtClass: {
4736     const ForStmt *FS = cast<ForStmt>(S);
4737     BlockScopeRAII ForScope(Info);
4738     if (FS->getInit()) {
4739       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4740       if (ESR != ESR_Succeeded) {
4741         if (ESR != ESR_Failed && !ForScope.destroy())
4742           return ESR_Failed;
4743         return ESR;
4744       }
4745     }
4746     while (true) {
4747       BlockScopeRAII IterScope(Info);
4748       bool Continue = true;
4749       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4750                                          FS->getCond(), Continue))
4751         return ESR_Failed;
4752       if (!Continue)
4753         break;
4754 
4755       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4756       if (ESR != ESR_Continue) {
4757         if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
4758           return ESR_Failed;
4759         return ESR;
4760       }
4761 
4762       if (FS->getInc()) {
4763         FullExpressionRAII IncScope(Info);
4764         if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
4765           return ESR_Failed;
4766       }
4767 
4768       if (!IterScope.destroy())
4769         return ESR_Failed;
4770     }
4771     return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
4772   }
4773 
4774   case Stmt::CXXForRangeStmtClass: {
4775     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
4776     BlockScopeRAII Scope(Info);
4777 
4778     // Evaluate the init-statement if present.
4779     if (FS->getInit()) {
4780       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4781       if (ESR != ESR_Succeeded) {
4782         if (ESR != ESR_Failed && !Scope.destroy())
4783           return ESR_Failed;
4784         return ESR;
4785       }
4786     }
4787 
4788     // Initialize the __range variable.
4789     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4790     if (ESR != ESR_Succeeded) {
4791       if (ESR != ESR_Failed && !Scope.destroy())
4792         return ESR_Failed;
4793       return ESR;
4794     }
4795 
4796     // Create the __begin and __end iterators.
4797     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4798     if (ESR != ESR_Succeeded) {
4799       if (ESR != ESR_Failed && !Scope.destroy())
4800         return ESR_Failed;
4801       return ESR;
4802     }
4803     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
4804     if (ESR != ESR_Succeeded) {
4805       if (ESR != ESR_Failed && !Scope.destroy())
4806         return ESR_Failed;
4807       return ESR;
4808     }
4809 
4810     while (true) {
4811       // Condition: __begin != __end.
4812       {
4813         bool Continue = true;
4814         FullExpressionRAII CondExpr(Info);
4815         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4816           return ESR_Failed;
4817         if (!Continue)
4818           break;
4819       }
4820 
4821       // User's variable declaration, initialized by *__begin.
4822       BlockScopeRAII InnerScope(Info);
4823       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4824       if (ESR != ESR_Succeeded) {
4825         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
4826           return ESR_Failed;
4827         return ESR;
4828       }
4829 
4830       // Loop body.
4831       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4832       if (ESR != ESR_Continue) {
4833         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
4834           return ESR_Failed;
4835         return ESR;
4836       }
4837 
4838       // Increment: ++__begin
4839       if (!EvaluateIgnoredValue(Info, FS->getInc()))
4840         return ESR_Failed;
4841 
4842       if (!InnerScope.destroy())
4843         return ESR_Failed;
4844     }
4845 
4846     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4847   }
4848 
4849   case Stmt::SwitchStmtClass:
4850     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4851 
4852   case Stmt::ContinueStmtClass:
4853     return ESR_Continue;
4854 
4855   case Stmt::BreakStmtClass:
4856     return ESR_Break;
4857 
4858   case Stmt::LabelStmtClass:
4859     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4860 
4861   case Stmt::AttributedStmtClass:
4862     // As a general principle, C++11 attributes can be ignored without
4863     // any semantic impact.
4864     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4865                         Case);
4866 
4867   case Stmt::CaseStmtClass:
4868   case Stmt::DefaultStmtClass:
4869     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
4870   case Stmt::CXXTryStmtClass:
4871     // Evaluate try blocks by evaluating all sub statements.
4872     return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
4873   }
4874 }
4875 
4876 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4877 /// default constructor. If so, we'll fold it whether or not it's marked as
4878 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
4879 /// so we need special handling.
4880 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
4881                                            const CXXConstructorDecl *CD,
4882                                            bool IsValueInitialization) {
4883   if (!CD->isTrivial() || !CD->isDefaultConstructor())
4884     return false;
4885 
4886   // Value-initialization does not call a trivial default constructor, so such a
4887   // call is a core constant expression whether or not the constructor is
4888   // constexpr.
4889   if (!CD->isConstexpr() && !IsValueInitialization) {
4890     if (Info.getLangOpts().CPlusPlus11) {
4891       // FIXME: If DiagDecl is an implicitly-declared special member function,
4892       // we should be much more explicit about why it's not constexpr.
4893       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4894         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4895       Info.Note(CD->getLocation(), diag::note_declared_at);
4896     } else {
4897       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4898     }
4899   }
4900   return true;
4901 }
4902 
4903 /// CheckConstexprFunction - Check that a function can be called in a constant
4904 /// expression.
4905 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4906                                    const FunctionDecl *Declaration,
4907                                    const FunctionDecl *Definition,
4908                                    const Stmt *Body) {
4909   // Potential constant expressions can contain calls to declared, but not yet
4910   // defined, constexpr functions.
4911   if (Info.checkingPotentialConstantExpression() && !Definition &&
4912       Declaration->isConstexpr())
4913     return false;
4914 
4915   // Bail out if the function declaration itself is invalid.  We will
4916   // have produced a relevant diagnostic while parsing it, so just
4917   // note the problematic sub-expression.
4918   if (Declaration->isInvalidDecl()) {
4919     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4920     return false;
4921   }
4922 
4923   // DR1872: An instantiated virtual constexpr function can't be called in a
4924   // constant expression (prior to C++20). We can still constant-fold such a
4925   // call.
4926   if (!Info.Ctx.getLangOpts().CPlusPlus2a && isa<CXXMethodDecl>(Declaration) &&
4927       cast<CXXMethodDecl>(Declaration)->isVirtual())
4928     Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
4929 
4930   if (Definition && Definition->isInvalidDecl()) {
4931     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4932     return false;
4933   }
4934 
4935   // Can we evaluate this function call?
4936   if (Definition && Definition->isConstexpr() && Body)
4937     return true;
4938 
4939   if (Info.getLangOpts().CPlusPlus11) {
4940     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
4941 
4942     // If this function is not constexpr because it is an inherited
4943     // non-constexpr constructor, diagnose that directly.
4944     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4945     if (CD && CD->isInheritingConstructor()) {
4946       auto *Inherited = CD->getInheritedConstructor().getConstructor();
4947       if (!Inherited->isConstexpr())
4948         DiagDecl = CD = Inherited;
4949     }
4950 
4951     // FIXME: If DiagDecl is an implicitly-declared special member function
4952     // or an inheriting constructor, we should be much more explicit about why
4953     // it's not constexpr.
4954     if (CD && CD->isInheritingConstructor())
4955       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
4956         << CD->getInheritedConstructor().getConstructor()->getParent();
4957     else
4958       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
4959         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
4960     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4961   } else {
4962     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4963   }
4964   return false;
4965 }
4966 
4967 namespace {
4968 struct CheckDynamicTypeHandler {
4969   AccessKinds AccessKind;
4970   typedef bool result_type;
4971   bool failed() { return false; }
4972   bool found(APValue &Subobj, QualType SubobjType) { return true; }
4973   bool found(APSInt &Value, QualType SubobjType) { return true; }
4974   bool found(APFloat &Value, QualType SubobjType) { return true; }
4975 };
4976 } // end anonymous namespace
4977 
4978 /// Check that we can access the notional vptr of an object / determine its
4979 /// dynamic type.
4980 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
4981                              AccessKinds AK, bool Polymorphic) {
4982   if (This.Designator.Invalid)
4983     return false;
4984 
4985   CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
4986 
4987   if (!Obj)
4988     return false;
4989 
4990   if (!Obj.Value) {
4991     // The object is not usable in constant expressions, so we can't inspect
4992     // its value to see if it's in-lifetime or what the active union members
4993     // are. We can still check for a one-past-the-end lvalue.
4994     if (This.Designator.isOnePastTheEnd() ||
4995         This.Designator.isMostDerivedAnUnsizedArray()) {
4996       Info.FFDiag(E, This.Designator.isOnePastTheEnd()
4997                          ? diag::note_constexpr_access_past_end
4998                          : diag::note_constexpr_access_unsized_array)
4999           << AK;
5000       return false;
5001     } else if (Polymorphic) {
5002       // Conservatively refuse to perform a polymorphic operation if we would
5003       // not be able to read a notional 'vptr' value.
5004       APValue Val;
5005       This.moveInto(Val);
5006       QualType StarThisType =
5007           Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5008       Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5009           << AK << Val.getAsString(Info.Ctx, StarThisType);
5010       return false;
5011     }
5012     return true;
5013   }
5014 
5015   CheckDynamicTypeHandler Handler{AK};
5016   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5017 }
5018 
5019 /// Check that the pointee of the 'this' pointer in a member function call is
5020 /// either within its lifetime or in its period of construction or destruction.
5021 static bool
5022 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5023                                      const LValue &This,
5024                                      const CXXMethodDecl *NamedMember) {
5025   return checkDynamicType(
5026       Info, E, This,
5027       isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5028 }
5029 
5030 struct DynamicType {
5031   /// The dynamic class type of the object.
5032   const CXXRecordDecl *Type;
5033   /// The corresponding path length in the lvalue.
5034   unsigned PathLength;
5035 };
5036 
5037 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5038                                              unsigned PathLength) {
5039   assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5040       Designator.Entries.size() && "invalid path length");
5041   return (PathLength == Designator.MostDerivedPathLength)
5042              ? Designator.MostDerivedType->getAsCXXRecordDecl()
5043              : getAsBaseClass(Designator.Entries[PathLength - 1]);
5044 }
5045 
5046 /// Determine the dynamic type of an object.
5047 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
5048                                                 LValue &This, AccessKinds AK) {
5049   // If we don't have an lvalue denoting an object of class type, there is no
5050   // meaningful dynamic type. (We consider objects of non-class type to have no
5051   // dynamic type.)
5052   if (!checkDynamicType(Info, E, This, AK, true))
5053     return None;
5054 
5055   // Refuse to compute a dynamic type in the presence of virtual bases. This
5056   // shouldn't happen other than in constant-folding situations, since literal
5057   // types can't have virtual bases.
5058   //
5059   // Note that consumers of DynamicType assume that the type has no virtual
5060   // bases, and will need modifications if this restriction is relaxed.
5061   const CXXRecordDecl *Class =
5062       This.Designator.MostDerivedType->getAsCXXRecordDecl();
5063   if (!Class || Class->getNumVBases()) {
5064     Info.FFDiag(E);
5065     return None;
5066   }
5067 
5068   // FIXME: For very deep class hierarchies, it might be beneficial to use a
5069   // binary search here instead. But the overwhelmingly common case is that
5070   // we're not in the middle of a constructor, so it probably doesn't matter
5071   // in practice.
5072   ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5073   for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5074        PathLength <= Path.size(); ++PathLength) {
5075     switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5076                                       Path.slice(0, PathLength))) {
5077     case ConstructionPhase::Bases:
5078     case ConstructionPhase::DestroyingBases:
5079       // We're constructing or destroying a base class. This is not the dynamic
5080       // type.
5081       break;
5082 
5083     case ConstructionPhase::None:
5084     case ConstructionPhase::AfterBases:
5085     case ConstructionPhase::Destroying:
5086       // We've finished constructing the base classes and not yet started
5087       // destroying them again, so this is the dynamic type.
5088       return DynamicType{getBaseClassType(This.Designator, PathLength),
5089                          PathLength};
5090     }
5091   }
5092 
5093   // CWG issue 1517: we're constructing a base class of the object described by
5094   // 'This', so that object has not yet begun its period of construction and
5095   // any polymorphic operation on it results in undefined behavior.
5096   Info.FFDiag(E);
5097   return None;
5098 }
5099 
5100 /// Perform virtual dispatch.
5101 static const CXXMethodDecl *HandleVirtualDispatch(
5102     EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5103     llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5104   Optional<DynamicType> DynType = ComputeDynamicType(
5105       Info, E, This,
5106       isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5107   if (!DynType)
5108     return nullptr;
5109 
5110   // Find the final overrider. It must be declared in one of the classes on the
5111   // path from the dynamic type to the static type.
5112   // FIXME: If we ever allow literal types to have virtual base classes, that
5113   // won't be true.
5114   const CXXMethodDecl *Callee = Found;
5115   unsigned PathLength = DynType->PathLength;
5116   for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5117     const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5118     const CXXMethodDecl *Overrider =
5119         Found->getCorrespondingMethodDeclaredInClass(Class, false);
5120     if (Overrider) {
5121       Callee = Overrider;
5122       break;
5123     }
5124   }
5125 
5126   // C++2a [class.abstract]p6:
5127   //   the effect of making a virtual call to a pure virtual function [...] is
5128   //   undefined
5129   if (Callee->isPure()) {
5130     Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5131     Info.Note(Callee->getLocation(), diag::note_declared_at);
5132     return nullptr;
5133   }
5134 
5135   // If necessary, walk the rest of the path to determine the sequence of
5136   // covariant adjustment steps to apply.
5137   if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5138                                        Found->getReturnType())) {
5139     CovariantAdjustmentPath.push_back(Callee->getReturnType());
5140     for (unsigned CovariantPathLength = PathLength + 1;
5141          CovariantPathLength != This.Designator.Entries.size();
5142          ++CovariantPathLength) {
5143       const CXXRecordDecl *NextClass =
5144           getBaseClassType(This.Designator, CovariantPathLength);
5145       const CXXMethodDecl *Next =
5146           Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5147       if (Next && !Info.Ctx.hasSameUnqualifiedType(
5148                       Next->getReturnType(), CovariantAdjustmentPath.back()))
5149         CovariantAdjustmentPath.push_back(Next->getReturnType());
5150     }
5151     if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5152                                          CovariantAdjustmentPath.back()))
5153       CovariantAdjustmentPath.push_back(Found->getReturnType());
5154   }
5155 
5156   // Perform 'this' adjustment.
5157   if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5158     return nullptr;
5159 
5160   return Callee;
5161 }
5162 
5163 /// Perform the adjustment from a value returned by a virtual function to
5164 /// a value of the statically expected type, which may be a pointer or
5165 /// reference to a base class of the returned type.
5166 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5167                                             APValue &Result,
5168                                             ArrayRef<QualType> Path) {
5169   assert(Result.isLValue() &&
5170          "unexpected kind of APValue for covariant return");
5171   if (Result.isNullPointer())
5172     return true;
5173 
5174   LValue LVal;
5175   LVal.setFrom(Info.Ctx, Result);
5176 
5177   const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5178   for (unsigned I = 1; I != Path.size(); ++I) {
5179     const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5180     assert(OldClass && NewClass && "unexpected kind of covariant return");
5181     if (OldClass != NewClass &&
5182         !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5183       return false;
5184     OldClass = NewClass;
5185   }
5186 
5187   LVal.moveInto(Result);
5188   return true;
5189 }
5190 
5191 /// Determine whether \p Base, which is known to be a direct base class of
5192 /// \p Derived, is a public base class.
5193 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5194                               const CXXRecordDecl *Base) {
5195   for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5196     auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5197     if (BaseClass && declaresSameEntity(BaseClass, Base))
5198       return BaseSpec.getAccessSpecifier() == AS_public;
5199   }
5200   llvm_unreachable("Base is not a direct base of Derived");
5201 }
5202 
5203 /// Apply the given dynamic cast operation on the provided lvalue.
5204 ///
5205 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
5206 /// to find a suitable target subobject.
5207 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5208                               LValue &Ptr) {
5209   // We can't do anything with a non-symbolic pointer value.
5210   SubobjectDesignator &D = Ptr.Designator;
5211   if (D.Invalid)
5212     return false;
5213 
5214   // C++ [expr.dynamic.cast]p6:
5215   //   If v is a null pointer value, the result is a null pointer value.
5216   if (Ptr.isNullPointer() && !E->isGLValue())
5217     return true;
5218 
5219   // For all the other cases, we need the pointer to point to an object within
5220   // its lifetime / period of construction / destruction, and we need to know
5221   // its dynamic type.
5222   Optional<DynamicType> DynType =
5223       ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5224   if (!DynType)
5225     return false;
5226 
5227   // C++ [expr.dynamic.cast]p7:
5228   //   If T is "pointer to cv void", then the result is a pointer to the most
5229   //   derived object
5230   if (E->getType()->isVoidPointerType())
5231     return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5232 
5233   const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5234   assert(C && "dynamic_cast target is not void pointer nor class");
5235   CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5236 
5237   auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5238     // C++ [expr.dynamic.cast]p9:
5239     if (!E->isGLValue()) {
5240       //   The value of a failed cast to pointer type is the null pointer value
5241       //   of the required result type.
5242       Ptr.setNull(Info.Ctx, E->getType());
5243       return true;
5244     }
5245 
5246     //   A failed cast to reference type throws [...] std::bad_cast.
5247     unsigned DiagKind;
5248     if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5249                    DynType->Type->isDerivedFrom(C)))
5250       DiagKind = 0;
5251     else if (!Paths || Paths->begin() == Paths->end())
5252       DiagKind = 1;
5253     else if (Paths->isAmbiguous(CQT))
5254       DiagKind = 2;
5255     else {
5256       assert(Paths->front().Access != AS_public && "why did the cast fail?");
5257       DiagKind = 3;
5258     }
5259     Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5260         << DiagKind << Ptr.Designator.getType(Info.Ctx)
5261         << Info.Ctx.getRecordType(DynType->Type)
5262         << E->getType().getUnqualifiedType();
5263     return false;
5264   };
5265 
5266   // Runtime check, phase 1:
5267   //   Walk from the base subobject towards the derived object looking for the
5268   //   target type.
5269   for (int PathLength = Ptr.Designator.Entries.size();
5270        PathLength >= (int)DynType->PathLength; --PathLength) {
5271     const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5272     if (declaresSameEntity(Class, C))
5273       return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5274     // We can only walk across public inheritance edges.
5275     if (PathLength > (int)DynType->PathLength &&
5276         !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5277                            Class))
5278       return RuntimeCheckFailed(nullptr);
5279   }
5280 
5281   // Runtime check, phase 2:
5282   //   Search the dynamic type for an unambiguous public base of type C.
5283   CXXBasePaths Paths(/*FindAmbiguities=*/true,
5284                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
5285   if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5286       Paths.front().Access == AS_public) {
5287     // Downcast to the dynamic type...
5288     if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5289       return false;
5290     // ... then upcast to the chosen base class subobject.
5291     for (CXXBasePathElement &Elem : Paths.front())
5292       if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5293         return false;
5294     return true;
5295   }
5296 
5297   // Otherwise, the runtime check fails.
5298   return RuntimeCheckFailed(&Paths);
5299 }
5300 
5301 namespace {
5302 struct StartLifetimeOfUnionMemberHandler {
5303   const FieldDecl *Field;
5304 
5305   static const AccessKinds AccessKind = AK_Assign;
5306 
5307   typedef bool result_type;
5308   bool failed() { return false; }
5309   bool found(APValue &Subobj, QualType SubobjType) {
5310     // We are supposed to perform no initialization but begin the lifetime of
5311     // the object. We interpret that as meaning to do what default
5312     // initialization of the object would do if all constructors involved were
5313     // trivial:
5314     //  * All base, non-variant member, and array element subobjects' lifetimes
5315     //    begin
5316     //  * No variant members' lifetimes begin
5317     //  * All scalar subobjects whose lifetimes begin have indeterminate values
5318     assert(SubobjType->isUnionType());
5319     if (!declaresSameEntity(Subobj.getUnionField(), Field) ||
5320         !Subobj.getUnionValue().hasValue())
5321       Subobj.setUnion(Field, getDefaultInitValue(Field->getType()));
5322     return true;
5323   }
5324   bool found(APSInt &Value, QualType SubobjType) {
5325     llvm_unreachable("wrong value kind for union object");
5326   }
5327   bool found(APFloat &Value, QualType SubobjType) {
5328     llvm_unreachable("wrong value kind for union object");
5329   }
5330 };
5331 } // end anonymous namespace
5332 
5333 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5334 
5335 /// Handle a builtin simple-assignment or a call to a trivial assignment
5336 /// operator whose left-hand side might involve a union member access. If it
5337 /// does, implicitly start the lifetime of any accessed union elements per
5338 /// C++20 [class.union]5.
5339 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5340                                           const LValue &LHS) {
5341   if (LHS.InvalidBase || LHS.Designator.Invalid)
5342     return false;
5343 
5344   llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5345   // C++ [class.union]p5:
5346   //   define the set S(E) of subexpressions of E as follows:
5347   unsigned PathLength = LHS.Designator.Entries.size();
5348   for (const Expr *E = LHSExpr; E != nullptr;) {
5349     //   -- If E is of the form A.B, S(E) contains the elements of S(A)...
5350     if (auto *ME = dyn_cast<MemberExpr>(E)) {
5351       auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5352       // Note that we can't implicitly start the lifetime of a reference,
5353       // so we don't need to proceed any further if we reach one.
5354       if (!FD || FD->getType()->isReferenceType())
5355         break;
5356 
5357       //    ... and also contains A.B if B names a union member ...
5358       if (FD->getParent()->isUnion()) {
5359         //    ... of a non-class, non-array type, or of a class type with a
5360         //    trivial default constructor that is not deleted, or an array of
5361         //    such types.
5362         auto *RD =
5363             FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5364         if (!RD || RD->hasTrivialDefaultConstructor())
5365           UnionPathLengths.push_back({PathLength - 1, FD});
5366       }
5367 
5368       E = ME->getBase();
5369       --PathLength;
5370       assert(declaresSameEntity(FD,
5371                                 LHS.Designator.Entries[PathLength]
5372                                     .getAsBaseOrMember().getPointer()));
5373 
5374       //   -- If E is of the form A[B] and is interpreted as a built-in array
5375       //      subscripting operator, S(E) is [S(the array operand, if any)].
5376     } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5377       // Step over an ArrayToPointerDecay implicit cast.
5378       auto *Base = ASE->getBase()->IgnoreImplicit();
5379       if (!Base->getType()->isArrayType())
5380         break;
5381 
5382       E = Base;
5383       --PathLength;
5384 
5385     } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5386       // Step over a derived-to-base conversion.
5387       E = ICE->getSubExpr();
5388       if (ICE->getCastKind() == CK_NoOp)
5389         continue;
5390       if (ICE->getCastKind() != CK_DerivedToBase &&
5391           ICE->getCastKind() != CK_UncheckedDerivedToBase)
5392         break;
5393       // Walk path backwards as we walk up from the base to the derived class.
5394       for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
5395         --PathLength;
5396         (void)Elt;
5397         assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
5398                                   LHS.Designator.Entries[PathLength]
5399                                       .getAsBaseOrMember().getPointer()));
5400       }
5401 
5402     //   -- Otherwise, S(E) is empty.
5403     } else {
5404       break;
5405     }
5406   }
5407 
5408   // Common case: no unions' lifetimes are started.
5409   if (UnionPathLengths.empty())
5410     return true;
5411 
5412   //   if modification of X [would access an inactive union member], an object
5413   //   of the type of X is implicitly created
5414   CompleteObject Obj =
5415       findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
5416   if (!Obj)
5417     return false;
5418   for (std::pair<unsigned, const FieldDecl *> LengthAndField :
5419            llvm::reverse(UnionPathLengths)) {
5420     // Form a designator for the union object.
5421     SubobjectDesignator D = LHS.Designator;
5422     D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
5423 
5424     StartLifetimeOfUnionMemberHandler StartLifetime{LengthAndField.second};
5425     if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
5426       return false;
5427   }
5428 
5429   return true;
5430 }
5431 
5432 /// Determine if a class has any fields that might need to be copied by a
5433 /// trivial copy or move operation.
5434 static bool hasFields(const CXXRecordDecl *RD) {
5435   if (!RD || RD->isEmpty())
5436     return false;
5437   for (auto *FD : RD->fields()) {
5438     if (FD->isUnnamedBitfield())
5439       continue;
5440     return true;
5441   }
5442   for (auto &Base : RD->bases())
5443     if (hasFields(Base.getType()->getAsCXXRecordDecl()))
5444       return true;
5445   return false;
5446 }
5447 
5448 namespace {
5449 typedef SmallVector<APValue, 8> ArgVector;
5450 }
5451 
5452 /// EvaluateArgs - Evaluate the arguments to a function call.
5453 static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues,
5454                          EvalInfo &Info, const FunctionDecl *Callee) {
5455   bool Success = true;
5456   llvm::SmallBitVector ForbiddenNullArgs;
5457   if (Callee->hasAttr<NonNullAttr>()) {
5458     ForbiddenNullArgs.resize(Args.size());
5459     for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
5460       if (!Attr->args_size()) {
5461         ForbiddenNullArgs.set();
5462         break;
5463       } else
5464         for (auto Idx : Attr->args()) {
5465           unsigned ASTIdx = Idx.getASTIndex();
5466           if (ASTIdx >= Args.size())
5467             continue;
5468           ForbiddenNullArgs[ASTIdx] = 1;
5469         }
5470     }
5471   }
5472   for (unsigned Idx = 0; Idx < Args.size(); Idx++) {
5473     if (!Evaluate(ArgValues[Idx], Info, Args[Idx])) {
5474       // If we're checking for a potential constant expression, evaluate all
5475       // initializers even if some of them fail.
5476       if (!Info.noteFailure())
5477         return false;
5478       Success = false;
5479     } else if (!ForbiddenNullArgs.empty() &&
5480                ForbiddenNullArgs[Idx] &&
5481                ArgValues[Idx].isLValue() &&
5482                ArgValues[Idx].isNullPointer()) {
5483       Info.CCEDiag(Args[Idx], diag::note_non_null_attribute_failed);
5484       if (!Info.noteFailure())
5485         return false;
5486       Success = false;
5487     }
5488   }
5489   return Success;
5490 }
5491 
5492 /// Evaluate a function call.
5493 static bool HandleFunctionCall(SourceLocation CallLoc,
5494                                const FunctionDecl *Callee, const LValue *This,
5495                                ArrayRef<const Expr*> Args, const Stmt *Body,
5496                                EvalInfo &Info, APValue &Result,
5497                                const LValue *ResultSlot) {
5498   ArgVector ArgValues(Args.size());
5499   if (!EvaluateArgs(Args, ArgValues, Info, Callee))
5500     return false;
5501 
5502   if (!Info.CheckCallLimit(CallLoc))
5503     return false;
5504 
5505   CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
5506 
5507   // For a trivial copy or move assignment, perform an APValue copy. This is
5508   // essential for unions, where the operations performed by the assignment
5509   // operator cannot be represented as statements.
5510   //
5511   // Skip this for non-union classes with no fields; in that case, the defaulted
5512   // copy/move does not actually read the object.
5513   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
5514   if (MD && MD->isDefaulted() &&
5515       (MD->getParent()->isUnion() ||
5516        (MD->isTrivial() && hasFields(MD->getParent())))) {
5517     assert(This &&
5518            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
5519     LValue RHS;
5520     RHS.setFrom(Info.Ctx, ArgValues[0]);
5521     APValue RHSValue;
5522     if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), RHS,
5523                                         RHSValue, MD->getParent()->isUnion()))
5524       return false;
5525     if (Info.getLangOpts().CPlusPlus2a && MD->isTrivial() &&
5526         !HandleUnionActiveMemberChange(Info, Args[0], *This))
5527       return false;
5528     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
5529                           RHSValue))
5530       return false;
5531     This->moveInto(Result);
5532     return true;
5533   } else if (MD && isLambdaCallOperator(MD)) {
5534     // We're in a lambda; determine the lambda capture field maps unless we're
5535     // just constexpr checking a lambda's call operator. constexpr checking is
5536     // done before the captures have been added to the closure object (unless
5537     // we're inferring constexpr-ness), so we don't have access to them in this
5538     // case. But since we don't need the captures to constexpr check, we can
5539     // just ignore them.
5540     if (!Info.checkingPotentialConstantExpression())
5541       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
5542                                         Frame.LambdaThisCaptureField);
5543   }
5544 
5545   StmtResult Ret = {Result, ResultSlot};
5546   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
5547   if (ESR == ESR_Succeeded) {
5548     if (Callee->getReturnType()->isVoidType())
5549       return true;
5550     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
5551   }
5552   return ESR == ESR_Returned;
5553 }
5554 
5555 /// Evaluate a constructor call.
5556 static bool HandleConstructorCall(const Expr *E, const LValue &This,
5557                                   APValue *ArgValues,
5558                                   const CXXConstructorDecl *Definition,
5559                                   EvalInfo &Info, APValue &Result) {
5560   SourceLocation CallLoc = E->getExprLoc();
5561   if (!Info.CheckCallLimit(CallLoc))
5562     return false;
5563 
5564   const CXXRecordDecl *RD = Definition->getParent();
5565   if (RD->getNumVBases()) {
5566     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
5567     return false;
5568   }
5569 
5570   EvalInfo::EvaluatingConstructorRAII EvalObj(
5571       Info,
5572       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
5573       RD->getNumBases());
5574   CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
5575 
5576   // FIXME: Creating an APValue just to hold a nonexistent return value is
5577   // wasteful.
5578   APValue RetVal;
5579   StmtResult Ret = {RetVal, nullptr};
5580 
5581   // If it's a delegating constructor, delegate.
5582   if (Definition->isDelegatingConstructor()) {
5583     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
5584     {
5585       FullExpressionRAII InitScope(Info);
5586       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
5587           !InitScope.destroy())
5588         return false;
5589     }
5590     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
5591   }
5592 
5593   // For a trivial copy or move constructor, perform an APValue copy. This is
5594   // essential for unions (or classes with anonymous union members), where the
5595   // operations performed by the constructor cannot be represented by
5596   // ctor-initializers.
5597   //
5598   // Skip this for empty non-union classes; we should not perform an
5599   // lvalue-to-rvalue conversion on them because their copy constructor does not
5600   // actually read them.
5601   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
5602       (Definition->getParent()->isUnion() ||
5603        (Definition->isTrivial() && hasFields(Definition->getParent())))) {
5604     LValue RHS;
5605     RHS.setFrom(Info.Ctx, ArgValues[0]);
5606     return handleLValueToRValueConversion(
5607         Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
5608         RHS, Result, Definition->getParent()->isUnion());
5609   }
5610 
5611   // Reserve space for the struct members.
5612   if (!Result.hasValue()) {
5613     if (!RD->isUnion())
5614       Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
5615                        std::distance(RD->field_begin(), RD->field_end()));
5616     else
5617       // A union starts with no active member.
5618       Result = APValue((const FieldDecl*)nullptr);
5619   }
5620 
5621   if (RD->isInvalidDecl()) return false;
5622   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5623 
5624   // A scope for temporaries lifetime-extended by reference members.
5625   BlockScopeRAII LifetimeExtendedScope(Info);
5626 
5627   bool Success = true;
5628   unsigned BasesSeen = 0;
5629 #ifndef NDEBUG
5630   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
5631 #endif
5632   CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
5633   auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
5634     // We might be initializing the same field again if this is an indirect
5635     // field initialization.
5636     if (FieldIt == RD->field_end() ||
5637         FieldIt->getFieldIndex() > FD->getFieldIndex()) {
5638       assert(Indirect && "fields out of order?");
5639       return;
5640     }
5641 
5642     // Default-initialize any fields with no explicit initializer.
5643     for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
5644       assert(FieldIt != RD->field_end() && "missing field?");
5645       if (!FieldIt->isUnnamedBitfield())
5646         Result.getStructField(FieldIt->getFieldIndex()) =
5647             getDefaultInitValue(FieldIt->getType());
5648     }
5649     ++FieldIt;
5650   };
5651   for (const auto *I : Definition->inits()) {
5652     LValue Subobject = This;
5653     LValue SubobjectParent = This;
5654     APValue *Value = &Result;
5655 
5656     // Determine the subobject to initialize.
5657     FieldDecl *FD = nullptr;
5658     if (I->isBaseInitializer()) {
5659       QualType BaseType(I->getBaseClass(), 0);
5660 #ifndef NDEBUG
5661       // Non-virtual base classes are initialized in the order in the class
5662       // definition. We have already checked for virtual base classes.
5663       assert(!BaseIt->isVirtual() && "virtual base for literal type");
5664       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
5665              "base class initializers not in expected order");
5666       ++BaseIt;
5667 #endif
5668       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
5669                                   BaseType->getAsCXXRecordDecl(), &Layout))
5670         return false;
5671       Value = &Result.getStructBase(BasesSeen++);
5672     } else if ((FD = I->getMember())) {
5673       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
5674         return false;
5675       if (RD->isUnion()) {
5676         Result = APValue(FD);
5677         Value = &Result.getUnionValue();
5678       } else {
5679         SkipToField(FD, false);
5680         Value = &Result.getStructField(FD->getFieldIndex());
5681       }
5682     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
5683       // Walk the indirect field decl's chain to find the object to initialize,
5684       // and make sure we've initialized every step along it.
5685       auto IndirectFieldChain = IFD->chain();
5686       for (auto *C : IndirectFieldChain) {
5687         FD = cast<FieldDecl>(C);
5688         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
5689         // Switch the union field if it differs. This happens if we had
5690         // preceding zero-initialization, and we're now initializing a union
5691         // subobject other than the first.
5692         // FIXME: In this case, the values of the other subobjects are
5693         // specified, since zero-initialization sets all padding bits to zero.
5694         if (!Value->hasValue() ||
5695             (Value->isUnion() && Value->getUnionField() != FD)) {
5696           if (CD->isUnion())
5697             *Value = APValue(FD);
5698           else
5699             // FIXME: This immediately starts the lifetime of all members of an
5700             // anonymous struct. It would be preferable to strictly start member
5701             // lifetime in initialization order.
5702             *Value = getDefaultInitValue(Info.Ctx.getRecordType(CD));
5703         }
5704         // Store Subobject as its parent before updating it for the last element
5705         // in the chain.
5706         if (C == IndirectFieldChain.back())
5707           SubobjectParent = Subobject;
5708         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
5709           return false;
5710         if (CD->isUnion())
5711           Value = &Value->getUnionValue();
5712         else {
5713           if (C == IndirectFieldChain.front() && !RD->isUnion())
5714             SkipToField(FD, true);
5715           Value = &Value->getStructField(FD->getFieldIndex());
5716         }
5717       }
5718     } else {
5719       llvm_unreachable("unknown base initializer kind");
5720     }
5721 
5722     // Need to override This for implicit field initializers as in this case
5723     // This refers to innermost anonymous struct/union containing initializer,
5724     // not to currently constructed class.
5725     const Expr *Init = I->getInit();
5726     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
5727                                   isa<CXXDefaultInitExpr>(Init));
5728     FullExpressionRAII InitScope(Info);
5729     if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
5730         (FD && FD->isBitField() &&
5731          !truncateBitfieldValue(Info, Init, *Value, FD))) {
5732       // If we're checking for a potential constant expression, evaluate all
5733       // initializers even if some of them fail.
5734       if (!Info.noteFailure())
5735         return false;
5736       Success = false;
5737     }
5738 
5739     // This is the point at which the dynamic type of the object becomes this
5740     // class type.
5741     if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
5742       EvalObj.finishedConstructingBases();
5743   }
5744 
5745   // Default-initialize any remaining fields.
5746   if (!RD->isUnion()) {
5747     for (; FieldIt != RD->field_end(); ++FieldIt) {
5748       if (!FieldIt->isUnnamedBitfield())
5749         Result.getStructField(FieldIt->getFieldIndex()) =
5750             getDefaultInitValue(FieldIt->getType());
5751     }
5752   }
5753 
5754   return Success &&
5755          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
5756          LifetimeExtendedScope.destroy();
5757 }
5758 
5759 static bool HandleConstructorCall(const Expr *E, const LValue &This,
5760                                   ArrayRef<const Expr*> Args,
5761                                   const CXXConstructorDecl *Definition,
5762                                   EvalInfo &Info, APValue &Result) {
5763   ArgVector ArgValues(Args.size());
5764   if (!EvaluateArgs(Args, ArgValues, Info, Definition))
5765     return false;
5766 
5767   return HandleConstructorCall(E, This, ArgValues.data(), Definition,
5768                                Info, Result);
5769 }
5770 
5771 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
5772                                   const LValue &This, APValue &Value,
5773                                   QualType T) {
5774   // Objects can only be destroyed while they're within their lifetimes.
5775   // FIXME: We have no representation for whether an object of type nullptr_t
5776   // is in its lifetime; it usually doesn't matter. Perhaps we should model it
5777   // as indeterminate instead?
5778   if (Value.isAbsent() && !T->isNullPtrType()) {
5779     APValue Printable;
5780     This.moveInto(Printable);
5781     Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
5782       << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
5783     return false;
5784   }
5785 
5786   // Invent an expression for location purposes.
5787   // FIXME: We shouldn't need to do this.
5788   OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue);
5789 
5790   // For arrays, destroy elements right-to-left.
5791   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
5792     uint64_t Size = CAT->getSize().getZExtValue();
5793     QualType ElemT = CAT->getElementType();
5794 
5795     LValue ElemLV = This;
5796     ElemLV.addArray(Info, &LocE, CAT);
5797     if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
5798       return false;
5799 
5800     // Ensure that we have actual array elements available to destroy; the
5801     // destructors might mutate the value, so we can't run them on the array
5802     // filler.
5803     if (Size && Size > Value.getArrayInitializedElts())
5804       expandArray(Value, Value.getArraySize() - 1);
5805 
5806     for (; Size != 0; --Size) {
5807       APValue &Elem = Value.getArrayInitializedElt(Size - 1);
5808       if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
5809           !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
5810         return false;
5811     }
5812 
5813     // End the lifetime of this array now.
5814     Value = APValue();
5815     return true;
5816   }
5817 
5818   const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
5819   if (!RD) {
5820     if (T.isDestructedType()) {
5821       Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
5822       return false;
5823     }
5824 
5825     Value = APValue();
5826     return true;
5827   }
5828 
5829   if (RD->getNumVBases()) {
5830     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
5831     return false;
5832   }
5833 
5834   const CXXDestructorDecl *DD = RD->getDestructor();
5835   if (!DD && !RD->hasTrivialDestructor()) {
5836     Info.FFDiag(CallLoc);
5837     return false;
5838   }
5839 
5840   if (!DD || DD->isTrivial() ||
5841       (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
5842     // A trivial destructor just ends the lifetime of the object. Check for
5843     // this case before checking for a body, because we might not bother
5844     // building a body for a trivial destructor. Note that it doesn't matter
5845     // whether the destructor is constexpr in this case; all trivial
5846     // destructors are constexpr.
5847     //
5848     // If an anonymous union would be destroyed, some enclosing destructor must
5849     // have been explicitly defined, and the anonymous union destruction should
5850     // have no effect.
5851     Value = APValue();
5852     return true;
5853   }
5854 
5855   if (!Info.CheckCallLimit(CallLoc))
5856     return false;
5857 
5858   const FunctionDecl *Definition = nullptr;
5859   const Stmt *Body = DD->getBody(Definition);
5860 
5861   if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
5862     return false;
5863 
5864   CallStackFrame Frame(Info, CallLoc, Definition, &This, nullptr);
5865 
5866   // We're now in the period of destruction of this object.
5867   unsigned BasesLeft = RD->getNumBases();
5868   EvalInfo::EvaluatingDestructorRAII EvalObj(
5869       Info,
5870       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
5871   if (!EvalObj.DidInsert) {
5872     // C++2a [class.dtor]p19:
5873     //   the behavior is undefined if the destructor is invoked for an object
5874     //   whose lifetime has ended
5875     // (Note that formally the lifetime ends when the period of destruction
5876     // begins, even though certain uses of the object remain valid until the
5877     // period of destruction ends.)
5878     Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
5879     return false;
5880   }
5881 
5882   // FIXME: Creating an APValue just to hold a nonexistent return value is
5883   // wasteful.
5884   APValue RetVal;
5885   StmtResult Ret = {RetVal, nullptr};
5886   if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
5887     return false;
5888 
5889   // A union destructor does not implicitly destroy its members.
5890   if (RD->isUnion())
5891     return true;
5892 
5893   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5894 
5895   // We don't have a good way to iterate fields in reverse, so collect all the
5896   // fields first and then walk them backwards.
5897   SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
5898   for (const FieldDecl *FD : llvm::reverse(Fields)) {
5899     if (FD->isUnnamedBitfield())
5900       continue;
5901 
5902     LValue Subobject = This;
5903     if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
5904       return false;
5905 
5906     APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
5907     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
5908                                FD->getType()))
5909       return false;
5910   }
5911 
5912   if (BasesLeft != 0)
5913     EvalObj.startedDestroyingBases();
5914 
5915   // Destroy base classes in reverse order.
5916   for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
5917     --BasesLeft;
5918 
5919     QualType BaseType = Base.getType();
5920     LValue Subobject = This;
5921     if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
5922                                 BaseType->getAsCXXRecordDecl(), &Layout))
5923       return false;
5924 
5925     APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
5926     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
5927                                BaseType))
5928       return false;
5929   }
5930   assert(BasesLeft == 0 && "NumBases was wrong?");
5931 
5932   // The period of destruction ends now. The object is gone.
5933   Value = APValue();
5934   return true;
5935 }
5936 
5937 namespace {
5938 struct DestroyObjectHandler {
5939   EvalInfo &Info;
5940   const Expr *E;
5941   const LValue &This;
5942   const AccessKinds AccessKind;
5943 
5944   typedef bool result_type;
5945   bool failed() { return false; }
5946   bool found(APValue &Subobj, QualType SubobjType) {
5947     return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
5948                                  SubobjType);
5949   }
5950   bool found(APSInt &Value, QualType SubobjType) {
5951     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
5952     return false;
5953   }
5954   bool found(APFloat &Value, QualType SubobjType) {
5955     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
5956     return false;
5957   }
5958 };
5959 }
5960 
5961 /// Perform a destructor or pseudo-destructor call on the given object, which
5962 /// might in general not be a complete object.
5963 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
5964                               const LValue &This, QualType ThisType) {
5965   CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
5966   DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
5967   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5968 }
5969 
5970 /// Destroy and end the lifetime of the given complete object.
5971 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
5972                               APValue::LValueBase LVBase, APValue &Value,
5973                               QualType T) {
5974   // If we've had an unmodeled side-effect, we can't rely on mutable state
5975   // (such as the object we're about to destroy) being correct.
5976   if (Info.EvalStatus.HasSideEffects)
5977     return false;
5978 
5979   LValue LV;
5980   LV.set({LVBase});
5981   return HandleDestructionImpl(Info, Loc, LV, Value, T);
5982 }
5983 
5984 /// Perform a call to 'perator new' or to `__builtin_operator_new'.
5985 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
5986                                   LValue &Result) {
5987   if (Info.checkingPotentialConstantExpression() ||
5988       Info.SpeculativeEvaluationDepth)
5989     return false;
5990 
5991   // This is permitted only within a call to std::allocator<T>::allocate.
5992   auto Caller = Info.getStdAllocatorCaller("allocate");
5993   if (!Caller) {
5994     Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus2a
5995                                      ? diag::note_constexpr_new_untyped
5996                                      : diag::note_constexpr_new);
5997     return false;
5998   }
5999 
6000   QualType ElemType = Caller.ElemType;
6001   if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6002     Info.FFDiag(E->getExprLoc(),
6003                 diag::note_constexpr_new_not_complete_object_type)
6004         << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6005     return false;
6006   }
6007 
6008   APSInt ByteSize;
6009   if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6010     return false;
6011   bool IsNothrow = false;
6012   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6013     EvaluateIgnoredValue(Info, E->getArg(I));
6014     IsNothrow |= E->getType()->isNothrowT();
6015   }
6016 
6017   CharUnits ElemSize;
6018   if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6019     return false;
6020   APInt Size, Remainder;
6021   APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6022   APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6023   if (Remainder != 0) {
6024     // This likely indicates a bug in the implementation of 'std::allocator'.
6025     Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6026         << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6027     return false;
6028   }
6029 
6030   if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
6031     if (IsNothrow) {
6032       Result.setNull(Info.Ctx, E->getType());
6033       return true;
6034     }
6035 
6036     Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
6037     return false;
6038   }
6039 
6040   QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
6041                                                      ArrayType::Normal, 0);
6042   APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6043   *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6044   Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6045   return true;
6046 }
6047 
6048 static bool hasVirtualDestructor(QualType T) {
6049   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6050     if (CXXDestructorDecl *DD = RD->getDestructor())
6051       return DD->isVirtual();
6052   return false;
6053 }
6054 
6055 static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6056   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6057     if (CXXDestructorDecl *DD = RD->getDestructor())
6058       return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6059   return nullptr;
6060 }
6061 
6062 /// Check that the given object is a suitable pointer to a heap allocation that
6063 /// still exists and is of the right kind for the purpose of a deletion.
6064 ///
6065 /// On success, returns the heap allocation to deallocate. On failure, produces
6066 /// a diagnostic and returns None.
6067 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6068                                             const LValue &Pointer,
6069                                             DynAlloc::Kind DeallocKind) {
6070   auto PointerAsString = [&] {
6071     return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6072   };
6073 
6074   DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6075   if (!DA) {
6076     Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6077         << PointerAsString();
6078     if (Pointer.Base)
6079       NoteLValueLocation(Info, Pointer.Base);
6080     return None;
6081   }
6082 
6083   Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6084   if (!Alloc) {
6085     Info.FFDiag(E, diag::note_constexpr_double_delete);
6086     return None;
6087   }
6088 
6089   QualType AllocType = Pointer.Base.getDynamicAllocType();
6090   if (DeallocKind != (*Alloc)->getKind()) {
6091     Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6092         << DeallocKind << (*Alloc)->getKind() << AllocType;
6093     NoteLValueLocation(Info, Pointer.Base);
6094     return None;
6095   }
6096 
6097   bool Subobject = false;
6098   if (DeallocKind == DynAlloc::New) {
6099     Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6100                 Pointer.Designator.isOnePastTheEnd();
6101   } else {
6102     Subobject = Pointer.Designator.Entries.size() != 1 ||
6103                 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6104   }
6105   if (Subobject) {
6106     Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6107         << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6108     return None;
6109   }
6110 
6111   return Alloc;
6112 }
6113 
6114 // Perform a call to 'operator delete' or '__builtin_operator_delete'.
6115 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6116   if (Info.checkingPotentialConstantExpression() ||
6117       Info.SpeculativeEvaluationDepth)
6118     return false;
6119 
6120   // This is permitted only within a call to std::allocator<T>::deallocate.
6121   if (!Info.getStdAllocatorCaller("deallocate")) {
6122     Info.FFDiag(E->getExprLoc());
6123     return true;
6124   }
6125 
6126   LValue Pointer;
6127   if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6128     return false;
6129   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6130     EvaluateIgnoredValue(Info, E->getArg(I));
6131 
6132   if (Pointer.Designator.Invalid)
6133     return false;
6134 
6135   // Deleting a null pointer has no effect.
6136   if (Pointer.isNullPointer())
6137     return true;
6138 
6139   if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6140     return false;
6141 
6142   Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6143   return true;
6144 }
6145 
6146 //===----------------------------------------------------------------------===//
6147 // Generic Evaluation
6148 //===----------------------------------------------------------------------===//
6149 namespace {
6150 
6151 class BitCastBuffer {
6152   // FIXME: We're going to need bit-level granularity when we support
6153   // bit-fields.
6154   // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6155   // we don't support a host or target where that is the case. Still, we should
6156   // use a more generic type in case we ever do.
6157   SmallVector<Optional<unsigned char>, 32> Bytes;
6158 
6159   static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6160                 "Need at least 8 bit unsigned char");
6161 
6162   bool TargetIsLittleEndian;
6163 
6164 public:
6165   BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6166       : Bytes(Width.getQuantity()),
6167         TargetIsLittleEndian(TargetIsLittleEndian) {}
6168 
6169   LLVM_NODISCARD
6170   bool readObject(CharUnits Offset, CharUnits Width,
6171                   SmallVectorImpl<unsigned char> &Output) const {
6172     for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6173       // If a byte of an integer is uninitialized, then the whole integer is
6174       // uninitalized.
6175       if (!Bytes[I.getQuantity()])
6176         return false;
6177       Output.push_back(*Bytes[I.getQuantity()]);
6178     }
6179     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6180       std::reverse(Output.begin(), Output.end());
6181     return true;
6182   }
6183 
6184   void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6185     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6186       std::reverse(Input.begin(), Input.end());
6187 
6188     size_t Index = 0;
6189     for (unsigned char Byte : Input) {
6190       assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
6191       Bytes[Offset.getQuantity() + Index] = Byte;
6192       ++Index;
6193     }
6194   }
6195 
6196   size_t size() { return Bytes.size(); }
6197 };
6198 
6199 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6200 /// target would represent the value at runtime.
6201 class APValueToBufferConverter {
6202   EvalInfo &Info;
6203   BitCastBuffer Buffer;
6204   const CastExpr *BCE;
6205 
6206   APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6207                            const CastExpr *BCE)
6208       : Info(Info),
6209         Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6210         BCE(BCE) {}
6211 
6212   bool visit(const APValue &Val, QualType Ty) {
6213     return visit(Val, Ty, CharUnits::fromQuantity(0));
6214   }
6215 
6216   // Write out Val with type Ty into Buffer starting at Offset.
6217   bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6218     assert((size_t)Offset.getQuantity() <= Buffer.size());
6219 
6220     // As a special case, nullptr_t has an indeterminate value.
6221     if (Ty->isNullPtrType())
6222       return true;
6223 
6224     // Dig through Src to find the byte at SrcOffset.
6225     switch (Val.getKind()) {
6226     case APValue::Indeterminate:
6227     case APValue::None:
6228       return true;
6229 
6230     case APValue::Int:
6231       return visitInt(Val.getInt(), Ty, Offset);
6232     case APValue::Float:
6233       return visitFloat(Val.getFloat(), Ty, Offset);
6234     case APValue::Array:
6235       return visitArray(Val, Ty, Offset);
6236     case APValue::Struct:
6237       return visitRecord(Val, Ty, Offset);
6238 
6239     case APValue::ComplexInt:
6240     case APValue::ComplexFloat:
6241     case APValue::Vector:
6242     case APValue::FixedPoint:
6243       // FIXME: We should support these.
6244 
6245     case APValue::Union:
6246     case APValue::MemberPointer:
6247     case APValue::AddrLabelDiff: {
6248       Info.FFDiag(BCE->getBeginLoc(),
6249                   diag::note_constexpr_bit_cast_unsupported_type)
6250           << Ty;
6251       return false;
6252     }
6253 
6254     case APValue::LValue:
6255       llvm_unreachable("LValue subobject in bit_cast?");
6256     }
6257     llvm_unreachable("Unhandled APValue::ValueKind");
6258   }
6259 
6260   bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
6261     const RecordDecl *RD = Ty->getAsRecordDecl();
6262     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6263 
6264     // Visit the base classes.
6265     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6266       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6267         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6268         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6269 
6270         if (!visitRecord(Val.getStructBase(I), BS.getType(),
6271                          Layout.getBaseClassOffset(BaseDecl) + Offset))
6272           return false;
6273       }
6274     }
6275 
6276     // Visit the fields.
6277     unsigned FieldIdx = 0;
6278     for (FieldDecl *FD : RD->fields()) {
6279       if (FD->isBitField()) {
6280         Info.FFDiag(BCE->getBeginLoc(),
6281                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6282         return false;
6283       }
6284 
6285       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6286 
6287       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
6288              "only bit-fields can have sub-char alignment");
6289       CharUnits FieldOffset =
6290           Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
6291       QualType FieldTy = FD->getType();
6292       if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
6293         return false;
6294       ++FieldIdx;
6295     }
6296 
6297     return true;
6298   }
6299 
6300   bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
6301     const auto *CAT =
6302         dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
6303     if (!CAT)
6304       return false;
6305 
6306     CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
6307     unsigned NumInitializedElts = Val.getArrayInitializedElts();
6308     unsigned ArraySize = Val.getArraySize();
6309     // First, initialize the initialized elements.
6310     for (unsigned I = 0; I != NumInitializedElts; ++I) {
6311       const APValue &SubObj = Val.getArrayInitializedElt(I);
6312       if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
6313         return false;
6314     }
6315 
6316     // Next, initialize the rest of the array using the filler.
6317     if (Val.hasArrayFiller()) {
6318       const APValue &Filler = Val.getArrayFiller();
6319       for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
6320         if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
6321           return false;
6322       }
6323     }
6324 
6325     return true;
6326   }
6327 
6328   bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
6329     CharUnits Width = Info.Ctx.getTypeSizeInChars(Ty);
6330     SmallVector<unsigned char, 8> Bytes(Width.getQuantity());
6331     llvm::StoreIntToMemory(Val, &*Bytes.begin(), Width.getQuantity());
6332     Buffer.writeObject(Offset, Bytes);
6333     return true;
6334   }
6335 
6336   bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
6337     APSInt AsInt(Val.bitcastToAPInt());
6338     return visitInt(AsInt, Ty, Offset);
6339   }
6340 
6341 public:
6342   static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
6343                                          const CastExpr *BCE) {
6344     CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
6345     APValueToBufferConverter Converter(Info, DstSize, BCE);
6346     if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
6347       return None;
6348     return Converter.Buffer;
6349   }
6350 };
6351 
6352 /// Write an BitCastBuffer into an APValue.
6353 class BufferToAPValueConverter {
6354   EvalInfo &Info;
6355   const BitCastBuffer &Buffer;
6356   const CastExpr *BCE;
6357 
6358   BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
6359                            const CastExpr *BCE)
6360       : Info(Info), Buffer(Buffer), BCE(BCE) {}
6361 
6362   // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
6363   // with an invalid type, so anything left is a deficiency on our part (FIXME).
6364   // Ideally this will be unreachable.
6365   llvm::NoneType unsupportedType(QualType Ty) {
6366     Info.FFDiag(BCE->getBeginLoc(),
6367                 diag::note_constexpr_bit_cast_unsupported_type)
6368         << Ty;
6369     return None;
6370   }
6371 
6372   Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
6373                           const EnumType *EnumSugar = nullptr) {
6374     if (T->isNullPtrType()) {
6375       uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
6376       return APValue((Expr *)nullptr,
6377                      /*Offset=*/CharUnits::fromQuantity(NullValue),
6378                      APValue::NoLValuePath{}, /*IsNullPtr=*/true);
6379     }
6380 
6381     CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
6382     SmallVector<uint8_t, 8> Bytes;
6383     if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
6384       // If this is std::byte or unsigned char, then its okay to store an
6385       // indeterminate value.
6386       bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
6387       bool IsUChar =
6388           !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
6389                          T->isSpecificBuiltinType(BuiltinType::Char_U));
6390       if (!IsStdByte && !IsUChar) {
6391         QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
6392         Info.FFDiag(BCE->getExprLoc(),
6393                     diag::note_constexpr_bit_cast_indet_dest)
6394             << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
6395         return None;
6396       }
6397 
6398       return APValue::IndeterminateValue();
6399     }
6400 
6401     APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
6402     llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
6403 
6404     if (T->isIntegralOrEnumerationType()) {
6405       Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
6406       return APValue(Val);
6407     }
6408 
6409     if (T->isRealFloatingType()) {
6410       const llvm::fltSemantics &Semantics =
6411           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
6412       return APValue(APFloat(Semantics, Val));
6413     }
6414 
6415     return unsupportedType(QualType(T, 0));
6416   }
6417 
6418   Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
6419     const RecordDecl *RD = RTy->getAsRecordDecl();
6420     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6421 
6422     unsigned NumBases = 0;
6423     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6424       NumBases = CXXRD->getNumBases();
6425 
6426     APValue ResultVal(APValue::UninitStruct(), NumBases,
6427                       std::distance(RD->field_begin(), RD->field_end()));
6428 
6429     // Visit the base classes.
6430     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6431       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6432         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6433         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6434         if (BaseDecl->isEmpty() ||
6435             Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
6436           continue;
6437 
6438         Optional<APValue> SubObj = visitType(
6439             BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
6440         if (!SubObj)
6441           return None;
6442         ResultVal.getStructBase(I) = *SubObj;
6443       }
6444     }
6445 
6446     // Visit the fields.
6447     unsigned FieldIdx = 0;
6448     for (FieldDecl *FD : RD->fields()) {
6449       // FIXME: We don't currently support bit-fields. A lot of the logic for
6450       // this is in CodeGen, so we need to factor it around.
6451       if (FD->isBitField()) {
6452         Info.FFDiag(BCE->getBeginLoc(),
6453                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6454         return None;
6455       }
6456 
6457       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6458       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
6459 
6460       CharUnits FieldOffset =
6461           CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
6462           Offset;
6463       QualType FieldTy = FD->getType();
6464       Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
6465       if (!SubObj)
6466         return None;
6467       ResultVal.getStructField(FieldIdx) = *SubObj;
6468       ++FieldIdx;
6469     }
6470 
6471     return ResultVal;
6472   }
6473 
6474   Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
6475     QualType RepresentationType = Ty->getDecl()->getIntegerType();
6476     assert(!RepresentationType.isNull() &&
6477            "enum forward decl should be caught by Sema");
6478     const auto *AsBuiltin =
6479         RepresentationType.getCanonicalType()->castAs<BuiltinType>();
6480     // Recurse into the underlying type. Treat std::byte transparently as
6481     // unsigned char.
6482     return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
6483   }
6484 
6485   Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
6486     size_t Size = Ty->getSize().getLimitedValue();
6487     CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
6488 
6489     APValue ArrayValue(APValue::UninitArray(), Size, Size);
6490     for (size_t I = 0; I != Size; ++I) {
6491       Optional<APValue> ElementValue =
6492           visitType(Ty->getElementType(), Offset + I * ElementWidth);
6493       if (!ElementValue)
6494         return None;
6495       ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
6496     }
6497 
6498     return ArrayValue;
6499   }
6500 
6501   Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
6502     return unsupportedType(QualType(Ty, 0));
6503   }
6504 
6505   Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
6506     QualType Can = Ty.getCanonicalType();
6507 
6508     switch (Can->getTypeClass()) {
6509 #define TYPE(Class, Base)                                                      \
6510   case Type::Class:                                                            \
6511     return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
6512 #define ABSTRACT_TYPE(Class, Base)
6513 #define NON_CANONICAL_TYPE(Class, Base)                                        \
6514   case Type::Class:                                                            \
6515     llvm_unreachable("non-canonical type should be impossible!");
6516 #define DEPENDENT_TYPE(Class, Base)                                            \
6517   case Type::Class:                                                            \
6518     llvm_unreachable(                                                          \
6519         "dependent types aren't supported in the constant evaluator!");
6520 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)                            \
6521   case Type::Class:                                                            \
6522     llvm_unreachable("either dependent or not canonical!");
6523 #include "clang/AST/TypeNodes.inc"
6524     }
6525     llvm_unreachable("Unhandled Type::TypeClass");
6526   }
6527 
6528 public:
6529   // Pull out a full value of type DstType.
6530   static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
6531                                    const CastExpr *BCE) {
6532     BufferToAPValueConverter Converter(Info, Buffer, BCE);
6533     return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
6534   }
6535 };
6536 
6537 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
6538                                                  QualType Ty, EvalInfo *Info,
6539                                                  const ASTContext &Ctx,
6540                                                  bool CheckingDest) {
6541   Ty = Ty.getCanonicalType();
6542 
6543   auto diag = [&](int Reason) {
6544     if (Info)
6545       Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
6546           << CheckingDest << (Reason == 4) << Reason;
6547     return false;
6548   };
6549   auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
6550     if (Info)
6551       Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
6552           << NoteTy << Construct << Ty;
6553     return false;
6554   };
6555 
6556   if (Ty->isUnionType())
6557     return diag(0);
6558   if (Ty->isPointerType())
6559     return diag(1);
6560   if (Ty->isMemberPointerType())
6561     return diag(2);
6562   if (Ty.isVolatileQualified())
6563     return diag(3);
6564 
6565   if (RecordDecl *Record = Ty->getAsRecordDecl()) {
6566     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
6567       for (CXXBaseSpecifier &BS : CXXRD->bases())
6568         if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
6569                                                   CheckingDest))
6570           return note(1, BS.getType(), BS.getBeginLoc());
6571     }
6572     for (FieldDecl *FD : Record->fields()) {
6573       if (FD->getType()->isReferenceType())
6574         return diag(4);
6575       if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
6576                                                 CheckingDest))
6577         return note(0, FD->getType(), FD->getBeginLoc());
6578     }
6579   }
6580 
6581   if (Ty->isArrayType() &&
6582       !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
6583                                             Info, Ctx, CheckingDest))
6584     return false;
6585 
6586   return true;
6587 }
6588 
6589 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
6590                                              const ASTContext &Ctx,
6591                                              const CastExpr *BCE) {
6592   bool DestOK = checkBitCastConstexprEligibilityType(
6593       BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
6594   bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
6595                                 BCE->getBeginLoc(),
6596                                 BCE->getSubExpr()->getType(), Info, Ctx, false);
6597   return SourceOK;
6598 }
6599 
6600 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
6601                                         APValue &SourceValue,
6602                                         const CastExpr *BCE) {
6603   assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
6604          "no host or target supports non 8-bit chars");
6605   assert(SourceValue.isLValue() &&
6606          "LValueToRValueBitcast requires an lvalue operand!");
6607 
6608   if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
6609     return false;
6610 
6611   LValue SourceLValue;
6612   APValue SourceRValue;
6613   SourceLValue.setFrom(Info.Ctx, SourceValue);
6614   if (!handleLValueToRValueConversion(
6615           Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
6616           SourceRValue, /*WantObjectRepresentation=*/true))
6617     return false;
6618 
6619   // Read out SourceValue into a char buffer.
6620   Optional<BitCastBuffer> Buffer =
6621       APValueToBufferConverter::convert(Info, SourceRValue, BCE);
6622   if (!Buffer)
6623     return false;
6624 
6625   // Write out the buffer into a new APValue.
6626   Optional<APValue> MaybeDestValue =
6627       BufferToAPValueConverter::convert(Info, *Buffer, BCE);
6628   if (!MaybeDestValue)
6629     return false;
6630 
6631   DestValue = std::move(*MaybeDestValue);
6632   return true;
6633 }
6634 
6635 template <class Derived>
6636 class ExprEvaluatorBase
6637   : public ConstStmtVisitor<Derived, bool> {
6638 private:
6639   Derived &getDerived() { return static_cast<Derived&>(*this); }
6640   bool DerivedSuccess(const APValue &V, const Expr *E) {
6641     return getDerived().Success(V, E);
6642   }
6643   bool DerivedZeroInitialization(const Expr *E) {
6644     return getDerived().ZeroInitialization(E);
6645   }
6646 
6647   // Check whether a conditional operator with a non-constant condition is a
6648   // potential constant expression. If neither arm is a potential constant
6649   // expression, then the conditional operator is not either.
6650   template<typename ConditionalOperator>
6651   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
6652     assert(Info.checkingPotentialConstantExpression());
6653 
6654     // Speculatively evaluate both arms.
6655     SmallVector<PartialDiagnosticAt, 8> Diag;
6656     {
6657       SpeculativeEvaluationRAII Speculate(Info, &Diag);
6658       StmtVisitorTy::Visit(E->getFalseExpr());
6659       if (Diag.empty())
6660         return;
6661     }
6662 
6663     {
6664       SpeculativeEvaluationRAII Speculate(Info, &Diag);
6665       Diag.clear();
6666       StmtVisitorTy::Visit(E->getTrueExpr());
6667       if (Diag.empty())
6668         return;
6669     }
6670 
6671     Error(E, diag::note_constexpr_conditional_never_const);
6672   }
6673 
6674 
6675   template<typename ConditionalOperator>
6676   bool HandleConditionalOperator(const ConditionalOperator *E) {
6677     bool BoolResult;
6678     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
6679       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
6680         CheckPotentialConstantConditional(E);
6681         return false;
6682       }
6683       if (Info.noteFailure()) {
6684         StmtVisitorTy::Visit(E->getTrueExpr());
6685         StmtVisitorTy::Visit(E->getFalseExpr());
6686       }
6687       return false;
6688     }
6689 
6690     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
6691     return StmtVisitorTy::Visit(EvalExpr);
6692   }
6693 
6694 protected:
6695   EvalInfo &Info;
6696   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
6697   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
6698 
6699   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
6700     return Info.CCEDiag(E, D);
6701   }
6702 
6703   bool ZeroInitialization(const Expr *E) { return Error(E); }
6704 
6705 public:
6706   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
6707 
6708   EvalInfo &getEvalInfo() { return Info; }
6709 
6710   /// Report an evaluation error. This should only be called when an error is
6711   /// first discovered. When propagating an error, just return false.
6712   bool Error(const Expr *E, diag::kind D) {
6713     Info.FFDiag(E, D);
6714     return false;
6715   }
6716   bool Error(const Expr *E) {
6717     return Error(E, diag::note_invalid_subexpr_in_const_expr);
6718   }
6719 
6720   bool VisitStmt(const Stmt *) {
6721     llvm_unreachable("Expression evaluator should not be called on stmts");
6722   }
6723   bool VisitExpr(const Expr *E) {
6724     return Error(E);
6725   }
6726 
6727   bool VisitConstantExpr(const ConstantExpr *E)
6728     { return StmtVisitorTy::Visit(E->getSubExpr()); }
6729   bool VisitParenExpr(const ParenExpr *E)
6730     { return StmtVisitorTy::Visit(E->getSubExpr()); }
6731   bool VisitUnaryExtension(const UnaryOperator *E)
6732     { return StmtVisitorTy::Visit(E->getSubExpr()); }
6733   bool VisitUnaryPlus(const UnaryOperator *E)
6734     { return StmtVisitorTy::Visit(E->getSubExpr()); }
6735   bool VisitChooseExpr(const ChooseExpr *E)
6736     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
6737   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
6738     { return StmtVisitorTy::Visit(E->getResultExpr()); }
6739   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
6740     { return StmtVisitorTy::Visit(E->getReplacement()); }
6741   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
6742     TempVersionRAII RAII(*Info.CurrentCall);
6743     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
6744     return StmtVisitorTy::Visit(E->getExpr());
6745   }
6746   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
6747     TempVersionRAII RAII(*Info.CurrentCall);
6748     // The initializer may not have been parsed yet, or might be erroneous.
6749     if (!E->getExpr())
6750       return Error(E);
6751     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
6752     return StmtVisitorTy::Visit(E->getExpr());
6753   }
6754 
6755   bool VisitExprWithCleanups(const ExprWithCleanups *E) {
6756     FullExpressionRAII Scope(Info);
6757     return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
6758   }
6759 
6760   // Temporaries are registered when created, so we don't care about
6761   // CXXBindTemporaryExpr.
6762   bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
6763     return StmtVisitorTy::Visit(E->getSubExpr());
6764   }
6765 
6766   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
6767     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
6768     return static_cast<Derived*>(this)->VisitCastExpr(E);
6769   }
6770   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
6771     if (!Info.Ctx.getLangOpts().CPlusPlus2a)
6772       CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
6773     return static_cast<Derived*>(this)->VisitCastExpr(E);
6774   }
6775   bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
6776     return static_cast<Derived*>(this)->VisitCastExpr(E);
6777   }
6778 
6779   bool VisitBinaryOperator(const BinaryOperator *E) {
6780     switch (E->getOpcode()) {
6781     default:
6782       return Error(E);
6783 
6784     case BO_Comma:
6785       VisitIgnoredValue(E->getLHS());
6786       return StmtVisitorTy::Visit(E->getRHS());
6787 
6788     case BO_PtrMemD:
6789     case BO_PtrMemI: {
6790       LValue Obj;
6791       if (!HandleMemberPointerAccess(Info, E, Obj))
6792         return false;
6793       APValue Result;
6794       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
6795         return false;
6796       return DerivedSuccess(Result, E);
6797     }
6798     }
6799   }
6800 
6801   bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
6802     return StmtVisitorTy::Visit(E->getSemanticForm());
6803   }
6804 
6805   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
6806     // Evaluate and cache the common expression. We treat it as a temporary,
6807     // even though it's not quite the same thing.
6808     LValue CommonLV;
6809     if (!Evaluate(Info.CurrentCall->createTemporary(
6810                       E->getOpaqueValue(),
6811                       getStorageType(Info.Ctx, E->getOpaqueValue()), false,
6812                       CommonLV),
6813                   Info, E->getCommon()))
6814       return false;
6815 
6816     return HandleConditionalOperator(E);
6817   }
6818 
6819   bool VisitConditionalOperator(const ConditionalOperator *E) {
6820     bool IsBcpCall = false;
6821     // If the condition (ignoring parens) is a __builtin_constant_p call,
6822     // the result is a constant expression if it can be folded without
6823     // side-effects. This is an important GNU extension. See GCC PR38377
6824     // for discussion.
6825     if (const CallExpr *CallCE =
6826           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
6827       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
6828         IsBcpCall = true;
6829 
6830     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
6831     // constant expression; we can't check whether it's potentially foldable.
6832     // FIXME: We should instead treat __builtin_constant_p as non-constant if
6833     // it would return 'false' in this mode.
6834     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
6835       return false;
6836 
6837     FoldConstant Fold(Info, IsBcpCall);
6838     if (!HandleConditionalOperator(E)) {
6839       Fold.keepDiagnostics();
6840       return false;
6841     }
6842 
6843     return true;
6844   }
6845 
6846   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
6847     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
6848       return DerivedSuccess(*Value, E);
6849 
6850     const Expr *Source = E->getSourceExpr();
6851     if (!Source)
6852       return Error(E);
6853     if (Source == E) { // sanity checking.
6854       assert(0 && "OpaqueValueExpr recursively refers to itself");
6855       return Error(E);
6856     }
6857     return StmtVisitorTy::Visit(Source);
6858   }
6859 
6860   bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
6861     for (const Expr *SemE : E->semantics()) {
6862       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
6863         // FIXME: We can't handle the case where an OpaqueValueExpr is also the
6864         // result expression: there could be two different LValues that would
6865         // refer to the same object in that case, and we can't model that.
6866         if (SemE == E->getResultExpr())
6867           return Error(E);
6868 
6869         // Unique OVEs get evaluated if and when we encounter them when
6870         // emitting the rest of the semantic form, rather than eagerly.
6871         if (OVE->isUnique())
6872           continue;
6873 
6874         LValue LV;
6875         if (!Evaluate(Info.CurrentCall->createTemporary(
6876                           OVE, getStorageType(Info.Ctx, OVE), false, LV),
6877                       Info, OVE->getSourceExpr()))
6878           return false;
6879       } else if (SemE == E->getResultExpr()) {
6880         if (!StmtVisitorTy::Visit(SemE))
6881           return false;
6882       } else {
6883         if (!EvaluateIgnoredValue(Info, SemE))
6884           return false;
6885       }
6886     }
6887     return true;
6888   }
6889 
6890   bool VisitCallExpr(const CallExpr *E) {
6891     APValue Result;
6892     if (!handleCallExpr(E, Result, nullptr))
6893       return false;
6894     return DerivedSuccess(Result, E);
6895   }
6896 
6897   bool handleCallExpr(const CallExpr *E, APValue &Result,
6898                      const LValue *ResultSlot) {
6899     const Expr *Callee = E->getCallee()->IgnoreParens();
6900     QualType CalleeType = Callee->getType();
6901 
6902     const FunctionDecl *FD = nullptr;
6903     LValue *This = nullptr, ThisVal;
6904     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
6905     bool HasQualifier = false;
6906 
6907     // Extract function decl and 'this' pointer from the callee.
6908     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
6909       const CXXMethodDecl *Member = nullptr;
6910       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
6911         // Explicit bound member calls, such as x.f() or p->g();
6912         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
6913           return false;
6914         Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
6915         if (!Member)
6916           return Error(Callee);
6917         This = &ThisVal;
6918         HasQualifier = ME->hasQualifier();
6919       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
6920         // Indirect bound member calls ('.*' or '->*').
6921         const ValueDecl *D =
6922             HandleMemberPointerAccess(Info, BE, ThisVal, false);
6923         if (!D)
6924           return false;
6925         Member = dyn_cast<CXXMethodDecl>(D);
6926         if (!Member)
6927           return Error(Callee);
6928         This = &ThisVal;
6929       } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
6930         if (!Info.getLangOpts().CPlusPlus2a)
6931           Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
6932         // FIXME: If pseudo-destructor calls ever start ending the lifetime of
6933         // their callee, we should start calling HandleDestruction here.
6934         // For now, we just evaluate the object argument and discard it.
6935         return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal);
6936       } else
6937         return Error(Callee);
6938       FD = Member;
6939     } else if (CalleeType->isFunctionPointerType()) {
6940       LValue Call;
6941       if (!EvaluatePointer(Callee, Call, Info))
6942         return false;
6943 
6944       if (!Call.getLValueOffset().isZero())
6945         return Error(Callee);
6946       FD = dyn_cast_or_null<FunctionDecl>(
6947                              Call.getLValueBase().dyn_cast<const ValueDecl*>());
6948       if (!FD)
6949         return Error(Callee);
6950       // Don't call function pointers which have been cast to some other type.
6951       // Per DR (no number yet), the caller and callee can differ in noexcept.
6952       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
6953         CalleeType->getPointeeType(), FD->getType())) {
6954         return Error(E);
6955       }
6956 
6957       // Overloaded operator calls to member functions are represented as normal
6958       // calls with '*this' as the first argument.
6959       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6960       if (MD && !MD->isStatic()) {
6961         // FIXME: When selecting an implicit conversion for an overloaded
6962         // operator delete, we sometimes try to evaluate calls to conversion
6963         // operators without a 'this' parameter!
6964         if (Args.empty())
6965           return Error(E);
6966 
6967         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
6968           return false;
6969         This = &ThisVal;
6970         Args = Args.slice(1);
6971       } else if (MD && MD->isLambdaStaticInvoker()) {
6972         // Map the static invoker for the lambda back to the call operator.
6973         // Conveniently, we don't have to slice out the 'this' argument (as is
6974         // being done for the non-static case), since a static member function
6975         // doesn't have an implicit argument passed in.
6976         const CXXRecordDecl *ClosureClass = MD->getParent();
6977         assert(
6978             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
6979             "Number of captures must be zero for conversion to function-ptr");
6980 
6981         const CXXMethodDecl *LambdaCallOp =
6982             ClosureClass->getLambdaCallOperator();
6983 
6984         // Set 'FD', the function that will be called below, to the call
6985         // operator.  If the closure object represents a generic lambda, find
6986         // the corresponding specialization of the call operator.
6987 
6988         if (ClosureClass->isGenericLambda()) {
6989           assert(MD->isFunctionTemplateSpecialization() &&
6990                  "A generic lambda's static-invoker function must be a "
6991                  "template specialization");
6992           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
6993           FunctionTemplateDecl *CallOpTemplate =
6994               LambdaCallOp->getDescribedFunctionTemplate();
6995           void *InsertPos = nullptr;
6996           FunctionDecl *CorrespondingCallOpSpecialization =
6997               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
6998           assert(CorrespondingCallOpSpecialization &&
6999                  "We must always have a function call operator specialization "
7000                  "that corresponds to our static invoker specialization");
7001           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7002         } else
7003           FD = LambdaCallOp;
7004       } else if (FD->isReplaceableGlobalAllocationFunction()) {
7005         if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7006             FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7007           LValue Ptr;
7008           if (!HandleOperatorNewCall(Info, E, Ptr))
7009             return false;
7010           Ptr.moveInto(Result);
7011           return true;
7012         } else {
7013           return HandleOperatorDeleteCall(Info, E);
7014         }
7015       }
7016     } else
7017       return Error(E);
7018 
7019     SmallVector<QualType, 4> CovariantAdjustmentPath;
7020     if (This) {
7021       auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7022       if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
7023         // Perform virtual dispatch, if necessary.
7024         FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
7025                                    CovariantAdjustmentPath);
7026         if (!FD)
7027           return false;
7028       } else {
7029         // Check that the 'this' pointer points to an object of the right type.
7030         // FIXME: If this is an assignment operator call, we may need to change
7031         // the active union member before we check this.
7032         if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
7033           return false;
7034       }
7035     }
7036 
7037     // Destructor calls are different enough that they have their own codepath.
7038     if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
7039       assert(This && "no 'this' pointer for destructor call");
7040       return HandleDestruction(Info, E, *This,
7041                                Info.Ctx.getRecordType(DD->getParent()));
7042     }
7043 
7044     const FunctionDecl *Definition = nullptr;
7045     Stmt *Body = FD->getBody(Definition);
7046 
7047     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
7048         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
7049                             Result, ResultSlot))
7050       return false;
7051 
7052     if (!CovariantAdjustmentPath.empty() &&
7053         !HandleCovariantReturnAdjustment(Info, E, Result,
7054                                          CovariantAdjustmentPath))
7055       return false;
7056 
7057     return true;
7058   }
7059 
7060   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7061     return StmtVisitorTy::Visit(E->getInitializer());
7062   }
7063   bool VisitInitListExpr(const InitListExpr *E) {
7064     if (E->getNumInits() == 0)
7065       return DerivedZeroInitialization(E);
7066     if (E->getNumInits() == 1)
7067       return StmtVisitorTy::Visit(E->getInit(0));
7068     return Error(E);
7069   }
7070   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
7071     return DerivedZeroInitialization(E);
7072   }
7073   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
7074     return DerivedZeroInitialization(E);
7075   }
7076   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
7077     return DerivedZeroInitialization(E);
7078   }
7079 
7080   /// A member expression where the object is a prvalue is itself a prvalue.
7081   bool VisitMemberExpr(const MemberExpr *E) {
7082     assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
7083            "missing temporary materialization conversion");
7084     assert(!E->isArrow() && "missing call to bound member function?");
7085 
7086     APValue Val;
7087     if (!Evaluate(Val, Info, E->getBase()))
7088       return false;
7089 
7090     QualType BaseTy = E->getBase()->getType();
7091 
7092     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
7093     if (!FD) return Error(E);
7094     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
7095     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7096            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7097 
7098     // Note: there is no lvalue base here. But this case should only ever
7099     // happen in C or in C++98, where we cannot be evaluating a constexpr
7100     // constructor, which is the only case the base matters.
7101     CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
7102     SubobjectDesignator Designator(BaseTy);
7103     Designator.addDeclUnchecked(FD);
7104 
7105     APValue Result;
7106     return extractSubobject(Info, E, Obj, Designator, Result) &&
7107            DerivedSuccess(Result, E);
7108   }
7109 
7110   bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
7111     APValue Val;
7112     if (!Evaluate(Val, Info, E->getBase()))
7113       return false;
7114 
7115     if (Val.isVector()) {
7116       SmallVector<uint32_t, 4> Indices;
7117       E->getEncodedElementAccess(Indices);
7118       if (Indices.size() == 1) {
7119         // Return scalar.
7120         return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
7121       } else {
7122         // Construct new APValue vector.
7123         SmallVector<APValue, 4> Elts;
7124         for (unsigned I = 0; I < Indices.size(); ++I) {
7125           Elts.push_back(Val.getVectorElt(Indices[I]));
7126         }
7127         APValue VecResult(Elts.data(), Indices.size());
7128         return DerivedSuccess(VecResult, E);
7129       }
7130     }
7131 
7132     return false;
7133   }
7134 
7135   bool VisitCastExpr(const CastExpr *E) {
7136     switch (E->getCastKind()) {
7137     default:
7138       break;
7139 
7140     case CK_AtomicToNonAtomic: {
7141       APValue AtomicVal;
7142       // This does not need to be done in place even for class/array types:
7143       // atomic-to-non-atomic conversion implies copying the object
7144       // representation.
7145       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
7146         return false;
7147       return DerivedSuccess(AtomicVal, E);
7148     }
7149 
7150     case CK_NoOp:
7151     case CK_UserDefinedConversion:
7152       return StmtVisitorTy::Visit(E->getSubExpr());
7153 
7154     case CK_LValueToRValue: {
7155       LValue LVal;
7156       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
7157         return false;
7158       APValue RVal;
7159       // Note, we use the subexpression's type in order to retain cv-qualifiers.
7160       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7161                                           LVal, RVal))
7162         return false;
7163       return DerivedSuccess(RVal, E);
7164     }
7165     case CK_LValueToRValueBitCast: {
7166       APValue DestValue, SourceValue;
7167       if (!Evaluate(SourceValue, Info, E->getSubExpr()))
7168         return false;
7169       if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
7170         return false;
7171       return DerivedSuccess(DestValue, E);
7172     }
7173 
7174     case CK_AddressSpaceConversion: {
7175       APValue Value;
7176       if (!Evaluate(Value, Info, E->getSubExpr()))
7177         return false;
7178       return DerivedSuccess(Value, E);
7179     }
7180     }
7181 
7182     return Error(E);
7183   }
7184 
7185   bool VisitUnaryPostInc(const UnaryOperator *UO) {
7186     return VisitUnaryPostIncDec(UO);
7187   }
7188   bool VisitUnaryPostDec(const UnaryOperator *UO) {
7189     return VisitUnaryPostIncDec(UO);
7190   }
7191   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
7192     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7193       return Error(UO);
7194 
7195     LValue LVal;
7196     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
7197       return false;
7198     APValue RVal;
7199     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
7200                       UO->isIncrementOp(), &RVal))
7201       return false;
7202     return DerivedSuccess(RVal, UO);
7203   }
7204 
7205   bool VisitStmtExpr(const StmtExpr *E) {
7206     // We will have checked the full-expressions inside the statement expression
7207     // when they were completed, and don't need to check them again now.
7208     if (Info.checkingForUndefinedBehavior())
7209       return Error(E);
7210 
7211     const CompoundStmt *CS = E->getSubStmt();
7212     if (CS->body_empty())
7213       return true;
7214 
7215     BlockScopeRAII Scope(Info);
7216     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
7217                                            BE = CS->body_end();
7218          /**/; ++BI) {
7219       if (BI + 1 == BE) {
7220         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
7221         if (!FinalExpr) {
7222           Info.FFDiag((*BI)->getBeginLoc(),
7223                       diag::note_constexpr_stmt_expr_unsupported);
7224           return false;
7225         }
7226         return this->Visit(FinalExpr) && Scope.destroy();
7227       }
7228 
7229       APValue ReturnValue;
7230       StmtResult Result = { ReturnValue, nullptr };
7231       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
7232       if (ESR != ESR_Succeeded) {
7233         // FIXME: If the statement-expression terminated due to 'return',
7234         // 'break', or 'continue', it would be nice to propagate that to
7235         // the outer statement evaluation rather than bailing out.
7236         if (ESR != ESR_Failed)
7237           Info.FFDiag((*BI)->getBeginLoc(),
7238                       diag::note_constexpr_stmt_expr_unsupported);
7239         return false;
7240       }
7241     }
7242 
7243     llvm_unreachable("Return from function from the loop above.");
7244   }
7245 
7246   /// Visit a value which is evaluated, but whose value is ignored.
7247   void VisitIgnoredValue(const Expr *E) {
7248     EvaluateIgnoredValue(Info, E);
7249   }
7250 
7251   /// Potentially visit a MemberExpr's base expression.
7252   void VisitIgnoredBaseExpression(const Expr *E) {
7253     // While MSVC doesn't evaluate the base expression, it does diagnose the
7254     // presence of side-effecting behavior.
7255     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
7256       return;
7257     VisitIgnoredValue(E);
7258   }
7259 };
7260 
7261 } // namespace
7262 
7263 //===----------------------------------------------------------------------===//
7264 // Common base class for lvalue and temporary evaluation.
7265 //===----------------------------------------------------------------------===//
7266 namespace {
7267 template<class Derived>
7268 class LValueExprEvaluatorBase
7269   : public ExprEvaluatorBase<Derived> {
7270 protected:
7271   LValue &Result;
7272   bool InvalidBaseOK;
7273   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
7274   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
7275 
7276   bool Success(APValue::LValueBase B) {
7277     Result.set(B);
7278     return true;
7279   }
7280 
7281   bool evaluatePointer(const Expr *E, LValue &Result) {
7282     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
7283   }
7284 
7285 public:
7286   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
7287       : ExprEvaluatorBaseTy(Info), Result(Result),
7288         InvalidBaseOK(InvalidBaseOK) {}
7289 
7290   bool Success(const APValue &V, const Expr *E) {
7291     Result.setFrom(this->Info.Ctx, V);
7292     return true;
7293   }
7294 
7295   bool VisitMemberExpr(const MemberExpr *E) {
7296     // Handle non-static data members.
7297     QualType BaseTy;
7298     bool EvalOK;
7299     if (E->isArrow()) {
7300       EvalOK = evaluatePointer(E->getBase(), Result);
7301       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
7302     } else if (E->getBase()->isRValue()) {
7303       assert(E->getBase()->getType()->isRecordType());
7304       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
7305       BaseTy = E->getBase()->getType();
7306     } else {
7307       EvalOK = this->Visit(E->getBase());
7308       BaseTy = E->getBase()->getType();
7309     }
7310     if (!EvalOK) {
7311       if (!InvalidBaseOK)
7312         return false;
7313       Result.setInvalid(E);
7314       return true;
7315     }
7316 
7317     const ValueDecl *MD = E->getMemberDecl();
7318     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
7319       assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7320              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7321       (void)BaseTy;
7322       if (!HandleLValueMember(this->Info, E, Result, FD))
7323         return false;
7324     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
7325       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
7326         return false;
7327     } else
7328       return this->Error(E);
7329 
7330     if (MD->getType()->isReferenceType()) {
7331       APValue RefValue;
7332       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
7333                                           RefValue))
7334         return false;
7335       return Success(RefValue, E);
7336     }
7337     return true;
7338   }
7339 
7340   bool VisitBinaryOperator(const BinaryOperator *E) {
7341     switch (E->getOpcode()) {
7342     default:
7343       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7344 
7345     case BO_PtrMemD:
7346     case BO_PtrMemI:
7347       return HandleMemberPointerAccess(this->Info, E, Result);
7348     }
7349   }
7350 
7351   bool VisitCastExpr(const CastExpr *E) {
7352     switch (E->getCastKind()) {
7353     default:
7354       return ExprEvaluatorBaseTy::VisitCastExpr(E);
7355 
7356     case CK_DerivedToBase:
7357     case CK_UncheckedDerivedToBase:
7358       if (!this->Visit(E->getSubExpr()))
7359         return false;
7360 
7361       // Now figure out the necessary offset to add to the base LV to get from
7362       // the derived class to the base class.
7363       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
7364                                   Result);
7365     }
7366   }
7367 };
7368 }
7369 
7370 //===----------------------------------------------------------------------===//
7371 // LValue Evaluation
7372 //
7373 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
7374 // function designators (in C), decl references to void objects (in C), and
7375 // temporaries (if building with -Wno-address-of-temporary).
7376 //
7377 // LValue evaluation produces values comprising a base expression of one of the
7378 // following types:
7379 // - Declarations
7380 //  * VarDecl
7381 //  * FunctionDecl
7382 // - Literals
7383 //  * CompoundLiteralExpr in C (and in global scope in C++)
7384 //  * StringLiteral
7385 //  * PredefinedExpr
7386 //  * ObjCStringLiteralExpr
7387 //  * ObjCEncodeExpr
7388 //  * AddrLabelExpr
7389 //  * BlockExpr
7390 //  * CallExpr for a MakeStringConstant builtin
7391 // - typeid(T) expressions, as TypeInfoLValues
7392 // - Locals and temporaries
7393 //  * MaterializeTemporaryExpr
7394 //  * Any Expr, with a CallIndex indicating the function in which the temporary
7395 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
7396 //    from the AST (FIXME).
7397 //  * A MaterializeTemporaryExpr that has static storage duration, with no
7398 //    CallIndex, for a lifetime-extended temporary.
7399 //  * The ConstantExpr that is currently being evaluated during evaluation of an
7400 //    immediate invocation.
7401 // plus an offset in bytes.
7402 //===----------------------------------------------------------------------===//
7403 namespace {
7404 class LValueExprEvaluator
7405   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
7406 public:
7407   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
7408     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
7409 
7410   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
7411   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
7412 
7413   bool VisitDeclRefExpr(const DeclRefExpr *E);
7414   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
7415   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
7416   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
7417   bool VisitMemberExpr(const MemberExpr *E);
7418   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
7419   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
7420   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
7421   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
7422   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
7423   bool VisitUnaryDeref(const UnaryOperator *E);
7424   bool VisitUnaryReal(const UnaryOperator *E);
7425   bool VisitUnaryImag(const UnaryOperator *E);
7426   bool VisitUnaryPreInc(const UnaryOperator *UO) {
7427     return VisitUnaryPreIncDec(UO);
7428   }
7429   bool VisitUnaryPreDec(const UnaryOperator *UO) {
7430     return VisitUnaryPreIncDec(UO);
7431   }
7432   bool VisitBinAssign(const BinaryOperator *BO);
7433   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
7434 
7435   bool VisitCastExpr(const CastExpr *E) {
7436     switch (E->getCastKind()) {
7437     default:
7438       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
7439 
7440     case CK_LValueBitCast:
7441       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7442       if (!Visit(E->getSubExpr()))
7443         return false;
7444       Result.Designator.setInvalid();
7445       return true;
7446 
7447     case CK_BaseToDerived:
7448       if (!Visit(E->getSubExpr()))
7449         return false;
7450       return HandleBaseToDerivedCast(Info, E, Result);
7451 
7452     case CK_Dynamic:
7453       if (!Visit(E->getSubExpr()))
7454         return false;
7455       return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
7456     }
7457   }
7458 };
7459 } // end anonymous namespace
7460 
7461 /// Evaluate an expression as an lvalue. This can be legitimately called on
7462 /// expressions which are not glvalues, in three cases:
7463 ///  * function designators in C, and
7464 ///  * "extern void" objects
7465 ///  * @selector() expressions in Objective-C
7466 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
7467                            bool InvalidBaseOK) {
7468   assert(E->isGLValue() || E->getType()->isFunctionType() ||
7469          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
7470   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
7471 }
7472 
7473 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
7474   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
7475     return Success(FD);
7476   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
7477     return VisitVarDecl(E, VD);
7478   if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
7479     return Visit(BD->getBinding());
7480   return Error(E);
7481 }
7482 
7483 
7484 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
7485 
7486   // If we are within a lambda's call operator, check whether the 'VD' referred
7487   // to within 'E' actually represents a lambda-capture that maps to a
7488   // data-member/field within the closure object, and if so, evaluate to the
7489   // field or what the field refers to.
7490   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
7491       isa<DeclRefExpr>(E) &&
7492       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
7493     // We don't always have a complete capture-map when checking or inferring if
7494     // the function call operator meets the requirements of a constexpr function
7495     // - but we don't need to evaluate the captures to determine constexprness
7496     // (dcl.constexpr C++17).
7497     if (Info.checkingPotentialConstantExpression())
7498       return false;
7499 
7500     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
7501       // Start with 'Result' referring to the complete closure object...
7502       Result = *Info.CurrentCall->This;
7503       // ... then update it to refer to the field of the closure object
7504       // that represents the capture.
7505       if (!HandleLValueMember(Info, E, Result, FD))
7506         return false;
7507       // And if the field is of reference type, update 'Result' to refer to what
7508       // the field refers to.
7509       if (FD->getType()->isReferenceType()) {
7510         APValue RVal;
7511         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
7512                                             RVal))
7513           return false;
7514         Result.setFrom(Info.Ctx, RVal);
7515       }
7516       return true;
7517     }
7518   }
7519   CallStackFrame *Frame = nullptr;
7520   if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
7521     // Only if a local variable was declared in the function currently being
7522     // evaluated, do we expect to be able to find its value in the current
7523     // frame. (Otherwise it was likely declared in an enclosing context and
7524     // could either have a valid evaluatable value (for e.g. a constexpr
7525     // variable) or be ill-formed (and trigger an appropriate evaluation
7526     // diagnostic)).
7527     if (Info.CurrentCall->Callee &&
7528         Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
7529       Frame = Info.CurrentCall;
7530     }
7531   }
7532 
7533   if (!VD->getType()->isReferenceType()) {
7534     if (Frame) {
7535       Result.set({VD, Frame->Index,
7536                   Info.CurrentCall->getCurrentTemporaryVersion(VD)});
7537       return true;
7538     }
7539     return Success(VD);
7540   }
7541 
7542   APValue *V;
7543   if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
7544     return false;
7545   if (!V->hasValue()) {
7546     // FIXME: Is it possible for V to be indeterminate here? If so, we should
7547     // adjust the diagnostic to say that.
7548     if (!Info.checkingPotentialConstantExpression())
7549       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
7550     return false;
7551   }
7552   return Success(*V, E);
7553 }
7554 
7555 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
7556     const MaterializeTemporaryExpr *E) {
7557   // Walk through the expression to find the materialized temporary itself.
7558   SmallVector<const Expr *, 2> CommaLHSs;
7559   SmallVector<SubobjectAdjustment, 2> Adjustments;
7560   const Expr *Inner =
7561       E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
7562 
7563   // If we passed any comma operators, evaluate their LHSs.
7564   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
7565     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
7566       return false;
7567 
7568   // A materialized temporary with static storage duration can appear within the
7569   // result of a constant expression evaluation, so we need to preserve its
7570   // value for use outside this evaluation.
7571   APValue *Value;
7572   if (E->getStorageDuration() == SD_Static) {
7573     Value = E->getOrCreateValue(true);
7574     *Value = APValue();
7575     Result.set(E);
7576   } else {
7577     Value = &Info.CurrentCall->createTemporary(
7578         E, E->getType(), E->getStorageDuration() == SD_Automatic, Result);
7579   }
7580 
7581   QualType Type = Inner->getType();
7582 
7583   // Materialize the temporary itself.
7584   if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
7585     *Value = APValue();
7586     return false;
7587   }
7588 
7589   // Adjust our lvalue to refer to the desired subobject.
7590   for (unsigned I = Adjustments.size(); I != 0; /**/) {
7591     --I;
7592     switch (Adjustments[I].Kind) {
7593     case SubobjectAdjustment::DerivedToBaseAdjustment:
7594       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
7595                                 Type, Result))
7596         return false;
7597       Type = Adjustments[I].DerivedToBase.BasePath->getType();
7598       break;
7599 
7600     case SubobjectAdjustment::FieldAdjustment:
7601       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
7602         return false;
7603       Type = Adjustments[I].Field->getType();
7604       break;
7605 
7606     case SubobjectAdjustment::MemberPointerAdjustment:
7607       if (!HandleMemberPointerAccess(this->Info, Type, Result,
7608                                      Adjustments[I].Ptr.RHS))
7609         return false;
7610       Type = Adjustments[I].Ptr.MPT->getPointeeType();
7611       break;
7612     }
7613   }
7614 
7615   return true;
7616 }
7617 
7618 bool
7619 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7620   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
7621          "lvalue compound literal in c++?");
7622   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
7623   // only see this when folding in C, so there's no standard to follow here.
7624   return Success(E);
7625 }
7626 
7627 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
7628   TypeInfoLValue TypeInfo;
7629 
7630   if (!E->isPotentiallyEvaluated()) {
7631     if (E->isTypeOperand())
7632       TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
7633     else
7634       TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
7635   } else {
7636     if (!Info.Ctx.getLangOpts().CPlusPlus2a) {
7637       Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
7638         << E->getExprOperand()->getType()
7639         << E->getExprOperand()->getSourceRange();
7640     }
7641 
7642     if (!Visit(E->getExprOperand()))
7643       return false;
7644 
7645     Optional<DynamicType> DynType =
7646         ComputeDynamicType(Info, E, Result, AK_TypeId);
7647     if (!DynType)
7648       return false;
7649 
7650     TypeInfo =
7651         TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
7652   }
7653 
7654   return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
7655 }
7656 
7657 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
7658   return Success(E);
7659 }
7660 
7661 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
7662   // Handle static data members.
7663   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
7664     VisitIgnoredBaseExpression(E->getBase());
7665     return VisitVarDecl(E, VD);
7666   }
7667 
7668   // Handle static member functions.
7669   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
7670     if (MD->isStatic()) {
7671       VisitIgnoredBaseExpression(E->getBase());
7672       return Success(MD);
7673     }
7674   }
7675 
7676   // Handle non-static data members.
7677   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
7678 }
7679 
7680 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
7681   // FIXME: Deal with vectors as array subscript bases.
7682   if (E->getBase()->getType()->isVectorType())
7683     return Error(E);
7684 
7685   bool Success = true;
7686   if (!evaluatePointer(E->getBase(), Result)) {
7687     if (!Info.noteFailure())
7688       return false;
7689     Success = false;
7690   }
7691 
7692   APSInt Index;
7693   if (!EvaluateInteger(E->getIdx(), Index, Info))
7694     return false;
7695 
7696   return Success &&
7697          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
7698 }
7699 
7700 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
7701   return evaluatePointer(E->getSubExpr(), Result);
7702 }
7703 
7704 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7705   if (!Visit(E->getSubExpr()))
7706     return false;
7707   // __real is a no-op on scalar lvalues.
7708   if (E->getSubExpr()->getType()->isAnyComplexType())
7709     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
7710   return true;
7711 }
7712 
7713 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
7714   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
7715          "lvalue __imag__ on scalar?");
7716   if (!Visit(E->getSubExpr()))
7717     return false;
7718   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
7719   return true;
7720 }
7721 
7722 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
7723   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7724     return Error(UO);
7725 
7726   if (!this->Visit(UO->getSubExpr()))
7727     return false;
7728 
7729   return handleIncDec(
7730       this->Info, UO, Result, UO->getSubExpr()->getType(),
7731       UO->isIncrementOp(), nullptr);
7732 }
7733 
7734 bool LValueExprEvaluator::VisitCompoundAssignOperator(
7735     const CompoundAssignOperator *CAO) {
7736   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7737     return Error(CAO);
7738 
7739   APValue RHS;
7740 
7741   // The overall lvalue result is the result of evaluating the LHS.
7742   if (!this->Visit(CAO->getLHS())) {
7743     if (Info.noteFailure())
7744       Evaluate(RHS, this->Info, CAO->getRHS());
7745     return false;
7746   }
7747 
7748   if (!Evaluate(RHS, this->Info, CAO->getRHS()))
7749     return false;
7750 
7751   return handleCompoundAssignment(
7752       this->Info, CAO,
7753       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
7754       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
7755 }
7756 
7757 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
7758   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7759     return Error(E);
7760 
7761   APValue NewVal;
7762 
7763   if (!this->Visit(E->getLHS())) {
7764     if (Info.noteFailure())
7765       Evaluate(NewVal, this->Info, E->getRHS());
7766     return false;
7767   }
7768 
7769   if (!Evaluate(NewVal, this->Info, E->getRHS()))
7770     return false;
7771 
7772   if (Info.getLangOpts().CPlusPlus2a &&
7773       !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
7774     return false;
7775 
7776   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
7777                           NewVal);
7778 }
7779 
7780 //===----------------------------------------------------------------------===//
7781 // Pointer Evaluation
7782 //===----------------------------------------------------------------------===//
7783 
7784 /// Attempts to compute the number of bytes available at the pointer
7785 /// returned by a function with the alloc_size attribute. Returns true if we
7786 /// were successful. Places an unsigned number into `Result`.
7787 ///
7788 /// This expects the given CallExpr to be a call to a function with an
7789 /// alloc_size attribute.
7790 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
7791                                             const CallExpr *Call,
7792                                             llvm::APInt &Result) {
7793   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
7794 
7795   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
7796   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
7797   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
7798   if (Call->getNumArgs() <= SizeArgNo)
7799     return false;
7800 
7801   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
7802     Expr::EvalResult ExprResult;
7803     if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
7804       return false;
7805     Into = ExprResult.Val.getInt();
7806     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
7807       return false;
7808     Into = Into.zextOrSelf(BitsInSizeT);
7809     return true;
7810   };
7811 
7812   APSInt SizeOfElem;
7813   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
7814     return false;
7815 
7816   if (!AllocSize->getNumElemsParam().isValid()) {
7817     Result = std::move(SizeOfElem);
7818     return true;
7819   }
7820 
7821   APSInt NumberOfElems;
7822   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
7823   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
7824     return false;
7825 
7826   bool Overflow;
7827   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
7828   if (Overflow)
7829     return false;
7830 
7831   Result = std::move(BytesAvailable);
7832   return true;
7833 }
7834 
7835 /// Convenience function. LVal's base must be a call to an alloc_size
7836 /// function.
7837 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
7838                                             const LValue &LVal,
7839                                             llvm::APInt &Result) {
7840   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7841          "Can't get the size of a non alloc_size function");
7842   const auto *Base = LVal.getLValueBase().get<const Expr *>();
7843   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
7844   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
7845 }
7846 
7847 /// Attempts to evaluate the given LValueBase as the result of a call to
7848 /// a function with the alloc_size attribute. If it was possible to do so, this
7849 /// function will return true, make Result's Base point to said function call,
7850 /// and mark Result's Base as invalid.
7851 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
7852                                       LValue &Result) {
7853   if (Base.isNull())
7854     return false;
7855 
7856   // Because we do no form of static analysis, we only support const variables.
7857   //
7858   // Additionally, we can't support parameters, nor can we support static
7859   // variables (in the latter case, use-before-assign isn't UB; in the former,
7860   // we have no clue what they'll be assigned to).
7861   const auto *VD =
7862       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
7863   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
7864     return false;
7865 
7866   const Expr *Init = VD->getAnyInitializer();
7867   if (!Init)
7868     return false;
7869 
7870   const Expr *E = Init->IgnoreParens();
7871   if (!tryUnwrapAllocSizeCall(E))
7872     return false;
7873 
7874   // Store E instead of E unwrapped so that the type of the LValue's base is
7875   // what the user wanted.
7876   Result.setInvalid(E);
7877 
7878   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
7879   Result.addUnsizedArray(Info, E, Pointee);
7880   return true;
7881 }
7882 
7883 namespace {
7884 class PointerExprEvaluator
7885   : public ExprEvaluatorBase<PointerExprEvaluator> {
7886   LValue &Result;
7887   bool InvalidBaseOK;
7888 
7889   bool Success(const Expr *E) {
7890     Result.set(E);
7891     return true;
7892   }
7893 
7894   bool evaluateLValue(const Expr *E, LValue &Result) {
7895     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
7896   }
7897 
7898   bool evaluatePointer(const Expr *E, LValue &Result) {
7899     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
7900   }
7901 
7902   bool visitNonBuiltinCallExpr(const CallExpr *E);
7903 public:
7904 
7905   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
7906       : ExprEvaluatorBaseTy(info), Result(Result),
7907         InvalidBaseOK(InvalidBaseOK) {}
7908 
7909   bool Success(const APValue &V, const Expr *E) {
7910     Result.setFrom(Info.Ctx, V);
7911     return true;
7912   }
7913   bool ZeroInitialization(const Expr *E) {
7914     Result.setNull(Info.Ctx, E->getType());
7915     return true;
7916   }
7917 
7918   bool VisitBinaryOperator(const BinaryOperator *E);
7919   bool VisitCastExpr(const CastExpr* E);
7920   bool VisitUnaryAddrOf(const UnaryOperator *E);
7921   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
7922       { return Success(E); }
7923   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
7924     if (E->isExpressibleAsConstantInitializer())
7925       return Success(E);
7926     if (Info.noteFailure())
7927       EvaluateIgnoredValue(Info, E->getSubExpr());
7928     return Error(E);
7929   }
7930   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
7931       { return Success(E); }
7932   bool VisitCallExpr(const CallExpr *E);
7933   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
7934   bool VisitBlockExpr(const BlockExpr *E) {
7935     if (!E->getBlockDecl()->hasCaptures())
7936       return Success(E);
7937     return Error(E);
7938   }
7939   bool VisitCXXThisExpr(const CXXThisExpr *E) {
7940     // Can't look at 'this' when checking a potential constant expression.
7941     if (Info.checkingPotentialConstantExpression())
7942       return false;
7943     if (!Info.CurrentCall->This) {
7944       if (Info.getLangOpts().CPlusPlus11)
7945         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
7946       else
7947         Info.FFDiag(E);
7948       return false;
7949     }
7950     Result = *Info.CurrentCall->This;
7951     // If we are inside a lambda's call operator, the 'this' expression refers
7952     // to the enclosing '*this' object (either by value or reference) which is
7953     // either copied into the closure object's field that represents the '*this'
7954     // or refers to '*this'.
7955     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
7956       // Ensure we actually have captured 'this'. (an error will have
7957       // been previously reported if not).
7958       if (!Info.CurrentCall->LambdaThisCaptureField)
7959         return false;
7960 
7961       // Update 'Result' to refer to the data member/field of the closure object
7962       // that represents the '*this' capture.
7963       if (!HandleLValueMember(Info, E, Result,
7964                              Info.CurrentCall->LambdaThisCaptureField))
7965         return false;
7966       // If we captured '*this' by reference, replace the field with its referent.
7967       if (Info.CurrentCall->LambdaThisCaptureField->getType()
7968               ->isPointerType()) {
7969         APValue RVal;
7970         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
7971                                             RVal))
7972           return false;
7973 
7974         Result.setFrom(Info.Ctx, RVal);
7975       }
7976     }
7977     return true;
7978   }
7979 
7980   bool VisitCXXNewExpr(const CXXNewExpr *E);
7981 
7982   bool VisitSourceLocExpr(const SourceLocExpr *E) {
7983     assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
7984     APValue LValResult = E->EvaluateInContext(
7985         Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
7986     Result.setFrom(Info.Ctx, LValResult);
7987     return true;
7988   }
7989 
7990   // FIXME: Missing: @protocol, @selector
7991 };
7992 } // end anonymous namespace
7993 
7994 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
7995                             bool InvalidBaseOK) {
7996   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7997   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
7998 }
7999 
8000 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8001   if (E->getOpcode() != BO_Add &&
8002       E->getOpcode() != BO_Sub)
8003     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8004 
8005   const Expr *PExp = E->getLHS();
8006   const Expr *IExp = E->getRHS();
8007   if (IExp->getType()->isPointerType())
8008     std::swap(PExp, IExp);
8009 
8010   bool EvalPtrOK = evaluatePointer(PExp, Result);
8011   if (!EvalPtrOK && !Info.noteFailure())
8012     return false;
8013 
8014   llvm::APSInt Offset;
8015   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
8016     return false;
8017 
8018   if (E->getOpcode() == BO_Sub)
8019     negateAsSigned(Offset);
8020 
8021   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
8022   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
8023 }
8024 
8025 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8026   return evaluateLValue(E->getSubExpr(), Result);
8027 }
8028 
8029 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8030   const Expr *SubExpr = E->getSubExpr();
8031 
8032   switch (E->getCastKind()) {
8033   default:
8034     break;
8035   case CK_BitCast:
8036   case CK_CPointerToObjCPointerCast:
8037   case CK_BlockPointerToObjCPointerCast:
8038   case CK_AnyPointerToBlockPointerCast:
8039   case CK_AddressSpaceConversion:
8040     if (!Visit(SubExpr))
8041       return false;
8042     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
8043     // permitted in constant expressions in C++11. Bitcasts from cv void* are
8044     // also static_casts, but we disallow them as a resolution to DR1312.
8045     if (!E->getType()->isVoidPointerType()) {
8046       if (!Result.InvalidBase && !Result.Designator.Invalid &&
8047           !Result.IsNullPtr &&
8048           Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
8049                                           E->getType()->getPointeeType()) &&
8050           Info.getStdAllocatorCaller("allocate")) {
8051         // Inside a call to std::allocator::allocate and friends, we permit
8052         // casting from void* back to cv1 T* for a pointer that points to a
8053         // cv2 T.
8054       } else {
8055         Result.Designator.setInvalid();
8056         if (SubExpr->getType()->isVoidPointerType())
8057           CCEDiag(E, diag::note_constexpr_invalid_cast)
8058             << 3 << SubExpr->getType();
8059         else
8060           CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8061       }
8062     }
8063     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
8064       ZeroInitialization(E);
8065     return true;
8066 
8067   case CK_DerivedToBase:
8068   case CK_UncheckedDerivedToBase:
8069     if (!evaluatePointer(E->getSubExpr(), Result))
8070       return false;
8071     if (!Result.Base && Result.Offset.isZero())
8072       return true;
8073 
8074     // Now figure out the necessary offset to add to the base LV to get from
8075     // the derived class to the base class.
8076     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
8077                                   castAs<PointerType>()->getPointeeType(),
8078                                 Result);
8079 
8080   case CK_BaseToDerived:
8081     if (!Visit(E->getSubExpr()))
8082       return false;
8083     if (!Result.Base && Result.Offset.isZero())
8084       return true;
8085     return HandleBaseToDerivedCast(Info, E, Result);
8086 
8087   case CK_Dynamic:
8088     if (!Visit(E->getSubExpr()))
8089       return false;
8090     return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8091 
8092   case CK_NullToPointer:
8093     VisitIgnoredValue(E->getSubExpr());
8094     return ZeroInitialization(E);
8095 
8096   case CK_IntegralToPointer: {
8097     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8098 
8099     APValue Value;
8100     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
8101       break;
8102 
8103     if (Value.isInt()) {
8104       unsigned Size = Info.Ctx.getTypeSize(E->getType());
8105       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
8106       Result.Base = (Expr*)nullptr;
8107       Result.InvalidBase = false;
8108       Result.Offset = CharUnits::fromQuantity(N);
8109       Result.Designator.setInvalid();
8110       Result.IsNullPtr = false;
8111       return true;
8112     } else {
8113       // Cast is of an lvalue, no need to change value.
8114       Result.setFrom(Info.Ctx, Value);
8115       return true;
8116     }
8117   }
8118 
8119   case CK_ArrayToPointerDecay: {
8120     if (SubExpr->isGLValue()) {
8121       if (!evaluateLValue(SubExpr, Result))
8122         return false;
8123     } else {
8124       APValue &Value = Info.CurrentCall->createTemporary(
8125           SubExpr, SubExpr->getType(), false, Result);
8126       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
8127         return false;
8128     }
8129     // The result is a pointer to the first element of the array.
8130     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
8131     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
8132       Result.addArray(Info, E, CAT);
8133     else
8134       Result.addUnsizedArray(Info, E, AT->getElementType());
8135     return true;
8136   }
8137 
8138   case CK_FunctionToPointerDecay:
8139     return evaluateLValue(SubExpr, Result);
8140 
8141   case CK_LValueToRValue: {
8142     LValue LVal;
8143     if (!evaluateLValue(E->getSubExpr(), LVal))
8144       return false;
8145 
8146     APValue RVal;
8147     // Note, we use the subexpression's type in order to retain cv-qualifiers.
8148     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8149                                         LVal, RVal))
8150       return InvalidBaseOK &&
8151              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
8152     return Success(RVal, E);
8153   }
8154   }
8155 
8156   return ExprEvaluatorBaseTy::VisitCastExpr(E);
8157 }
8158 
8159 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
8160                                 UnaryExprOrTypeTrait ExprKind) {
8161   // C++ [expr.alignof]p3:
8162   //     When alignof is applied to a reference type, the result is the
8163   //     alignment of the referenced type.
8164   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
8165     T = Ref->getPointeeType();
8166 
8167   if (T.getQualifiers().hasUnaligned())
8168     return CharUnits::One();
8169 
8170   const bool AlignOfReturnsPreferred =
8171       Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
8172 
8173   // __alignof is defined to return the preferred alignment.
8174   // Before 8, clang returned the preferred alignment for alignof and _Alignof
8175   // as well.
8176   if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
8177     return Info.Ctx.toCharUnitsFromBits(
8178       Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
8179   // alignof and _Alignof are defined to return the ABI alignment.
8180   else if (ExprKind == UETT_AlignOf)
8181     return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
8182   else
8183     llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
8184 }
8185 
8186 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
8187                                 UnaryExprOrTypeTrait ExprKind) {
8188   E = E->IgnoreParens();
8189 
8190   // The kinds of expressions that we have special-case logic here for
8191   // should be kept up to date with the special checks for those
8192   // expressions in Sema.
8193 
8194   // alignof decl is always accepted, even if it doesn't make sense: we default
8195   // to 1 in those cases.
8196   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8197     return Info.Ctx.getDeclAlign(DRE->getDecl(),
8198                                  /*RefAsPointee*/true);
8199 
8200   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
8201     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
8202                                  /*RefAsPointee*/true);
8203 
8204   return GetAlignOfType(Info, E->getType(), ExprKind);
8205 }
8206 
8207 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
8208   if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
8209     return Info.Ctx.getDeclAlign(VD);
8210   if (const auto *E = Value.Base.dyn_cast<const Expr *>())
8211     return GetAlignOfExpr(Info, E, UETT_AlignOf);
8212   return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
8213 }
8214 
8215 /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
8216 /// __builtin_is_aligned and __builtin_assume_aligned.
8217 static bool getAlignmentArgument(const Expr *E, QualType ForType,
8218                                  EvalInfo &Info, APSInt &Alignment) {
8219   if (!EvaluateInteger(E, Alignment, Info))
8220     return false;
8221   if (Alignment < 0 || !Alignment.isPowerOf2()) {
8222     Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
8223     return false;
8224   }
8225   unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
8226   APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
8227   if (APSInt::compareValues(Alignment, MaxValue) > 0) {
8228     Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
8229         << MaxValue << ForType << Alignment;
8230     return false;
8231   }
8232   // Ensure both alignment and source value have the same bit width so that we
8233   // don't assert when computing the resulting value.
8234   APSInt ExtAlignment =
8235       APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
8236   assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
8237          "Alignment should not be changed by ext/trunc");
8238   Alignment = ExtAlignment;
8239   assert(Alignment.getBitWidth() == SrcWidth);
8240   return true;
8241 }
8242 
8243 // To be clear: this happily visits unsupported builtins. Better name welcomed.
8244 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
8245   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
8246     return true;
8247 
8248   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
8249     return false;
8250 
8251   Result.setInvalid(E);
8252   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
8253   Result.addUnsizedArray(Info, E, PointeeTy);
8254   return true;
8255 }
8256 
8257 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
8258   if (IsStringLiteralCall(E))
8259     return Success(E);
8260 
8261   if (unsigned BuiltinOp = E->getBuiltinCallee())
8262     return VisitBuiltinCallExpr(E, BuiltinOp);
8263 
8264   return visitNonBuiltinCallExpr(E);
8265 }
8266 
8267 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8268                                                 unsigned BuiltinOp) {
8269   switch (BuiltinOp) {
8270   case Builtin::BI__builtin_addressof:
8271     return evaluateLValue(E->getArg(0), Result);
8272   case Builtin::BI__builtin_assume_aligned: {
8273     // We need to be very careful here because: if the pointer does not have the
8274     // asserted alignment, then the behavior is undefined, and undefined
8275     // behavior is non-constant.
8276     if (!evaluatePointer(E->getArg(0), Result))
8277       return false;
8278 
8279     LValue OffsetResult(Result);
8280     APSInt Alignment;
8281     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
8282                               Alignment))
8283       return false;
8284     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
8285 
8286     if (E->getNumArgs() > 2) {
8287       APSInt Offset;
8288       if (!EvaluateInteger(E->getArg(2), Offset, Info))
8289         return false;
8290 
8291       int64_t AdditionalOffset = -Offset.getZExtValue();
8292       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
8293     }
8294 
8295     // If there is a base object, then it must have the correct alignment.
8296     if (OffsetResult.Base) {
8297       CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
8298 
8299       if (BaseAlignment < Align) {
8300         Result.Designator.setInvalid();
8301         // FIXME: Add support to Diagnostic for long / long long.
8302         CCEDiag(E->getArg(0),
8303                 diag::note_constexpr_baa_insufficient_alignment) << 0
8304           << (unsigned)BaseAlignment.getQuantity()
8305           << (unsigned)Align.getQuantity();
8306         return false;
8307       }
8308     }
8309 
8310     // The offset must also have the correct alignment.
8311     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
8312       Result.Designator.setInvalid();
8313 
8314       (OffsetResult.Base
8315            ? CCEDiag(E->getArg(0),
8316                      diag::note_constexpr_baa_insufficient_alignment) << 1
8317            : CCEDiag(E->getArg(0),
8318                      diag::note_constexpr_baa_value_insufficient_alignment))
8319         << (int)OffsetResult.Offset.getQuantity()
8320         << (unsigned)Align.getQuantity();
8321       return false;
8322     }
8323 
8324     return true;
8325   }
8326   case Builtin::BI__builtin_align_up:
8327   case Builtin::BI__builtin_align_down: {
8328     if (!evaluatePointer(E->getArg(0), Result))
8329       return false;
8330     APSInt Alignment;
8331     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
8332                               Alignment))
8333       return false;
8334     CharUnits BaseAlignment = getBaseAlignment(Info, Result);
8335     CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
8336     // For align_up/align_down, we can return the same value if the alignment
8337     // is known to be greater or equal to the requested value.
8338     if (PtrAlign.getQuantity() >= Alignment)
8339       return true;
8340 
8341     // The alignment could be greater than the minimum at run-time, so we cannot
8342     // infer much about the resulting pointer value. One case is possible:
8343     // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
8344     // can infer the correct index if the requested alignment is smaller than
8345     // the base alignment so we can perform the computation on the offset.
8346     if (BaseAlignment.getQuantity() >= Alignment) {
8347       assert(Alignment.getBitWidth() <= 64 &&
8348              "Cannot handle > 64-bit address-space");
8349       uint64_t Alignment64 = Alignment.getZExtValue();
8350       CharUnits NewOffset = CharUnits::fromQuantity(
8351           BuiltinOp == Builtin::BI__builtin_align_down
8352               ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
8353               : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
8354       Result.adjustOffset(NewOffset - Result.Offset);
8355       // TODO: diagnose out-of-bounds values/only allow for arrays?
8356       return true;
8357     }
8358     // Otherwise, we cannot constant-evaluate the result.
8359     Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
8360         << Alignment;
8361     return false;
8362   }
8363   case Builtin::BI__builtin_operator_new:
8364     return HandleOperatorNewCall(Info, E, Result);
8365   case Builtin::BI__builtin_launder:
8366     return evaluatePointer(E->getArg(0), Result);
8367   case Builtin::BIstrchr:
8368   case Builtin::BIwcschr:
8369   case Builtin::BImemchr:
8370   case Builtin::BIwmemchr:
8371     if (Info.getLangOpts().CPlusPlus11)
8372       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8373         << /*isConstexpr*/0 << /*isConstructor*/0
8374         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
8375     else
8376       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
8377     LLVM_FALLTHROUGH;
8378   case Builtin::BI__builtin_strchr:
8379   case Builtin::BI__builtin_wcschr:
8380   case Builtin::BI__builtin_memchr:
8381   case Builtin::BI__builtin_char_memchr:
8382   case Builtin::BI__builtin_wmemchr: {
8383     if (!Visit(E->getArg(0)))
8384       return false;
8385     APSInt Desired;
8386     if (!EvaluateInteger(E->getArg(1), Desired, Info))
8387       return false;
8388     uint64_t MaxLength = uint64_t(-1);
8389     if (BuiltinOp != Builtin::BIstrchr &&
8390         BuiltinOp != Builtin::BIwcschr &&
8391         BuiltinOp != Builtin::BI__builtin_strchr &&
8392         BuiltinOp != Builtin::BI__builtin_wcschr) {
8393       APSInt N;
8394       if (!EvaluateInteger(E->getArg(2), N, Info))
8395         return false;
8396       MaxLength = N.getExtValue();
8397     }
8398     // We cannot find the value if there are no candidates to match against.
8399     if (MaxLength == 0u)
8400       return ZeroInitialization(E);
8401     if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
8402         Result.Designator.Invalid)
8403       return false;
8404     QualType CharTy = Result.Designator.getType(Info.Ctx);
8405     bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
8406                      BuiltinOp == Builtin::BI__builtin_memchr;
8407     assert(IsRawByte ||
8408            Info.Ctx.hasSameUnqualifiedType(
8409                CharTy, E->getArg(0)->getType()->getPointeeType()));
8410     // Pointers to const void may point to objects of incomplete type.
8411     if (IsRawByte && CharTy->isIncompleteType()) {
8412       Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
8413       return false;
8414     }
8415     // Give up on byte-oriented matching against multibyte elements.
8416     // FIXME: We can compare the bytes in the correct order.
8417     if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One())
8418       return false;
8419     // Figure out what value we're actually looking for (after converting to
8420     // the corresponding unsigned type if necessary).
8421     uint64_t DesiredVal;
8422     bool StopAtNull = false;
8423     switch (BuiltinOp) {
8424     case Builtin::BIstrchr:
8425     case Builtin::BI__builtin_strchr:
8426       // strchr compares directly to the passed integer, and therefore
8427       // always fails if given an int that is not a char.
8428       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
8429                                                   E->getArg(1)->getType(),
8430                                                   Desired),
8431                                Desired))
8432         return ZeroInitialization(E);
8433       StopAtNull = true;
8434       LLVM_FALLTHROUGH;
8435     case Builtin::BImemchr:
8436     case Builtin::BI__builtin_memchr:
8437     case Builtin::BI__builtin_char_memchr:
8438       // memchr compares by converting both sides to unsigned char. That's also
8439       // correct for strchr if we get this far (to cope with plain char being
8440       // unsigned in the strchr case).
8441       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
8442       break;
8443 
8444     case Builtin::BIwcschr:
8445     case Builtin::BI__builtin_wcschr:
8446       StopAtNull = true;
8447       LLVM_FALLTHROUGH;
8448     case Builtin::BIwmemchr:
8449     case Builtin::BI__builtin_wmemchr:
8450       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
8451       DesiredVal = Desired.getZExtValue();
8452       break;
8453     }
8454 
8455     for (; MaxLength; --MaxLength) {
8456       APValue Char;
8457       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
8458           !Char.isInt())
8459         return false;
8460       if (Char.getInt().getZExtValue() == DesiredVal)
8461         return true;
8462       if (StopAtNull && !Char.getInt())
8463         break;
8464       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
8465         return false;
8466     }
8467     // Not found: return nullptr.
8468     return ZeroInitialization(E);
8469   }
8470 
8471   case Builtin::BImemcpy:
8472   case Builtin::BImemmove:
8473   case Builtin::BIwmemcpy:
8474   case Builtin::BIwmemmove:
8475     if (Info.getLangOpts().CPlusPlus11)
8476       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8477         << /*isConstexpr*/0 << /*isConstructor*/0
8478         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
8479     else
8480       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
8481     LLVM_FALLTHROUGH;
8482   case Builtin::BI__builtin_memcpy:
8483   case Builtin::BI__builtin_memmove:
8484   case Builtin::BI__builtin_wmemcpy:
8485   case Builtin::BI__builtin_wmemmove: {
8486     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
8487                  BuiltinOp == Builtin::BIwmemmove ||
8488                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
8489                  BuiltinOp == Builtin::BI__builtin_wmemmove;
8490     bool Move = BuiltinOp == Builtin::BImemmove ||
8491                 BuiltinOp == Builtin::BIwmemmove ||
8492                 BuiltinOp == Builtin::BI__builtin_memmove ||
8493                 BuiltinOp == Builtin::BI__builtin_wmemmove;
8494 
8495     // The result of mem* is the first argument.
8496     if (!Visit(E->getArg(0)))
8497       return false;
8498     LValue Dest = Result;
8499 
8500     LValue Src;
8501     if (!EvaluatePointer(E->getArg(1), Src, Info))
8502       return false;
8503 
8504     APSInt N;
8505     if (!EvaluateInteger(E->getArg(2), N, Info))
8506       return false;
8507     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
8508 
8509     // If the size is zero, we treat this as always being a valid no-op.
8510     // (Even if one of the src and dest pointers is null.)
8511     if (!N)
8512       return true;
8513 
8514     // Otherwise, if either of the operands is null, we can't proceed. Don't
8515     // try to determine the type of the copied objects, because there aren't
8516     // any.
8517     if (!Src.Base || !Dest.Base) {
8518       APValue Val;
8519       (!Src.Base ? Src : Dest).moveInto(Val);
8520       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
8521           << Move << WChar << !!Src.Base
8522           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
8523       return false;
8524     }
8525     if (Src.Designator.Invalid || Dest.Designator.Invalid)
8526       return false;
8527 
8528     // We require that Src and Dest are both pointers to arrays of
8529     // trivially-copyable type. (For the wide version, the designator will be
8530     // invalid if the designated object is not a wchar_t.)
8531     QualType T = Dest.Designator.getType(Info.Ctx);
8532     QualType SrcT = Src.Designator.getType(Info.Ctx);
8533     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
8534       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
8535       return false;
8536     }
8537     if (T->isIncompleteType()) {
8538       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
8539       return false;
8540     }
8541     if (!T.isTriviallyCopyableType(Info.Ctx)) {
8542       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
8543       return false;
8544     }
8545 
8546     // Figure out how many T's we're copying.
8547     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
8548     if (!WChar) {
8549       uint64_t Remainder;
8550       llvm::APInt OrigN = N;
8551       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
8552       if (Remainder) {
8553         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
8554             << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
8555             << (unsigned)TSize;
8556         return false;
8557       }
8558     }
8559 
8560     // Check that the copying will remain within the arrays, just so that we
8561     // can give a more meaningful diagnostic. This implicitly also checks that
8562     // N fits into 64 bits.
8563     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
8564     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
8565     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
8566       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
8567           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
8568           << N.toString(10, /*Signed*/false);
8569       return false;
8570     }
8571     uint64_t NElems = N.getZExtValue();
8572     uint64_t NBytes = NElems * TSize;
8573 
8574     // Check for overlap.
8575     int Direction = 1;
8576     if (HasSameBase(Src, Dest)) {
8577       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
8578       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
8579       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
8580         // Dest is inside the source region.
8581         if (!Move) {
8582           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
8583           return false;
8584         }
8585         // For memmove and friends, copy backwards.
8586         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
8587             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
8588           return false;
8589         Direction = -1;
8590       } else if (!Move && SrcOffset >= DestOffset &&
8591                  SrcOffset - DestOffset < NBytes) {
8592         // Src is inside the destination region for memcpy: invalid.
8593         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
8594         return false;
8595       }
8596     }
8597 
8598     while (true) {
8599       APValue Val;
8600       // FIXME: Set WantObjectRepresentation to true if we're copying a
8601       // char-like type?
8602       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
8603           !handleAssignment(Info, E, Dest, T, Val))
8604         return false;
8605       // Do not iterate past the last element; if we're copying backwards, that
8606       // might take us off the start of the array.
8607       if (--NElems == 0)
8608         return true;
8609       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
8610           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
8611         return false;
8612     }
8613   }
8614 
8615   default:
8616     break;
8617   }
8618 
8619   return visitNonBuiltinCallExpr(E);
8620 }
8621 
8622 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
8623                                      APValue &Result, const InitListExpr *ILE,
8624                                      QualType AllocType);
8625 
8626 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
8627   if (!Info.getLangOpts().CPlusPlus2a)
8628     Info.CCEDiag(E, diag::note_constexpr_new);
8629 
8630   // We cannot speculatively evaluate a delete expression.
8631   if (Info.SpeculativeEvaluationDepth)
8632     return false;
8633 
8634   FunctionDecl *OperatorNew = E->getOperatorNew();
8635 
8636   bool IsNothrow = false;
8637   bool IsPlacement = false;
8638   if (OperatorNew->isReservedGlobalPlacementOperator() &&
8639       Info.CurrentCall->isStdFunction() && !E->isArray()) {
8640     // FIXME Support array placement new.
8641     assert(E->getNumPlacementArgs() == 1);
8642     if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
8643       return false;
8644     if (Result.Designator.Invalid)
8645       return false;
8646     IsPlacement = true;
8647   } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
8648     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
8649         << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
8650     return false;
8651   } else if (E->getNumPlacementArgs()) {
8652     // The only new-placement list we support is of the form (std::nothrow).
8653     //
8654     // FIXME: There is no restriction on this, but it's not clear that any
8655     // other form makes any sense. We get here for cases such as:
8656     //
8657     //   new (std::align_val_t{N}) X(int)
8658     //
8659     // (which should presumably be valid only if N is a multiple of
8660     // alignof(int), and in any case can't be deallocated unless N is
8661     // alignof(X) and X has new-extended alignment).
8662     if (E->getNumPlacementArgs() != 1 ||
8663         !E->getPlacementArg(0)->getType()->isNothrowT())
8664       return Error(E, diag::note_constexpr_new_placement);
8665 
8666     LValue Nothrow;
8667     if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
8668       return false;
8669     IsNothrow = true;
8670   }
8671 
8672   const Expr *Init = E->getInitializer();
8673   const InitListExpr *ResizedArrayILE = nullptr;
8674 
8675   QualType AllocType = E->getAllocatedType();
8676   if (Optional<const Expr*> ArraySize = E->getArraySize()) {
8677     const Expr *Stripped = *ArraySize;
8678     for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
8679          Stripped = ICE->getSubExpr())
8680       if (ICE->getCastKind() != CK_NoOp &&
8681           ICE->getCastKind() != CK_IntegralCast)
8682         break;
8683 
8684     llvm::APSInt ArrayBound;
8685     if (!EvaluateInteger(Stripped, ArrayBound, Info))
8686       return false;
8687 
8688     // C++ [expr.new]p9:
8689     //   The expression is erroneous if:
8690     //   -- [...] its value before converting to size_t [or] applying the
8691     //      second standard conversion sequence is less than zero
8692     if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
8693       if (IsNothrow)
8694         return ZeroInitialization(E);
8695 
8696       Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
8697           << ArrayBound << (*ArraySize)->getSourceRange();
8698       return false;
8699     }
8700 
8701     //   -- its value is such that the size of the allocated object would
8702     //      exceed the implementation-defined limit
8703     if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
8704                                                 ArrayBound) >
8705         ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
8706       if (IsNothrow)
8707         return ZeroInitialization(E);
8708 
8709       Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
8710         << ArrayBound << (*ArraySize)->getSourceRange();
8711       return false;
8712     }
8713 
8714     //   -- the new-initializer is a braced-init-list and the number of
8715     //      array elements for which initializers are provided [...]
8716     //      exceeds the number of elements to initialize
8717     if (Init) {
8718       auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
8719       assert(CAT && "unexpected type for array initializer");
8720 
8721       unsigned Bits =
8722           std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
8723       llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits);
8724       llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits);
8725       if (InitBound.ugt(AllocBound)) {
8726         if (IsNothrow)
8727           return ZeroInitialization(E);
8728 
8729         Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
8730             << AllocBound.toString(10, /*Signed=*/false)
8731             << InitBound.toString(10, /*Signed=*/false)
8732             << (*ArraySize)->getSourceRange();
8733         return false;
8734       }
8735 
8736       // If the sizes differ, we must have an initializer list, and we need
8737       // special handling for this case when we initialize.
8738       if (InitBound != AllocBound)
8739         ResizedArrayILE = cast<InitListExpr>(Init);
8740     }
8741 
8742     AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
8743                                               ArrayType::Normal, 0);
8744   } else {
8745     assert(!AllocType->isArrayType() &&
8746            "array allocation with non-array new");
8747   }
8748 
8749   APValue *Val;
8750   if (IsPlacement) {
8751     AccessKinds AK = AK_Construct;
8752     struct FindObjectHandler {
8753       EvalInfo &Info;
8754       const Expr *E;
8755       QualType AllocType;
8756       const AccessKinds AccessKind;
8757       APValue *Value;
8758 
8759       typedef bool result_type;
8760       bool failed() { return false; }
8761       bool found(APValue &Subobj, QualType SubobjType) {
8762         // FIXME: Reject the cases where [basic.life]p8 would not permit the
8763         // old name of the object to be used to name the new object.
8764         if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
8765           Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
8766             SubobjType << AllocType;
8767           return false;
8768         }
8769         Value = &Subobj;
8770         return true;
8771       }
8772       bool found(APSInt &Value, QualType SubobjType) {
8773         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
8774         return false;
8775       }
8776       bool found(APFloat &Value, QualType SubobjType) {
8777         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
8778         return false;
8779       }
8780     } Handler = {Info, E, AllocType, AK, nullptr};
8781 
8782     CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
8783     if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
8784       return false;
8785 
8786     Val = Handler.Value;
8787 
8788     // [basic.life]p1:
8789     //   The lifetime of an object o of type T ends when [...] the storage
8790     //   which the object occupies is [...] reused by an object that is not
8791     //   nested within o (6.6.2).
8792     *Val = APValue();
8793   } else {
8794     // Perform the allocation and obtain a pointer to the resulting object.
8795     Val = Info.createHeapAlloc(E, AllocType, Result);
8796     if (!Val)
8797       return false;
8798   }
8799 
8800   if (ResizedArrayILE) {
8801     if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
8802                                   AllocType))
8803       return false;
8804   } else if (Init) {
8805     if (!EvaluateInPlace(*Val, Info, Result, Init))
8806       return false;
8807   } else {
8808     *Val = getDefaultInitValue(AllocType);
8809   }
8810 
8811   // Array new returns a pointer to the first element, not a pointer to the
8812   // array.
8813   if (auto *AT = AllocType->getAsArrayTypeUnsafe())
8814     Result.addArray(Info, E, cast<ConstantArrayType>(AT));
8815 
8816   return true;
8817 }
8818 //===----------------------------------------------------------------------===//
8819 // Member Pointer Evaluation
8820 //===----------------------------------------------------------------------===//
8821 
8822 namespace {
8823 class MemberPointerExprEvaluator
8824   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
8825   MemberPtr &Result;
8826 
8827   bool Success(const ValueDecl *D) {
8828     Result = MemberPtr(D);
8829     return true;
8830   }
8831 public:
8832 
8833   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
8834     : ExprEvaluatorBaseTy(Info), Result(Result) {}
8835 
8836   bool Success(const APValue &V, const Expr *E) {
8837     Result.setFrom(V);
8838     return true;
8839   }
8840   bool ZeroInitialization(const Expr *E) {
8841     return Success((const ValueDecl*)nullptr);
8842   }
8843 
8844   bool VisitCastExpr(const CastExpr *E);
8845   bool VisitUnaryAddrOf(const UnaryOperator *E);
8846 };
8847 } // end anonymous namespace
8848 
8849 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
8850                                   EvalInfo &Info) {
8851   assert(E->isRValue() && E->getType()->isMemberPointerType());
8852   return MemberPointerExprEvaluator(Info, Result).Visit(E);
8853 }
8854 
8855 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8856   switch (E->getCastKind()) {
8857   default:
8858     return ExprEvaluatorBaseTy::VisitCastExpr(E);
8859 
8860   case CK_NullToMemberPointer:
8861     VisitIgnoredValue(E->getSubExpr());
8862     return ZeroInitialization(E);
8863 
8864   case CK_BaseToDerivedMemberPointer: {
8865     if (!Visit(E->getSubExpr()))
8866       return false;
8867     if (E->path_empty())
8868       return true;
8869     // Base-to-derived member pointer casts store the path in derived-to-base
8870     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
8871     // the wrong end of the derived->base arc, so stagger the path by one class.
8872     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
8873     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
8874          PathI != PathE; ++PathI) {
8875       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
8876       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
8877       if (!Result.castToDerived(Derived))
8878         return Error(E);
8879     }
8880     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
8881     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
8882       return Error(E);
8883     return true;
8884   }
8885 
8886   case CK_DerivedToBaseMemberPointer:
8887     if (!Visit(E->getSubExpr()))
8888       return false;
8889     for (CastExpr::path_const_iterator PathI = E->path_begin(),
8890          PathE = E->path_end(); PathI != PathE; ++PathI) {
8891       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
8892       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
8893       if (!Result.castToBase(Base))
8894         return Error(E);
8895     }
8896     return true;
8897   }
8898 }
8899 
8900 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8901   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
8902   // member can be formed.
8903   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
8904 }
8905 
8906 //===----------------------------------------------------------------------===//
8907 // Record Evaluation
8908 //===----------------------------------------------------------------------===//
8909 
8910 namespace {
8911   class RecordExprEvaluator
8912   : public ExprEvaluatorBase<RecordExprEvaluator> {
8913     const LValue &This;
8914     APValue &Result;
8915   public:
8916 
8917     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
8918       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
8919 
8920     bool Success(const APValue &V, const Expr *E) {
8921       Result = V;
8922       return true;
8923     }
8924     bool ZeroInitialization(const Expr *E) {
8925       return ZeroInitialization(E, E->getType());
8926     }
8927     bool ZeroInitialization(const Expr *E, QualType T);
8928 
8929     bool VisitCallExpr(const CallExpr *E) {
8930       return handleCallExpr(E, Result, &This);
8931     }
8932     bool VisitCastExpr(const CastExpr *E);
8933     bool VisitInitListExpr(const InitListExpr *E);
8934     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
8935       return VisitCXXConstructExpr(E, E->getType());
8936     }
8937     bool VisitLambdaExpr(const LambdaExpr *E);
8938     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
8939     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
8940     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
8941     bool VisitBinCmp(const BinaryOperator *E);
8942   };
8943 }
8944 
8945 /// Perform zero-initialization on an object of non-union class type.
8946 /// C++11 [dcl.init]p5:
8947 ///  To zero-initialize an object or reference of type T means:
8948 ///    [...]
8949 ///    -- if T is a (possibly cv-qualified) non-union class type,
8950 ///       each non-static data member and each base-class subobject is
8951 ///       zero-initialized
8952 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
8953                                           const RecordDecl *RD,
8954                                           const LValue &This, APValue &Result) {
8955   assert(!RD->isUnion() && "Expected non-union class type");
8956   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
8957   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
8958                    std::distance(RD->field_begin(), RD->field_end()));
8959 
8960   if (RD->isInvalidDecl()) return false;
8961   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
8962 
8963   if (CD) {
8964     unsigned Index = 0;
8965     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
8966            End = CD->bases_end(); I != End; ++I, ++Index) {
8967       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
8968       LValue Subobject = This;
8969       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
8970         return false;
8971       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
8972                                          Result.getStructBase(Index)))
8973         return false;
8974     }
8975   }
8976 
8977   for (const auto *I : RD->fields()) {
8978     // -- if T is a reference type, no initialization is performed.
8979     if (I->getType()->isReferenceType())
8980       continue;
8981 
8982     LValue Subobject = This;
8983     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
8984       return false;
8985 
8986     ImplicitValueInitExpr VIE(I->getType());
8987     if (!EvaluateInPlace(
8988           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
8989       return false;
8990   }
8991 
8992   return true;
8993 }
8994 
8995 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
8996   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
8997   if (RD->isInvalidDecl()) return false;
8998   if (RD->isUnion()) {
8999     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
9000     // object's first non-static named data member is zero-initialized
9001     RecordDecl::field_iterator I = RD->field_begin();
9002     if (I == RD->field_end()) {
9003       Result = APValue((const FieldDecl*)nullptr);
9004       return true;
9005     }
9006 
9007     LValue Subobject = This;
9008     if (!HandleLValueMember(Info, E, Subobject, *I))
9009       return false;
9010     Result = APValue(*I);
9011     ImplicitValueInitExpr VIE(I->getType());
9012     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
9013   }
9014 
9015   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
9016     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
9017     return false;
9018   }
9019 
9020   return HandleClassZeroInitialization(Info, E, RD, This, Result);
9021 }
9022 
9023 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
9024   switch (E->getCastKind()) {
9025   default:
9026     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9027 
9028   case CK_ConstructorConversion:
9029     return Visit(E->getSubExpr());
9030 
9031   case CK_DerivedToBase:
9032   case CK_UncheckedDerivedToBase: {
9033     APValue DerivedObject;
9034     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
9035       return false;
9036     if (!DerivedObject.isStruct())
9037       return Error(E->getSubExpr());
9038 
9039     // Derived-to-base rvalue conversion: just slice off the derived part.
9040     APValue *Value = &DerivedObject;
9041     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
9042     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9043          PathE = E->path_end(); PathI != PathE; ++PathI) {
9044       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
9045       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9046       Value = &Value->getStructBase(getBaseIndex(RD, Base));
9047       RD = Base;
9048     }
9049     Result = *Value;
9050     return true;
9051   }
9052   }
9053 }
9054 
9055 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9056   if (E->isTransparent())
9057     return Visit(E->getInit(0));
9058 
9059   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
9060   if (RD->isInvalidDecl()) return false;
9061   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9062   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
9063 
9064   EvalInfo::EvaluatingConstructorRAII EvalObj(
9065       Info,
9066       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
9067       CXXRD && CXXRD->getNumBases());
9068 
9069   if (RD->isUnion()) {
9070     const FieldDecl *Field = E->getInitializedFieldInUnion();
9071     Result = APValue(Field);
9072     if (!Field)
9073       return true;
9074 
9075     // If the initializer list for a union does not contain any elements, the
9076     // first element of the union is value-initialized.
9077     // FIXME: The element should be initialized from an initializer list.
9078     //        Is this difference ever observable for initializer lists which
9079     //        we don't build?
9080     ImplicitValueInitExpr VIE(Field->getType());
9081     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
9082 
9083     LValue Subobject = This;
9084     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
9085       return false;
9086 
9087     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9088     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9089                                   isa<CXXDefaultInitExpr>(InitExpr));
9090 
9091     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
9092   }
9093 
9094   if (!Result.hasValue())
9095     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
9096                      std::distance(RD->field_begin(), RD->field_end()));
9097   unsigned ElementNo = 0;
9098   bool Success = true;
9099 
9100   // Initialize base classes.
9101   if (CXXRD && CXXRD->getNumBases()) {
9102     for (const auto &Base : CXXRD->bases()) {
9103       assert(ElementNo < E->getNumInits() && "missing init for base class");
9104       const Expr *Init = E->getInit(ElementNo);
9105 
9106       LValue Subobject = This;
9107       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
9108         return false;
9109 
9110       APValue &FieldVal = Result.getStructBase(ElementNo);
9111       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
9112         if (!Info.noteFailure())
9113           return false;
9114         Success = false;
9115       }
9116       ++ElementNo;
9117     }
9118 
9119     EvalObj.finishedConstructingBases();
9120   }
9121 
9122   // Initialize members.
9123   for (const auto *Field : RD->fields()) {
9124     // Anonymous bit-fields are not considered members of the class for
9125     // purposes of aggregate initialization.
9126     if (Field->isUnnamedBitfield())
9127       continue;
9128 
9129     LValue Subobject = This;
9130 
9131     bool HaveInit = ElementNo < E->getNumInits();
9132 
9133     // FIXME: Diagnostics here should point to the end of the initializer
9134     // list, not the start.
9135     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
9136                             Subobject, Field, &Layout))
9137       return false;
9138 
9139     // Perform an implicit value-initialization for members beyond the end of
9140     // the initializer list.
9141     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
9142     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
9143 
9144     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9145     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9146                                   isa<CXXDefaultInitExpr>(Init));
9147 
9148     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9149     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
9150         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
9151                                                        FieldVal, Field))) {
9152       if (!Info.noteFailure())
9153         return false;
9154       Success = false;
9155     }
9156   }
9157 
9158   return Success;
9159 }
9160 
9161 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
9162                                                 QualType T) {
9163   // Note that E's type is not necessarily the type of our class here; we might
9164   // be initializing an array element instead.
9165   const CXXConstructorDecl *FD = E->getConstructor();
9166   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
9167 
9168   bool ZeroInit = E->requiresZeroInitialization();
9169   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
9170     // If we've already performed zero-initialization, we're already done.
9171     if (Result.hasValue())
9172       return true;
9173 
9174     if (ZeroInit)
9175       return ZeroInitialization(E, T);
9176 
9177     Result = getDefaultInitValue(T);
9178     return true;
9179   }
9180 
9181   const FunctionDecl *Definition = nullptr;
9182   auto Body = FD->getBody(Definition);
9183 
9184   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9185     return false;
9186 
9187   // Avoid materializing a temporary for an elidable copy/move constructor.
9188   if (E->isElidable() && !ZeroInit)
9189     if (const MaterializeTemporaryExpr *ME
9190           = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
9191       return Visit(ME->getSubExpr());
9192 
9193   if (ZeroInit && !ZeroInitialization(E, T))
9194     return false;
9195 
9196   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
9197   return HandleConstructorCall(E, This, Args,
9198                                cast<CXXConstructorDecl>(Definition), Info,
9199                                Result);
9200 }
9201 
9202 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
9203     const CXXInheritedCtorInitExpr *E) {
9204   if (!Info.CurrentCall) {
9205     assert(Info.checkingPotentialConstantExpression());
9206     return false;
9207   }
9208 
9209   const CXXConstructorDecl *FD = E->getConstructor();
9210   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
9211     return false;
9212 
9213   const FunctionDecl *Definition = nullptr;
9214   auto Body = FD->getBody(Definition);
9215 
9216   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9217     return false;
9218 
9219   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
9220                                cast<CXXConstructorDecl>(Definition), Info,
9221                                Result);
9222 }
9223 
9224 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
9225     const CXXStdInitializerListExpr *E) {
9226   const ConstantArrayType *ArrayType =
9227       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
9228 
9229   LValue Array;
9230   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
9231     return false;
9232 
9233   // Get a pointer to the first element of the array.
9234   Array.addArray(Info, E, ArrayType);
9235 
9236   // FIXME: Perform the checks on the field types in SemaInit.
9237   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
9238   RecordDecl::field_iterator Field = Record->field_begin();
9239   if (Field == Record->field_end())
9240     return Error(E);
9241 
9242   // Start pointer.
9243   if (!Field->getType()->isPointerType() ||
9244       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
9245                             ArrayType->getElementType()))
9246     return Error(E);
9247 
9248   // FIXME: What if the initializer_list type has base classes, etc?
9249   Result = APValue(APValue::UninitStruct(), 0, 2);
9250   Array.moveInto(Result.getStructField(0));
9251 
9252   if (++Field == Record->field_end())
9253     return Error(E);
9254 
9255   if (Field->getType()->isPointerType() &&
9256       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
9257                            ArrayType->getElementType())) {
9258     // End pointer.
9259     if (!HandleLValueArrayAdjustment(Info, E, Array,
9260                                      ArrayType->getElementType(),
9261                                      ArrayType->getSize().getZExtValue()))
9262       return false;
9263     Array.moveInto(Result.getStructField(1));
9264   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
9265     // Length.
9266     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
9267   else
9268     return Error(E);
9269 
9270   if (++Field != Record->field_end())
9271     return Error(E);
9272 
9273   return true;
9274 }
9275 
9276 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
9277   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
9278   if (ClosureClass->isInvalidDecl())
9279     return false;
9280 
9281   const size_t NumFields =
9282       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
9283 
9284   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
9285                                             E->capture_init_end()) &&
9286          "The number of lambda capture initializers should equal the number of "
9287          "fields within the closure type");
9288 
9289   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
9290   // Iterate through all the lambda's closure object's fields and initialize
9291   // them.
9292   auto *CaptureInitIt = E->capture_init_begin();
9293   const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
9294   bool Success = true;
9295   for (const auto *Field : ClosureClass->fields()) {
9296     assert(CaptureInitIt != E->capture_init_end());
9297     // Get the initializer for this field
9298     Expr *const CurFieldInit = *CaptureInitIt++;
9299 
9300     // If there is no initializer, either this is a VLA or an error has
9301     // occurred.
9302     if (!CurFieldInit)
9303       return Error(E);
9304 
9305     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9306     if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
9307       if (!Info.keepEvaluatingAfterFailure())
9308         return false;
9309       Success = false;
9310     }
9311     ++CaptureIt;
9312   }
9313   return Success;
9314 }
9315 
9316 static bool EvaluateRecord(const Expr *E, const LValue &This,
9317                            APValue &Result, EvalInfo &Info) {
9318   assert(E->isRValue() && E->getType()->isRecordType() &&
9319          "can't evaluate expression as a record rvalue");
9320   return RecordExprEvaluator(Info, This, Result).Visit(E);
9321 }
9322 
9323 //===----------------------------------------------------------------------===//
9324 // Temporary Evaluation
9325 //
9326 // Temporaries are represented in the AST as rvalues, but generally behave like
9327 // lvalues. The full-object of which the temporary is a subobject is implicitly
9328 // materialized so that a reference can bind to it.
9329 //===----------------------------------------------------------------------===//
9330 namespace {
9331 class TemporaryExprEvaluator
9332   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
9333 public:
9334   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
9335     LValueExprEvaluatorBaseTy(Info, Result, false) {}
9336 
9337   /// Visit an expression which constructs the value of this temporary.
9338   bool VisitConstructExpr(const Expr *E) {
9339     APValue &Value =
9340         Info.CurrentCall->createTemporary(E, E->getType(), false, Result);
9341     return EvaluateInPlace(Value, Info, Result, E);
9342   }
9343 
9344   bool VisitCastExpr(const CastExpr *E) {
9345     switch (E->getCastKind()) {
9346     default:
9347       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
9348 
9349     case CK_ConstructorConversion:
9350       return VisitConstructExpr(E->getSubExpr());
9351     }
9352   }
9353   bool VisitInitListExpr(const InitListExpr *E) {
9354     return VisitConstructExpr(E);
9355   }
9356   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9357     return VisitConstructExpr(E);
9358   }
9359   bool VisitCallExpr(const CallExpr *E) {
9360     return VisitConstructExpr(E);
9361   }
9362   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
9363     return VisitConstructExpr(E);
9364   }
9365   bool VisitLambdaExpr(const LambdaExpr *E) {
9366     return VisitConstructExpr(E);
9367   }
9368 };
9369 } // end anonymous namespace
9370 
9371 /// Evaluate an expression of record type as a temporary.
9372 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
9373   assert(E->isRValue() && E->getType()->isRecordType());
9374   return TemporaryExprEvaluator(Info, Result).Visit(E);
9375 }
9376 
9377 //===----------------------------------------------------------------------===//
9378 // Vector Evaluation
9379 //===----------------------------------------------------------------------===//
9380 
9381 namespace {
9382   class VectorExprEvaluator
9383   : public ExprEvaluatorBase<VectorExprEvaluator> {
9384     APValue &Result;
9385   public:
9386 
9387     VectorExprEvaluator(EvalInfo &info, APValue &Result)
9388       : ExprEvaluatorBaseTy(info), Result(Result) {}
9389 
9390     bool Success(ArrayRef<APValue> V, const Expr *E) {
9391       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
9392       // FIXME: remove this APValue copy.
9393       Result = APValue(V.data(), V.size());
9394       return true;
9395     }
9396     bool Success(const APValue &V, const Expr *E) {
9397       assert(V.isVector());
9398       Result = V;
9399       return true;
9400     }
9401     bool ZeroInitialization(const Expr *E);
9402 
9403     bool VisitUnaryReal(const UnaryOperator *E)
9404       { return Visit(E->getSubExpr()); }
9405     bool VisitCastExpr(const CastExpr* E);
9406     bool VisitInitListExpr(const InitListExpr *E);
9407     bool VisitUnaryImag(const UnaryOperator *E);
9408     // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
9409     //                 binary comparisons, binary and/or/xor,
9410     //                 conditional operator (for GNU conditional select),
9411     //                 shufflevector, ExtVectorElementExpr
9412   };
9413 } // end anonymous namespace
9414 
9415 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
9416   assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
9417   return VectorExprEvaluator(Info, Result).Visit(E);
9418 }
9419 
9420 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
9421   const VectorType *VTy = E->getType()->castAs<VectorType>();
9422   unsigned NElts = VTy->getNumElements();
9423 
9424   const Expr *SE = E->getSubExpr();
9425   QualType SETy = SE->getType();
9426 
9427   switch (E->getCastKind()) {
9428   case CK_VectorSplat: {
9429     APValue Val = APValue();
9430     if (SETy->isIntegerType()) {
9431       APSInt IntResult;
9432       if (!EvaluateInteger(SE, IntResult, Info))
9433         return false;
9434       Val = APValue(std::move(IntResult));
9435     } else if (SETy->isRealFloatingType()) {
9436       APFloat FloatResult(0.0);
9437       if (!EvaluateFloat(SE, FloatResult, Info))
9438         return false;
9439       Val = APValue(std::move(FloatResult));
9440     } else {
9441       return Error(E);
9442     }
9443 
9444     // Splat and create vector APValue.
9445     SmallVector<APValue, 4> Elts(NElts, Val);
9446     return Success(Elts, E);
9447   }
9448   case CK_BitCast: {
9449     // Evaluate the operand into an APInt we can extract from.
9450     llvm::APInt SValInt;
9451     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
9452       return false;
9453     // Extract the elements
9454     QualType EltTy = VTy->getElementType();
9455     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
9456     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
9457     SmallVector<APValue, 4> Elts;
9458     if (EltTy->isRealFloatingType()) {
9459       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
9460       unsigned FloatEltSize = EltSize;
9461       if (&Sem == &APFloat::x87DoubleExtended())
9462         FloatEltSize = 80;
9463       for (unsigned i = 0; i < NElts; i++) {
9464         llvm::APInt Elt;
9465         if (BigEndian)
9466           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
9467         else
9468           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
9469         Elts.push_back(APValue(APFloat(Sem, Elt)));
9470       }
9471     } else if (EltTy->isIntegerType()) {
9472       for (unsigned i = 0; i < NElts; i++) {
9473         llvm::APInt Elt;
9474         if (BigEndian)
9475           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
9476         else
9477           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
9478         Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
9479       }
9480     } else {
9481       return Error(E);
9482     }
9483     return Success(Elts, E);
9484   }
9485   default:
9486     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9487   }
9488 }
9489 
9490 bool
9491 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9492   const VectorType *VT = E->getType()->castAs<VectorType>();
9493   unsigned NumInits = E->getNumInits();
9494   unsigned NumElements = VT->getNumElements();
9495 
9496   QualType EltTy = VT->getElementType();
9497   SmallVector<APValue, 4> Elements;
9498 
9499   // The number of initializers can be less than the number of
9500   // vector elements. For OpenCL, this can be due to nested vector
9501   // initialization. For GCC compatibility, missing trailing elements
9502   // should be initialized with zeroes.
9503   unsigned CountInits = 0, CountElts = 0;
9504   while (CountElts < NumElements) {
9505     // Handle nested vector initialization.
9506     if (CountInits < NumInits
9507         && E->getInit(CountInits)->getType()->isVectorType()) {
9508       APValue v;
9509       if (!EvaluateVector(E->getInit(CountInits), v, Info))
9510         return Error(E);
9511       unsigned vlen = v.getVectorLength();
9512       for (unsigned j = 0; j < vlen; j++)
9513         Elements.push_back(v.getVectorElt(j));
9514       CountElts += vlen;
9515     } else if (EltTy->isIntegerType()) {
9516       llvm::APSInt sInt(32);
9517       if (CountInits < NumInits) {
9518         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
9519           return false;
9520       } else // trailing integer zero.
9521         sInt = Info.Ctx.MakeIntValue(0, EltTy);
9522       Elements.push_back(APValue(sInt));
9523       CountElts++;
9524     } else {
9525       llvm::APFloat f(0.0);
9526       if (CountInits < NumInits) {
9527         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
9528           return false;
9529       } else // trailing float zero.
9530         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
9531       Elements.push_back(APValue(f));
9532       CountElts++;
9533     }
9534     CountInits++;
9535   }
9536   return Success(Elements, E);
9537 }
9538 
9539 bool
9540 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
9541   const auto *VT = E->getType()->castAs<VectorType>();
9542   QualType EltTy = VT->getElementType();
9543   APValue ZeroElement;
9544   if (EltTy->isIntegerType())
9545     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
9546   else
9547     ZeroElement =
9548         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
9549 
9550   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
9551   return Success(Elements, E);
9552 }
9553 
9554 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9555   VisitIgnoredValue(E->getSubExpr());
9556   return ZeroInitialization(E);
9557 }
9558 
9559 //===----------------------------------------------------------------------===//
9560 // Array Evaluation
9561 //===----------------------------------------------------------------------===//
9562 
9563 namespace {
9564   class ArrayExprEvaluator
9565   : public ExprEvaluatorBase<ArrayExprEvaluator> {
9566     const LValue &This;
9567     APValue &Result;
9568   public:
9569 
9570     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
9571       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
9572 
9573     bool Success(const APValue &V, const Expr *E) {
9574       assert(V.isArray() && "expected array");
9575       Result = V;
9576       return true;
9577     }
9578 
9579     bool ZeroInitialization(const Expr *E) {
9580       const ConstantArrayType *CAT =
9581           Info.Ctx.getAsConstantArrayType(E->getType());
9582       if (!CAT)
9583         return Error(E);
9584 
9585       Result = APValue(APValue::UninitArray(), 0,
9586                        CAT->getSize().getZExtValue());
9587       if (!Result.hasArrayFiller()) return true;
9588 
9589       // Zero-initialize all elements.
9590       LValue Subobject = This;
9591       Subobject.addArray(Info, E, CAT);
9592       ImplicitValueInitExpr VIE(CAT->getElementType());
9593       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
9594     }
9595 
9596     bool VisitCallExpr(const CallExpr *E) {
9597       return handleCallExpr(E, Result, &This);
9598     }
9599     bool VisitInitListExpr(const InitListExpr *E,
9600                            QualType AllocType = QualType());
9601     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
9602     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
9603     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
9604                                const LValue &Subobject,
9605                                APValue *Value, QualType Type);
9606     bool VisitStringLiteral(const StringLiteral *E,
9607                             QualType AllocType = QualType()) {
9608       expandStringLiteral(Info, E, Result, AllocType);
9609       return true;
9610     }
9611   };
9612 } // end anonymous namespace
9613 
9614 static bool EvaluateArray(const Expr *E, const LValue &This,
9615                           APValue &Result, EvalInfo &Info) {
9616   assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
9617   return ArrayExprEvaluator(Info, This, Result).Visit(E);
9618 }
9619 
9620 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9621                                      APValue &Result, const InitListExpr *ILE,
9622                                      QualType AllocType) {
9623   assert(ILE->isRValue() && ILE->getType()->isArrayType() &&
9624          "not an array rvalue");
9625   return ArrayExprEvaluator(Info, This, Result)
9626       .VisitInitListExpr(ILE, AllocType);
9627 }
9628 
9629 // Return true iff the given array filler may depend on the element index.
9630 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
9631   // For now, just whitelist non-class value-initialization and initialization
9632   // lists comprised of them.
9633   if (isa<ImplicitValueInitExpr>(FillerExpr))
9634     return false;
9635   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
9636     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
9637       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
9638         return true;
9639     }
9640     return false;
9641   }
9642   return true;
9643 }
9644 
9645 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
9646                                            QualType AllocType) {
9647   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
9648       AllocType.isNull() ? E->getType() : AllocType);
9649   if (!CAT)
9650     return Error(E);
9651 
9652   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
9653   // an appropriately-typed string literal enclosed in braces.
9654   if (E->isStringLiteralInit()) {
9655     auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens());
9656     // FIXME: Support ObjCEncodeExpr here once we support it in
9657     // ArrayExprEvaluator generally.
9658     if (!SL)
9659       return Error(E);
9660     return VisitStringLiteral(SL, AllocType);
9661   }
9662 
9663   bool Success = true;
9664 
9665   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
9666          "zero-initialized array shouldn't have any initialized elts");
9667   APValue Filler;
9668   if (Result.isArray() && Result.hasArrayFiller())
9669     Filler = Result.getArrayFiller();
9670 
9671   unsigned NumEltsToInit = E->getNumInits();
9672   unsigned NumElts = CAT->getSize().getZExtValue();
9673   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
9674 
9675   // If the initializer might depend on the array index, run it for each
9676   // array element.
9677   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
9678     NumEltsToInit = NumElts;
9679 
9680   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
9681                           << NumEltsToInit << ".\n");
9682 
9683   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
9684 
9685   // If the array was previously zero-initialized, preserve the
9686   // zero-initialized values.
9687   if (Filler.hasValue()) {
9688     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
9689       Result.getArrayInitializedElt(I) = Filler;
9690     if (Result.hasArrayFiller())
9691       Result.getArrayFiller() = Filler;
9692   }
9693 
9694   LValue Subobject = This;
9695   Subobject.addArray(Info, E, CAT);
9696   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
9697     const Expr *Init =
9698         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
9699     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
9700                          Info, Subobject, Init) ||
9701         !HandleLValueArrayAdjustment(Info, Init, Subobject,
9702                                      CAT->getElementType(), 1)) {
9703       if (!Info.noteFailure())
9704         return false;
9705       Success = false;
9706     }
9707   }
9708 
9709   if (!Result.hasArrayFiller())
9710     return Success;
9711 
9712   // If we get here, we have a trivial filler, which we can just evaluate
9713   // once and splat over the rest of the array elements.
9714   assert(FillerExpr && "no array filler for incomplete init list");
9715   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
9716                          FillerExpr) && Success;
9717 }
9718 
9719 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
9720   LValue CommonLV;
9721   if (E->getCommonExpr() &&
9722       !Evaluate(Info.CurrentCall->createTemporary(
9723                     E->getCommonExpr(),
9724                     getStorageType(Info.Ctx, E->getCommonExpr()), false,
9725                     CommonLV),
9726                 Info, E->getCommonExpr()->getSourceExpr()))
9727     return false;
9728 
9729   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
9730 
9731   uint64_t Elements = CAT->getSize().getZExtValue();
9732   Result = APValue(APValue::UninitArray(), Elements, Elements);
9733 
9734   LValue Subobject = This;
9735   Subobject.addArray(Info, E, CAT);
9736 
9737   bool Success = true;
9738   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
9739     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
9740                          Info, Subobject, E->getSubExpr()) ||
9741         !HandleLValueArrayAdjustment(Info, E, Subobject,
9742                                      CAT->getElementType(), 1)) {
9743       if (!Info.noteFailure())
9744         return false;
9745       Success = false;
9746     }
9747   }
9748 
9749   return Success;
9750 }
9751 
9752 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
9753   return VisitCXXConstructExpr(E, This, &Result, E->getType());
9754 }
9755 
9756 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
9757                                                const LValue &Subobject,
9758                                                APValue *Value,
9759                                                QualType Type) {
9760   bool HadZeroInit = Value->hasValue();
9761 
9762   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
9763     unsigned N = CAT->getSize().getZExtValue();
9764 
9765     // Preserve the array filler if we had prior zero-initialization.
9766     APValue Filler =
9767       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
9768                                              : APValue();
9769 
9770     *Value = APValue(APValue::UninitArray(), N, N);
9771 
9772     if (HadZeroInit)
9773       for (unsigned I = 0; I != N; ++I)
9774         Value->getArrayInitializedElt(I) = Filler;
9775 
9776     // Initialize the elements.
9777     LValue ArrayElt = Subobject;
9778     ArrayElt.addArray(Info, E, CAT);
9779     for (unsigned I = 0; I != N; ++I)
9780       if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
9781                                  CAT->getElementType()) ||
9782           !HandleLValueArrayAdjustment(Info, E, ArrayElt,
9783                                        CAT->getElementType(), 1))
9784         return false;
9785 
9786     return true;
9787   }
9788 
9789   if (!Type->isRecordType())
9790     return Error(E);
9791 
9792   return RecordExprEvaluator(Info, Subobject, *Value)
9793              .VisitCXXConstructExpr(E, Type);
9794 }
9795 
9796 //===----------------------------------------------------------------------===//
9797 // Integer Evaluation
9798 //
9799 // As a GNU extension, we support casting pointers to sufficiently-wide integer
9800 // types and back in constant folding. Integer values are thus represented
9801 // either as an integer-valued APValue, or as an lvalue-valued APValue.
9802 //===----------------------------------------------------------------------===//
9803 
9804 namespace {
9805 class IntExprEvaluator
9806         : public ExprEvaluatorBase<IntExprEvaluator> {
9807   APValue &Result;
9808 public:
9809   IntExprEvaluator(EvalInfo &info, APValue &result)
9810       : ExprEvaluatorBaseTy(info), Result(result) {}
9811 
9812   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
9813     assert(E->getType()->isIntegralOrEnumerationType() &&
9814            "Invalid evaluation result.");
9815     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
9816            "Invalid evaluation result.");
9817     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
9818            "Invalid evaluation result.");
9819     Result = APValue(SI);
9820     return true;
9821   }
9822   bool Success(const llvm::APSInt &SI, const Expr *E) {
9823     return Success(SI, E, Result);
9824   }
9825 
9826   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
9827     assert(E->getType()->isIntegralOrEnumerationType() &&
9828            "Invalid evaluation result.");
9829     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
9830            "Invalid evaluation result.");
9831     Result = APValue(APSInt(I));
9832     Result.getInt().setIsUnsigned(
9833                             E->getType()->isUnsignedIntegerOrEnumerationType());
9834     return true;
9835   }
9836   bool Success(const llvm::APInt &I, const Expr *E) {
9837     return Success(I, E, Result);
9838   }
9839 
9840   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
9841     assert(E->getType()->isIntegralOrEnumerationType() &&
9842            "Invalid evaluation result.");
9843     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
9844     return true;
9845   }
9846   bool Success(uint64_t Value, const Expr *E) {
9847     return Success(Value, E, Result);
9848   }
9849 
9850   bool Success(CharUnits Size, const Expr *E) {
9851     return Success(Size.getQuantity(), E);
9852   }
9853 
9854   bool Success(const APValue &V, const Expr *E) {
9855     if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
9856       Result = V;
9857       return true;
9858     }
9859     return Success(V.getInt(), E);
9860   }
9861 
9862   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
9863 
9864   //===--------------------------------------------------------------------===//
9865   //                            Visitor Methods
9866   //===--------------------------------------------------------------------===//
9867 
9868   bool VisitConstantExpr(const ConstantExpr *E);
9869 
9870   bool VisitIntegerLiteral(const IntegerLiteral *E) {
9871     return Success(E->getValue(), E);
9872   }
9873   bool VisitCharacterLiteral(const CharacterLiteral *E) {
9874     return Success(E->getValue(), E);
9875   }
9876 
9877   bool CheckReferencedDecl(const Expr *E, const Decl *D);
9878   bool VisitDeclRefExpr(const DeclRefExpr *E) {
9879     if (CheckReferencedDecl(E, E->getDecl()))
9880       return true;
9881 
9882     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
9883   }
9884   bool VisitMemberExpr(const MemberExpr *E) {
9885     if (CheckReferencedDecl(E, E->getMemberDecl())) {
9886       VisitIgnoredBaseExpression(E->getBase());
9887       return true;
9888     }
9889 
9890     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
9891   }
9892 
9893   bool VisitCallExpr(const CallExpr *E);
9894   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
9895   bool VisitBinaryOperator(const BinaryOperator *E);
9896   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
9897   bool VisitUnaryOperator(const UnaryOperator *E);
9898 
9899   bool VisitCastExpr(const CastExpr* E);
9900   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
9901 
9902   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
9903     return Success(E->getValue(), E);
9904   }
9905 
9906   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
9907     return Success(E->getValue(), E);
9908   }
9909 
9910   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
9911     if (Info.ArrayInitIndex == uint64_t(-1)) {
9912       // We were asked to evaluate this subexpression independent of the
9913       // enclosing ArrayInitLoopExpr. We can't do that.
9914       Info.FFDiag(E);
9915       return false;
9916     }
9917     return Success(Info.ArrayInitIndex, E);
9918   }
9919 
9920   // Note, GNU defines __null as an integer, not a pointer.
9921   bool VisitGNUNullExpr(const GNUNullExpr *E) {
9922     return ZeroInitialization(E);
9923   }
9924 
9925   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
9926     return Success(E->getValue(), E);
9927   }
9928 
9929   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
9930     return Success(E->getValue(), E);
9931   }
9932 
9933   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
9934     return Success(E->getValue(), E);
9935   }
9936 
9937   bool VisitUnaryReal(const UnaryOperator *E);
9938   bool VisitUnaryImag(const UnaryOperator *E);
9939 
9940   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
9941   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
9942   bool VisitSourceLocExpr(const SourceLocExpr *E);
9943   bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
9944   bool VisitRequiresExpr(const RequiresExpr *E);
9945   // FIXME: Missing: array subscript of vector, member of vector
9946 };
9947 
9948 class FixedPointExprEvaluator
9949     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
9950   APValue &Result;
9951 
9952  public:
9953   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
9954       : ExprEvaluatorBaseTy(info), Result(result) {}
9955 
9956   bool Success(const llvm::APInt &I, const Expr *E) {
9957     return Success(
9958         APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
9959   }
9960 
9961   bool Success(uint64_t Value, const Expr *E) {
9962     return Success(
9963         APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
9964   }
9965 
9966   bool Success(const APValue &V, const Expr *E) {
9967     return Success(V.getFixedPoint(), E);
9968   }
9969 
9970   bool Success(const APFixedPoint &V, const Expr *E) {
9971     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
9972     assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
9973            "Invalid evaluation result.");
9974     Result = APValue(V);
9975     return true;
9976   }
9977 
9978   //===--------------------------------------------------------------------===//
9979   //                            Visitor Methods
9980   //===--------------------------------------------------------------------===//
9981 
9982   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
9983     return Success(E->getValue(), E);
9984   }
9985 
9986   bool VisitCastExpr(const CastExpr *E);
9987   bool VisitUnaryOperator(const UnaryOperator *E);
9988   bool VisitBinaryOperator(const BinaryOperator *E);
9989 };
9990 } // end anonymous namespace
9991 
9992 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
9993 /// produce either the integer value or a pointer.
9994 ///
9995 /// GCC has a heinous extension which folds casts between pointer types and
9996 /// pointer-sized integral types. We support this by allowing the evaluation of
9997 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
9998 /// Some simple arithmetic on such values is supported (they are treated much
9999 /// like char*).
10000 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
10001                                     EvalInfo &Info) {
10002   assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
10003   return IntExprEvaluator(Info, Result).Visit(E);
10004 }
10005 
10006 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
10007   APValue Val;
10008   if (!EvaluateIntegerOrLValue(E, Val, Info))
10009     return false;
10010   if (!Val.isInt()) {
10011     // FIXME: It would be better to produce the diagnostic for casting
10012     //        a pointer to an integer.
10013     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10014     return false;
10015   }
10016   Result = Val.getInt();
10017   return true;
10018 }
10019 
10020 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
10021   APValue Evaluated = E->EvaluateInContext(
10022       Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
10023   return Success(Evaluated, E);
10024 }
10025 
10026 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
10027                                EvalInfo &Info) {
10028   if (E->getType()->isFixedPointType()) {
10029     APValue Val;
10030     if (!FixedPointExprEvaluator(Info, Val).Visit(E))
10031       return false;
10032     if (!Val.isFixedPoint())
10033       return false;
10034 
10035     Result = Val.getFixedPoint();
10036     return true;
10037   }
10038   return false;
10039 }
10040 
10041 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
10042                                         EvalInfo &Info) {
10043   if (E->getType()->isIntegerType()) {
10044     auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
10045     APSInt Val;
10046     if (!EvaluateInteger(E, Val, Info))
10047       return false;
10048     Result = APFixedPoint(Val, FXSema);
10049     return true;
10050   } else if (E->getType()->isFixedPointType()) {
10051     return EvaluateFixedPoint(E, Result, Info);
10052   }
10053   return false;
10054 }
10055 
10056 /// Check whether the given declaration can be directly converted to an integral
10057 /// rvalue. If not, no diagnostic is produced; there are other things we can
10058 /// try.
10059 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
10060   // Enums are integer constant exprs.
10061   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
10062     // Check for signedness/width mismatches between E type and ECD value.
10063     bool SameSign = (ECD->getInitVal().isSigned()
10064                      == E->getType()->isSignedIntegerOrEnumerationType());
10065     bool SameWidth = (ECD->getInitVal().getBitWidth()
10066                       == Info.Ctx.getIntWidth(E->getType()));
10067     if (SameSign && SameWidth)
10068       return Success(ECD->getInitVal(), E);
10069     else {
10070       // Get rid of mismatch (otherwise Success assertions will fail)
10071       // by computing a new value matching the type of E.
10072       llvm::APSInt Val = ECD->getInitVal();
10073       if (!SameSign)
10074         Val.setIsSigned(!ECD->getInitVal().isSigned());
10075       if (!SameWidth)
10076         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
10077       return Success(Val, E);
10078     }
10079   }
10080   return false;
10081 }
10082 
10083 /// Values returned by __builtin_classify_type, chosen to match the values
10084 /// produced by GCC's builtin.
10085 enum class GCCTypeClass {
10086   None = -1,
10087   Void = 0,
10088   Integer = 1,
10089   // GCC reserves 2 for character types, but instead classifies them as
10090   // integers.
10091   Enum = 3,
10092   Bool = 4,
10093   Pointer = 5,
10094   // GCC reserves 6 for references, but appears to never use it (because
10095   // expressions never have reference type, presumably).
10096   PointerToDataMember = 7,
10097   RealFloat = 8,
10098   Complex = 9,
10099   // GCC reserves 10 for functions, but does not use it since GCC version 6 due
10100   // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
10101   // GCC claims to reserve 11 for pointers to member functions, but *actually*
10102   // uses 12 for that purpose, same as for a class or struct. Maybe it
10103   // internally implements a pointer to member as a struct?  Who knows.
10104   PointerToMemberFunction = 12, // Not a bug, see above.
10105   ClassOrStruct = 12,
10106   Union = 13,
10107   // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
10108   // decay to pointer. (Prior to version 6 it was only used in C++ mode).
10109   // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
10110   // literals.
10111 };
10112 
10113 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
10114 /// as GCC.
10115 static GCCTypeClass
10116 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
10117   assert(!T->isDependentType() && "unexpected dependent type");
10118 
10119   QualType CanTy = T.getCanonicalType();
10120   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
10121 
10122   switch (CanTy->getTypeClass()) {
10123 #define TYPE(ID, BASE)
10124 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
10125 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
10126 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
10127 #include "clang/AST/TypeNodes.inc"
10128   case Type::Auto:
10129   case Type::DeducedTemplateSpecialization:
10130       llvm_unreachable("unexpected non-canonical or dependent type");
10131 
10132   case Type::Builtin:
10133     switch (BT->getKind()) {
10134 #define BUILTIN_TYPE(ID, SINGLETON_ID)
10135 #define SIGNED_TYPE(ID, SINGLETON_ID) \
10136     case BuiltinType::ID: return GCCTypeClass::Integer;
10137 #define FLOATING_TYPE(ID, SINGLETON_ID) \
10138     case BuiltinType::ID: return GCCTypeClass::RealFloat;
10139 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
10140     case BuiltinType::ID: break;
10141 #include "clang/AST/BuiltinTypes.def"
10142     case BuiltinType::Void:
10143       return GCCTypeClass::Void;
10144 
10145     case BuiltinType::Bool:
10146       return GCCTypeClass::Bool;
10147 
10148     case BuiltinType::Char_U:
10149     case BuiltinType::UChar:
10150     case BuiltinType::WChar_U:
10151     case BuiltinType::Char8:
10152     case BuiltinType::Char16:
10153     case BuiltinType::Char32:
10154     case BuiltinType::UShort:
10155     case BuiltinType::UInt:
10156     case BuiltinType::ULong:
10157     case BuiltinType::ULongLong:
10158     case BuiltinType::UInt128:
10159       return GCCTypeClass::Integer;
10160 
10161     case BuiltinType::UShortAccum:
10162     case BuiltinType::UAccum:
10163     case BuiltinType::ULongAccum:
10164     case BuiltinType::UShortFract:
10165     case BuiltinType::UFract:
10166     case BuiltinType::ULongFract:
10167     case BuiltinType::SatUShortAccum:
10168     case BuiltinType::SatUAccum:
10169     case BuiltinType::SatULongAccum:
10170     case BuiltinType::SatUShortFract:
10171     case BuiltinType::SatUFract:
10172     case BuiltinType::SatULongFract:
10173       return GCCTypeClass::None;
10174 
10175     case BuiltinType::NullPtr:
10176 
10177     case BuiltinType::ObjCId:
10178     case BuiltinType::ObjCClass:
10179     case BuiltinType::ObjCSel:
10180 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
10181     case BuiltinType::Id:
10182 #include "clang/Basic/OpenCLImageTypes.def"
10183 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
10184     case BuiltinType::Id:
10185 #include "clang/Basic/OpenCLExtensionTypes.def"
10186     case BuiltinType::OCLSampler:
10187     case BuiltinType::OCLEvent:
10188     case BuiltinType::OCLClkEvent:
10189     case BuiltinType::OCLQueue:
10190     case BuiltinType::OCLReserveID:
10191 #define SVE_TYPE(Name, Id, SingletonId) \
10192     case BuiltinType::Id:
10193 #include "clang/Basic/AArch64SVEACLETypes.def"
10194       return GCCTypeClass::None;
10195 
10196     case BuiltinType::Dependent:
10197       llvm_unreachable("unexpected dependent type");
10198     };
10199     llvm_unreachable("unexpected placeholder type");
10200 
10201   case Type::Enum:
10202     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
10203 
10204   case Type::Pointer:
10205   case Type::ConstantArray:
10206   case Type::VariableArray:
10207   case Type::IncompleteArray:
10208   case Type::FunctionNoProto:
10209   case Type::FunctionProto:
10210     return GCCTypeClass::Pointer;
10211 
10212   case Type::MemberPointer:
10213     return CanTy->isMemberDataPointerType()
10214                ? GCCTypeClass::PointerToDataMember
10215                : GCCTypeClass::PointerToMemberFunction;
10216 
10217   case Type::Complex:
10218     return GCCTypeClass::Complex;
10219 
10220   case Type::Record:
10221     return CanTy->isUnionType() ? GCCTypeClass::Union
10222                                 : GCCTypeClass::ClassOrStruct;
10223 
10224   case Type::Atomic:
10225     // GCC classifies _Atomic T the same as T.
10226     return EvaluateBuiltinClassifyType(
10227         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
10228 
10229   case Type::BlockPointer:
10230   case Type::Vector:
10231   case Type::ExtVector:
10232   case Type::ObjCObject:
10233   case Type::ObjCInterface:
10234   case Type::ObjCObjectPointer:
10235   case Type::Pipe:
10236     // GCC classifies vectors as None. We follow its lead and classify all
10237     // other types that don't fit into the regular classification the same way.
10238     return GCCTypeClass::None;
10239 
10240   case Type::LValueReference:
10241   case Type::RValueReference:
10242     llvm_unreachable("invalid type for expression");
10243   }
10244 
10245   llvm_unreachable("unexpected type class");
10246 }
10247 
10248 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
10249 /// as GCC.
10250 static GCCTypeClass
10251 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
10252   // If no argument was supplied, default to None. This isn't
10253   // ideal, however it is what gcc does.
10254   if (E->getNumArgs() == 0)
10255     return GCCTypeClass::None;
10256 
10257   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
10258   // being an ICE, but still folds it to a constant using the type of the first
10259   // argument.
10260   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
10261 }
10262 
10263 /// EvaluateBuiltinConstantPForLValue - Determine the result of
10264 /// __builtin_constant_p when applied to the given pointer.
10265 ///
10266 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
10267 /// or it points to the first character of a string literal.
10268 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
10269   APValue::LValueBase Base = LV.getLValueBase();
10270   if (Base.isNull()) {
10271     // A null base is acceptable.
10272     return true;
10273   } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
10274     if (!isa<StringLiteral>(E))
10275       return false;
10276     return LV.getLValueOffset().isZero();
10277   } else if (Base.is<TypeInfoLValue>()) {
10278     // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
10279     // evaluate to true.
10280     return true;
10281   } else {
10282     // Any other base is not constant enough for GCC.
10283     return false;
10284   }
10285 }
10286 
10287 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
10288 /// GCC as we can manage.
10289 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
10290   // This evaluation is not permitted to have side-effects, so evaluate it in
10291   // a speculative evaluation context.
10292   SpeculativeEvaluationRAII SpeculativeEval(Info);
10293 
10294   // Constant-folding is always enabled for the operand of __builtin_constant_p
10295   // (even when the enclosing evaluation context otherwise requires a strict
10296   // language-specific constant expression).
10297   FoldConstant Fold(Info, true);
10298 
10299   QualType ArgType = Arg->getType();
10300 
10301   // __builtin_constant_p always has one operand. The rules which gcc follows
10302   // are not precisely documented, but are as follows:
10303   //
10304   //  - If the operand is of integral, floating, complex or enumeration type,
10305   //    and can be folded to a known value of that type, it returns 1.
10306   //  - If the operand can be folded to a pointer to the first character
10307   //    of a string literal (or such a pointer cast to an integral type)
10308   //    or to a null pointer or an integer cast to a pointer, it returns 1.
10309   //
10310   // Otherwise, it returns 0.
10311   //
10312   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
10313   // its support for this did not work prior to GCC 9 and is not yet well
10314   // understood.
10315   if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
10316       ArgType->isAnyComplexType() || ArgType->isPointerType() ||
10317       ArgType->isNullPtrType()) {
10318     APValue V;
10319     if (!::EvaluateAsRValue(Info, Arg, V)) {
10320       Fold.keepDiagnostics();
10321       return false;
10322     }
10323 
10324     // For a pointer (possibly cast to integer), there are special rules.
10325     if (V.getKind() == APValue::LValue)
10326       return EvaluateBuiltinConstantPForLValue(V);
10327 
10328     // Otherwise, any constant value is good enough.
10329     return V.hasValue();
10330   }
10331 
10332   // Anything else isn't considered to be sufficiently constant.
10333   return false;
10334 }
10335 
10336 /// Retrieves the "underlying object type" of the given expression,
10337 /// as used by __builtin_object_size.
10338 static QualType getObjectType(APValue::LValueBase B) {
10339   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
10340     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
10341       return VD->getType();
10342   } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
10343     if (isa<CompoundLiteralExpr>(E))
10344       return E->getType();
10345   } else if (B.is<TypeInfoLValue>()) {
10346     return B.getTypeInfoType();
10347   } else if (B.is<DynamicAllocLValue>()) {
10348     return B.getDynamicAllocType();
10349   }
10350 
10351   return QualType();
10352 }
10353 
10354 /// A more selective version of E->IgnoreParenCasts for
10355 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
10356 /// to change the type of E.
10357 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
10358 ///
10359 /// Always returns an RValue with a pointer representation.
10360 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
10361   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
10362 
10363   auto *NoParens = E->IgnoreParens();
10364   auto *Cast = dyn_cast<CastExpr>(NoParens);
10365   if (Cast == nullptr)
10366     return NoParens;
10367 
10368   // We only conservatively allow a few kinds of casts, because this code is
10369   // inherently a simple solution that seeks to support the common case.
10370   auto CastKind = Cast->getCastKind();
10371   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
10372       CastKind != CK_AddressSpaceConversion)
10373     return NoParens;
10374 
10375   auto *SubExpr = Cast->getSubExpr();
10376   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
10377     return NoParens;
10378   return ignorePointerCastsAndParens(SubExpr);
10379 }
10380 
10381 /// Checks to see if the given LValue's Designator is at the end of the LValue's
10382 /// record layout. e.g.
10383 ///   struct { struct { int a, b; } fst, snd; } obj;
10384 ///   obj.fst   // no
10385 ///   obj.snd   // yes
10386 ///   obj.fst.a // no
10387 ///   obj.fst.b // no
10388 ///   obj.snd.a // no
10389 ///   obj.snd.b // yes
10390 ///
10391 /// Please note: this function is specialized for how __builtin_object_size
10392 /// views "objects".
10393 ///
10394 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
10395 /// correct result, it will always return true.
10396 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
10397   assert(!LVal.Designator.Invalid);
10398 
10399   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
10400     const RecordDecl *Parent = FD->getParent();
10401     Invalid = Parent->isInvalidDecl();
10402     if (Invalid || Parent->isUnion())
10403       return true;
10404     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
10405     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
10406   };
10407 
10408   auto &Base = LVal.getLValueBase();
10409   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
10410     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
10411       bool Invalid;
10412       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
10413         return Invalid;
10414     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
10415       for (auto *FD : IFD->chain()) {
10416         bool Invalid;
10417         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
10418           return Invalid;
10419       }
10420     }
10421   }
10422 
10423   unsigned I = 0;
10424   QualType BaseType = getType(Base);
10425   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
10426     // If we don't know the array bound, conservatively assume we're looking at
10427     // the final array element.
10428     ++I;
10429     if (BaseType->isIncompleteArrayType())
10430       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
10431     else
10432       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
10433   }
10434 
10435   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
10436     const auto &Entry = LVal.Designator.Entries[I];
10437     if (BaseType->isArrayType()) {
10438       // Because __builtin_object_size treats arrays as objects, we can ignore
10439       // the index iff this is the last array in the Designator.
10440       if (I + 1 == E)
10441         return true;
10442       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
10443       uint64_t Index = Entry.getAsArrayIndex();
10444       if (Index + 1 != CAT->getSize())
10445         return false;
10446       BaseType = CAT->getElementType();
10447     } else if (BaseType->isAnyComplexType()) {
10448       const auto *CT = BaseType->castAs<ComplexType>();
10449       uint64_t Index = Entry.getAsArrayIndex();
10450       if (Index != 1)
10451         return false;
10452       BaseType = CT->getElementType();
10453     } else if (auto *FD = getAsField(Entry)) {
10454       bool Invalid;
10455       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
10456         return Invalid;
10457       BaseType = FD->getType();
10458     } else {
10459       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
10460       return false;
10461     }
10462   }
10463   return true;
10464 }
10465 
10466 /// Tests to see if the LValue has a user-specified designator (that isn't
10467 /// necessarily valid). Note that this always returns 'true' if the LValue has
10468 /// an unsized array as its first designator entry, because there's currently no
10469 /// way to tell if the user typed *foo or foo[0].
10470 static bool refersToCompleteObject(const LValue &LVal) {
10471   if (LVal.Designator.Invalid)
10472     return false;
10473 
10474   if (!LVal.Designator.Entries.empty())
10475     return LVal.Designator.isMostDerivedAnUnsizedArray();
10476 
10477   if (!LVal.InvalidBase)
10478     return true;
10479 
10480   // If `E` is a MemberExpr, then the first part of the designator is hiding in
10481   // the LValueBase.
10482   const auto *E = LVal.Base.dyn_cast<const Expr *>();
10483   return !E || !isa<MemberExpr>(E);
10484 }
10485 
10486 /// Attempts to detect a user writing into a piece of memory that's impossible
10487 /// to figure out the size of by just using types.
10488 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
10489   const SubobjectDesignator &Designator = LVal.Designator;
10490   // Notes:
10491   // - Users can only write off of the end when we have an invalid base. Invalid
10492   //   bases imply we don't know where the memory came from.
10493   // - We used to be a bit more aggressive here; we'd only be conservative if
10494   //   the array at the end was flexible, or if it had 0 or 1 elements. This
10495   //   broke some common standard library extensions (PR30346), but was
10496   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
10497   //   with some sort of whitelist. OTOH, it seems that GCC is always
10498   //   conservative with the last element in structs (if it's an array), so our
10499   //   current behavior is more compatible than a whitelisting approach would
10500   //   be.
10501   return LVal.InvalidBase &&
10502          Designator.Entries.size() == Designator.MostDerivedPathLength &&
10503          Designator.MostDerivedIsArrayElement &&
10504          isDesignatorAtObjectEnd(Ctx, LVal);
10505 }
10506 
10507 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
10508 /// Fails if the conversion would cause loss of precision.
10509 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
10510                                             CharUnits &Result) {
10511   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
10512   if (Int.ugt(CharUnitsMax))
10513     return false;
10514   Result = CharUnits::fromQuantity(Int.getZExtValue());
10515   return true;
10516 }
10517 
10518 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
10519 /// determine how many bytes exist from the beginning of the object to either
10520 /// the end of the current subobject, or the end of the object itself, depending
10521 /// on what the LValue looks like + the value of Type.
10522 ///
10523 /// If this returns false, the value of Result is undefined.
10524 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
10525                                unsigned Type, const LValue &LVal,
10526                                CharUnits &EndOffset) {
10527   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
10528 
10529   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
10530     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
10531       return false;
10532     return HandleSizeof(Info, ExprLoc, Ty, Result);
10533   };
10534 
10535   // We want to evaluate the size of the entire object. This is a valid fallback
10536   // for when Type=1 and the designator is invalid, because we're asked for an
10537   // upper-bound.
10538   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
10539     // Type=3 wants a lower bound, so we can't fall back to this.
10540     if (Type == 3 && !DetermineForCompleteObject)
10541       return false;
10542 
10543     llvm::APInt APEndOffset;
10544     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
10545         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
10546       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
10547 
10548     if (LVal.InvalidBase)
10549       return false;
10550 
10551     QualType BaseTy = getObjectType(LVal.getLValueBase());
10552     return CheckedHandleSizeof(BaseTy, EndOffset);
10553   }
10554 
10555   // We want to evaluate the size of a subobject.
10556   const SubobjectDesignator &Designator = LVal.Designator;
10557 
10558   // The following is a moderately common idiom in C:
10559   //
10560   // struct Foo { int a; char c[1]; };
10561   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
10562   // strcpy(&F->c[0], Bar);
10563   //
10564   // In order to not break too much legacy code, we need to support it.
10565   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
10566     // If we can resolve this to an alloc_size call, we can hand that back,
10567     // because we know for certain how many bytes there are to write to.
10568     llvm::APInt APEndOffset;
10569     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
10570         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
10571       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
10572 
10573     // If we cannot determine the size of the initial allocation, then we can't
10574     // given an accurate upper-bound. However, we are still able to give
10575     // conservative lower-bounds for Type=3.
10576     if (Type == 1)
10577       return false;
10578   }
10579 
10580   CharUnits BytesPerElem;
10581   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
10582     return false;
10583 
10584   // According to the GCC documentation, we want the size of the subobject
10585   // denoted by the pointer. But that's not quite right -- what we actually
10586   // want is the size of the immediately-enclosing array, if there is one.
10587   int64_t ElemsRemaining;
10588   if (Designator.MostDerivedIsArrayElement &&
10589       Designator.Entries.size() == Designator.MostDerivedPathLength) {
10590     uint64_t ArraySize = Designator.getMostDerivedArraySize();
10591     uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
10592     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
10593   } else {
10594     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
10595   }
10596 
10597   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
10598   return true;
10599 }
10600 
10601 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
10602 /// returns true and stores the result in @p Size.
10603 ///
10604 /// If @p WasError is non-null, this will report whether the failure to evaluate
10605 /// is to be treated as an Error in IntExprEvaluator.
10606 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
10607                                          EvalInfo &Info, uint64_t &Size) {
10608   // Determine the denoted object.
10609   LValue LVal;
10610   {
10611     // The operand of __builtin_object_size is never evaluated for side-effects.
10612     // If there are any, but we can determine the pointed-to object anyway, then
10613     // ignore the side-effects.
10614     SpeculativeEvaluationRAII SpeculativeEval(Info);
10615     IgnoreSideEffectsRAII Fold(Info);
10616 
10617     if (E->isGLValue()) {
10618       // It's possible for us to be given GLValues if we're called via
10619       // Expr::tryEvaluateObjectSize.
10620       APValue RVal;
10621       if (!EvaluateAsRValue(Info, E, RVal))
10622         return false;
10623       LVal.setFrom(Info.Ctx, RVal);
10624     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
10625                                 /*InvalidBaseOK=*/true))
10626       return false;
10627   }
10628 
10629   // If we point to before the start of the object, there are no accessible
10630   // bytes.
10631   if (LVal.getLValueOffset().isNegative()) {
10632     Size = 0;
10633     return true;
10634   }
10635 
10636   CharUnits EndOffset;
10637   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
10638     return false;
10639 
10640   // If we've fallen outside of the end offset, just pretend there's nothing to
10641   // write to/read from.
10642   if (EndOffset <= LVal.getLValueOffset())
10643     Size = 0;
10644   else
10645     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
10646   return true;
10647 }
10648 
10649 bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
10650   llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
10651   if (E->getResultAPValueKind() != APValue::None)
10652     return Success(E->getAPValueResult(), E);
10653   return ExprEvaluatorBaseTy::VisitConstantExpr(E);
10654 }
10655 
10656 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
10657   if (unsigned BuiltinOp = E->getBuiltinCallee())
10658     return VisitBuiltinCallExpr(E, BuiltinOp);
10659 
10660   return ExprEvaluatorBaseTy::VisitCallExpr(E);
10661 }
10662 
10663 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
10664                                      APValue &Val, APSInt &Alignment) {
10665   QualType SrcTy = E->getArg(0)->getType();
10666   if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
10667     return false;
10668   // Even though we are evaluating integer expressions we could get a pointer
10669   // argument for the __builtin_is_aligned() case.
10670   if (SrcTy->isPointerType()) {
10671     LValue Ptr;
10672     if (!EvaluatePointer(E->getArg(0), Ptr, Info))
10673       return false;
10674     Ptr.moveInto(Val);
10675   } else if (!SrcTy->isIntegralOrEnumerationType()) {
10676     Info.FFDiag(E->getArg(0));
10677     return false;
10678   } else {
10679     APSInt SrcInt;
10680     if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
10681       return false;
10682     assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
10683            "Bit widths must be the same");
10684     Val = APValue(SrcInt);
10685   }
10686   assert(Val.hasValue());
10687   return true;
10688 }
10689 
10690 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
10691                                             unsigned BuiltinOp) {
10692   switch (BuiltinOp) {
10693   default:
10694     return ExprEvaluatorBaseTy::VisitCallExpr(E);
10695 
10696   case Builtin::BI__builtin_dynamic_object_size:
10697   case Builtin::BI__builtin_object_size: {
10698     // The type was checked when we built the expression.
10699     unsigned Type =
10700         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
10701     assert(Type <= 3 && "unexpected type");
10702 
10703     uint64_t Size;
10704     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
10705       return Success(Size, E);
10706 
10707     if (E->getArg(0)->HasSideEffects(Info.Ctx))
10708       return Success((Type & 2) ? 0 : -1, E);
10709 
10710     // Expression had no side effects, but we couldn't statically determine the
10711     // size of the referenced object.
10712     switch (Info.EvalMode) {
10713     case EvalInfo::EM_ConstantExpression:
10714     case EvalInfo::EM_ConstantFold:
10715     case EvalInfo::EM_IgnoreSideEffects:
10716       // Leave it to IR generation.
10717       return Error(E);
10718     case EvalInfo::EM_ConstantExpressionUnevaluated:
10719       // Reduce it to a constant now.
10720       return Success((Type & 2) ? 0 : -1, E);
10721     }
10722 
10723     llvm_unreachable("unexpected EvalMode");
10724   }
10725 
10726   case Builtin::BI__builtin_os_log_format_buffer_size: {
10727     analyze_os_log::OSLogBufferLayout Layout;
10728     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
10729     return Success(Layout.size().getQuantity(), E);
10730   }
10731 
10732   case Builtin::BI__builtin_is_aligned: {
10733     APValue Src;
10734     APSInt Alignment;
10735     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
10736       return false;
10737     if (Src.isLValue()) {
10738       // If we evaluated a pointer, check the minimum known alignment.
10739       LValue Ptr;
10740       Ptr.setFrom(Info.Ctx, Src);
10741       CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
10742       CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
10743       // We can return true if the known alignment at the computed offset is
10744       // greater than the requested alignment.
10745       assert(PtrAlign.isPowerOfTwo());
10746       assert(Alignment.isPowerOf2());
10747       if (PtrAlign.getQuantity() >= Alignment)
10748         return Success(1, E);
10749       // If the alignment is not known to be sufficient, some cases could still
10750       // be aligned at run time. However, if the requested alignment is less or
10751       // equal to the base alignment and the offset is not aligned, we know that
10752       // the run-time value can never be aligned.
10753       if (BaseAlignment.getQuantity() >= Alignment &&
10754           PtrAlign.getQuantity() < Alignment)
10755         return Success(0, E);
10756       // Otherwise we can't infer whether the value is sufficiently aligned.
10757       // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
10758       //  in cases where we can't fully evaluate the pointer.
10759       Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
10760           << Alignment;
10761       return false;
10762     }
10763     assert(Src.isInt());
10764     return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
10765   }
10766   case Builtin::BI__builtin_align_up: {
10767     APValue Src;
10768     APSInt Alignment;
10769     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
10770       return false;
10771     if (!Src.isInt())
10772       return Error(E);
10773     APSInt AlignedVal =
10774         APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
10775                Src.getInt().isUnsigned());
10776     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
10777     return Success(AlignedVal, E);
10778   }
10779   case Builtin::BI__builtin_align_down: {
10780     APValue Src;
10781     APSInt Alignment;
10782     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
10783       return false;
10784     if (!Src.isInt())
10785       return Error(E);
10786     APSInt AlignedVal =
10787         APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
10788     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
10789     return Success(AlignedVal, E);
10790   }
10791 
10792   case Builtin::BI__builtin_bswap16:
10793   case Builtin::BI__builtin_bswap32:
10794   case Builtin::BI__builtin_bswap64: {
10795     APSInt Val;
10796     if (!EvaluateInteger(E->getArg(0), Val, Info))
10797       return false;
10798 
10799     return Success(Val.byteSwap(), E);
10800   }
10801 
10802   case Builtin::BI__builtin_classify_type:
10803     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
10804 
10805   case Builtin::BI__builtin_clrsb:
10806   case Builtin::BI__builtin_clrsbl:
10807   case Builtin::BI__builtin_clrsbll: {
10808     APSInt Val;
10809     if (!EvaluateInteger(E->getArg(0), Val, Info))
10810       return false;
10811 
10812     return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
10813   }
10814 
10815   case Builtin::BI__builtin_clz:
10816   case Builtin::BI__builtin_clzl:
10817   case Builtin::BI__builtin_clzll:
10818   case Builtin::BI__builtin_clzs: {
10819     APSInt Val;
10820     if (!EvaluateInteger(E->getArg(0), Val, Info))
10821       return false;
10822     if (!Val)
10823       return Error(E);
10824 
10825     return Success(Val.countLeadingZeros(), E);
10826   }
10827 
10828   case Builtin::BI__builtin_constant_p: {
10829     const Expr *Arg = E->getArg(0);
10830     if (EvaluateBuiltinConstantP(Info, Arg))
10831       return Success(true, E);
10832     if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
10833       // Outside a constant context, eagerly evaluate to false in the presence
10834       // of side-effects in order to avoid -Wunsequenced false-positives in
10835       // a branch on __builtin_constant_p(expr).
10836       return Success(false, E);
10837     }
10838     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10839     return false;
10840   }
10841 
10842   case Builtin::BI__builtin_is_constant_evaluated: {
10843     const auto *Callee = Info.CurrentCall->getCallee();
10844     if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
10845         (Info.CallStackDepth == 1 ||
10846          (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
10847           Callee->getIdentifier() &&
10848           Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
10849       // FIXME: Find a better way to avoid duplicated diagnostics.
10850       if (Info.EvalStatus.Diag)
10851         Info.report((Info.CallStackDepth == 1) ? E->getExprLoc()
10852                                                : Info.CurrentCall->CallLoc,
10853                     diag::warn_is_constant_evaluated_always_true_constexpr)
10854             << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
10855                                          : "std::is_constant_evaluated");
10856     }
10857 
10858     return Success(Info.InConstantContext, E);
10859   }
10860 
10861   case Builtin::BI__builtin_ctz:
10862   case Builtin::BI__builtin_ctzl:
10863   case Builtin::BI__builtin_ctzll:
10864   case Builtin::BI__builtin_ctzs: {
10865     APSInt Val;
10866     if (!EvaluateInteger(E->getArg(0), Val, Info))
10867       return false;
10868     if (!Val)
10869       return Error(E);
10870 
10871     return Success(Val.countTrailingZeros(), E);
10872   }
10873 
10874   case Builtin::BI__builtin_eh_return_data_regno: {
10875     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
10876     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
10877     return Success(Operand, E);
10878   }
10879 
10880   case Builtin::BI__builtin_expect:
10881     return Visit(E->getArg(0));
10882 
10883   case Builtin::BI__builtin_ffs:
10884   case Builtin::BI__builtin_ffsl:
10885   case Builtin::BI__builtin_ffsll: {
10886     APSInt Val;
10887     if (!EvaluateInteger(E->getArg(0), Val, Info))
10888       return false;
10889 
10890     unsigned N = Val.countTrailingZeros();
10891     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
10892   }
10893 
10894   case Builtin::BI__builtin_fpclassify: {
10895     APFloat Val(0.0);
10896     if (!EvaluateFloat(E->getArg(5), Val, Info))
10897       return false;
10898     unsigned Arg;
10899     switch (Val.getCategory()) {
10900     case APFloat::fcNaN: Arg = 0; break;
10901     case APFloat::fcInfinity: Arg = 1; break;
10902     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
10903     case APFloat::fcZero: Arg = 4; break;
10904     }
10905     return Visit(E->getArg(Arg));
10906   }
10907 
10908   case Builtin::BI__builtin_isinf_sign: {
10909     APFloat Val(0.0);
10910     return EvaluateFloat(E->getArg(0), Val, Info) &&
10911            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
10912   }
10913 
10914   case Builtin::BI__builtin_isinf: {
10915     APFloat Val(0.0);
10916     return EvaluateFloat(E->getArg(0), Val, Info) &&
10917            Success(Val.isInfinity() ? 1 : 0, E);
10918   }
10919 
10920   case Builtin::BI__builtin_isfinite: {
10921     APFloat Val(0.0);
10922     return EvaluateFloat(E->getArg(0), Val, Info) &&
10923            Success(Val.isFinite() ? 1 : 0, E);
10924   }
10925 
10926   case Builtin::BI__builtin_isnan: {
10927     APFloat Val(0.0);
10928     return EvaluateFloat(E->getArg(0), Val, Info) &&
10929            Success(Val.isNaN() ? 1 : 0, E);
10930   }
10931 
10932   case Builtin::BI__builtin_isnormal: {
10933     APFloat Val(0.0);
10934     return EvaluateFloat(E->getArg(0), Val, Info) &&
10935            Success(Val.isNormal() ? 1 : 0, E);
10936   }
10937 
10938   case Builtin::BI__builtin_parity:
10939   case Builtin::BI__builtin_parityl:
10940   case Builtin::BI__builtin_parityll: {
10941     APSInt Val;
10942     if (!EvaluateInteger(E->getArg(0), Val, Info))
10943       return false;
10944 
10945     return Success(Val.countPopulation() % 2, E);
10946   }
10947 
10948   case Builtin::BI__builtin_popcount:
10949   case Builtin::BI__builtin_popcountl:
10950   case Builtin::BI__builtin_popcountll: {
10951     APSInt Val;
10952     if (!EvaluateInteger(E->getArg(0), Val, Info))
10953       return false;
10954 
10955     return Success(Val.countPopulation(), E);
10956   }
10957 
10958   case Builtin::BIstrlen:
10959   case Builtin::BIwcslen:
10960     // A call to strlen is not a constant expression.
10961     if (Info.getLangOpts().CPlusPlus11)
10962       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10963         << /*isConstexpr*/0 << /*isConstructor*/0
10964         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
10965     else
10966       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10967     LLVM_FALLTHROUGH;
10968   case Builtin::BI__builtin_strlen:
10969   case Builtin::BI__builtin_wcslen: {
10970     // As an extension, we support __builtin_strlen() as a constant expression,
10971     // and support folding strlen() to a constant.
10972     LValue String;
10973     if (!EvaluatePointer(E->getArg(0), String, Info))
10974       return false;
10975 
10976     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
10977 
10978     // Fast path: if it's a string literal, search the string value.
10979     if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
10980             String.getLValueBase().dyn_cast<const Expr *>())) {
10981       // The string literal may have embedded null characters. Find the first
10982       // one and truncate there.
10983       StringRef Str = S->getBytes();
10984       int64_t Off = String.Offset.getQuantity();
10985       if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
10986           S->getCharByteWidth() == 1 &&
10987           // FIXME: Add fast-path for wchar_t too.
10988           Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
10989         Str = Str.substr(Off);
10990 
10991         StringRef::size_type Pos = Str.find(0);
10992         if (Pos != StringRef::npos)
10993           Str = Str.substr(0, Pos);
10994 
10995         return Success(Str.size(), E);
10996       }
10997 
10998       // Fall through to slow path to issue appropriate diagnostic.
10999     }
11000 
11001     // Slow path: scan the bytes of the string looking for the terminating 0.
11002     for (uint64_t Strlen = 0; /**/; ++Strlen) {
11003       APValue Char;
11004       if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
11005           !Char.isInt())
11006         return false;
11007       if (!Char.getInt())
11008         return Success(Strlen, E);
11009       if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
11010         return false;
11011     }
11012   }
11013 
11014   case Builtin::BIstrcmp:
11015   case Builtin::BIwcscmp:
11016   case Builtin::BIstrncmp:
11017   case Builtin::BIwcsncmp:
11018   case Builtin::BImemcmp:
11019   case Builtin::BIbcmp:
11020   case Builtin::BIwmemcmp:
11021     // A call to strlen is not a constant expression.
11022     if (Info.getLangOpts().CPlusPlus11)
11023       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11024         << /*isConstexpr*/0 << /*isConstructor*/0
11025         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11026     else
11027       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11028     LLVM_FALLTHROUGH;
11029   case Builtin::BI__builtin_strcmp:
11030   case Builtin::BI__builtin_wcscmp:
11031   case Builtin::BI__builtin_strncmp:
11032   case Builtin::BI__builtin_wcsncmp:
11033   case Builtin::BI__builtin_memcmp:
11034   case Builtin::BI__builtin_bcmp:
11035   case Builtin::BI__builtin_wmemcmp: {
11036     LValue String1, String2;
11037     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
11038         !EvaluatePointer(E->getArg(1), String2, Info))
11039       return false;
11040 
11041     uint64_t MaxLength = uint64_t(-1);
11042     if (BuiltinOp != Builtin::BIstrcmp &&
11043         BuiltinOp != Builtin::BIwcscmp &&
11044         BuiltinOp != Builtin::BI__builtin_strcmp &&
11045         BuiltinOp != Builtin::BI__builtin_wcscmp) {
11046       APSInt N;
11047       if (!EvaluateInteger(E->getArg(2), N, Info))
11048         return false;
11049       MaxLength = N.getExtValue();
11050     }
11051 
11052     // Empty substrings compare equal by definition.
11053     if (MaxLength == 0u)
11054       return Success(0, E);
11055 
11056     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11057         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11058         String1.Designator.Invalid || String2.Designator.Invalid)
11059       return false;
11060 
11061     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
11062     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
11063 
11064     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
11065                      BuiltinOp == Builtin::BIbcmp ||
11066                      BuiltinOp == Builtin::BI__builtin_memcmp ||
11067                      BuiltinOp == Builtin::BI__builtin_bcmp;
11068 
11069     assert(IsRawByte ||
11070            (Info.Ctx.hasSameUnqualifiedType(
11071                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
11072             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
11073 
11074     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
11075       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
11076              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
11077              Char1.isInt() && Char2.isInt();
11078     };
11079     const auto &AdvanceElems = [&] {
11080       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
11081              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
11082     };
11083 
11084     if (IsRawByte) {
11085       uint64_t BytesRemaining = MaxLength;
11086       // Pointers to const void may point to objects of incomplete type.
11087       if (CharTy1->isIncompleteType()) {
11088         Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1;
11089         return false;
11090       }
11091       if (CharTy2->isIncompleteType()) {
11092         Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2;
11093         return false;
11094       }
11095       uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)};
11096       CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width);
11097       // Give up on comparing between elements with disparate widths.
11098       if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2))
11099         return false;
11100       uint64_t BytesPerElement = CharTy1Size.getQuantity();
11101       assert(BytesRemaining && "BytesRemaining should not be zero: the "
11102                                "following loop considers at least one element");
11103       while (true) {
11104         APValue Char1, Char2;
11105         if (!ReadCurElems(Char1, Char2))
11106           return false;
11107         // We have compatible in-memory widths, but a possible type and
11108         // (for `bool`) internal representation mismatch.
11109         // Assuming two's complement representation, including 0 for `false` and
11110         // 1 for `true`, we can check an appropriate number of elements for
11111         // equality even if they are not byte-sized.
11112         APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width);
11113         APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width);
11114         if (Char1InMem.ne(Char2InMem)) {
11115           // If the elements are byte-sized, then we can produce a three-way
11116           // comparison result in a straightforward manner.
11117           if (BytesPerElement == 1u) {
11118             // memcmp always compares unsigned chars.
11119             return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E);
11120           }
11121           // The result is byte-order sensitive, and we have multibyte elements.
11122           // FIXME: We can compare the remaining bytes in the correct order.
11123           return false;
11124         }
11125         if (!AdvanceElems())
11126           return false;
11127         if (BytesRemaining <= BytesPerElement)
11128           break;
11129         BytesRemaining -= BytesPerElement;
11130       }
11131       // Enough elements are equal to account for the memcmp limit.
11132       return Success(0, E);
11133     }
11134 
11135     bool StopAtNull =
11136         (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
11137          BuiltinOp != Builtin::BIwmemcmp &&
11138          BuiltinOp != Builtin::BI__builtin_memcmp &&
11139          BuiltinOp != Builtin::BI__builtin_bcmp &&
11140          BuiltinOp != Builtin::BI__builtin_wmemcmp);
11141     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
11142                   BuiltinOp == Builtin::BIwcsncmp ||
11143                   BuiltinOp == Builtin::BIwmemcmp ||
11144                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
11145                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
11146                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
11147 
11148     for (; MaxLength; --MaxLength) {
11149       APValue Char1, Char2;
11150       if (!ReadCurElems(Char1, Char2))
11151         return false;
11152       if (Char1.getInt() != Char2.getInt()) {
11153         if (IsWide) // wmemcmp compares with wchar_t signedness.
11154           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
11155         // memcmp always compares unsigned chars.
11156         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
11157       }
11158       if (StopAtNull && !Char1.getInt())
11159         return Success(0, E);
11160       assert(!(StopAtNull && !Char2.getInt()));
11161       if (!AdvanceElems())
11162         return false;
11163     }
11164     // We hit the strncmp / memcmp limit.
11165     return Success(0, E);
11166   }
11167 
11168   case Builtin::BI__atomic_always_lock_free:
11169   case Builtin::BI__atomic_is_lock_free:
11170   case Builtin::BI__c11_atomic_is_lock_free: {
11171     APSInt SizeVal;
11172     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
11173       return false;
11174 
11175     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
11176     // of two less than the maximum inline atomic width, we know it is
11177     // lock-free.  If the size isn't a power of two, or greater than the
11178     // maximum alignment where we promote atomics, we know it is not lock-free
11179     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
11180     // the answer can only be determined at runtime; for example, 16-byte
11181     // atomics have lock-free implementations on some, but not all,
11182     // x86-64 processors.
11183 
11184     // Check power-of-two.
11185     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
11186     if (Size.isPowerOfTwo()) {
11187       // Check against inlining width.
11188       unsigned InlineWidthBits =
11189           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
11190       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
11191         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
11192             Size == CharUnits::One() ||
11193             E->getArg(1)->isNullPointerConstant(Info.Ctx,
11194                                                 Expr::NPC_NeverValueDependent))
11195           // OK, we will inline appropriately-aligned operations of this size,
11196           // and _Atomic(T) is appropriately-aligned.
11197           return Success(1, E);
11198 
11199         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
11200           castAs<PointerType>()->getPointeeType();
11201         if (!PointeeType->isIncompleteType() &&
11202             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
11203           // OK, we will inline operations on this object.
11204           return Success(1, E);
11205         }
11206       }
11207     }
11208 
11209     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
11210         Success(0, E) : Error(E);
11211   }
11212   case Builtin::BIomp_is_initial_device:
11213     // We can decide statically which value the runtime would return if called.
11214     return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
11215   case Builtin::BI__builtin_add_overflow:
11216   case Builtin::BI__builtin_sub_overflow:
11217   case Builtin::BI__builtin_mul_overflow:
11218   case Builtin::BI__builtin_sadd_overflow:
11219   case Builtin::BI__builtin_uadd_overflow:
11220   case Builtin::BI__builtin_uaddl_overflow:
11221   case Builtin::BI__builtin_uaddll_overflow:
11222   case Builtin::BI__builtin_usub_overflow:
11223   case Builtin::BI__builtin_usubl_overflow:
11224   case Builtin::BI__builtin_usubll_overflow:
11225   case Builtin::BI__builtin_umul_overflow:
11226   case Builtin::BI__builtin_umull_overflow:
11227   case Builtin::BI__builtin_umulll_overflow:
11228   case Builtin::BI__builtin_saddl_overflow:
11229   case Builtin::BI__builtin_saddll_overflow:
11230   case Builtin::BI__builtin_ssub_overflow:
11231   case Builtin::BI__builtin_ssubl_overflow:
11232   case Builtin::BI__builtin_ssubll_overflow:
11233   case Builtin::BI__builtin_smul_overflow:
11234   case Builtin::BI__builtin_smull_overflow:
11235   case Builtin::BI__builtin_smulll_overflow: {
11236     LValue ResultLValue;
11237     APSInt LHS, RHS;
11238 
11239     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
11240     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
11241         !EvaluateInteger(E->getArg(1), RHS, Info) ||
11242         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
11243       return false;
11244 
11245     APSInt Result;
11246     bool DidOverflow = false;
11247 
11248     // If the types don't have to match, enlarge all 3 to the largest of them.
11249     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
11250         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
11251         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
11252       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
11253                       ResultType->isSignedIntegerOrEnumerationType();
11254       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
11255                       ResultType->isSignedIntegerOrEnumerationType();
11256       uint64_t LHSSize = LHS.getBitWidth();
11257       uint64_t RHSSize = RHS.getBitWidth();
11258       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
11259       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
11260 
11261       // Add an additional bit if the signedness isn't uniformly agreed to. We
11262       // could do this ONLY if there is a signed and an unsigned that both have
11263       // MaxBits, but the code to check that is pretty nasty.  The issue will be
11264       // caught in the shrink-to-result later anyway.
11265       if (IsSigned && !AllSigned)
11266         ++MaxBits;
11267 
11268       LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
11269       RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
11270       Result = APSInt(MaxBits, !IsSigned);
11271     }
11272 
11273     // Find largest int.
11274     switch (BuiltinOp) {
11275     default:
11276       llvm_unreachable("Invalid value for BuiltinOp");
11277     case Builtin::BI__builtin_add_overflow:
11278     case Builtin::BI__builtin_sadd_overflow:
11279     case Builtin::BI__builtin_saddl_overflow:
11280     case Builtin::BI__builtin_saddll_overflow:
11281     case Builtin::BI__builtin_uadd_overflow:
11282     case Builtin::BI__builtin_uaddl_overflow:
11283     case Builtin::BI__builtin_uaddll_overflow:
11284       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
11285                               : LHS.uadd_ov(RHS, DidOverflow);
11286       break;
11287     case Builtin::BI__builtin_sub_overflow:
11288     case Builtin::BI__builtin_ssub_overflow:
11289     case Builtin::BI__builtin_ssubl_overflow:
11290     case Builtin::BI__builtin_ssubll_overflow:
11291     case Builtin::BI__builtin_usub_overflow:
11292     case Builtin::BI__builtin_usubl_overflow:
11293     case Builtin::BI__builtin_usubll_overflow:
11294       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
11295                               : LHS.usub_ov(RHS, DidOverflow);
11296       break;
11297     case Builtin::BI__builtin_mul_overflow:
11298     case Builtin::BI__builtin_smul_overflow:
11299     case Builtin::BI__builtin_smull_overflow:
11300     case Builtin::BI__builtin_smulll_overflow:
11301     case Builtin::BI__builtin_umul_overflow:
11302     case Builtin::BI__builtin_umull_overflow:
11303     case Builtin::BI__builtin_umulll_overflow:
11304       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
11305                               : LHS.umul_ov(RHS, DidOverflow);
11306       break;
11307     }
11308 
11309     // In the case where multiple sizes are allowed, truncate and see if
11310     // the values are the same.
11311     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
11312         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
11313         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
11314       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
11315       // since it will give us the behavior of a TruncOrSelf in the case where
11316       // its parameter <= its size.  We previously set Result to be at least the
11317       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
11318       // will work exactly like TruncOrSelf.
11319       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
11320       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
11321 
11322       if (!APSInt::isSameValue(Temp, Result))
11323         DidOverflow = true;
11324       Result = Temp;
11325     }
11326 
11327     APValue APV{Result};
11328     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
11329       return false;
11330     return Success(DidOverflow, E);
11331   }
11332   }
11333 }
11334 
11335 /// Determine whether this is a pointer past the end of the complete
11336 /// object referred to by the lvalue.
11337 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
11338                                             const LValue &LV) {
11339   // A null pointer can be viewed as being "past the end" but we don't
11340   // choose to look at it that way here.
11341   if (!LV.getLValueBase())
11342     return false;
11343 
11344   // If the designator is valid and refers to a subobject, we're not pointing
11345   // past the end.
11346   if (!LV.getLValueDesignator().Invalid &&
11347       !LV.getLValueDesignator().isOnePastTheEnd())
11348     return false;
11349 
11350   // A pointer to an incomplete type might be past-the-end if the type's size is
11351   // zero.  We cannot tell because the type is incomplete.
11352   QualType Ty = getType(LV.getLValueBase());
11353   if (Ty->isIncompleteType())
11354     return true;
11355 
11356   // We're a past-the-end pointer if we point to the byte after the object,
11357   // no matter what our type or path is.
11358   auto Size = Ctx.getTypeSizeInChars(Ty);
11359   return LV.getLValueOffset() == Size;
11360 }
11361 
11362 namespace {
11363 
11364 /// Data recursive integer evaluator of certain binary operators.
11365 ///
11366 /// We use a data recursive algorithm for binary operators so that we are able
11367 /// to handle extreme cases of chained binary operators without causing stack
11368 /// overflow.
11369 class DataRecursiveIntBinOpEvaluator {
11370   struct EvalResult {
11371     APValue Val;
11372     bool Failed;
11373 
11374     EvalResult() : Failed(false) { }
11375 
11376     void swap(EvalResult &RHS) {
11377       Val.swap(RHS.Val);
11378       Failed = RHS.Failed;
11379       RHS.Failed = false;
11380     }
11381   };
11382 
11383   struct Job {
11384     const Expr *E;
11385     EvalResult LHSResult; // meaningful only for binary operator expression.
11386     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
11387 
11388     Job() = default;
11389     Job(Job &&) = default;
11390 
11391     void startSpeculativeEval(EvalInfo &Info) {
11392       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
11393     }
11394 
11395   private:
11396     SpeculativeEvaluationRAII SpecEvalRAII;
11397   };
11398 
11399   SmallVector<Job, 16> Queue;
11400 
11401   IntExprEvaluator &IntEval;
11402   EvalInfo &Info;
11403   APValue &FinalResult;
11404 
11405 public:
11406   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
11407     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
11408 
11409   /// True if \param E is a binary operator that we are going to handle
11410   /// data recursively.
11411   /// We handle binary operators that are comma, logical, or that have operands
11412   /// with integral or enumeration type.
11413   static bool shouldEnqueue(const BinaryOperator *E) {
11414     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
11415            (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
11416             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
11417             E->getRHS()->getType()->isIntegralOrEnumerationType());
11418   }
11419 
11420   bool Traverse(const BinaryOperator *E) {
11421     enqueue(E);
11422     EvalResult PrevResult;
11423     while (!Queue.empty())
11424       process(PrevResult);
11425 
11426     if (PrevResult.Failed) return false;
11427 
11428     FinalResult.swap(PrevResult.Val);
11429     return true;
11430   }
11431 
11432 private:
11433   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
11434     return IntEval.Success(Value, E, Result);
11435   }
11436   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
11437     return IntEval.Success(Value, E, Result);
11438   }
11439   bool Error(const Expr *E) {
11440     return IntEval.Error(E);
11441   }
11442   bool Error(const Expr *E, diag::kind D) {
11443     return IntEval.Error(E, D);
11444   }
11445 
11446   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
11447     return Info.CCEDiag(E, D);
11448   }
11449 
11450   // Returns true if visiting the RHS is necessary, false otherwise.
11451   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
11452                          bool &SuppressRHSDiags);
11453 
11454   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
11455                   const BinaryOperator *E, APValue &Result);
11456 
11457   void EvaluateExpr(const Expr *E, EvalResult &Result) {
11458     Result.Failed = !Evaluate(Result.Val, Info, E);
11459     if (Result.Failed)
11460       Result.Val = APValue();
11461   }
11462 
11463   void process(EvalResult &Result);
11464 
11465   void enqueue(const Expr *E) {
11466     E = E->IgnoreParens();
11467     Queue.resize(Queue.size()+1);
11468     Queue.back().E = E;
11469     Queue.back().Kind = Job::AnyExprKind;
11470   }
11471 };
11472 
11473 }
11474 
11475 bool DataRecursiveIntBinOpEvaluator::
11476        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
11477                          bool &SuppressRHSDiags) {
11478   if (E->getOpcode() == BO_Comma) {
11479     // Ignore LHS but note if we could not evaluate it.
11480     if (LHSResult.Failed)
11481       return Info.noteSideEffect();
11482     return true;
11483   }
11484 
11485   if (E->isLogicalOp()) {
11486     bool LHSAsBool;
11487     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
11488       // We were able to evaluate the LHS, see if we can get away with not
11489       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
11490       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
11491         Success(LHSAsBool, E, LHSResult.Val);
11492         return false; // Ignore RHS
11493       }
11494     } else {
11495       LHSResult.Failed = true;
11496 
11497       // Since we weren't able to evaluate the left hand side, it
11498       // might have had side effects.
11499       if (!Info.noteSideEffect())
11500         return false;
11501 
11502       // We can't evaluate the LHS; however, sometimes the result
11503       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
11504       // Don't ignore RHS and suppress diagnostics from this arm.
11505       SuppressRHSDiags = true;
11506     }
11507 
11508     return true;
11509   }
11510 
11511   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
11512          E->getRHS()->getType()->isIntegralOrEnumerationType());
11513 
11514   if (LHSResult.Failed && !Info.noteFailure())
11515     return false; // Ignore RHS;
11516 
11517   return true;
11518 }
11519 
11520 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
11521                                     bool IsSub) {
11522   // Compute the new offset in the appropriate width, wrapping at 64 bits.
11523   // FIXME: When compiling for a 32-bit target, we should use 32-bit
11524   // offsets.
11525   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
11526   CharUnits &Offset = LVal.getLValueOffset();
11527   uint64_t Offset64 = Offset.getQuantity();
11528   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
11529   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
11530                                          : Offset64 + Index64);
11531 }
11532 
11533 bool DataRecursiveIntBinOpEvaluator::
11534        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
11535                   const BinaryOperator *E, APValue &Result) {
11536   if (E->getOpcode() == BO_Comma) {
11537     if (RHSResult.Failed)
11538       return false;
11539     Result = RHSResult.Val;
11540     return true;
11541   }
11542 
11543   if (E->isLogicalOp()) {
11544     bool lhsResult, rhsResult;
11545     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
11546     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
11547 
11548     if (LHSIsOK) {
11549       if (RHSIsOK) {
11550         if (E->getOpcode() == BO_LOr)
11551           return Success(lhsResult || rhsResult, E, Result);
11552         else
11553           return Success(lhsResult && rhsResult, E, Result);
11554       }
11555     } else {
11556       if (RHSIsOK) {
11557         // We can't evaluate the LHS; however, sometimes the result
11558         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
11559         if (rhsResult == (E->getOpcode() == BO_LOr))
11560           return Success(rhsResult, E, Result);
11561       }
11562     }
11563 
11564     return false;
11565   }
11566 
11567   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
11568          E->getRHS()->getType()->isIntegralOrEnumerationType());
11569 
11570   if (LHSResult.Failed || RHSResult.Failed)
11571     return false;
11572 
11573   const APValue &LHSVal = LHSResult.Val;
11574   const APValue &RHSVal = RHSResult.Val;
11575 
11576   // Handle cases like (unsigned long)&a + 4.
11577   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
11578     Result = LHSVal;
11579     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
11580     return true;
11581   }
11582 
11583   // Handle cases like 4 + (unsigned long)&a
11584   if (E->getOpcode() == BO_Add &&
11585       RHSVal.isLValue() && LHSVal.isInt()) {
11586     Result = RHSVal;
11587     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
11588     return true;
11589   }
11590 
11591   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
11592     // Handle (intptr_t)&&A - (intptr_t)&&B.
11593     if (!LHSVal.getLValueOffset().isZero() ||
11594         !RHSVal.getLValueOffset().isZero())
11595       return false;
11596     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
11597     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
11598     if (!LHSExpr || !RHSExpr)
11599       return false;
11600     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
11601     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
11602     if (!LHSAddrExpr || !RHSAddrExpr)
11603       return false;
11604     // Make sure both labels come from the same function.
11605     if (LHSAddrExpr->getLabel()->getDeclContext() !=
11606         RHSAddrExpr->getLabel()->getDeclContext())
11607       return false;
11608     Result = APValue(LHSAddrExpr, RHSAddrExpr);
11609     return true;
11610   }
11611 
11612   // All the remaining cases expect both operands to be an integer
11613   if (!LHSVal.isInt() || !RHSVal.isInt())
11614     return Error(E);
11615 
11616   // Set up the width and signedness manually, in case it can't be deduced
11617   // from the operation we're performing.
11618   // FIXME: Don't do this in the cases where we can deduce it.
11619   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
11620                E->getType()->isUnsignedIntegerOrEnumerationType());
11621   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
11622                          RHSVal.getInt(), Value))
11623     return false;
11624   return Success(Value, E, Result);
11625 }
11626 
11627 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
11628   Job &job = Queue.back();
11629 
11630   switch (job.Kind) {
11631     case Job::AnyExprKind: {
11632       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
11633         if (shouldEnqueue(Bop)) {
11634           job.Kind = Job::BinOpKind;
11635           enqueue(Bop->getLHS());
11636           return;
11637         }
11638       }
11639 
11640       EvaluateExpr(job.E, Result);
11641       Queue.pop_back();
11642       return;
11643     }
11644 
11645     case Job::BinOpKind: {
11646       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
11647       bool SuppressRHSDiags = false;
11648       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
11649         Queue.pop_back();
11650         return;
11651       }
11652       if (SuppressRHSDiags)
11653         job.startSpeculativeEval(Info);
11654       job.LHSResult.swap(Result);
11655       job.Kind = Job::BinOpVisitedLHSKind;
11656       enqueue(Bop->getRHS());
11657       return;
11658     }
11659 
11660     case Job::BinOpVisitedLHSKind: {
11661       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
11662       EvalResult RHS;
11663       RHS.swap(Result);
11664       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
11665       Queue.pop_back();
11666       return;
11667     }
11668   }
11669 
11670   llvm_unreachable("Invalid Job::Kind!");
11671 }
11672 
11673 namespace {
11674 /// Used when we determine that we should fail, but can keep evaluating prior to
11675 /// noting that we had a failure.
11676 class DelayedNoteFailureRAII {
11677   EvalInfo &Info;
11678   bool NoteFailure;
11679 
11680 public:
11681   DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
11682       : Info(Info), NoteFailure(NoteFailure) {}
11683   ~DelayedNoteFailureRAII() {
11684     if (NoteFailure) {
11685       bool ContinueAfterFailure = Info.noteFailure();
11686       (void)ContinueAfterFailure;
11687       assert(ContinueAfterFailure &&
11688              "Shouldn't have kept evaluating on failure.");
11689     }
11690   }
11691 };
11692 
11693 enum class CmpResult {
11694   Unequal,
11695   Less,
11696   Equal,
11697   Greater,
11698   Unordered,
11699 };
11700 }
11701 
11702 template <class SuccessCB, class AfterCB>
11703 static bool
11704 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
11705                                  SuccessCB &&Success, AfterCB &&DoAfter) {
11706   assert(E->isComparisonOp() && "expected comparison operator");
11707   assert((E->getOpcode() == BO_Cmp ||
11708           E->getType()->isIntegralOrEnumerationType()) &&
11709          "unsupported binary expression evaluation");
11710   auto Error = [&](const Expr *E) {
11711     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11712     return false;
11713   };
11714 
11715   bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
11716   bool IsEquality = E->isEqualityOp();
11717 
11718   QualType LHSTy = E->getLHS()->getType();
11719   QualType RHSTy = E->getRHS()->getType();
11720 
11721   if (LHSTy->isIntegralOrEnumerationType() &&
11722       RHSTy->isIntegralOrEnumerationType()) {
11723     APSInt LHS, RHS;
11724     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
11725     if (!LHSOK && !Info.noteFailure())
11726       return false;
11727     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
11728       return false;
11729     if (LHS < RHS)
11730       return Success(CmpResult::Less, E);
11731     if (LHS > RHS)
11732       return Success(CmpResult::Greater, E);
11733     return Success(CmpResult::Equal, E);
11734   }
11735 
11736   if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
11737     APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
11738     APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
11739 
11740     bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
11741     if (!LHSOK && !Info.noteFailure())
11742       return false;
11743     if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
11744       return false;
11745     if (LHSFX < RHSFX)
11746       return Success(CmpResult::Less, E);
11747     if (LHSFX > RHSFX)
11748       return Success(CmpResult::Greater, E);
11749     return Success(CmpResult::Equal, E);
11750   }
11751 
11752   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
11753     ComplexValue LHS, RHS;
11754     bool LHSOK;
11755     if (E->isAssignmentOp()) {
11756       LValue LV;
11757       EvaluateLValue(E->getLHS(), LV, Info);
11758       LHSOK = false;
11759     } else if (LHSTy->isRealFloatingType()) {
11760       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
11761       if (LHSOK) {
11762         LHS.makeComplexFloat();
11763         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
11764       }
11765     } else {
11766       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
11767     }
11768     if (!LHSOK && !Info.noteFailure())
11769       return false;
11770 
11771     if (E->getRHS()->getType()->isRealFloatingType()) {
11772       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
11773         return false;
11774       RHS.makeComplexFloat();
11775       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
11776     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
11777       return false;
11778 
11779     if (LHS.isComplexFloat()) {
11780       APFloat::cmpResult CR_r =
11781         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
11782       APFloat::cmpResult CR_i =
11783         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
11784       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
11785       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
11786     } else {
11787       assert(IsEquality && "invalid complex comparison");
11788       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
11789                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
11790       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
11791     }
11792   }
11793 
11794   if (LHSTy->isRealFloatingType() &&
11795       RHSTy->isRealFloatingType()) {
11796     APFloat RHS(0.0), LHS(0.0);
11797 
11798     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
11799     if (!LHSOK && !Info.noteFailure())
11800       return false;
11801 
11802     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
11803       return false;
11804 
11805     assert(E->isComparisonOp() && "Invalid binary operator!");
11806     auto GetCmpRes = [&]() {
11807       switch (LHS.compare(RHS)) {
11808       case APFloat::cmpEqual:
11809         return CmpResult::Equal;
11810       case APFloat::cmpLessThan:
11811         return CmpResult::Less;
11812       case APFloat::cmpGreaterThan:
11813         return CmpResult::Greater;
11814       case APFloat::cmpUnordered:
11815         return CmpResult::Unordered;
11816       }
11817       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
11818     };
11819     return Success(GetCmpRes(), E);
11820   }
11821 
11822   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
11823     LValue LHSValue, RHSValue;
11824 
11825     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
11826     if (!LHSOK && !Info.noteFailure())
11827       return false;
11828 
11829     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
11830       return false;
11831 
11832     // Reject differing bases from the normal codepath; we special-case
11833     // comparisons to null.
11834     if (!HasSameBase(LHSValue, RHSValue)) {
11835       // Inequalities and subtractions between unrelated pointers have
11836       // unspecified or undefined behavior.
11837       if (!IsEquality) {
11838         Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified);
11839         return false;
11840       }
11841       // A constant address may compare equal to the address of a symbol.
11842       // The one exception is that address of an object cannot compare equal
11843       // to a null pointer constant.
11844       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
11845           (!RHSValue.Base && !RHSValue.Offset.isZero()))
11846         return Error(E);
11847       // It's implementation-defined whether distinct literals will have
11848       // distinct addresses. In clang, the result of such a comparison is
11849       // unspecified, so it is not a constant expression. However, we do know
11850       // that the address of a literal will be non-null.
11851       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
11852           LHSValue.Base && RHSValue.Base)
11853         return Error(E);
11854       // We can't tell whether weak symbols will end up pointing to the same
11855       // object.
11856       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
11857         return Error(E);
11858       // We can't compare the address of the start of one object with the
11859       // past-the-end address of another object, per C++ DR1652.
11860       if ((LHSValue.Base && LHSValue.Offset.isZero() &&
11861            isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
11862           (RHSValue.Base && RHSValue.Offset.isZero() &&
11863            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
11864         return Error(E);
11865       // We can't tell whether an object is at the same address as another
11866       // zero sized object.
11867       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
11868           (LHSValue.Base && isZeroSized(RHSValue)))
11869         return Error(E);
11870       return Success(CmpResult::Unequal, E);
11871     }
11872 
11873     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
11874     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
11875 
11876     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
11877     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
11878 
11879     // C++11 [expr.rel]p3:
11880     //   Pointers to void (after pointer conversions) can be compared, with a
11881     //   result defined as follows: If both pointers represent the same
11882     //   address or are both the null pointer value, the result is true if the
11883     //   operator is <= or >= and false otherwise; otherwise the result is
11884     //   unspecified.
11885     // We interpret this as applying to pointers to *cv* void.
11886     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
11887       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
11888 
11889     // C++11 [expr.rel]p2:
11890     // - If two pointers point to non-static data members of the same object,
11891     //   or to subobjects or array elements fo such members, recursively, the
11892     //   pointer to the later declared member compares greater provided the
11893     //   two members have the same access control and provided their class is
11894     //   not a union.
11895     //   [...]
11896     // - Otherwise pointer comparisons are unspecified.
11897     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
11898       bool WasArrayIndex;
11899       unsigned Mismatch = FindDesignatorMismatch(
11900           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
11901       // At the point where the designators diverge, the comparison has a
11902       // specified value if:
11903       //  - we are comparing array indices
11904       //  - we are comparing fields of a union, or fields with the same access
11905       // Otherwise, the result is unspecified and thus the comparison is not a
11906       // constant expression.
11907       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
11908           Mismatch < RHSDesignator.Entries.size()) {
11909         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
11910         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
11911         if (!LF && !RF)
11912           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
11913         else if (!LF)
11914           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
11915               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
11916               << RF->getParent() << RF;
11917         else if (!RF)
11918           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
11919               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
11920               << LF->getParent() << LF;
11921         else if (!LF->getParent()->isUnion() &&
11922                  LF->getAccess() != RF->getAccess())
11923           Info.CCEDiag(E,
11924                        diag::note_constexpr_pointer_comparison_differing_access)
11925               << LF << LF->getAccess() << RF << RF->getAccess()
11926               << LF->getParent();
11927       }
11928     }
11929 
11930     // The comparison here must be unsigned, and performed with the same
11931     // width as the pointer.
11932     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
11933     uint64_t CompareLHS = LHSOffset.getQuantity();
11934     uint64_t CompareRHS = RHSOffset.getQuantity();
11935     assert(PtrSize <= 64 && "Unexpected pointer width");
11936     uint64_t Mask = ~0ULL >> (64 - PtrSize);
11937     CompareLHS &= Mask;
11938     CompareRHS &= Mask;
11939 
11940     // If there is a base and this is a relational operator, we can only
11941     // compare pointers within the object in question; otherwise, the result
11942     // depends on where the object is located in memory.
11943     if (!LHSValue.Base.isNull() && IsRelational) {
11944       QualType BaseTy = getType(LHSValue.Base);
11945       if (BaseTy->isIncompleteType())
11946         return Error(E);
11947       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
11948       uint64_t OffsetLimit = Size.getQuantity();
11949       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
11950         return Error(E);
11951     }
11952 
11953     if (CompareLHS < CompareRHS)
11954       return Success(CmpResult::Less, E);
11955     if (CompareLHS > CompareRHS)
11956       return Success(CmpResult::Greater, E);
11957     return Success(CmpResult::Equal, E);
11958   }
11959 
11960   if (LHSTy->isMemberPointerType()) {
11961     assert(IsEquality && "unexpected member pointer operation");
11962     assert(RHSTy->isMemberPointerType() && "invalid comparison");
11963 
11964     MemberPtr LHSValue, RHSValue;
11965 
11966     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
11967     if (!LHSOK && !Info.noteFailure())
11968       return false;
11969 
11970     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
11971       return false;
11972 
11973     // C++11 [expr.eq]p2:
11974     //   If both operands are null, they compare equal. Otherwise if only one is
11975     //   null, they compare unequal.
11976     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
11977       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
11978       return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
11979     }
11980 
11981     //   Otherwise if either is a pointer to a virtual member function, the
11982     //   result is unspecified.
11983     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
11984       if (MD->isVirtual())
11985         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
11986     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
11987       if (MD->isVirtual())
11988         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
11989 
11990     //   Otherwise they compare equal if and only if they would refer to the
11991     //   same member of the same most derived object or the same subobject if
11992     //   they were dereferenced with a hypothetical object of the associated
11993     //   class type.
11994     bool Equal = LHSValue == RHSValue;
11995     return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
11996   }
11997 
11998   if (LHSTy->isNullPtrType()) {
11999     assert(E->isComparisonOp() && "unexpected nullptr operation");
12000     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
12001     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
12002     // are compared, the result is true of the operator is <=, >= or ==, and
12003     // false otherwise.
12004     return Success(CmpResult::Equal, E);
12005   }
12006 
12007   return DoAfter();
12008 }
12009 
12010 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
12011   if (!CheckLiteralType(Info, E))
12012     return false;
12013 
12014   auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12015     ComparisonCategoryResult CCR;
12016     switch (CR) {
12017     case CmpResult::Unequal:
12018       llvm_unreachable("should never produce Unequal for three-way comparison");
12019     case CmpResult::Less:
12020       CCR = ComparisonCategoryResult::Less;
12021       break;
12022     case CmpResult::Equal:
12023       CCR = ComparisonCategoryResult::Equal;
12024       break;
12025     case CmpResult::Greater:
12026       CCR = ComparisonCategoryResult::Greater;
12027       break;
12028     case CmpResult::Unordered:
12029       CCR = ComparisonCategoryResult::Unordered;
12030       break;
12031     }
12032     // Evaluation succeeded. Lookup the information for the comparison category
12033     // type and fetch the VarDecl for the result.
12034     const ComparisonCategoryInfo &CmpInfo =
12035         Info.Ctx.CompCategories.getInfoForType(E->getType());
12036     const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
12037     // Check and evaluate the result as a constant expression.
12038     LValue LV;
12039     LV.set(VD);
12040     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
12041       return false;
12042     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
12043   };
12044   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12045     return ExprEvaluatorBaseTy::VisitBinCmp(E);
12046   });
12047 }
12048 
12049 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12050   // We don't call noteFailure immediately because the assignment happens after
12051   // we evaluate LHS and RHS.
12052   if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
12053     return Error(E);
12054 
12055   DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
12056   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
12057     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
12058 
12059   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
12060           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
12061          "DataRecursiveIntBinOpEvaluator should have handled integral types");
12062 
12063   if (E->isComparisonOp()) {
12064     // Evaluate builtin binary comparisons by evaluating them as three-way
12065     // comparisons and then translating the result.
12066     auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12067       assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
12068              "should only produce Unequal for equality comparisons");
12069       bool IsEqual   = CR == CmpResult::Equal,
12070            IsLess    = CR == CmpResult::Less,
12071            IsGreater = CR == CmpResult::Greater;
12072       auto Op = E->getOpcode();
12073       switch (Op) {
12074       default:
12075         llvm_unreachable("unsupported binary operator");
12076       case BO_EQ:
12077       case BO_NE:
12078         return Success(IsEqual == (Op == BO_EQ), E);
12079       case BO_LT:
12080         return Success(IsLess, E);
12081       case BO_GT:
12082         return Success(IsGreater, E);
12083       case BO_LE:
12084         return Success(IsEqual || IsLess, E);
12085       case BO_GE:
12086         return Success(IsEqual || IsGreater, E);
12087       }
12088     };
12089     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12090       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12091     });
12092   }
12093 
12094   QualType LHSTy = E->getLHS()->getType();
12095   QualType RHSTy = E->getRHS()->getType();
12096 
12097   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
12098       E->getOpcode() == BO_Sub) {
12099     LValue LHSValue, RHSValue;
12100 
12101     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12102     if (!LHSOK && !Info.noteFailure())
12103       return false;
12104 
12105     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12106       return false;
12107 
12108     // Reject differing bases from the normal codepath; we special-case
12109     // comparisons to null.
12110     if (!HasSameBase(LHSValue, RHSValue)) {
12111       // Handle &&A - &&B.
12112       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
12113         return Error(E);
12114       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
12115       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
12116       if (!LHSExpr || !RHSExpr)
12117         return Error(E);
12118       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12119       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12120       if (!LHSAddrExpr || !RHSAddrExpr)
12121         return Error(E);
12122       // Make sure both labels come from the same function.
12123       if (LHSAddrExpr->getLabel()->getDeclContext() !=
12124           RHSAddrExpr->getLabel()->getDeclContext())
12125         return Error(E);
12126       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
12127     }
12128     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12129     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12130 
12131     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12132     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12133 
12134     // C++11 [expr.add]p6:
12135     //   Unless both pointers point to elements of the same array object, or
12136     //   one past the last element of the array object, the behavior is
12137     //   undefined.
12138     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
12139         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
12140                                 RHSDesignator))
12141       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
12142 
12143     QualType Type = E->getLHS()->getType();
12144     QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
12145 
12146     CharUnits ElementSize;
12147     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
12148       return false;
12149 
12150     // As an extension, a type may have zero size (empty struct or union in
12151     // C, array of zero length). Pointer subtraction in such cases has
12152     // undefined behavior, so is not constant.
12153     if (ElementSize.isZero()) {
12154       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
12155           << ElementType;
12156       return false;
12157     }
12158 
12159     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
12160     // and produce incorrect results when it overflows. Such behavior
12161     // appears to be non-conforming, but is common, so perhaps we should
12162     // assume the standard intended for such cases to be undefined behavior
12163     // and check for them.
12164 
12165     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
12166     // overflow in the final conversion to ptrdiff_t.
12167     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
12168     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
12169     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
12170                     false);
12171     APSInt TrueResult = (LHS - RHS) / ElemSize;
12172     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
12173 
12174     if (Result.extend(65) != TrueResult &&
12175         !HandleOverflow(Info, E, TrueResult, E->getType()))
12176       return false;
12177     return Success(Result, E);
12178   }
12179 
12180   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12181 }
12182 
12183 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
12184 /// a result as the expression's type.
12185 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
12186                                     const UnaryExprOrTypeTraitExpr *E) {
12187   switch(E->getKind()) {
12188   case UETT_PreferredAlignOf:
12189   case UETT_AlignOf: {
12190     if (E->isArgumentType())
12191       return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
12192                      E);
12193     else
12194       return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
12195                      E);
12196   }
12197 
12198   case UETT_VecStep: {
12199     QualType Ty = E->getTypeOfArgument();
12200 
12201     if (Ty->isVectorType()) {
12202       unsigned n = Ty->castAs<VectorType>()->getNumElements();
12203 
12204       // The vec_step built-in functions that take a 3-component
12205       // vector return 4. (OpenCL 1.1 spec 6.11.12)
12206       if (n == 3)
12207         n = 4;
12208 
12209       return Success(n, E);
12210     } else
12211       return Success(1, E);
12212   }
12213 
12214   case UETT_SizeOf: {
12215     QualType SrcTy = E->getTypeOfArgument();
12216     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
12217     //   the result is the size of the referenced type."
12218     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
12219       SrcTy = Ref->getPointeeType();
12220 
12221     CharUnits Sizeof;
12222     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
12223       return false;
12224     return Success(Sizeof, E);
12225   }
12226   case UETT_OpenMPRequiredSimdAlign:
12227     assert(E->isArgumentType());
12228     return Success(
12229         Info.Ctx.toCharUnitsFromBits(
12230                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
12231             .getQuantity(),
12232         E);
12233   }
12234 
12235   llvm_unreachable("unknown expr/type trait");
12236 }
12237 
12238 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
12239   CharUnits Result;
12240   unsigned n = OOE->getNumComponents();
12241   if (n == 0)
12242     return Error(OOE);
12243   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
12244   for (unsigned i = 0; i != n; ++i) {
12245     OffsetOfNode ON = OOE->getComponent(i);
12246     switch (ON.getKind()) {
12247     case OffsetOfNode::Array: {
12248       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
12249       APSInt IdxResult;
12250       if (!EvaluateInteger(Idx, IdxResult, Info))
12251         return false;
12252       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
12253       if (!AT)
12254         return Error(OOE);
12255       CurrentType = AT->getElementType();
12256       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
12257       Result += IdxResult.getSExtValue() * ElementSize;
12258       break;
12259     }
12260 
12261     case OffsetOfNode::Field: {
12262       FieldDecl *MemberDecl = ON.getField();
12263       const RecordType *RT = CurrentType->getAs<RecordType>();
12264       if (!RT)
12265         return Error(OOE);
12266       RecordDecl *RD = RT->getDecl();
12267       if (RD->isInvalidDecl()) return false;
12268       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
12269       unsigned i = MemberDecl->getFieldIndex();
12270       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
12271       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
12272       CurrentType = MemberDecl->getType().getNonReferenceType();
12273       break;
12274     }
12275 
12276     case OffsetOfNode::Identifier:
12277       llvm_unreachable("dependent __builtin_offsetof");
12278 
12279     case OffsetOfNode::Base: {
12280       CXXBaseSpecifier *BaseSpec = ON.getBase();
12281       if (BaseSpec->isVirtual())
12282         return Error(OOE);
12283 
12284       // Find the layout of the class whose base we are looking into.
12285       const RecordType *RT = CurrentType->getAs<RecordType>();
12286       if (!RT)
12287         return Error(OOE);
12288       RecordDecl *RD = RT->getDecl();
12289       if (RD->isInvalidDecl()) return false;
12290       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
12291 
12292       // Find the base class itself.
12293       CurrentType = BaseSpec->getType();
12294       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
12295       if (!BaseRT)
12296         return Error(OOE);
12297 
12298       // Add the offset to the base.
12299       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
12300       break;
12301     }
12302     }
12303   }
12304   return Success(Result, OOE);
12305 }
12306 
12307 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12308   switch (E->getOpcode()) {
12309   default:
12310     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
12311     // See C99 6.6p3.
12312     return Error(E);
12313   case UO_Extension:
12314     // FIXME: Should extension allow i-c-e extension expressions in its scope?
12315     // If so, we could clear the diagnostic ID.
12316     return Visit(E->getSubExpr());
12317   case UO_Plus:
12318     // The result is just the value.
12319     return Visit(E->getSubExpr());
12320   case UO_Minus: {
12321     if (!Visit(E->getSubExpr()))
12322       return false;
12323     if (!Result.isInt()) return Error(E);
12324     const APSInt &Value = Result.getInt();
12325     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
12326         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
12327                         E->getType()))
12328       return false;
12329     return Success(-Value, E);
12330   }
12331   case UO_Not: {
12332     if (!Visit(E->getSubExpr()))
12333       return false;
12334     if (!Result.isInt()) return Error(E);
12335     return Success(~Result.getInt(), E);
12336   }
12337   case UO_LNot: {
12338     bool bres;
12339     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
12340       return false;
12341     return Success(!bres, E);
12342   }
12343   }
12344 }
12345 
12346 /// HandleCast - This is used to evaluate implicit or explicit casts where the
12347 /// result type is integer.
12348 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
12349   const Expr *SubExpr = E->getSubExpr();
12350   QualType DestType = E->getType();
12351   QualType SrcType = SubExpr->getType();
12352 
12353   switch (E->getCastKind()) {
12354   case CK_BaseToDerived:
12355   case CK_DerivedToBase:
12356   case CK_UncheckedDerivedToBase:
12357   case CK_Dynamic:
12358   case CK_ToUnion:
12359   case CK_ArrayToPointerDecay:
12360   case CK_FunctionToPointerDecay:
12361   case CK_NullToPointer:
12362   case CK_NullToMemberPointer:
12363   case CK_BaseToDerivedMemberPointer:
12364   case CK_DerivedToBaseMemberPointer:
12365   case CK_ReinterpretMemberPointer:
12366   case CK_ConstructorConversion:
12367   case CK_IntegralToPointer:
12368   case CK_ToVoid:
12369   case CK_VectorSplat:
12370   case CK_IntegralToFloating:
12371   case CK_FloatingCast:
12372   case CK_CPointerToObjCPointerCast:
12373   case CK_BlockPointerToObjCPointerCast:
12374   case CK_AnyPointerToBlockPointerCast:
12375   case CK_ObjCObjectLValueCast:
12376   case CK_FloatingRealToComplex:
12377   case CK_FloatingComplexToReal:
12378   case CK_FloatingComplexCast:
12379   case CK_FloatingComplexToIntegralComplex:
12380   case CK_IntegralRealToComplex:
12381   case CK_IntegralComplexCast:
12382   case CK_IntegralComplexToFloatingComplex:
12383   case CK_BuiltinFnToFnPtr:
12384   case CK_ZeroToOCLOpaqueType:
12385   case CK_NonAtomicToAtomic:
12386   case CK_AddressSpaceConversion:
12387   case CK_IntToOCLSampler:
12388   case CK_FixedPointCast:
12389   case CK_IntegralToFixedPoint:
12390     llvm_unreachable("invalid cast kind for integral value");
12391 
12392   case CK_BitCast:
12393   case CK_Dependent:
12394   case CK_LValueBitCast:
12395   case CK_ARCProduceObject:
12396   case CK_ARCConsumeObject:
12397   case CK_ARCReclaimReturnedObject:
12398   case CK_ARCExtendBlockObject:
12399   case CK_CopyAndAutoreleaseBlockObject:
12400     return Error(E);
12401 
12402   case CK_UserDefinedConversion:
12403   case CK_LValueToRValue:
12404   case CK_AtomicToNonAtomic:
12405   case CK_NoOp:
12406   case CK_LValueToRValueBitCast:
12407     return ExprEvaluatorBaseTy::VisitCastExpr(E);
12408 
12409   case CK_MemberPointerToBoolean:
12410   case CK_PointerToBoolean:
12411   case CK_IntegralToBoolean:
12412   case CK_FloatingToBoolean:
12413   case CK_BooleanToSignedIntegral:
12414   case CK_FloatingComplexToBoolean:
12415   case CK_IntegralComplexToBoolean: {
12416     bool BoolResult;
12417     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
12418       return false;
12419     uint64_t IntResult = BoolResult;
12420     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
12421       IntResult = (uint64_t)-1;
12422     return Success(IntResult, E);
12423   }
12424 
12425   case CK_FixedPointToIntegral: {
12426     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
12427     if (!EvaluateFixedPoint(SubExpr, Src, Info))
12428       return false;
12429     bool Overflowed;
12430     llvm::APSInt Result = Src.convertToInt(
12431         Info.Ctx.getIntWidth(DestType),
12432         DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
12433     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
12434       return false;
12435     return Success(Result, E);
12436   }
12437 
12438   case CK_FixedPointToBoolean: {
12439     // Unsigned padding does not affect this.
12440     APValue Val;
12441     if (!Evaluate(Val, Info, SubExpr))
12442       return false;
12443     return Success(Val.getFixedPoint().getBoolValue(), E);
12444   }
12445 
12446   case CK_IntegralCast: {
12447     if (!Visit(SubExpr))
12448       return false;
12449 
12450     if (!Result.isInt()) {
12451       // Allow casts of address-of-label differences if they are no-ops
12452       // or narrowing.  (The narrowing case isn't actually guaranteed to
12453       // be constant-evaluatable except in some narrow cases which are hard
12454       // to detect here.  We let it through on the assumption the user knows
12455       // what they are doing.)
12456       if (Result.isAddrLabelDiff())
12457         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
12458       // Only allow casts of lvalues if they are lossless.
12459       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
12460     }
12461 
12462     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
12463                                       Result.getInt()), E);
12464   }
12465 
12466   case CK_PointerToIntegral: {
12467     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
12468 
12469     LValue LV;
12470     if (!EvaluatePointer(SubExpr, LV, Info))
12471       return false;
12472 
12473     if (LV.getLValueBase()) {
12474       // Only allow based lvalue casts if they are lossless.
12475       // FIXME: Allow a larger integer size than the pointer size, and allow
12476       // narrowing back down to pointer width in subsequent integral casts.
12477       // FIXME: Check integer type's active bits, not its type size.
12478       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
12479         return Error(E);
12480 
12481       LV.Designator.setInvalid();
12482       LV.moveInto(Result);
12483       return true;
12484     }
12485 
12486     APSInt AsInt;
12487     APValue V;
12488     LV.moveInto(V);
12489     if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
12490       llvm_unreachable("Can't cast this!");
12491 
12492     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
12493   }
12494 
12495   case CK_IntegralComplexToReal: {
12496     ComplexValue C;
12497     if (!EvaluateComplex(SubExpr, C, Info))
12498       return false;
12499     return Success(C.getComplexIntReal(), E);
12500   }
12501 
12502   case CK_FloatingToIntegral: {
12503     APFloat F(0.0);
12504     if (!EvaluateFloat(SubExpr, F, Info))
12505       return false;
12506 
12507     APSInt Value;
12508     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
12509       return false;
12510     return Success(Value, E);
12511   }
12512   }
12513 
12514   llvm_unreachable("unknown cast resulting in integral value");
12515 }
12516 
12517 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
12518   if (E->getSubExpr()->getType()->isAnyComplexType()) {
12519     ComplexValue LV;
12520     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
12521       return false;
12522     if (!LV.isComplexInt())
12523       return Error(E);
12524     return Success(LV.getComplexIntReal(), E);
12525   }
12526 
12527   return Visit(E->getSubExpr());
12528 }
12529 
12530 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
12531   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
12532     ComplexValue LV;
12533     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
12534       return false;
12535     if (!LV.isComplexInt())
12536       return Error(E);
12537     return Success(LV.getComplexIntImag(), E);
12538   }
12539 
12540   VisitIgnoredValue(E->getSubExpr());
12541   return Success(0, E);
12542 }
12543 
12544 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
12545   return Success(E->getPackLength(), E);
12546 }
12547 
12548 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
12549   return Success(E->getValue(), E);
12550 }
12551 
12552 bool IntExprEvaluator::VisitConceptSpecializationExpr(
12553        const ConceptSpecializationExpr *E) {
12554   return Success(E->isSatisfied(), E);
12555 }
12556 
12557 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
12558   return Success(E->isSatisfied(), E);
12559 }
12560 
12561 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12562   switch (E->getOpcode()) {
12563     default:
12564       // Invalid unary operators
12565       return Error(E);
12566     case UO_Plus:
12567       // The result is just the value.
12568       return Visit(E->getSubExpr());
12569     case UO_Minus: {
12570       if (!Visit(E->getSubExpr())) return false;
12571       if (!Result.isFixedPoint())
12572         return Error(E);
12573       bool Overflowed;
12574       APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
12575       if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
12576         return false;
12577       return Success(Negated, E);
12578     }
12579     case UO_LNot: {
12580       bool bres;
12581       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
12582         return false;
12583       return Success(!bres, E);
12584     }
12585   }
12586 }
12587 
12588 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
12589   const Expr *SubExpr = E->getSubExpr();
12590   QualType DestType = E->getType();
12591   assert(DestType->isFixedPointType() &&
12592          "Expected destination type to be a fixed point type");
12593   auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
12594 
12595   switch (E->getCastKind()) {
12596   case CK_FixedPointCast: {
12597     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
12598     if (!EvaluateFixedPoint(SubExpr, Src, Info))
12599       return false;
12600     bool Overflowed;
12601     APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
12602     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
12603       return false;
12604     return Success(Result, E);
12605   }
12606   case CK_IntegralToFixedPoint: {
12607     APSInt Src;
12608     if (!EvaluateInteger(SubExpr, Src, Info))
12609       return false;
12610 
12611     bool Overflowed;
12612     APFixedPoint IntResult = APFixedPoint::getFromIntValue(
12613         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
12614 
12615     if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType))
12616       return false;
12617 
12618     return Success(IntResult, E);
12619   }
12620   case CK_NoOp:
12621   case CK_LValueToRValue:
12622     return ExprEvaluatorBaseTy::VisitCastExpr(E);
12623   default:
12624     return Error(E);
12625   }
12626 }
12627 
12628 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12629   const Expr *LHS = E->getLHS();
12630   const Expr *RHS = E->getRHS();
12631   FixedPointSemantics ResultFXSema =
12632       Info.Ctx.getFixedPointSemantics(E->getType());
12633 
12634   APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
12635   if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
12636     return false;
12637   APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
12638   if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
12639     return false;
12640 
12641   switch (E->getOpcode()) {
12642   case BO_Add: {
12643     bool AddOverflow, ConversionOverflow;
12644     APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow)
12645                               .convert(ResultFXSema, &ConversionOverflow);
12646     if ((AddOverflow || ConversionOverflow) &&
12647         !HandleOverflow(Info, E, Result, E->getType()))
12648       return false;
12649     return Success(Result, E);
12650   }
12651   default:
12652     return false;
12653   }
12654   llvm_unreachable("Should've exited before this");
12655 }
12656 
12657 //===----------------------------------------------------------------------===//
12658 // Float Evaluation
12659 //===----------------------------------------------------------------------===//
12660 
12661 namespace {
12662 class FloatExprEvaluator
12663   : public ExprEvaluatorBase<FloatExprEvaluator> {
12664   APFloat &Result;
12665 public:
12666   FloatExprEvaluator(EvalInfo &info, APFloat &result)
12667     : ExprEvaluatorBaseTy(info), Result(result) {}
12668 
12669   bool Success(const APValue &V, const Expr *e) {
12670     Result = V.getFloat();
12671     return true;
12672   }
12673 
12674   bool ZeroInitialization(const Expr *E) {
12675     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
12676     return true;
12677   }
12678 
12679   bool VisitCallExpr(const CallExpr *E);
12680 
12681   bool VisitUnaryOperator(const UnaryOperator *E);
12682   bool VisitBinaryOperator(const BinaryOperator *E);
12683   bool VisitFloatingLiteral(const FloatingLiteral *E);
12684   bool VisitCastExpr(const CastExpr *E);
12685 
12686   bool VisitUnaryReal(const UnaryOperator *E);
12687   bool VisitUnaryImag(const UnaryOperator *E);
12688 
12689   // FIXME: Missing: array subscript of vector, member of vector
12690 };
12691 } // end anonymous namespace
12692 
12693 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
12694   assert(E->isRValue() && E->getType()->isRealFloatingType());
12695   return FloatExprEvaluator(Info, Result).Visit(E);
12696 }
12697 
12698 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
12699                                   QualType ResultTy,
12700                                   const Expr *Arg,
12701                                   bool SNaN,
12702                                   llvm::APFloat &Result) {
12703   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
12704   if (!S) return false;
12705 
12706   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
12707 
12708   llvm::APInt fill;
12709 
12710   // Treat empty strings as if they were zero.
12711   if (S->getString().empty())
12712     fill = llvm::APInt(32, 0);
12713   else if (S->getString().getAsInteger(0, fill))
12714     return false;
12715 
12716   if (Context.getTargetInfo().isNan2008()) {
12717     if (SNaN)
12718       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
12719     else
12720       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
12721   } else {
12722     // Prior to IEEE 754-2008, architectures were allowed to choose whether
12723     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
12724     // a different encoding to what became a standard in 2008, and for pre-
12725     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
12726     // sNaN. This is now known as "legacy NaN" encoding.
12727     if (SNaN)
12728       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
12729     else
12730       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
12731   }
12732 
12733   return true;
12734 }
12735 
12736 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
12737   switch (E->getBuiltinCallee()) {
12738   default:
12739     return ExprEvaluatorBaseTy::VisitCallExpr(E);
12740 
12741   case Builtin::BI__builtin_huge_val:
12742   case Builtin::BI__builtin_huge_valf:
12743   case Builtin::BI__builtin_huge_vall:
12744   case Builtin::BI__builtin_huge_valf128:
12745   case Builtin::BI__builtin_inf:
12746   case Builtin::BI__builtin_inff:
12747   case Builtin::BI__builtin_infl:
12748   case Builtin::BI__builtin_inff128: {
12749     const llvm::fltSemantics &Sem =
12750       Info.Ctx.getFloatTypeSemantics(E->getType());
12751     Result = llvm::APFloat::getInf(Sem);
12752     return true;
12753   }
12754 
12755   case Builtin::BI__builtin_nans:
12756   case Builtin::BI__builtin_nansf:
12757   case Builtin::BI__builtin_nansl:
12758   case Builtin::BI__builtin_nansf128:
12759     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
12760                                true, Result))
12761       return Error(E);
12762     return true;
12763 
12764   case Builtin::BI__builtin_nan:
12765   case Builtin::BI__builtin_nanf:
12766   case Builtin::BI__builtin_nanl:
12767   case Builtin::BI__builtin_nanf128:
12768     // If this is __builtin_nan() turn this into a nan, otherwise we
12769     // can't constant fold it.
12770     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
12771                                false, Result))
12772       return Error(E);
12773     return true;
12774 
12775   case Builtin::BI__builtin_fabs:
12776   case Builtin::BI__builtin_fabsf:
12777   case Builtin::BI__builtin_fabsl:
12778   case Builtin::BI__builtin_fabsf128:
12779     if (!EvaluateFloat(E->getArg(0), Result, Info))
12780       return false;
12781 
12782     if (Result.isNegative())
12783       Result.changeSign();
12784     return true;
12785 
12786   // FIXME: Builtin::BI__builtin_powi
12787   // FIXME: Builtin::BI__builtin_powif
12788   // FIXME: Builtin::BI__builtin_powil
12789 
12790   case Builtin::BI__builtin_copysign:
12791   case Builtin::BI__builtin_copysignf:
12792   case Builtin::BI__builtin_copysignl:
12793   case Builtin::BI__builtin_copysignf128: {
12794     APFloat RHS(0.);
12795     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
12796         !EvaluateFloat(E->getArg(1), RHS, Info))
12797       return false;
12798     Result.copySign(RHS);
12799     return true;
12800   }
12801   }
12802 }
12803 
12804 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
12805   if (E->getSubExpr()->getType()->isAnyComplexType()) {
12806     ComplexValue CV;
12807     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
12808       return false;
12809     Result = CV.FloatReal;
12810     return true;
12811   }
12812 
12813   return Visit(E->getSubExpr());
12814 }
12815 
12816 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
12817   if (E->getSubExpr()->getType()->isAnyComplexType()) {
12818     ComplexValue CV;
12819     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
12820       return false;
12821     Result = CV.FloatImag;
12822     return true;
12823   }
12824 
12825   VisitIgnoredValue(E->getSubExpr());
12826   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
12827   Result = llvm::APFloat::getZero(Sem);
12828   return true;
12829 }
12830 
12831 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12832   switch (E->getOpcode()) {
12833   default: return Error(E);
12834   case UO_Plus:
12835     return EvaluateFloat(E->getSubExpr(), Result, Info);
12836   case UO_Minus:
12837     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
12838       return false;
12839     Result.changeSign();
12840     return true;
12841   }
12842 }
12843 
12844 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12845   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
12846     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12847 
12848   APFloat RHS(0.0);
12849   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
12850   if (!LHSOK && !Info.noteFailure())
12851     return false;
12852   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
12853          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
12854 }
12855 
12856 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
12857   Result = E->getValue();
12858   return true;
12859 }
12860 
12861 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
12862   const Expr* SubExpr = E->getSubExpr();
12863 
12864   switch (E->getCastKind()) {
12865   default:
12866     return ExprEvaluatorBaseTy::VisitCastExpr(E);
12867 
12868   case CK_IntegralToFloating: {
12869     APSInt IntResult;
12870     return EvaluateInteger(SubExpr, IntResult, Info) &&
12871            HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
12872                                 E->getType(), Result);
12873   }
12874 
12875   case CK_FloatingCast: {
12876     if (!Visit(SubExpr))
12877       return false;
12878     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
12879                                   Result);
12880   }
12881 
12882   case CK_FloatingComplexToReal: {
12883     ComplexValue V;
12884     if (!EvaluateComplex(SubExpr, V, Info))
12885       return false;
12886     Result = V.getComplexFloatReal();
12887     return true;
12888   }
12889   }
12890 }
12891 
12892 //===----------------------------------------------------------------------===//
12893 // Complex Evaluation (for float and integer)
12894 //===----------------------------------------------------------------------===//
12895 
12896 namespace {
12897 class ComplexExprEvaluator
12898   : public ExprEvaluatorBase<ComplexExprEvaluator> {
12899   ComplexValue &Result;
12900 
12901 public:
12902   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
12903     : ExprEvaluatorBaseTy(info), Result(Result) {}
12904 
12905   bool Success(const APValue &V, const Expr *e) {
12906     Result.setFrom(V);
12907     return true;
12908   }
12909 
12910   bool ZeroInitialization(const Expr *E);
12911 
12912   //===--------------------------------------------------------------------===//
12913   //                            Visitor Methods
12914   //===--------------------------------------------------------------------===//
12915 
12916   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
12917   bool VisitCastExpr(const CastExpr *E);
12918   bool VisitBinaryOperator(const BinaryOperator *E);
12919   bool VisitUnaryOperator(const UnaryOperator *E);
12920   bool VisitInitListExpr(const InitListExpr *E);
12921 };
12922 } // end anonymous namespace
12923 
12924 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
12925                             EvalInfo &Info) {
12926   assert(E->isRValue() && E->getType()->isAnyComplexType());
12927   return ComplexExprEvaluator(Info, Result).Visit(E);
12928 }
12929 
12930 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
12931   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
12932   if (ElemTy->isRealFloatingType()) {
12933     Result.makeComplexFloat();
12934     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
12935     Result.FloatReal = Zero;
12936     Result.FloatImag = Zero;
12937   } else {
12938     Result.makeComplexInt();
12939     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
12940     Result.IntReal = Zero;
12941     Result.IntImag = Zero;
12942   }
12943   return true;
12944 }
12945 
12946 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
12947   const Expr* SubExpr = E->getSubExpr();
12948 
12949   if (SubExpr->getType()->isRealFloatingType()) {
12950     Result.makeComplexFloat();
12951     APFloat &Imag = Result.FloatImag;
12952     if (!EvaluateFloat(SubExpr, Imag, Info))
12953       return false;
12954 
12955     Result.FloatReal = APFloat(Imag.getSemantics());
12956     return true;
12957   } else {
12958     assert(SubExpr->getType()->isIntegerType() &&
12959            "Unexpected imaginary literal.");
12960 
12961     Result.makeComplexInt();
12962     APSInt &Imag = Result.IntImag;
12963     if (!EvaluateInteger(SubExpr, Imag, Info))
12964       return false;
12965 
12966     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
12967     return true;
12968   }
12969 }
12970 
12971 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
12972 
12973   switch (E->getCastKind()) {
12974   case CK_BitCast:
12975   case CK_BaseToDerived:
12976   case CK_DerivedToBase:
12977   case CK_UncheckedDerivedToBase:
12978   case CK_Dynamic:
12979   case CK_ToUnion:
12980   case CK_ArrayToPointerDecay:
12981   case CK_FunctionToPointerDecay:
12982   case CK_NullToPointer:
12983   case CK_NullToMemberPointer:
12984   case CK_BaseToDerivedMemberPointer:
12985   case CK_DerivedToBaseMemberPointer:
12986   case CK_MemberPointerToBoolean:
12987   case CK_ReinterpretMemberPointer:
12988   case CK_ConstructorConversion:
12989   case CK_IntegralToPointer:
12990   case CK_PointerToIntegral:
12991   case CK_PointerToBoolean:
12992   case CK_ToVoid:
12993   case CK_VectorSplat:
12994   case CK_IntegralCast:
12995   case CK_BooleanToSignedIntegral:
12996   case CK_IntegralToBoolean:
12997   case CK_IntegralToFloating:
12998   case CK_FloatingToIntegral:
12999   case CK_FloatingToBoolean:
13000   case CK_FloatingCast:
13001   case CK_CPointerToObjCPointerCast:
13002   case CK_BlockPointerToObjCPointerCast:
13003   case CK_AnyPointerToBlockPointerCast:
13004   case CK_ObjCObjectLValueCast:
13005   case CK_FloatingComplexToReal:
13006   case CK_FloatingComplexToBoolean:
13007   case CK_IntegralComplexToReal:
13008   case CK_IntegralComplexToBoolean:
13009   case CK_ARCProduceObject:
13010   case CK_ARCConsumeObject:
13011   case CK_ARCReclaimReturnedObject:
13012   case CK_ARCExtendBlockObject:
13013   case CK_CopyAndAutoreleaseBlockObject:
13014   case CK_BuiltinFnToFnPtr:
13015   case CK_ZeroToOCLOpaqueType:
13016   case CK_NonAtomicToAtomic:
13017   case CK_AddressSpaceConversion:
13018   case CK_IntToOCLSampler:
13019   case CK_FixedPointCast:
13020   case CK_FixedPointToBoolean:
13021   case CK_FixedPointToIntegral:
13022   case CK_IntegralToFixedPoint:
13023     llvm_unreachable("invalid cast kind for complex value");
13024 
13025   case CK_LValueToRValue:
13026   case CK_AtomicToNonAtomic:
13027   case CK_NoOp:
13028   case CK_LValueToRValueBitCast:
13029     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13030 
13031   case CK_Dependent:
13032   case CK_LValueBitCast:
13033   case CK_UserDefinedConversion:
13034     return Error(E);
13035 
13036   case CK_FloatingRealToComplex: {
13037     APFloat &Real = Result.FloatReal;
13038     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
13039       return false;
13040 
13041     Result.makeComplexFloat();
13042     Result.FloatImag = APFloat(Real.getSemantics());
13043     return true;
13044   }
13045 
13046   case CK_FloatingComplexCast: {
13047     if (!Visit(E->getSubExpr()))
13048       return false;
13049 
13050     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13051     QualType From
13052       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13053 
13054     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
13055            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
13056   }
13057 
13058   case CK_FloatingComplexToIntegralComplex: {
13059     if (!Visit(E->getSubExpr()))
13060       return false;
13061 
13062     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13063     QualType From
13064       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13065     Result.makeComplexInt();
13066     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
13067                                 To, Result.IntReal) &&
13068            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
13069                                 To, Result.IntImag);
13070   }
13071 
13072   case CK_IntegralRealToComplex: {
13073     APSInt &Real = Result.IntReal;
13074     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
13075       return false;
13076 
13077     Result.makeComplexInt();
13078     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
13079     return true;
13080   }
13081 
13082   case CK_IntegralComplexCast: {
13083     if (!Visit(E->getSubExpr()))
13084       return false;
13085 
13086     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13087     QualType From
13088       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13089 
13090     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
13091     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
13092     return true;
13093   }
13094 
13095   case CK_IntegralComplexToFloatingComplex: {
13096     if (!Visit(E->getSubExpr()))
13097       return false;
13098 
13099     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13100     QualType From
13101       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13102     Result.makeComplexFloat();
13103     return HandleIntToFloatCast(Info, E, From, Result.IntReal,
13104                                 To, Result.FloatReal) &&
13105            HandleIntToFloatCast(Info, E, From, Result.IntImag,
13106                                 To, Result.FloatImag);
13107   }
13108   }
13109 
13110   llvm_unreachable("unknown cast resulting in complex value");
13111 }
13112 
13113 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13114   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13115     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13116 
13117   // Track whether the LHS or RHS is real at the type system level. When this is
13118   // the case we can simplify our evaluation strategy.
13119   bool LHSReal = false, RHSReal = false;
13120 
13121   bool LHSOK;
13122   if (E->getLHS()->getType()->isRealFloatingType()) {
13123     LHSReal = true;
13124     APFloat &Real = Result.FloatReal;
13125     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
13126     if (LHSOK) {
13127       Result.makeComplexFloat();
13128       Result.FloatImag = APFloat(Real.getSemantics());
13129     }
13130   } else {
13131     LHSOK = Visit(E->getLHS());
13132   }
13133   if (!LHSOK && !Info.noteFailure())
13134     return false;
13135 
13136   ComplexValue RHS;
13137   if (E->getRHS()->getType()->isRealFloatingType()) {
13138     RHSReal = true;
13139     APFloat &Real = RHS.FloatReal;
13140     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
13141       return false;
13142     RHS.makeComplexFloat();
13143     RHS.FloatImag = APFloat(Real.getSemantics());
13144   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
13145     return false;
13146 
13147   assert(!(LHSReal && RHSReal) &&
13148          "Cannot have both operands of a complex operation be real.");
13149   switch (E->getOpcode()) {
13150   default: return Error(E);
13151   case BO_Add:
13152     if (Result.isComplexFloat()) {
13153       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
13154                                        APFloat::rmNearestTiesToEven);
13155       if (LHSReal)
13156         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
13157       else if (!RHSReal)
13158         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
13159                                          APFloat::rmNearestTiesToEven);
13160     } else {
13161       Result.getComplexIntReal() += RHS.getComplexIntReal();
13162       Result.getComplexIntImag() += RHS.getComplexIntImag();
13163     }
13164     break;
13165   case BO_Sub:
13166     if (Result.isComplexFloat()) {
13167       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
13168                                             APFloat::rmNearestTiesToEven);
13169       if (LHSReal) {
13170         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
13171         Result.getComplexFloatImag().changeSign();
13172       } else if (!RHSReal) {
13173         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
13174                                               APFloat::rmNearestTiesToEven);
13175       }
13176     } else {
13177       Result.getComplexIntReal() -= RHS.getComplexIntReal();
13178       Result.getComplexIntImag() -= RHS.getComplexIntImag();
13179     }
13180     break;
13181   case BO_Mul:
13182     if (Result.isComplexFloat()) {
13183       // This is an implementation of complex multiplication according to the
13184       // constraints laid out in C11 Annex G. The implementation uses the
13185       // following naming scheme:
13186       //   (a + ib) * (c + id)
13187       ComplexValue LHS = Result;
13188       APFloat &A = LHS.getComplexFloatReal();
13189       APFloat &B = LHS.getComplexFloatImag();
13190       APFloat &C = RHS.getComplexFloatReal();
13191       APFloat &D = RHS.getComplexFloatImag();
13192       APFloat &ResR = Result.getComplexFloatReal();
13193       APFloat &ResI = Result.getComplexFloatImag();
13194       if (LHSReal) {
13195         assert(!RHSReal && "Cannot have two real operands for a complex op!");
13196         ResR = A * C;
13197         ResI = A * D;
13198       } else if (RHSReal) {
13199         ResR = C * A;
13200         ResI = C * B;
13201       } else {
13202         // In the fully general case, we need to handle NaNs and infinities
13203         // robustly.
13204         APFloat AC = A * C;
13205         APFloat BD = B * D;
13206         APFloat AD = A * D;
13207         APFloat BC = B * C;
13208         ResR = AC - BD;
13209         ResI = AD + BC;
13210         if (ResR.isNaN() && ResI.isNaN()) {
13211           bool Recalc = false;
13212           if (A.isInfinity() || B.isInfinity()) {
13213             A = APFloat::copySign(
13214                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
13215             B = APFloat::copySign(
13216                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
13217             if (C.isNaN())
13218               C = APFloat::copySign(APFloat(C.getSemantics()), C);
13219             if (D.isNaN())
13220               D = APFloat::copySign(APFloat(D.getSemantics()), D);
13221             Recalc = true;
13222           }
13223           if (C.isInfinity() || D.isInfinity()) {
13224             C = APFloat::copySign(
13225                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
13226             D = APFloat::copySign(
13227                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
13228             if (A.isNaN())
13229               A = APFloat::copySign(APFloat(A.getSemantics()), A);
13230             if (B.isNaN())
13231               B = APFloat::copySign(APFloat(B.getSemantics()), B);
13232             Recalc = true;
13233           }
13234           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
13235                           AD.isInfinity() || BC.isInfinity())) {
13236             if (A.isNaN())
13237               A = APFloat::copySign(APFloat(A.getSemantics()), A);
13238             if (B.isNaN())
13239               B = APFloat::copySign(APFloat(B.getSemantics()), B);
13240             if (C.isNaN())
13241               C = APFloat::copySign(APFloat(C.getSemantics()), C);
13242             if (D.isNaN())
13243               D = APFloat::copySign(APFloat(D.getSemantics()), D);
13244             Recalc = true;
13245           }
13246           if (Recalc) {
13247             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
13248             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
13249           }
13250         }
13251       }
13252     } else {
13253       ComplexValue LHS = Result;
13254       Result.getComplexIntReal() =
13255         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
13256          LHS.getComplexIntImag() * RHS.getComplexIntImag());
13257       Result.getComplexIntImag() =
13258         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
13259          LHS.getComplexIntImag() * RHS.getComplexIntReal());
13260     }
13261     break;
13262   case BO_Div:
13263     if (Result.isComplexFloat()) {
13264       // This is an implementation of complex division according to the
13265       // constraints laid out in C11 Annex G. The implementation uses the
13266       // following naming scheme:
13267       //   (a + ib) / (c + id)
13268       ComplexValue LHS = Result;
13269       APFloat &A = LHS.getComplexFloatReal();
13270       APFloat &B = LHS.getComplexFloatImag();
13271       APFloat &C = RHS.getComplexFloatReal();
13272       APFloat &D = RHS.getComplexFloatImag();
13273       APFloat &ResR = Result.getComplexFloatReal();
13274       APFloat &ResI = Result.getComplexFloatImag();
13275       if (RHSReal) {
13276         ResR = A / C;
13277         ResI = B / C;
13278       } else {
13279         if (LHSReal) {
13280           // No real optimizations we can do here, stub out with zero.
13281           B = APFloat::getZero(A.getSemantics());
13282         }
13283         int DenomLogB = 0;
13284         APFloat MaxCD = maxnum(abs(C), abs(D));
13285         if (MaxCD.isFinite()) {
13286           DenomLogB = ilogb(MaxCD);
13287           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
13288           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
13289         }
13290         APFloat Denom = C * C + D * D;
13291         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
13292                       APFloat::rmNearestTiesToEven);
13293         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
13294                       APFloat::rmNearestTiesToEven);
13295         if (ResR.isNaN() && ResI.isNaN()) {
13296           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
13297             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
13298             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
13299           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
13300                      D.isFinite()) {
13301             A = APFloat::copySign(
13302                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
13303             B = APFloat::copySign(
13304                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
13305             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
13306             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
13307           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
13308             C = APFloat::copySign(
13309                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
13310             D = APFloat::copySign(
13311                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
13312             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
13313             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
13314           }
13315         }
13316       }
13317     } else {
13318       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
13319         return Error(E, diag::note_expr_divide_by_zero);
13320 
13321       ComplexValue LHS = Result;
13322       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
13323         RHS.getComplexIntImag() * RHS.getComplexIntImag();
13324       Result.getComplexIntReal() =
13325         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
13326          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
13327       Result.getComplexIntImag() =
13328         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
13329          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
13330     }
13331     break;
13332   }
13333 
13334   return true;
13335 }
13336 
13337 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13338   // Get the operand value into 'Result'.
13339   if (!Visit(E->getSubExpr()))
13340     return false;
13341 
13342   switch (E->getOpcode()) {
13343   default:
13344     return Error(E);
13345   case UO_Extension:
13346     return true;
13347   case UO_Plus:
13348     // The result is always just the subexpr.
13349     return true;
13350   case UO_Minus:
13351     if (Result.isComplexFloat()) {
13352       Result.getComplexFloatReal().changeSign();
13353       Result.getComplexFloatImag().changeSign();
13354     }
13355     else {
13356       Result.getComplexIntReal() = -Result.getComplexIntReal();
13357       Result.getComplexIntImag() = -Result.getComplexIntImag();
13358     }
13359     return true;
13360   case UO_Not:
13361     if (Result.isComplexFloat())
13362       Result.getComplexFloatImag().changeSign();
13363     else
13364       Result.getComplexIntImag() = -Result.getComplexIntImag();
13365     return true;
13366   }
13367 }
13368 
13369 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
13370   if (E->getNumInits() == 2) {
13371     if (E->getType()->isComplexType()) {
13372       Result.makeComplexFloat();
13373       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
13374         return false;
13375       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
13376         return false;
13377     } else {
13378       Result.makeComplexInt();
13379       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
13380         return false;
13381       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
13382         return false;
13383     }
13384     return true;
13385   }
13386   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
13387 }
13388 
13389 //===----------------------------------------------------------------------===//
13390 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
13391 // implicit conversion.
13392 //===----------------------------------------------------------------------===//
13393 
13394 namespace {
13395 class AtomicExprEvaluator :
13396     public ExprEvaluatorBase<AtomicExprEvaluator> {
13397   const LValue *This;
13398   APValue &Result;
13399 public:
13400   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
13401       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
13402 
13403   bool Success(const APValue &V, const Expr *E) {
13404     Result = V;
13405     return true;
13406   }
13407 
13408   bool ZeroInitialization(const Expr *E) {
13409     ImplicitValueInitExpr VIE(
13410         E->getType()->castAs<AtomicType>()->getValueType());
13411     // For atomic-qualified class (and array) types in C++, initialize the
13412     // _Atomic-wrapped subobject directly, in-place.
13413     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
13414                 : Evaluate(Result, Info, &VIE);
13415   }
13416 
13417   bool VisitCastExpr(const CastExpr *E) {
13418     switch (E->getCastKind()) {
13419     default:
13420       return ExprEvaluatorBaseTy::VisitCastExpr(E);
13421     case CK_NonAtomicToAtomic:
13422       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
13423                   : Evaluate(Result, Info, E->getSubExpr());
13424     }
13425   }
13426 };
13427 } // end anonymous namespace
13428 
13429 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
13430                            EvalInfo &Info) {
13431   assert(E->isRValue() && E->getType()->isAtomicType());
13432   return AtomicExprEvaluator(Info, This, Result).Visit(E);
13433 }
13434 
13435 //===----------------------------------------------------------------------===//
13436 // Void expression evaluation, primarily for a cast to void on the LHS of a
13437 // comma operator
13438 //===----------------------------------------------------------------------===//
13439 
13440 namespace {
13441 class VoidExprEvaluator
13442   : public ExprEvaluatorBase<VoidExprEvaluator> {
13443 public:
13444   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
13445 
13446   bool Success(const APValue &V, const Expr *e) { return true; }
13447 
13448   bool ZeroInitialization(const Expr *E) { return true; }
13449 
13450   bool VisitCastExpr(const CastExpr *E) {
13451     switch (E->getCastKind()) {
13452     default:
13453       return ExprEvaluatorBaseTy::VisitCastExpr(E);
13454     case CK_ToVoid:
13455       VisitIgnoredValue(E->getSubExpr());
13456       return true;
13457     }
13458   }
13459 
13460   bool VisitCallExpr(const CallExpr *E) {
13461     switch (E->getBuiltinCallee()) {
13462     case Builtin::BI__assume:
13463     case Builtin::BI__builtin_assume:
13464       // The argument is not evaluated!
13465       return true;
13466 
13467     case Builtin::BI__builtin_operator_delete:
13468       return HandleOperatorDeleteCall(Info, E);
13469 
13470     default:
13471       break;
13472     }
13473 
13474     return ExprEvaluatorBaseTy::VisitCallExpr(E);
13475   }
13476 
13477   bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
13478 };
13479 } // end anonymous namespace
13480 
13481 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
13482   // We cannot speculatively evaluate a delete expression.
13483   if (Info.SpeculativeEvaluationDepth)
13484     return false;
13485 
13486   FunctionDecl *OperatorDelete = E->getOperatorDelete();
13487   if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
13488     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
13489         << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
13490     return false;
13491   }
13492 
13493   const Expr *Arg = E->getArgument();
13494 
13495   LValue Pointer;
13496   if (!EvaluatePointer(Arg, Pointer, Info))
13497     return false;
13498   if (Pointer.Designator.Invalid)
13499     return false;
13500 
13501   // Deleting a null pointer has no effect.
13502   if (Pointer.isNullPointer()) {
13503     // This is the only case where we need to produce an extension warning:
13504     // the only other way we can succeed is if we find a dynamic allocation,
13505     // and we will have warned when we allocated it in that case.
13506     if (!Info.getLangOpts().CPlusPlus2a)
13507       Info.CCEDiag(E, diag::note_constexpr_new);
13508     return true;
13509   }
13510 
13511   Optional<DynAlloc *> Alloc = CheckDeleteKind(
13512       Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
13513   if (!Alloc)
13514     return false;
13515   QualType AllocType = Pointer.Base.getDynamicAllocType();
13516 
13517   // For the non-array case, the designator must be empty if the static type
13518   // does not have a virtual destructor.
13519   if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
13520       !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
13521     Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
13522         << Arg->getType()->getPointeeType() << AllocType;
13523     return false;
13524   }
13525 
13526   // For a class type with a virtual destructor, the selected operator delete
13527   // is the one looked up when building the destructor.
13528   if (!E->isArrayForm() && !E->isGlobalDelete()) {
13529     const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
13530     if (VirtualDelete &&
13531         !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
13532       Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
13533           << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
13534       return false;
13535     }
13536   }
13537 
13538   if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
13539                          (*Alloc)->Value, AllocType))
13540     return false;
13541 
13542   if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
13543     // The element was already erased. This means the destructor call also
13544     // deleted the object.
13545     // FIXME: This probably results in undefined behavior before we get this
13546     // far, and should be diagnosed elsewhere first.
13547     Info.FFDiag(E, diag::note_constexpr_double_delete);
13548     return false;
13549   }
13550 
13551   return true;
13552 }
13553 
13554 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
13555   assert(E->isRValue() && E->getType()->isVoidType());
13556   return VoidExprEvaluator(Info).Visit(E);
13557 }
13558 
13559 //===----------------------------------------------------------------------===//
13560 // Top level Expr::EvaluateAsRValue method.
13561 //===----------------------------------------------------------------------===//
13562 
13563 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
13564   // In C, function designators are not lvalues, but we evaluate them as if they
13565   // are.
13566   QualType T = E->getType();
13567   if (E->isGLValue() || T->isFunctionType()) {
13568     LValue LV;
13569     if (!EvaluateLValue(E, LV, Info))
13570       return false;
13571     LV.moveInto(Result);
13572   } else if (T->isVectorType()) {
13573     if (!EvaluateVector(E, Result, Info))
13574       return false;
13575   } else if (T->isIntegralOrEnumerationType()) {
13576     if (!IntExprEvaluator(Info, Result).Visit(E))
13577       return false;
13578   } else if (T->hasPointerRepresentation()) {
13579     LValue LV;
13580     if (!EvaluatePointer(E, LV, Info))
13581       return false;
13582     LV.moveInto(Result);
13583   } else if (T->isRealFloatingType()) {
13584     llvm::APFloat F(0.0);
13585     if (!EvaluateFloat(E, F, Info))
13586       return false;
13587     Result = APValue(F);
13588   } else if (T->isAnyComplexType()) {
13589     ComplexValue C;
13590     if (!EvaluateComplex(E, C, Info))
13591       return false;
13592     C.moveInto(Result);
13593   } else if (T->isFixedPointType()) {
13594     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
13595   } else if (T->isMemberPointerType()) {
13596     MemberPtr P;
13597     if (!EvaluateMemberPointer(E, P, Info))
13598       return false;
13599     P.moveInto(Result);
13600     return true;
13601   } else if (T->isArrayType()) {
13602     LValue LV;
13603     APValue &Value =
13604         Info.CurrentCall->createTemporary(E, T, false, LV);
13605     if (!EvaluateArray(E, LV, Value, Info))
13606       return false;
13607     Result = Value;
13608   } else if (T->isRecordType()) {
13609     LValue LV;
13610     APValue &Value = Info.CurrentCall->createTemporary(E, T, false, LV);
13611     if (!EvaluateRecord(E, LV, Value, Info))
13612       return false;
13613     Result = Value;
13614   } else if (T->isVoidType()) {
13615     if (!Info.getLangOpts().CPlusPlus11)
13616       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
13617         << E->getType();
13618     if (!EvaluateVoid(E, Info))
13619       return false;
13620   } else if (T->isAtomicType()) {
13621     QualType Unqual = T.getAtomicUnqualifiedType();
13622     if (Unqual->isArrayType() || Unqual->isRecordType()) {
13623       LValue LV;
13624       APValue &Value = Info.CurrentCall->createTemporary(E, Unqual, false, LV);
13625       if (!EvaluateAtomic(E, &LV, Value, Info))
13626         return false;
13627     } else {
13628       if (!EvaluateAtomic(E, nullptr, Result, Info))
13629         return false;
13630     }
13631   } else if (Info.getLangOpts().CPlusPlus11) {
13632     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
13633     return false;
13634   } else {
13635     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
13636     return false;
13637   }
13638 
13639   return true;
13640 }
13641 
13642 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
13643 /// cases, the in-place evaluation is essential, since later initializers for
13644 /// an object can indirectly refer to subobjects which were initialized earlier.
13645 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
13646                             const Expr *E, bool AllowNonLiteralTypes) {
13647   assert(!E->isValueDependent());
13648 
13649   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
13650     return false;
13651 
13652   if (E->isRValue()) {
13653     // Evaluate arrays and record types in-place, so that later initializers can
13654     // refer to earlier-initialized members of the object.
13655     QualType T = E->getType();
13656     if (T->isArrayType())
13657       return EvaluateArray(E, This, Result, Info);
13658     else if (T->isRecordType())
13659       return EvaluateRecord(E, This, Result, Info);
13660     else if (T->isAtomicType()) {
13661       QualType Unqual = T.getAtomicUnqualifiedType();
13662       if (Unqual->isArrayType() || Unqual->isRecordType())
13663         return EvaluateAtomic(E, &This, Result, Info);
13664     }
13665   }
13666 
13667   // For any other type, in-place evaluation is unimportant.
13668   return Evaluate(Result, Info, E);
13669 }
13670 
13671 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
13672 /// lvalue-to-rvalue cast if it is an lvalue.
13673 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
13674   if (Info.EnableNewConstInterp) {
13675     if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
13676       return false;
13677   } else {
13678     if (E->getType().isNull())
13679       return false;
13680 
13681     if (!CheckLiteralType(Info, E))
13682       return false;
13683 
13684     if (!::Evaluate(Result, Info, E))
13685       return false;
13686 
13687     if (E->isGLValue()) {
13688       LValue LV;
13689       LV.setFrom(Info.Ctx, Result);
13690       if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
13691         return false;
13692     }
13693   }
13694 
13695   // Check this core constant expression is a constant expression.
13696   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result) &&
13697          CheckMemoryLeaks(Info);
13698 }
13699 
13700 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
13701                                  const ASTContext &Ctx, bool &IsConst) {
13702   // Fast-path evaluations of integer literals, since we sometimes see files
13703   // containing vast quantities of these.
13704   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
13705     Result.Val = APValue(APSInt(L->getValue(),
13706                                 L->getType()->isUnsignedIntegerType()));
13707     IsConst = true;
13708     return true;
13709   }
13710 
13711   // This case should be rare, but we need to check it before we check on
13712   // the type below.
13713   if (Exp->getType().isNull()) {
13714     IsConst = false;
13715     return true;
13716   }
13717 
13718   // FIXME: Evaluating values of large array and record types can cause
13719   // performance problems. Only do so in C++11 for now.
13720   if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
13721                           Exp->getType()->isRecordType()) &&
13722       !Ctx.getLangOpts().CPlusPlus11) {
13723     IsConst = false;
13724     return true;
13725   }
13726   return false;
13727 }
13728 
13729 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
13730                                       Expr::SideEffectsKind SEK) {
13731   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
13732          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
13733 }
13734 
13735 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
13736                              const ASTContext &Ctx, EvalInfo &Info) {
13737   bool IsConst;
13738   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
13739     return IsConst;
13740 
13741   return EvaluateAsRValue(Info, E, Result.Val);
13742 }
13743 
13744 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
13745                           const ASTContext &Ctx,
13746                           Expr::SideEffectsKind AllowSideEffects,
13747                           EvalInfo &Info) {
13748   if (!E->getType()->isIntegralOrEnumerationType())
13749     return false;
13750 
13751   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
13752       !ExprResult.Val.isInt() ||
13753       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
13754     return false;
13755 
13756   return true;
13757 }
13758 
13759 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
13760                                  const ASTContext &Ctx,
13761                                  Expr::SideEffectsKind AllowSideEffects,
13762                                  EvalInfo &Info) {
13763   if (!E->getType()->isFixedPointType())
13764     return false;
13765 
13766   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
13767     return false;
13768 
13769   if (!ExprResult.Val.isFixedPoint() ||
13770       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
13771     return false;
13772 
13773   return true;
13774 }
13775 
13776 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
13777 /// any crazy technique (that has nothing to do with language standards) that
13778 /// we want to.  If this function returns true, it returns the folded constant
13779 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
13780 /// will be applied to the result.
13781 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
13782                             bool InConstantContext) const {
13783   assert(!isValueDependent() &&
13784          "Expression evaluator can't be called on a dependent expression.");
13785   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
13786   Info.InConstantContext = InConstantContext;
13787   return ::EvaluateAsRValue(this, Result, Ctx, Info);
13788 }
13789 
13790 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
13791                                       bool InConstantContext) const {
13792   assert(!isValueDependent() &&
13793          "Expression evaluator can't be called on a dependent expression.");
13794   EvalResult Scratch;
13795   return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
13796          HandleConversionToBool(Scratch.Val, Result);
13797 }
13798 
13799 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
13800                          SideEffectsKind AllowSideEffects,
13801                          bool InConstantContext) const {
13802   assert(!isValueDependent() &&
13803          "Expression evaluator can't be called on a dependent expression.");
13804   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
13805   Info.InConstantContext = InConstantContext;
13806   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
13807 }
13808 
13809 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
13810                                 SideEffectsKind AllowSideEffects,
13811                                 bool InConstantContext) const {
13812   assert(!isValueDependent() &&
13813          "Expression evaluator can't be called on a dependent expression.");
13814   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
13815   Info.InConstantContext = InConstantContext;
13816   return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
13817 }
13818 
13819 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
13820                            SideEffectsKind AllowSideEffects,
13821                            bool InConstantContext) const {
13822   assert(!isValueDependent() &&
13823          "Expression evaluator can't be called on a dependent expression.");
13824 
13825   if (!getType()->isRealFloatingType())
13826     return false;
13827 
13828   EvalResult ExprResult;
13829   if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
13830       !ExprResult.Val.isFloat() ||
13831       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
13832     return false;
13833 
13834   Result = ExprResult.Val.getFloat();
13835   return true;
13836 }
13837 
13838 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
13839                             bool InConstantContext) const {
13840   assert(!isValueDependent() &&
13841          "Expression evaluator can't be called on a dependent expression.");
13842 
13843   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
13844   Info.InConstantContext = InConstantContext;
13845   LValue LV;
13846   CheckedTemporaries CheckedTemps;
13847   if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
13848       Result.HasSideEffects ||
13849       !CheckLValueConstantExpression(Info, getExprLoc(),
13850                                      Ctx.getLValueReferenceType(getType()), LV,
13851                                      Expr::EvaluateForCodeGen, CheckedTemps))
13852     return false;
13853 
13854   LV.moveInto(Result.Val);
13855   return true;
13856 }
13857 
13858 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
13859                                   const ASTContext &Ctx, bool InPlace) const {
13860   assert(!isValueDependent() &&
13861          "Expression evaluator can't be called on a dependent expression.");
13862 
13863   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
13864   EvalInfo Info(Ctx, Result, EM);
13865   Info.InConstantContext = true;
13866 
13867   if (InPlace) {
13868     Info.setEvaluatingDecl(this, Result.Val);
13869     LValue LVal;
13870     LVal.set(this);
13871     if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
13872         Result.HasSideEffects)
13873       return false;
13874   } else if (!::Evaluate(Result.Val, Info, this) || Result.HasSideEffects)
13875     return false;
13876 
13877   if (!Info.discardCleanups())
13878     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
13879 
13880   return CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
13881                                  Result.Val, Usage) &&
13882          CheckMemoryLeaks(Info);
13883 }
13884 
13885 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
13886                                  const VarDecl *VD,
13887                             SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
13888   assert(!isValueDependent() &&
13889          "Expression evaluator can't be called on a dependent expression.");
13890 
13891   // FIXME: Evaluating initializers for large array and record types can cause
13892   // performance problems. Only do so in C++11 for now.
13893   if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
13894       !Ctx.getLangOpts().CPlusPlus11)
13895     return false;
13896 
13897   Expr::EvalStatus EStatus;
13898   EStatus.Diag = &Notes;
13899 
13900   EvalInfo Info(Ctx, EStatus, VD->isConstexpr()
13901                                       ? EvalInfo::EM_ConstantExpression
13902                                       : EvalInfo::EM_ConstantFold);
13903   Info.setEvaluatingDecl(VD, Value);
13904   Info.InConstantContext = true;
13905 
13906   SourceLocation DeclLoc = VD->getLocation();
13907   QualType DeclTy = VD->getType();
13908 
13909   if (Info.EnableNewConstInterp) {
13910     auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
13911     if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
13912       return false;
13913   } else {
13914     LValue LVal;
13915     LVal.set(VD);
13916 
13917     if (!EvaluateInPlace(Value, Info, LVal, this,
13918                          /*AllowNonLiteralTypes=*/true) ||
13919         EStatus.HasSideEffects)
13920       return false;
13921 
13922     // At this point, any lifetime-extended temporaries are completely
13923     // initialized.
13924     Info.performLifetimeExtension();
13925 
13926     if (!Info.discardCleanups())
13927       llvm_unreachable("Unhandled cleanup; missing full expression marker?");
13928   }
13929   return CheckConstantExpression(Info, DeclLoc, DeclTy, Value) &&
13930          CheckMemoryLeaks(Info);
13931 }
13932 
13933 bool VarDecl::evaluateDestruction(
13934     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
13935   Expr::EvalStatus EStatus;
13936   EStatus.Diag = &Notes;
13937 
13938   // Make a copy of the value for the destructor to mutate, if we know it.
13939   // Otherwise, treat the value as default-initialized; if the destructor works
13940   // anyway, then the destruction is constant (and must be essentially empty).
13941   APValue DestroyedValue =
13942       (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
13943           ? *getEvaluatedValue()
13944           : getDefaultInitValue(getType());
13945 
13946   EvalInfo Info(getASTContext(), EStatus, EvalInfo::EM_ConstantExpression);
13947   Info.setEvaluatingDecl(this, DestroyedValue,
13948                          EvalInfo::EvaluatingDeclKind::Dtor);
13949   Info.InConstantContext = true;
13950 
13951   SourceLocation DeclLoc = getLocation();
13952   QualType DeclTy = getType();
13953 
13954   LValue LVal;
13955   LVal.set(this);
13956 
13957   if (!HandleDestruction(Info, DeclLoc, LVal.Base, DestroyedValue, DeclTy) ||
13958       EStatus.HasSideEffects)
13959     return false;
13960 
13961   if (!Info.discardCleanups())
13962     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
13963 
13964   ensureEvaluatedStmt()->HasConstantDestruction = true;
13965   return true;
13966 }
13967 
13968 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
13969 /// constant folded, but discard the result.
13970 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
13971   assert(!isValueDependent() &&
13972          "Expression evaluator can't be called on a dependent expression.");
13973 
13974   EvalResult Result;
13975   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
13976          !hasUnacceptableSideEffect(Result, SEK);
13977 }
13978 
13979 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
13980                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
13981   assert(!isValueDependent() &&
13982          "Expression evaluator can't be called on a dependent expression.");
13983 
13984   EvalResult EVResult;
13985   EVResult.Diag = Diag;
13986   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
13987   Info.InConstantContext = true;
13988 
13989   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
13990   (void)Result;
13991   assert(Result && "Could not evaluate expression");
13992   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
13993 
13994   return EVResult.Val.getInt();
13995 }
13996 
13997 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
13998     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
13999   assert(!isValueDependent() &&
14000          "Expression evaluator can't be called on a dependent expression.");
14001 
14002   EvalResult EVResult;
14003   EVResult.Diag = Diag;
14004   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14005   Info.InConstantContext = true;
14006   Info.CheckingForUndefinedBehavior = true;
14007 
14008   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
14009   (void)Result;
14010   assert(Result && "Could not evaluate expression");
14011   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
14012 
14013   return EVResult.Val.getInt();
14014 }
14015 
14016 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
14017   assert(!isValueDependent() &&
14018          "Expression evaluator can't be called on a dependent expression.");
14019 
14020   bool IsConst;
14021   EvalResult EVResult;
14022   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
14023     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14024     Info.CheckingForUndefinedBehavior = true;
14025     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
14026   }
14027 }
14028 
14029 bool Expr::EvalResult::isGlobalLValue() const {
14030   assert(Val.isLValue());
14031   return IsGlobalLValue(Val.getLValueBase());
14032 }
14033 
14034 
14035 /// isIntegerConstantExpr - this recursive routine will test if an expression is
14036 /// an integer constant expression.
14037 
14038 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
14039 /// comma, etc
14040 
14041 // CheckICE - This function does the fundamental ICE checking: the returned
14042 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
14043 // and a (possibly null) SourceLocation indicating the location of the problem.
14044 //
14045 // Note that to reduce code duplication, this helper does no evaluation
14046 // itself; the caller checks whether the expression is evaluatable, and
14047 // in the rare cases where CheckICE actually cares about the evaluated
14048 // value, it calls into Evaluate.
14049 
14050 namespace {
14051 
14052 enum ICEKind {
14053   /// This expression is an ICE.
14054   IK_ICE,
14055   /// This expression is not an ICE, but if it isn't evaluated, it's
14056   /// a legal subexpression for an ICE. This return value is used to handle
14057   /// the comma operator in C99 mode, and non-constant subexpressions.
14058   IK_ICEIfUnevaluated,
14059   /// This expression is not an ICE, and is not a legal subexpression for one.
14060   IK_NotICE
14061 };
14062 
14063 struct ICEDiag {
14064   ICEKind Kind;
14065   SourceLocation Loc;
14066 
14067   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
14068 };
14069 
14070 }
14071 
14072 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
14073 
14074 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
14075 
14076 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
14077   Expr::EvalResult EVResult;
14078   Expr::EvalStatus Status;
14079   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
14080 
14081   Info.InConstantContext = true;
14082   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
14083       !EVResult.Val.isInt())
14084     return ICEDiag(IK_NotICE, E->getBeginLoc());
14085 
14086   return NoDiag();
14087 }
14088 
14089 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
14090   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
14091   if (!E->getType()->isIntegralOrEnumerationType())
14092     return ICEDiag(IK_NotICE, E->getBeginLoc());
14093 
14094   switch (E->getStmtClass()) {
14095 #define ABSTRACT_STMT(Node)
14096 #define STMT(Node, Base) case Expr::Node##Class:
14097 #define EXPR(Node, Base)
14098 #include "clang/AST/StmtNodes.inc"
14099   case Expr::PredefinedExprClass:
14100   case Expr::FloatingLiteralClass:
14101   case Expr::ImaginaryLiteralClass:
14102   case Expr::StringLiteralClass:
14103   case Expr::ArraySubscriptExprClass:
14104   case Expr::OMPArraySectionExprClass:
14105   case Expr::MemberExprClass:
14106   case Expr::CompoundAssignOperatorClass:
14107   case Expr::CompoundLiteralExprClass:
14108   case Expr::ExtVectorElementExprClass:
14109   case Expr::DesignatedInitExprClass:
14110   case Expr::ArrayInitLoopExprClass:
14111   case Expr::ArrayInitIndexExprClass:
14112   case Expr::NoInitExprClass:
14113   case Expr::DesignatedInitUpdateExprClass:
14114   case Expr::ImplicitValueInitExprClass:
14115   case Expr::ParenListExprClass:
14116   case Expr::VAArgExprClass:
14117   case Expr::AddrLabelExprClass:
14118   case Expr::StmtExprClass:
14119   case Expr::CXXMemberCallExprClass:
14120   case Expr::CUDAKernelCallExprClass:
14121   case Expr::CXXDynamicCastExprClass:
14122   case Expr::CXXTypeidExprClass:
14123   case Expr::CXXUuidofExprClass:
14124   case Expr::MSPropertyRefExprClass:
14125   case Expr::MSPropertySubscriptExprClass:
14126   case Expr::CXXNullPtrLiteralExprClass:
14127   case Expr::UserDefinedLiteralClass:
14128   case Expr::CXXThisExprClass:
14129   case Expr::CXXThrowExprClass:
14130   case Expr::CXXNewExprClass:
14131   case Expr::CXXDeleteExprClass:
14132   case Expr::CXXPseudoDestructorExprClass:
14133   case Expr::UnresolvedLookupExprClass:
14134   case Expr::TypoExprClass:
14135   case Expr::DependentScopeDeclRefExprClass:
14136   case Expr::CXXConstructExprClass:
14137   case Expr::CXXInheritedCtorInitExprClass:
14138   case Expr::CXXStdInitializerListExprClass:
14139   case Expr::CXXBindTemporaryExprClass:
14140   case Expr::ExprWithCleanupsClass:
14141   case Expr::CXXTemporaryObjectExprClass:
14142   case Expr::CXXUnresolvedConstructExprClass:
14143   case Expr::CXXDependentScopeMemberExprClass:
14144   case Expr::UnresolvedMemberExprClass:
14145   case Expr::ObjCStringLiteralClass:
14146   case Expr::ObjCBoxedExprClass:
14147   case Expr::ObjCArrayLiteralClass:
14148   case Expr::ObjCDictionaryLiteralClass:
14149   case Expr::ObjCEncodeExprClass:
14150   case Expr::ObjCMessageExprClass:
14151   case Expr::ObjCSelectorExprClass:
14152   case Expr::ObjCProtocolExprClass:
14153   case Expr::ObjCIvarRefExprClass:
14154   case Expr::ObjCPropertyRefExprClass:
14155   case Expr::ObjCSubscriptRefExprClass:
14156   case Expr::ObjCIsaExprClass:
14157   case Expr::ObjCAvailabilityCheckExprClass:
14158   case Expr::ShuffleVectorExprClass:
14159   case Expr::ConvertVectorExprClass:
14160   case Expr::BlockExprClass:
14161   case Expr::NoStmtClass:
14162   case Expr::OpaqueValueExprClass:
14163   case Expr::PackExpansionExprClass:
14164   case Expr::SubstNonTypeTemplateParmPackExprClass:
14165   case Expr::FunctionParmPackExprClass:
14166   case Expr::AsTypeExprClass:
14167   case Expr::ObjCIndirectCopyRestoreExprClass:
14168   case Expr::MaterializeTemporaryExprClass:
14169   case Expr::PseudoObjectExprClass:
14170   case Expr::AtomicExprClass:
14171   case Expr::LambdaExprClass:
14172   case Expr::CXXFoldExprClass:
14173   case Expr::CoawaitExprClass:
14174   case Expr::DependentCoawaitExprClass:
14175   case Expr::CoyieldExprClass:
14176     return ICEDiag(IK_NotICE, E->getBeginLoc());
14177 
14178   case Expr::InitListExprClass: {
14179     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
14180     // form "T x = { a };" is equivalent to "T x = a;".
14181     // Unless we're initializing a reference, T is a scalar as it is known to be
14182     // of integral or enumeration type.
14183     if (E->isRValue())
14184       if (cast<InitListExpr>(E)->getNumInits() == 1)
14185         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
14186     return ICEDiag(IK_NotICE, E->getBeginLoc());
14187   }
14188 
14189   case Expr::SizeOfPackExprClass:
14190   case Expr::GNUNullExprClass:
14191   case Expr::SourceLocExprClass:
14192     return NoDiag();
14193 
14194   case Expr::SubstNonTypeTemplateParmExprClass:
14195     return
14196       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
14197 
14198   case Expr::ConstantExprClass:
14199     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
14200 
14201   case Expr::ParenExprClass:
14202     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
14203   case Expr::GenericSelectionExprClass:
14204     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
14205   case Expr::IntegerLiteralClass:
14206   case Expr::FixedPointLiteralClass:
14207   case Expr::CharacterLiteralClass:
14208   case Expr::ObjCBoolLiteralExprClass:
14209   case Expr::CXXBoolLiteralExprClass:
14210   case Expr::CXXScalarValueInitExprClass:
14211   case Expr::TypeTraitExprClass:
14212   case Expr::ConceptSpecializationExprClass:
14213   case Expr::RequiresExprClass:
14214   case Expr::ArrayTypeTraitExprClass:
14215   case Expr::ExpressionTraitExprClass:
14216   case Expr::CXXNoexceptExprClass:
14217     return NoDiag();
14218   case Expr::CallExprClass:
14219   case Expr::CXXOperatorCallExprClass: {
14220     // C99 6.6/3 allows function calls within unevaluated subexpressions of
14221     // constant expressions, but they can never be ICEs because an ICE cannot
14222     // contain an operand of (pointer to) function type.
14223     const CallExpr *CE = cast<CallExpr>(E);
14224     if (CE->getBuiltinCallee())
14225       return CheckEvalInICE(E, Ctx);
14226     return ICEDiag(IK_NotICE, E->getBeginLoc());
14227   }
14228   case Expr::CXXRewrittenBinaryOperatorClass:
14229     return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
14230                     Ctx);
14231   case Expr::DeclRefExprClass: {
14232     if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
14233       return NoDiag();
14234     const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
14235     if (Ctx.getLangOpts().CPlusPlus &&
14236         D && IsConstNonVolatile(D->getType())) {
14237       // Parameter variables are never constants.  Without this check,
14238       // getAnyInitializer() can find a default argument, which leads
14239       // to chaos.
14240       if (isa<ParmVarDecl>(D))
14241         return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
14242 
14243       // C++ 7.1.5.1p2
14244       //   A variable of non-volatile const-qualified integral or enumeration
14245       //   type initialized by an ICE can be used in ICEs.
14246       if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
14247         if (!Dcl->getType()->isIntegralOrEnumerationType())
14248           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
14249 
14250         const VarDecl *VD;
14251         // Look for a declaration of this variable that has an initializer, and
14252         // check whether it is an ICE.
14253         if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
14254           return NoDiag();
14255         else
14256           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
14257       }
14258     }
14259     return ICEDiag(IK_NotICE, E->getBeginLoc());
14260   }
14261   case Expr::UnaryOperatorClass: {
14262     const UnaryOperator *Exp = cast<UnaryOperator>(E);
14263     switch (Exp->getOpcode()) {
14264     case UO_PostInc:
14265     case UO_PostDec:
14266     case UO_PreInc:
14267     case UO_PreDec:
14268     case UO_AddrOf:
14269     case UO_Deref:
14270     case UO_Coawait:
14271       // C99 6.6/3 allows increment and decrement within unevaluated
14272       // subexpressions of constant expressions, but they can never be ICEs
14273       // because an ICE cannot contain an lvalue operand.
14274       return ICEDiag(IK_NotICE, E->getBeginLoc());
14275     case UO_Extension:
14276     case UO_LNot:
14277     case UO_Plus:
14278     case UO_Minus:
14279     case UO_Not:
14280     case UO_Real:
14281     case UO_Imag:
14282       return CheckICE(Exp->getSubExpr(), Ctx);
14283     }
14284     llvm_unreachable("invalid unary operator class");
14285   }
14286   case Expr::OffsetOfExprClass: {
14287     // Note that per C99, offsetof must be an ICE. And AFAIK, using
14288     // EvaluateAsRValue matches the proposed gcc behavior for cases like
14289     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
14290     // compliance: we should warn earlier for offsetof expressions with
14291     // array subscripts that aren't ICEs, and if the array subscripts
14292     // are ICEs, the value of the offsetof must be an integer constant.
14293     return CheckEvalInICE(E, Ctx);
14294   }
14295   case Expr::UnaryExprOrTypeTraitExprClass: {
14296     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
14297     if ((Exp->getKind() ==  UETT_SizeOf) &&
14298         Exp->getTypeOfArgument()->isVariableArrayType())
14299       return ICEDiag(IK_NotICE, E->getBeginLoc());
14300     return NoDiag();
14301   }
14302   case Expr::BinaryOperatorClass: {
14303     const BinaryOperator *Exp = cast<BinaryOperator>(E);
14304     switch (Exp->getOpcode()) {
14305     case BO_PtrMemD:
14306     case BO_PtrMemI:
14307     case BO_Assign:
14308     case BO_MulAssign:
14309     case BO_DivAssign:
14310     case BO_RemAssign:
14311     case BO_AddAssign:
14312     case BO_SubAssign:
14313     case BO_ShlAssign:
14314     case BO_ShrAssign:
14315     case BO_AndAssign:
14316     case BO_XorAssign:
14317     case BO_OrAssign:
14318       // C99 6.6/3 allows assignments within unevaluated subexpressions of
14319       // constant expressions, but they can never be ICEs because an ICE cannot
14320       // contain an lvalue operand.
14321       return ICEDiag(IK_NotICE, E->getBeginLoc());
14322 
14323     case BO_Mul:
14324     case BO_Div:
14325     case BO_Rem:
14326     case BO_Add:
14327     case BO_Sub:
14328     case BO_Shl:
14329     case BO_Shr:
14330     case BO_LT:
14331     case BO_GT:
14332     case BO_LE:
14333     case BO_GE:
14334     case BO_EQ:
14335     case BO_NE:
14336     case BO_And:
14337     case BO_Xor:
14338     case BO_Or:
14339     case BO_Comma:
14340     case BO_Cmp: {
14341       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
14342       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
14343       if (Exp->getOpcode() == BO_Div ||
14344           Exp->getOpcode() == BO_Rem) {
14345         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
14346         // we don't evaluate one.
14347         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
14348           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
14349           if (REval == 0)
14350             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
14351           if (REval.isSigned() && REval.isAllOnesValue()) {
14352             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
14353             if (LEval.isMinSignedValue())
14354               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
14355           }
14356         }
14357       }
14358       if (Exp->getOpcode() == BO_Comma) {
14359         if (Ctx.getLangOpts().C99) {
14360           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
14361           // if it isn't evaluated.
14362           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
14363             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
14364         } else {
14365           // In both C89 and C++, commas in ICEs are illegal.
14366           return ICEDiag(IK_NotICE, E->getBeginLoc());
14367         }
14368       }
14369       return Worst(LHSResult, RHSResult);
14370     }
14371     case BO_LAnd:
14372     case BO_LOr: {
14373       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
14374       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
14375       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
14376         // Rare case where the RHS has a comma "side-effect"; we need
14377         // to actually check the condition to see whether the side
14378         // with the comma is evaluated.
14379         if ((Exp->getOpcode() == BO_LAnd) !=
14380             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
14381           return RHSResult;
14382         return NoDiag();
14383       }
14384 
14385       return Worst(LHSResult, RHSResult);
14386     }
14387     }
14388     llvm_unreachable("invalid binary operator kind");
14389   }
14390   case Expr::ImplicitCastExprClass:
14391   case Expr::CStyleCastExprClass:
14392   case Expr::CXXFunctionalCastExprClass:
14393   case Expr::CXXStaticCastExprClass:
14394   case Expr::CXXReinterpretCastExprClass:
14395   case Expr::CXXConstCastExprClass:
14396   case Expr::ObjCBridgedCastExprClass: {
14397     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
14398     if (isa<ExplicitCastExpr>(E)) {
14399       if (const FloatingLiteral *FL
14400             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
14401         unsigned DestWidth = Ctx.getIntWidth(E->getType());
14402         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
14403         APSInt IgnoredVal(DestWidth, !DestSigned);
14404         bool Ignored;
14405         // If the value does not fit in the destination type, the behavior is
14406         // undefined, so we are not required to treat it as a constant
14407         // expression.
14408         if (FL->getValue().convertToInteger(IgnoredVal,
14409                                             llvm::APFloat::rmTowardZero,
14410                                             &Ignored) & APFloat::opInvalidOp)
14411           return ICEDiag(IK_NotICE, E->getBeginLoc());
14412         return NoDiag();
14413       }
14414     }
14415     switch (cast<CastExpr>(E)->getCastKind()) {
14416     case CK_LValueToRValue:
14417     case CK_AtomicToNonAtomic:
14418     case CK_NonAtomicToAtomic:
14419     case CK_NoOp:
14420     case CK_IntegralToBoolean:
14421     case CK_IntegralCast:
14422       return CheckICE(SubExpr, Ctx);
14423     default:
14424       return ICEDiag(IK_NotICE, E->getBeginLoc());
14425     }
14426   }
14427   case Expr::BinaryConditionalOperatorClass: {
14428     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
14429     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
14430     if (CommonResult.Kind == IK_NotICE) return CommonResult;
14431     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
14432     if (FalseResult.Kind == IK_NotICE) return FalseResult;
14433     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
14434     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
14435         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
14436     return FalseResult;
14437   }
14438   case Expr::ConditionalOperatorClass: {
14439     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
14440     // If the condition (ignoring parens) is a __builtin_constant_p call,
14441     // then only the true side is actually considered in an integer constant
14442     // expression, and it is fully evaluated.  This is an important GNU
14443     // extension.  See GCC PR38377 for discussion.
14444     if (const CallExpr *CallCE
14445         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
14446       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
14447         return CheckEvalInICE(E, Ctx);
14448     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
14449     if (CondResult.Kind == IK_NotICE)
14450       return CondResult;
14451 
14452     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
14453     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
14454 
14455     if (TrueResult.Kind == IK_NotICE)
14456       return TrueResult;
14457     if (FalseResult.Kind == IK_NotICE)
14458       return FalseResult;
14459     if (CondResult.Kind == IK_ICEIfUnevaluated)
14460       return CondResult;
14461     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
14462       return NoDiag();
14463     // Rare case where the diagnostics depend on which side is evaluated
14464     // Note that if we get here, CondResult is 0, and at least one of
14465     // TrueResult and FalseResult is non-zero.
14466     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
14467       return FalseResult;
14468     return TrueResult;
14469   }
14470   case Expr::CXXDefaultArgExprClass:
14471     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
14472   case Expr::CXXDefaultInitExprClass:
14473     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
14474   case Expr::ChooseExprClass: {
14475     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
14476   }
14477   case Expr::BuiltinBitCastExprClass: {
14478     if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
14479       return ICEDiag(IK_NotICE, E->getBeginLoc());
14480     return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
14481   }
14482   }
14483 
14484   llvm_unreachable("Invalid StmtClass!");
14485 }
14486 
14487 /// Evaluate an expression as a C++11 integral constant expression.
14488 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
14489                                                     const Expr *E,
14490                                                     llvm::APSInt *Value,
14491                                                     SourceLocation *Loc) {
14492   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
14493     if (Loc) *Loc = E->getExprLoc();
14494     return false;
14495   }
14496 
14497   APValue Result;
14498   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
14499     return false;
14500 
14501   if (!Result.isInt()) {
14502     if (Loc) *Loc = E->getExprLoc();
14503     return false;
14504   }
14505 
14506   if (Value) *Value = Result.getInt();
14507   return true;
14508 }
14509 
14510 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
14511                                  SourceLocation *Loc) const {
14512   assert(!isValueDependent() &&
14513          "Expression evaluator can't be called on a dependent expression.");
14514 
14515   if (Ctx.getLangOpts().CPlusPlus11)
14516     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
14517 
14518   ICEDiag D = CheckICE(this, Ctx);
14519   if (D.Kind != IK_ICE) {
14520     if (Loc) *Loc = D.Loc;
14521     return false;
14522   }
14523   return true;
14524 }
14525 
14526 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
14527                                  SourceLocation *Loc, bool isEvaluated) const {
14528   assert(!isValueDependent() &&
14529          "Expression evaluator can't be called on a dependent expression.");
14530 
14531   if (Ctx.getLangOpts().CPlusPlus11)
14532     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
14533 
14534   if (!isIntegerConstantExpr(Ctx, Loc))
14535     return false;
14536 
14537   // The only possible side-effects here are due to UB discovered in the
14538   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
14539   // required to treat the expression as an ICE, so we produce the folded
14540   // value.
14541   EvalResult ExprResult;
14542   Expr::EvalStatus Status;
14543   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
14544   Info.InConstantContext = true;
14545 
14546   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
14547     llvm_unreachable("ICE cannot be evaluated!");
14548 
14549   Value = ExprResult.Val.getInt();
14550   return true;
14551 }
14552 
14553 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
14554   assert(!isValueDependent() &&
14555          "Expression evaluator can't be called on a dependent expression.");
14556 
14557   return CheckICE(this, Ctx).Kind == IK_ICE;
14558 }
14559 
14560 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
14561                                SourceLocation *Loc) const {
14562   assert(!isValueDependent() &&
14563          "Expression evaluator can't be called on a dependent expression.");
14564 
14565   // We support this checking in C++98 mode in order to diagnose compatibility
14566   // issues.
14567   assert(Ctx.getLangOpts().CPlusPlus);
14568 
14569   // Build evaluation settings.
14570   Expr::EvalStatus Status;
14571   SmallVector<PartialDiagnosticAt, 8> Diags;
14572   Status.Diag = &Diags;
14573   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
14574 
14575   APValue Scratch;
14576   bool IsConstExpr =
14577       ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
14578       // FIXME: We don't produce a diagnostic for this, but the callers that
14579       // call us on arbitrary full-expressions should generally not care.
14580       Info.discardCleanups() && !Status.HasSideEffects;
14581 
14582   if (!Diags.empty()) {
14583     IsConstExpr = false;
14584     if (Loc) *Loc = Diags[0].first;
14585   } else if (!IsConstExpr) {
14586     // FIXME: This shouldn't happen.
14587     if (Loc) *Loc = getExprLoc();
14588   }
14589 
14590   return IsConstExpr;
14591 }
14592 
14593 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
14594                                     const FunctionDecl *Callee,
14595                                     ArrayRef<const Expr*> Args,
14596                                     const Expr *This) const {
14597   assert(!isValueDependent() &&
14598          "Expression evaluator can't be called on a dependent expression.");
14599 
14600   Expr::EvalStatus Status;
14601   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
14602   Info.InConstantContext = true;
14603 
14604   LValue ThisVal;
14605   const LValue *ThisPtr = nullptr;
14606   if (This) {
14607 #ifndef NDEBUG
14608     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
14609     assert(MD && "Don't provide `this` for non-methods.");
14610     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
14611 #endif
14612     if (!This->isValueDependent() &&
14613         EvaluateObjectArgument(Info, This, ThisVal) &&
14614         !Info.EvalStatus.HasSideEffects)
14615       ThisPtr = &ThisVal;
14616 
14617     // Ignore any side-effects from a failed evaluation. This is safe because
14618     // they can't interfere with any other argument evaluation.
14619     Info.EvalStatus.HasSideEffects = false;
14620   }
14621 
14622   ArgVector ArgValues(Args.size());
14623   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
14624        I != E; ++I) {
14625     if ((*I)->isValueDependent() ||
14626         !Evaluate(ArgValues[I - Args.begin()], Info, *I) ||
14627         Info.EvalStatus.HasSideEffects)
14628       // If evaluation fails, throw away the argument entirely.
14629       ArgValues[I - Args.begin()] = APValue();
14630 
14631     // Ignore any side-effects from a failed evaluation. This is safe because
14632     // they can't interfere with any other argument evaluation.
14633     Info.EvalStatus.HasSideEffects = false;
14634   }
14635 
14636   // Parameter cleanups happen in the caller and are not part of this
14637   // evaluation.
14638   Info.discardCleanups();
14639   Info.EvalStatus.HasSideEffects = false;
14640 
14641   // Build fake call to Callee.
14642   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
14643                        ArgValues.data());
14644   // FIXME: Missing ExprWithCleanups in enable_if conditions?
14645   FullExpressionRAII Scope(Info);
14646   return Evaluate(Value, Info, this) && Scope.destroy() &&
14647          !Info.EvalStatus.HasSideEffects;
14648 }
14649 
14650 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
14651                                    SmallVectorImpl<
14652                                      PartialDiagnosticAt> &Diags) {
14653   // FIXME: It would be useful to check constexpr function templates, but at the
14654   // moment the constant expression evaluator cannot cope with the non-rigorous
14655   // ASTs which we build for dependent expressions.
14656   if (FD->isDependentContext())
14657     return true;
14658 
14659   Expr::EvalStatus Status;
14660   Status.Diag = &Diags;
14661 
14662   EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
14663   Info.InConstantContext = true;
14664   Info.CheckingPotentialConstantExpression = true;
14665 
14666   // The constexpr VM attempts to compile all methods to bytecode here.
14667   if (Info.EnableNewConstInterp) {
14668     Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
14669     return Diags.empty();
14670   }
14671 
14672   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
14673   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
14674 
14675   // Fabricate an arbitrary expression on the stack and pretend that it
14676   // is a temporary being used as the 'this' pointer.
14677   LValue This;
14678   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
14679   This.set({&VIE, Info.CurrentCall->Index});
14680 
14681   ArrayRef<const Expr*> Args;
14682 
14683   APValue Scratch;
14684   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
14685     // Evaluate the call as a constant initializer, to allow the construction
14686     // of objects of non-literal types.
14687     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
14688     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
14689   } else {
14690     SourceLocation Loc = FD->getLocation();
14691     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
14692                        Args, FD->getBody(), Info, Scratch, nullptr);
14693   }
14694 
14695   return Diags.empty();
14696 }
14697 
14698 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
14699                                               const FunctionDecl *FD,
14700                                               SmallVectorImpl<
14701                                                 PartialDiagnosticAt> &Diags) {
14702   assert(!E->isValueDependent() &&
14703          "Expression evaluator can't be called on a dependent expression.");
14704 
14705   Expr::EvalStatus Status;
14706   Status.Diag = &Diags;
14707 
14708   EvalInfo Info(FD->getASTContext(), Status,
14709                 EvalInfo::EM_ConstantExpressionUnevaluated);
14710   Info.InConstantContext = true;
14711   Info.CheckingPotentialConstantExpression = true;
14712 
14713   // Fabricate a call stack frame to give the arguments a plausible cover story.
14714   ArrayRef<const Expr*> Args;
14715   ArgVector ArgValues(0);
14716   bool Success = EvaluateArgs(Args, ArgValues, Info, FD);
14717   (void)Success;
14718   assert(Success &&
14719          "Failed to set up arguments for potential constant evaluation");
14720   CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
14721 
14722   APValue ResultScratch;
14723   Evaluate(ResultScratch, Info, E);
14724   return Diags.empty();
14725 }
14726 
14727 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
14728                                  unsigned Type) const {
14729   if (!getType()->isPointerType())
14730     return false;
14731 
14732   Expr::EvalStatus Status;
14733   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
14734   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
14735 }
14736