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     AfterFields,
678     Destroying,
679     DestroyingBases
680   };
681 }
682 
683 namespace llvm {
684 template<> struct DenseMapInfo<ObjectUnderConstruction> {
685   using Base = DenseMapInfo<APValue::LValueBase>;
686   static ObjectUnderConstruction getEmptyKey() {
687     return {Base::getEmptyKey(), {}}; }
688   static ObjectUnderConstruction getTombstoneKey() {
689     return {Base::getTombstoneKey(), {}};
690   }
691   static unsigned getHashValue(const ObjectUnderConstruction &Object) {
692     return hash_value(Object);
693   }
694   static bool isEqual(const ObjectUnderConstruction &LHS,
695                       const ObjectUnderConstruction &RHS) {
696     return LHS == RHS;
697   }
698 };
699 }
700 
701 namespace {
702   /// A dynamically-allocated heap object.
703   struct DynAlloc {
704     /// The value of this heap-allocated object.
705     APValue Value;
706     /// The allocating expression; used for diagnostics. Either a CXXNewExpr
707     /// or a CallExpr (the latter is for direct calls to operator new inside
708     /// std::allocator<T>::allocate).
709     const Expr *AllocExpr = nullptr;
710 
711     enum Kind {
712       New,
713       ArrayNew,
714       StdAllocator
715     };
716 
717     /// Get the kind of the allocation. This must match between allocation
718     /// and deallocation.
719     Kind getKind() const {
720       if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
721         return NE->isArray() ? ArrayNew : New;
722       assert(isa<CallExpr>(AllocExpr));
723       return StdAllocator;
724     }
725   };
726 
727   struct DynAllocOrder {
728     bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
729       return L.getIndex() < R.getIndex();
730     }
731   };
732 
733   /// EvalInfo - This is a private struct used by the evaluator to capture
734   /// information about a subexpression as it is folded.  It retains information
735   /// about the AST context, but also maintains information about the folded
736   /// expression.
737   ///
738   /// If an expression could be evaluated, it is still possible it is not a C
739   /// "integer constant expression" or constant expression.  If not, this struct
740   /// captures information about how and why not.
741   ///
742   /// One bit of information passed *into* the request for constant folding
743   /// indicates whether the subexpression is "evaluated" or not according to C
744   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
745   /// evaluate the expression regardless of what the RHS is, but C only allows
746   /// certain things in certain situations.
747   class EvalInfo : public interp::State {
748   public:
749     ASTContext &Ctx;
750 
751     /// EvalStatus - Contains information about the evaluation.
752     Expr::EvalStatus &EvalStatus;
753 
754     /// CurrentCall - The top of the constexpr call stack.
755     CallStackFrame *CurrentCall;
756 
757     /// CallStackDepth - The number of calls in the call stack right now.
758     unsigned CallStackDepth;
759 
760     /// NextCallIndex - The next call index to assign.
761     unsigned NextCallIndex;
762 
763     /// StepsLeft - The remaining number of evaluation steps we're permitted
764     /// to perform. This is essentially a limit for the number of statements
765     /// we will evaluate.
766     unsigned StepsLeft;
767 
768     /// Enable the experimental new constant interpreter. If an expression is
769     /// not supported by the interpreter, an error is triggered.
770     bool EnableNewConstInterp;
771 
772     /// BottomFrame - The frame in which evaluation started. This must be
773     /// initialized after CurrentCall and CallStackDepth.
774     CallStackFrame BottomFrame;
775 
776     /// A stack of values whose lifetimes end at the end of some surrounding
777     /// evaluation frame.
778     llvm::SmallVector<Cleanup, 16> CleanupStack;
779 
780     /// EvaluatingDecl - This is the declaration whose initializer is being
781     /// evaluated, if any.
782     APValue::LValueBase EvaluatingDecl;
783 
784     enum class EvaluatingDeclKind {
785       None,
786       /// We're evaluating the construction of EvaluatingDecl.
787       Ctor,
788       /// We're evaluating the destruction of EvaluatingDecl.
789       Dtor,
790     };
791     EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
792 
793     /// EvaluatingDeclValue - This is the value being constructed for the
794     /// declaration whose initializer is being evaluated, if any.
795     APValue *EvaluatingDeclValue;
796 
797     /// Set of objects that are currently being constructed.
798     llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
799         ObjectsUnderConstruction;
800 
801     /// Current heap allocations, along with the location where each was
802     /// allocated. We use std::map here because we need stable addresses
803     /// for the stored APValues.
804     std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
805 
806     /// The number of heap allocations performed so far in this evaluation.
807     unsigned NumHeapAllocs = 0;
808 
809     struct EvaluatingConstructorRAII {
810       EvalInfo &EI;
811       ObjectUnderConstruction Object;
812       bool DidInsert;
813       EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
814                                 bool HasBases)
815           : EI(EI), Object(Object) {
816         DidInsert =
817             EI.ObjectsUnderConstruction
818                 .insert({Object, HasBases ? ConstructionPhase::Bases
819                                           : ConstructionPhase::AfterBases})
820                 .second;
821       }
822       void finishedConstructingBases() {
823         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
824       }
825       void finishedConstructingFields() {
826         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
827       }
828       ~EvaluatingConstructorRAII() {
829         if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
830       }
831     };
832 
833     struct EvaluatingDestructorRAII {
834       EvalInfo &EI;
835       ObjectUnderConstruction Object;
836       bool DidInsert;
837       EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
838           : EI(EI), Object(Object) {
839         DidInsert = EI.ObjectsUnderConstruction
840                         .insert({Object, ConstructionPhase::Destroying})
841                         .second;
842       }
843       void startedDestroyingBases() {
844         EI.ObjectsUnderConstruction[Object] =
845             ConstructionPhase::DestroyingBases;
846       }
847       ~EvaluatingDestructorRAII() {
848         if (DidInsert)
849           EI.ObjectsUnderConstruction.erase(Object);
850       }
851     };
852 
853     ConstructionPhase
854     isEvaluatingCtorDtor(APValue::LValueBase Base,
855                          ArrayRef<APValue::LValuePathEntry> Path) {
856       return ObjectsUnderConstruction.lookup({Base, Path});
857     }
858 
859     /// If we're currently speculatively evaluating, the outermost call stack
860     /// depth at which we can mutate state, otherwise 0.
861     unsigned SpeculativeEvaluationDepth = 0;
862 
863     /// The current array initialization index, if we're performing array
864     /// initialization.
865     uint64_t ArrayInitIndex = -1;
866 
867     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
868     /// notes attached to it will also be stored, otherwise they will not be.
869     bool HasActiveDiagnostic;
870 
871     /// Have we emitted a diagnostic explaining why we couldn't constant
872     /// fold (not just why it's not strictly a constant expression)?
873     bool HasFoldFailureDiagnostic;
874 
875     /// Whether or not we're in a context where the front end requires a
876     /// constant value.
877     bool InConstantContext;
878 
879     /// Whether we're checking that an expression is a potential constant
880     /// expression. If so, do not fail on constructs that could become constant
881     /// later on (such as a use of an undefined global).
882     bool CheckingPotentialConstantExpression = false;
883 
884     /// Whether we're checking for an expression that has undefined behavior.
885     /// If so, we will produce warnings if we encounter an operation that is
886     /// always undefined.
887     bool CheckingForUndefinedBehavior = false;
888 
889     enum EvaluationMode {
890       /// Evaluate as a constant expression. Stop if we find that the expression
891       /// is not a constant expression.
892       EM_ConstantExpression,
893 
894       /// Evaluate as a constant expression. Stop if we find that the expression
895       /// is not a constant expression. Some expressions can be retried in the
896       /// optimizer if we don't constant fold them here, but in an unevaluated
897       /// context we try to fold them immediately since the optimizer never
898       /// gets a chance to look at it.
899       EM_ConstantExpressionUnevaluated,
900 
901       /// Fold the expression to a constant. Stop if we hit a side-effect that
902       /// we can't model.
903       EM_ConstantFold,
904 
905       /// Evaluate in any way we know how. Don't worry about side-effects that
906       /// can't be modeled.
907       EM_IgnoreSideEffects,
908     } EvalMode;
909 
910     /// Are we checking whether the expression is a potential constant
911     /// expression?
912     bool checkingPotentialConstantExpression() const override  {
913       return CheckingPotentialConstantExpression;
914     }
915 
916     /// Are we checking an expression for overflow?
917     // FIXME: We should check for any kind of undefined or suspicious behavior
918     // in such constructs, not just overflow.
919     bool checkingForUndefinedBehavior() const override {
920       return CheckingForUndefinedBehavior;
921     }
922 
923     EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
924         : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
925           CallStackDepth(0), NextCallIndex(1),
926           StepsLeft(C.getLangOpts().ConstexprStepLimit),
927           EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
928           BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
929           EvaluatingDecl((const ValueDecl *)nullptr),
930           EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
931           HasFoldFailureDiagnostic(false), InConstantContext(false),
932           EvalMode(Mode) {}
933 
934     ~EvalInfo() {
935       discardCleanups();
936     }
937 
938     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
939                            EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
940       EvaluatingDecl = Base;
941       IsEvaluatingDecl = EDK;
942       EvaluatingDeclValue = &Value;
943     }
944 
945     bool CheckCallLimit(SourceLocation Loc) {
946       // Don't perform any constexpr calls (other than the call we're checking)
947       // when checking a potential constant expression.
948       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
949         return false;
950       if (NextCallIndex == 0) {
951         // NextCallIndex has wrapped around.
952         FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
953         return false;
954       }
955       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
956         return true;
957       FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
958         << getLangOpts().ConstexprCallDepth;
959       return false;
960     }
961 
962     std::pair<CallStackFrame *, unsigned>
963     getCallFrameAndDepth(unsigned CallIndex) {
964       assert(CallIndex && "no call index in getCallFrameAndDepth");
965       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
966       // be null in this loop.
967       unsigned Depth = CallStackDepth;
968       CallStackFrame *Frame = CurrentCall;
969       while (Frame->Index > CallIndex) {
970         Frame = Frame->Caller;
971         --Depth;
972       }
973       if (Frame->Index == CallIndex)
974         return {Frame, Depth};
975       return {nullptr, 0};
976     }
977 
978     bool nextStep(const Stmt *S) {
979       if (!StepsLeft) {
980         FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
981         return false;
982       }
983       --StepsLeft;
984       return true;
985     }
986 
987     APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
988 
989     Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) {
990       Optional<DynAlloc*> Result;
991       auto It = HeapAllocs.find(DA);
992       if (It != HeapAllocs.end())
993         Result = &It->second;
994       return Result;
995     }
996 
997     /// Information about a stack frame for std::allocator<T>::[de]allocate.
998     struct StdAllocatorCaller {
999       unsigned FrameIndex;
1000       QualType ElemType;
1001       explicit operator bool() const { return FrameIndex != 0; };
1002     };
1003 
1004     StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1005       for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1006            Call = Call->Caller) {
1007         const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1008         if (!MD)
1009           continue;
1010         const IdentifierInfo *FnII = MD->getIdentifier();
1011         if (!FnII || !FnII->isStr(FnName))
1012           continue;
1013 
1014         const auto *CTSD =
1015             dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1016         if (!CTSD)
1017           continue;
1018 
1019         const IdentifierInfo *ClassII = CTSD->getIdentifier();
1020         const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1021         if (CTSD->isInStdNamespace() && ClassII &&
1022             ClassII->isStr("allocator") && TAL.size() >= 1 &&
1023             TAL[0].getKind() == TemplateArgument::Type)
1024           return {Call->Index, TAL[0].getAsType()};
1025       }
1026 
1027       return {};
1028     }
1029 
1030     void performLifetimeExtension() {
1031       // Disable the cleanups for lifetime-extended temporaries.
1032       CleanupStack.erase(
1033           std::remove_if(CleanupStack.begin(), CleanupStack.end(),
1034                          [](Cleanup &C) { return C.isLifetimeExtended(); }),
1035           CleanupStack.end());
1036      }
1037 
1038     /// Throw away any remaining cleanups at the end of evaluation. If any
1039     /// cleanups would have had a side-effect, note that as an unmodeled
1040     /// side-effect and return false. Otherwise, return true.
1041     bool discardCleanups() {
1042       for (Cleanup &C : CleanupStack) {
1043         if (C.hasSideEffect() && !noteSideEffect()) {
1044           CleanupStack.clear();
1045           return false;
1046         }
1047       }
1048       CleanupStack.clear();
1049       return true;
1050     }
1051 
1052   private:
1053     interp::Frame *getCurrentFrame() override { return CurrentCall; }
1054     const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1055 
1056     bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1057     void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1058 
1059     void setFoldFailureDiagnostic(bool Flag) override {
1060       HasFoldFailureDiagnostic = Flag;
1061     }
1062 
1063     Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1064 
1065     ASTContext &getCtx() const override { return Ctx; }
1066 
1067     // If we have a prior diagnostic, it will be noting that the expression
1068     // isn't a constant expression. This diagnostic is more important,
1069     // unless we require this evaluation to produce a constant expression.
1070     //
1071     // FIXME: We might want to show both diagnostics to the user in
1072     // EM_ConstantFold mode.
1073     bool hasPriorDiagnostic() override {
1074       if (!EvalStatus.Diag->empty()) {
1075         switch (EvalMode) {
1076         case EM_ConstantFold:
1077         case EM_IgnoreSideEffects:
1078           if (!HasFoldFailureDiagnostic)
1079             break;
1080           // We've already failed to fold something. Keep that diagnostic.
1081           LLVM_FALLTHROUGH;
1082         case EM_ConstantExpression:
1083         case EM_ConstantExpressionUnevaluated:
1084           setActiveDiagnostic(false);
1085           return true;
1086         }
1087       }
1088       return false;
1089     }
1090 
1091     unsigned getCallStackDepth() override { return CallStackDepth; }
1092 
1093   public:
1094     /// Should we continue evaluation after encountering a side-effect that we
1095     /// couldn't model?
1096     bool keepEvaluatingAfterSideEffect() {
1097       switch (EvalMode) {
1098       case EM_IgnoreSideEffects:
1099         return true;
1100 
1101       case EM_ConstantExpression:
1102       case EM_ConstantExpressionUnevaluated:
1103       case EM_ConstantFold:
1104         // By default, assume any side effect might be valid in some other
1105         // evaluation of this expression from a different context.
1106         return checkingPotentialConstantExpression() ||
1107                checkingForUndefinedBehavior();
1108       }
1109       llvm_unreachable("Missed EvalMode case");
1110     }
1111 
1112     /// Note that we have had a side-effect, and determine whether we should
1113     /// keep evaluating.
1114     bool noteSideEffect() {
1115       EvalStatus.HasSideEffects = true;
1116       return keepEvaluatingAfterSideEffect();
1117     }
1118 
1119     /// Should we continue evaluation after encountering undefined behavior?
1120     bool keepEvaluatingAfterUndefinedBehavior() {
1121       switch (EvalMode) {
1122       case EM_IgnoreSideEffects:
1123       case EM_ConstantFold:
1124         return true;
1125 
1126       case EM_ConstantExpression:
1127       case EM_ConstantExpressionUnevaluated:
1128         return checkingForUndefinedBehavior();
1129       }
1130       llvm_unreachable("Missed EvalMode case");
1131     }
1132 
1133     /// Note that we hit something that was technically undefined behavior, but
1134     /// that we can evaluate past it (such as signed overflow or floating-point
1135     /// division by zero.)
1136     bool noteUndefinedBehavior() override {
1137       EvalStatus.HasUndefinedBehavior = true;
1138       return keepEvaluatingAfterUndefinedBehavior();
1139     }
1140 
1141     /// Should we continue evaluation as much as possible after encountering a
1142     /// construct which can't be reduced to a value?
1143     bool keepEvaluatingAfterFailure() const override {
1144       if (!StepsLeft)
1145         return false;
1146 
1147       switch (EvalMode) {
1148       case EM_ConstantExpression:
1149       case EM_ConstantExpressionUnevaluated:
1150       case EM_ConstantFold:
1151       case EM_IgnoreSideEffects:
1152         return checkingPotentialConstantExpression() ||
1153                checkingForUndefinedBehavior();
1154       }
1155       llvm_unreachable("Missed EvalMode case");
1156     }
1157 
1158     /// Notes that we failed to evaluate an expression that other expressions
1159     /// directly depend on, and determine if we should keep evaluating. This
1160     /// should only be called if we actually intend to keep evaluating.
1161     ///
1162     /// Call noteSideEffect() instead if we may be able to ignore the value that
1163     /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1164     ///
1165     /// (Foo(), 1)      // use noteSideEffect
1166     /// (Foo() || true) // use noteSideEffect
1167     /// Foo() + 1       // use noteFailure
1168     LLVM_NODISCARD bool noteFailure() {
1169       // Failure when evaluating some expression often means there is some
1170       // subexpression whose evaluation was skipped. Therefore, (because we
1171       // don't track whether we skipped an expression when unwinding after an
1172       // evaluation failure) every evaluation failure that bubbles up from a
1173       // subexpression implies that a side-effect has potentially happened. We
1174       // skip setting the HasSideEffects flag to true until we decide to
1175       // continue evaluating after that point, which happens here.
1176       bool KeepGoing = keepEvaluatingAfterFailure();
1177       EvalStatus.HasSideEffects |= KeepGoing;
1178       return KeepGoing;
1179     }
1180 
1181     class ArrayInitLoopIndex {
1182       EvalInfo &Info;
1183       uint64_t OuterIndex;
1184 
1185     public:
1186       ArrayInitLoopIndex(EvalInfo &Info)
1187           : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1188         Info.ArrayInitIndex = 0;
1189       }
1190       ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1191 
1192       operator uint64_t&() { return Info.ArrayInitIndex; }
1193     };
1194   };
1195 
1196   /// Object used to treat all foldable expressions as constant expressions.
1197   struct FoldConstant {
1198     EvalInfo &Info;
1199     bool Enabled;
1200     bool HadNoPriorDiags;
1201     EvalInfo::EvaluationMode OldMode;
1202 
1203     explicit FoldConstant(EvalInfo &Info, bool Enabled)
1204       : Info(Info),
1205         Enabled(Enabled),
1206         HadNoPriorDiags(Info.EvalStatus.Diag &&
1207                         Info.EvalStatus.Diag->empty() &&
1208                         !Info.EvalStatus.HasSideEffects),
1209         OldMode(Info.EvalMode) {
1210       if (Enabled)
1211         Info.EvalMode = EvalInfo::EM_ConstantFold;
1212     }
1213     void keepDiagnostics() { Enabled = false; }
1214     ~FoldConstant() {
1215       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1216           !Info.EvalStatus.HasSideEffects)
1217         Info.EvalStatus.Diag->clear();
1218       Info.EvalMode = OldMode;
1219     }
1220   };
1221 
1222   /// RAII object used to set the current evaluation mode to ignore
1223   /// side-effects.
1224   struct IgnoreSideEffectsRAII {
1225     EvalInfo &Info;
1226     EvalInfo::EvaluationMode OldMode;
1227     explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1228         : Info(Info), OldMode(Info.EvalMode) {
1229       Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1230     }
1231 
1232     ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1233   };
1234 
1235   /// RAII object used to optionally suppress diagnostics and side-effects from
1236   /// a speculative evaluation.
1237   class SpeculativeEvaluationRAII {
1238     EvalInfo *Info = nullptr;
1239     Expr::EvalStatus OldStatus;
1240     unsigned OldSpeculativeEvaluationDepth;
1241 
1242     void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1243       Info = Other.Info;
1244       OldStatus = Other.OldStatus;
1245       OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1246       Other.Info = nullptr;
1247     }
1248 
1249     void maybeRestoreState() {
1250       if (!Info)
1251         return;
1252 
1253       Info->EvalStatus = OldStatus;
1254       Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1255     }
1256 
1257   public:
1258     SpeculativeEvaluationRAII() = default;
1259 
1260     SpeculativeEvaluationRAII(
1261         EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1262         : Info(&Info), OldStatus(Info.EvalStatus),
1263           OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1264       Info.EvalStatus.Diag = NewDiag;
1265       Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1266     }
1267 
1268     SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1269     SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1270       moveFromAndCancel(std::move(Other));
1271     }
1272 
1273     SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1274       maybeRestoreState();
1275       moveFromAndCancel(std::move(Other));
1276       return *this;
1277     }
1278 
1279     ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1280   };
1281 
1282   /// RAII object wrapping a full-expression or block scope, and handling
1283   /// the ending of the lifetime of temporaries created within it.
1284   template<bool IsFullExpression>
1285   class ScopeRAII {
1286     EvalInfo &Info;
1287     unsigned OldStackSize;
1288   public:
1289     ScopeRAII(EvalInfo &Info)
1290         : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1291       // Push a new temporary version. This is needed to distinguish between
1292       // temporaries created in different iterations of a loop.
1293       Info.CurrentCall->pushTempVersion();
1294     }
1295     bool destroy(bool RunDestructors = true) {
1296       bool OK = cleanup(Info, RunDestructors, OldStackSize);
1297       OldStackSize = -1U;
1298       return OK;
1299     }
1300     ~ScopeRAII() {
1301       if (OldStackSize != -1U)
1302         destroy(false);
1303       // Body moved to a static method to encourage the compiler to inline away
1304       // instances of this class.
1305       Info.CurrentCall->popTempVersion();
1306     }
1307   private:
1308     static bool cleanup(EvalInfo &Info, bool RunDestructors,
1309                         unsigned OldStackSize) {
1310       assert(OldStackSize <= Info.CleanupStack.size() &&
1311              "running cleanups out of order?");
1312 
1313       // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1314       // for a full-expression scope.
1315       bool Success = true;
1316       for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1317         if (!(IsFullExpression &&
1318               Info.CleanupStack[I - 1].isLifetimeExtended())) {
1319           if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1320             Success = false;
1321             break;
1322           }
1323         }
1324       }
1325 
1326       // Compact lifetime-extended cleanups.
1327       auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1328       if (IsFullExpression)
1329         NewEnd =
1330             std::remove_if(NewEnd, Info.CleanupStack.end(),
1331                            [](Cleanup &C) { return !C.isLifetimeExtended(); });
1332       Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1333       return Success;
1334     }
1335   };
1336   typedef ScopeRAII<false> BlockScopeRAII;
1337   typedef ScopeRAII<true> FullExpressionRAII;
1338 }
1339 
1340 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1341                                          CheckSubobjectKind CSK) {
1342   if (Invalid)
1343     return false;
1344   if (isOnePastTheEnd()) {
1345     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1346       << CSK;
1347     setInvalid();
1348     return false;
1349   }
1350   // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1351   // must actually be at least one array element; even a VLA cannot have a
1352   // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1353   return true;
1354 }
1355 
1356 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1357                                                                 const Expr *E) {
1358   Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1359   // Do not set the designator as invalid: we can represent this situation,
1360   // and correct handling of __builtin_object_size requires us to do so.
1361 }
1362 
1363 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1364                                                     const Expr *E,
1365                                                     const APSInt &N) {
1366   // If we're complaining, we must be able to statically determine the size of
1367   // the most derived array.
1368   if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1369     Info.CCEDiag(E, diag::note_constexpr_array_index)
1370       << N << /*array*/ 0
1371       << static_cast<unsigned>(getMostDerivedArraySize());
1372   else
1373     Info.CCEDiag(E, diag::note_constexpr_array_index)
1374       << N << /*non-array*/ 1;
1375   setInvalid();
1376 }
1377 
1378 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1379                                const FunctionDecl *Callee, const LValue *This,
1380                                APValue *Arguments)
1381     : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1382       Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1383   Info.CurrentCall = this;
1384   ++Info.CallStackDepth;
1385 }
1386 
1387 CallStackFrame::~CallStackFrame() {
1388   assert(Info.CurrentCall == this && "calls retired out of order");
1389   --Info.CallStackDepth;
1390   Info.CurrentCall = Caller;
1391 }
1392 
1393 static bool isRead(AccessKinds AK) {
1394   return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1395 }
1396 
1397 static bool isModification(AccessKinds AK) {
1398   switch (AK) {
1399   case AK_Read:
1400   case AK_ReadObjectRepresentation:
1401   case AK_MemberCall:
1402   case AK_DynamicCast:
1403   case AK_TypeId:
1404     return false;
1405   case AK_Assign:
1406   case AK_Increment:
1407   case AK_Decrement:
1408   case AK_Construct:
1409   case AK_Destroy:
1410     return true;
1411   }
1412   llvm_unreachable("unknown access kind");
1413 }
1414 
1415 static bool isAnyAccess(AccessKinds AK) {
1416   return isRead(AK) || isModification(AK);
1417 }
1418 
1419 /// Is this an access per the C++ definition?
1420 static bool isFormalAccess(AccessKinds AK) {
1421   return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
1422 }
1423 
1424 /// Is this kind of axcess valid on an indeterminate object value?
1425 static bool isValidIndeterminateAccess(AccessKinds AK) {
1426   switch (AK) {
1427   case AK_Read:
1428   case AK_Increment:
1429   case AK_Decrement:
1430     // These need the object's value.
1431     return false;
1432 
1433   case AK_ReadObjectRepresentation:
1434   case AK_Assign:
1435   case AK_Construct:
1436   case AK_Destroy:
1437     // Construction and destruction don't need the value.
1438     return true;
1439 
1440   case AK_MemberCall:
1441   case AK_DynamicCast:
1442   case AK_TypeId:
1443     // These aren't really meaningful on scalars.
1444     return true;
1445   }
1446   llvm_unreachable("unknown access kind");
1447 }
1448 
1449 namespace {
1450   struct ComplexValue {
1451   private:
1452     bool IsInt;
1453 
1454   public:
1455     APSInt IntReal, IntImag;
1456     APFloat FloatReal, FloatImag;
1457 
1458     ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1459 
1460     void makeComplexFloat() { IsInt = false; }
1461     bool isComplexFloat() const { return !IsInt; }
1462     APFloat &getComplexFloatReal() { return FloatReal; }
1463     APFloat &getComplexFloatImag() { return FloatImag; }
1464 
1465     void makeComplexInt() { IsInt = true; }
1466     bool isComplexInt() const { return IsInt; }
1467     APSInt &getComplexIntReal() { return IntReal; }
1468     APSInt &getComplexIntImag() { return IntImag; }
1469 
1470     void moveInto(APValue &v) const {
1471       if (isComplexFloat())
1472         v = APValue(FloatReal, FloatImag);
1473       else
1474         v = APValue(IntReal, IntImag);
1475     }
1476     void setFrom(const APValue &v) {
1477       assert(v.isComplexFloat() || v.isComplexInt());
1478       if (v.isComplexFloat()) {
1479         makeComplexFloat();
1480         FloatReal = v.getComplexFloatReal();
1481         FloatImag = v.getComplexFloatImag();
1482       } else {
1483         makeComplexInt();
1484         IntReal = v.getComplexIntReal();
1485         IntImag = v.getComplexIntImag();
1486       }
1487     }
1488   };
1489 
1490   struct LValue {
1491     APValue::LValueBase Base;
1492     CharUnits Offset;
1493     SubobjectDesignator Designator;
1494     bool IsNullPtr : 1;
1495     bool InvalidBase : 1;
1496 
1497     const APValue::LValueBase getLValueBase() const { return Base; }
1498     CharUnits &getLValueOffset() { return Offset; }
1499     const CharUnits &getLValueOffset() const { return Offset; }
1500     SubobjectDesignator &getLValueDesignator() { return Designator; }
1501     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1502     bool isNullPointer() const { return IsNullPtr;}
1503 
1504     unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1505     unsigned getLValueVersion() const { return Base.getVersion(); }
1506 
1507     void moveInto(APValue &V) const {
1508       if (Designator.Invalid)
1509         V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1510       else {
1511         assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1512         V = APValue(Base, Offset, Designator.Entries,
1513                     Designator.IsOnePastTheEnd, IsNullPtr);
1514       }
1515     }
1516     void setFrom(ASTContext &Ctx, const APValue &V) {
1517       assert(V.isLValue() && "Setting LValue from a non-LValue?");
1518       Base = V.getLValueBase();
1519       Offset = V.getLValueOffset();
1520       InvalidBase = false;
1521       Designator = SubobjectDesignator(Ctx, V);
1522       IsNullPtr = V.isNullPointer();
1523     }
1524 
1525     void set(APValue::LValueBase B, bool BInvalid = false) {
1526 #ifndef NDEBUG
1527       // We only allow a few types of invalid bases. Enforce that here.
1528       if (BInvalid) {
1529         const auto *E = B.get<const Expr *>();
1530         assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1531                "Unexpected type of invalid base");
1532       }
1533 #endif
1534 
1535       Base = B;
1536       Offset = CharUnits::fromQuantity(0);
1537       InvalidBase = BInvalid;
1538       Designator = SubobjectDesignator(getType(B));
1539       IsNullPtr = false;
1540     }
1541 
1542     void setNull(ASTContext &Ctx, QualType PointerTy) {
1543       Base = (Expr *)nullptr;
1544       Offset =
1545           CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
1546       InvalidBase = false;
1547       Designator = SubobjectDesignator(PointerTy->getPointeeType());
1548       IsNullPtr = true;
1549     }
1550 
1551     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1552       set(B, true);
1553     }
1554 
1555     std::string toString(ASTContext &Ctx, QualType T) const {
1556       APValue Printable;
1557       moveInto(Printable);
1558       return Printable.getAsString(Ctx, T);
1559     }
1560 
1561   private:
1562     // Check that this LValue is not based on a null pointer. If it is, produce
1563     // a diagnostic and mark the designator as invalid.
1564     template <typename GenDiagType>
1565     bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1566       if (Designator.Invalid)
1567         return false;
1568       if (IsNullPtr) {
1569         GenDiag();
1570         Designator.setInvalid();
1571         return false;
1572       }
1573       return true;
1574     }
1575 
1576   public:
1577     bool checkNullPointer(EvalInfo &Info, const Expr *E,
1578                           CheckSubobjectKind CSK) {
1579       return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1580         Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1581       });
1582     }
1583 
1584     bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1585                                        AccessKinds AK) {
1586       return checkNullPointerDiagnosingWith([&Info, E, AK] {
1587         Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1588       });
1589     }
1590 
1591     // Check this LValue refers to an object. If not, set the designator to be
1592     // invalid and emit a diagnostic.
1593     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1594       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1595              Designator.checkSubobject(Info, E, CSK);
1596     }
1597 
1598     void addDecl(EvalInfo &Info, const Expr *E,
1599                  const Decl *D, bool Virtual = false) {
1600       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1601         Designator.addDeclUnchecked(D, Virtual);
1602     }
1603     void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1604       if (!Designator.Entries.empty()) {
1605         Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1606         Designator.setInvalid();
1607         return;
1608       }
1609       if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1610         assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1611         Designator.FirstEntryIsAnUnsizedArray = true;
1612         Designator.addUnsizedArrayUnchecked(ElemTy);
1613       }
1614     }
1615     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1616       if (checkSubobject(Info, E, CSK_ArrayToPointer))
1617         Designator.addArrayUnchecked(CAT);
1618     }
1619     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1620       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1621         Designator.addComplexUnchecked(EltTy, Imag);
1622     }
1623     void clearIsNullPointer() {
1624       IsNullPtr = false;
1625     }
1626     void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1627                               const APSInt &Index, CharUnits ElementSize) {
1628       // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1629       // but we're not required to diagnose it and it's valid in C++.)
1630       if (!Index)
1631         return;
1632 
1633       // Compute the new offset in the appropriate width, wrapping at 64 bits.
1634       // FIXME: When compiling for a 32-bit target, we should use 32-bit
1635       // offsets.
1636       uint64_t Offset64 = Offset.getQuantity();
1637       uint64_t ElemSize64 = ElementSize.getQuantity();
1638       uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1639       Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1640 
1641       if (checkNullPointer(Info, E, CSK_ArrayIndex))
1642         Designator.adjustIndex(Info, E, Index);
1643       clearIsNullPointer();
1644     }
1645     void adjustOffset(CharUnits N) {
1646       Offset += N;
1647       if (N.getQuantity())
1648         clearIsNullPointer();
1649     }
1650   };
1651 
1652   struct MemberPtr {
1653     MemberPtr() {}
1654     explicit MemberPtr(const ValueDecl *Decl) :
1655       DeclAndIsDerivedMember(Decl, false), Path() {}
1656 
1657     /// The member or (direct or indirect) field referred to by this member
1658     /// pointer, or 0 if this is a null member pointer.
1659     const ValueDecl *getDecl() const {
1660       return DeclAndIsDerivedMember.getPointer();
1661     }
1662     /// Is this actually a member of some type derived from the relevant class?
1663     bool isDerivedMember() const {
1664       return DeclAndIsDerivedMember.getInt();
1665     }
1666     /// Get the class which the declaration actually lives in.
1667     const CXXRecordDecl *getContainingRecord() const {
1668       return cast<CXXRecordDecl>(
1669           DeclAndIsDerivedMember.getPointer()->getDeclContext());
1670     }
1671 
1672     void moveInto(APValue &V) const {
1673       V = APValue(getDecl(), isDerivedMember(), Path);
1674     }
1675     void setFrom(const APValue &V) {
1676       assert(V.isMemberPointer());
1677       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1678       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1679       Path.clear();
1680       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1681       Path.insert(Path.end(), P.begin(), P.end());
1682     }
1683 
1684     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1685     /// whether the member is a member of some class derived from the class type
1686     /// of the member pointer.
1687     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1688     /// Path - The path of base/derived classes from the member declaration's
1689     /// class (exclusive) to the class type of the member pointer (inclusive).
1690     SmallVector<const CXXRecordDecl*, 4> Path;
1691 
1692     /// Perform a cast towards the class of the Decl (either up or down the
1693     /// hierarchy).
1694     bool castBack(const CXXRecordDecl *Class) {
1695       assert(!Path.empty());
1696       const CXXRecordDecl *Expected;
1697       if (Path.size() >= 2)
1698         Expected = Path[Path.size() - 2];
1699       else
1700         Expected = getContainingRecord();
1701       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1702         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1703         // if B does not contain the original member and is not a base or
1704         // derived class of the class containing the original member, the result
1705         // of the cast is undefined.
1706         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1707         // (D::*). We consider that to be a language defect.
1708         return false;
1709       }
1710       Path.pop_back();
1711       return true;
1712     }
1713     /// Perform a base-to-derived member pointer cast.
1714     bool castToDerived(const CXXRecordDecl *Derived) {
1715       if (!getDecl())
1716         return true;
1717       if (!isDerivedMember()) {
1718         Path.push_back(Derived);
1719         return true;
1720       }
1721       if (!castBack(Derived))
1722         return false;
1723       if (Path.empty())
1724         DeclAndIsDerivedMember.setInt(false);
1725       return true;
1726     }
1727     /// Perform a derived-to-base member pointer cast.
1728     bool castToBase(const CXXRecordDecl *Base) {
1729       if (!getDecl())
1730         return true;
1731       if (Path.empty())
1732         DeclAndIsDerivedMember.setInt(true);
1733       if (isDerivedMember()) {
1734         Path.push_back(Base);
1735         return true;
1736       }
1737       return castBack(Base);
1738     }
1739   };
1740 
1741   /// Compare two member pointers, which are assumed to be of the same type.
1742   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1743     if (!LHS.getDecl() || !RHS.getDecl())
1744       return !LHS.getDecl() && !RHS.getDecl();
1745     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1746       return false;
1747     return LHS.Path == RHS.Path;
1748   }
1749 }
1750 
1751 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1752 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1753                             const LValue &This, const Expr *E,
1754                             bool AllowNonLiteralTypes = false);
1755 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1756                            bool InvalidBaseOK = false);
1757 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1758                             bool InvalidBaseOK = false);
1759 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1760                                   EvalInfo &Info);
1761 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1762 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1763 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1764                                     EvalInfo &Info);
1765 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1766 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1767 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1768                            EvalInfo &Info);
1769 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1770 
1771 /// Evaluate an integer or fixed point expression into an APResult.
1772 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1773                                         EvalInfo &Info);
1774 
1775 /// Evaluate only a fixed point expression into an APResult.
1776 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1777                                EvalInfo &Info);
1778 
1779 //===----------------------------------------------------------------------===//
1780 // Misc utilities
1781 //===----------------------------------------------------------------------===//
1782 
1783 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1784 /// preserving its value (by extending by up to one bit as needed).
1785 static void negateAsSigned(APSInt &Int) {
1786   if (Int.isUnsigned() || Int.isMinSignedValue()) {
1787     Int = Int.extend(Int.getBitWidth() + 1);
1788     Int.setIsSigned(true);
1789   }
1790   Int = -Int;
1791 }
1792 
1793 template<typename KeyT>
1794 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1795                                          bool IsLifetimeExtended, LValue &LV) {
1796   unsigned Version = getTempVersion();
1797   APValue::LValueBase Base(Key, Index, Version);
1798   LV.set(Base);
1799   APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1800   assert(Result.isAbsent() && "temporary created multiple times");
1801 
1802   // If we're creating a temporary immediately in the operand of a speculative
1803   // evaluation, don't register a cleanup to be run outside the speculative
1804   // evaluation context, since we won't actually be able to initialize this
1805   // object.
1806   if (Index <= Info.SpeculativeEvaluationDepth) {
1807     if (T.isDestructedType())
1808       Info.noteSideEffect();
1809   } else {
1810     Info.CleanupStack.push_back(Cleanup(&Result, Base, T, IsLifetimeExtended));
1811   }
1812   return Result;
1813 }
1814 
1815 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1816   if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1817     FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1818     return nullptr;
1819   }
1820 
1821   DynamicAllocLValue DA(NumHeapAllocs++);
1822   LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1823   auto Result = HeapAllocs.emplace(std::piecewise_construct,
1824                                    std::forward_as_tuple(DA), std::tuple<>());
1825   assert(Result.second && "reused a heap alloc index?");
1826   Result.first->second.AllocExpr = E;
1827   return &Result.first->second.Value;
1828 }
1829 
1830 /// Produce a string describing the given constexpr call.
1831 void CallStackFrame::describe(raw_ostream &Out) {
1832   unsigned ArgIndex = 0;
1833   bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1834                       !isa<CXXConstructorDecl>(Callee) &&
1835                       cast<CXXMethodDecl>(Callee)->isInstance();
1836 
1837   if (!IsMemberCall)
1838     Out << *Callee << '(';
1839 
1840   if (This && IsMemberCall) {
1841     APValue Val;
1842     This->moveInto(Val);
1843     Val.printPretty(Out, Info.Ctx,
1844                     This->Designator.MostDerivedType);
1845     // FIXME: Add parens around Val if needed.
1846     Out << "->" << *Callee << '(';
1847     IsMemberCall = false;
1848   }
1849 
1850   for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1851        E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
1852     if (ArgIndex > (unsigned)IsMemberCall)
1853       Out << ", ";
1854 
1855     const ParmVarDecl *Param = *I;
1856     const APValue &Arg = Arguments[ArgIndex];
1857     Arg.printPretty(Out, Info.Ctx, Param->getType());
1858 
1859     if (ArgIndex == 0 && IsMemberCall)
1860       Out << "->" << *Callee << '(';
1861   }
1862 
1863   Out << ')';
1864 }
1865 
1866 /// Evaluate an expression to see if it had side-effects, and discard its
1867 /// result.
1868 /// \return \c true if the caller should keep evaluating.
1869 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1870   APValue Scratch;
1871   if (!Evaluate(Scratch, Info, E))
1872     // We don't need the value, but we might have skipped a side effect here.
1873     return Info.noteSideEffect();
1874   return true;
1875 }
1876 
1877 /// Should this call expression be treated as a string literal?
1878 static bool IsStringLiteralCall(const CallExpr *E) {
1879   unsigned Builtin = E->getBuiltinCallee();
1880   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1881           Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1882 }
1883 
1884 static bool IsGlobalLValue(APValue::LValueBase B) {
1885   // C++11 [expr.const]p3 An address constant expression is a prvalue core
1886   // constant expression of pointer type that evaluates to...
1887 
1888   // ... a null pointer value, or a prvalue core constant expression of type
1889   // std::nullptr_t.
1890   if (!B) return true;
1891 
1892   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1893     // ... the address of an object with static storage duration,
1894     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1895       return VD->hasGlobalStorage();
1896     // ... the address of a function,
1897     return isa<FunctionDecl>(D);
1898   }
1899 
1900   if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
1901     return true;
1902 
1903   const Expr *E = B.get<const Expr*>();
1904   switch (E->getStmtClass()) {
1905   default:
1906     return false;
1907   case Expr::CompoundLiteralExprClass: {
1908     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1909     return CLE->isFileScope() && CLE->isLValue();
1910   }
1911   case Expr::MaterializeTemporaryExprClass:
1912     // A materialized temporary might have been lifetime-extended to static
1913     // storage duration.
1914     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1915   // A string literal has static storage duration.
1916   case Expr::StringLiteralClass:
1917   case Expr::PredefinedExprClass:
1918   case Expr::ObjCStringLiteralClass:
1919   case Expr::ObjCEncodeExprClass:
1920   case Expr::CXXUuidofExprClass:
1921     return true;
1922   case Expr::ObjCBoxedExprClass:
1923     return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
1924   case Expr::CallExprClass:
1925     return IsStringLiteralCall(cast<CallExpr>(E));
1926   // For GCC compatibility, &&label has static storage duration.
1927   case Expr::AddrLabelExprClass:
1928     return true;
1929   // A Block literal expression may be used as the initialization value for
1930   // Block variables at global or local static scope.
1931   case Expr::BlockExprClass:
1932     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1933   case Expr::ImplicitValueInitExprClass:
1934     // FIXME:
1935     // We can never form an lvalue with an implicit value initialization as its
1936     // base through expression evaluation, so these only appear in one case: the
1937     // implicit variable declaration we invent when checking whether a constexpr
1938     // constructor can produce a constant expression. We must assume that such
1939     // an expression might be a global lvalue.
1940     return true;
1941   }
1942 }
1943 
1944 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1945   return LVal.Base.dyn_cast<const ValueDecl*>();
1946 }
1947 
1948 static bool IsLiteralLValue(const LValue &Value) {
1949   if (Value.getLValueCallIndex())
1950     return false;
1951   const Expr *E = Value.Base.dyn_cast<const Expr*>();
1952   return E && !isa<MaterializeTemporaryExpr>(E);
1953 }
1954 
1955 static bool IsWeakLValue(const LValue &Value) {
1956   const ValueDecl *Decl = GetLValueBaseDecl(Value);
1957   return Decl && Decl->isWeak();
1958 }
1959 
1960 static bool isZeroSized(const LValue &Value) {
1961   const ValueDecl *Decl = GetLValueBaseDecl(Value);
1962   if (Decl && isa<VarDecl>(Decl)) {
1963     QualType Ty = Decl->getType();
1964     if (Ty->isArrayType())
1965       return Ty->isIncompleteType() ||
1966              Decl->getASTContext().getTypeSize(Ty) == 0;
1967   }
1968   return false;
1969 }
1970 
1971 static bool HasSameBase(const LValue &A, const LValue &B) {
1972   if (!A.getLValueBase())
1973     return !B.getLValueBase();
1974   if (!B.getLValueBase())
1975     return false;
1976 
1977   if (A.getLValueBase().getOpaqueValue() !=
1978       B.getLValueBase().getOpaqueValue()) {
1979     const Decl *ADecl = GetLValueBaseDecl(A);
1980     if (!ADecl)
1981       return false;
1982     const Decl *BDecl = GetLValueBaseDecl(B);
1983     if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
1984       return false;
1985   }
1986 
1987   return IsGlobalLValue(A.getLValueBase()) ||
1988          (A.getLValueCallIndex() == B.getLValueCallIndex() &&
1989           A.getLValueVersion() == B.getLValueVersion());
1990 }
1991 
1992 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1993   assert(Base && "no location for a null lvalue");
1994   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1995   if (VD)
1996     Info.Note(VD->getLocation(), diag::note_declared_at);
1997   else if (const Expr *E = Base.dyn_cast<const Expr*>())
1998     Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
1999   else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2000     // FIXME: Produce a note for dangling pointers too.
2001     if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA))
2002       Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2003                 diag::note_constexpr_dynamic_alloc_here);
2004   }
2005   // We have no information to show for a typeid(T) object.
2006 }
2007 
2008 enum class CheckEvaluationResultKind {
2009   ConstantExpression,
2010   FullyInitialized,
2011 };
2012 
2013 /// Materialized temporaries that we've already checked to determine if they're
2014 /// initializsed by a constant expression.
2015 using CheckedTemporaries =
2016     llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
2017 
2018 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2019                                   EvalInfo &Info, SourceLocation DiagLoc,
2020                                   QualType Type, const APValue &Value,
2021                                   Expr::ConstExprUsage Usage,
2022                                   SourceLocation SubobjectLoc,
2023                                   CheckedTemporaries &CheckedTemps);
2024 
2025 /// Check that this reference or pointer core constant expression is a valid
2026 /// value for an address or reference constant expression. Return true if we
2027 /// can fold this expression, whether or not it's a constant expression.
2028 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2029                                           QualType Type, const LValue &LVal,
2030                                           Expr::ConstExprUsage Usage,
2031                                           CheckedTemporaries &CheckedTemps) {
2032   bool IsReferenceType = Type->isReferenceType();
2033 
2034   APValue::LValueBase Base = LVal.getLValueBase();
2035   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2036 
2037   if (auto *VD = LVal.getLValueBase().dyn_cast<const ValueDecl *>()) {
2038     if (auto *FD = dyn_cast<FunctionDecl>(VD)) {
2039       if (FD->isConsteval()) {
2040         Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2041             << !Type->isAnyPointerType();
2042         Info.Note(FD->getLocation(), diag::note_declared_at);
2043         return false;
2044       }
2045     }
2046   }
2047 
2048   // Check that the object is a global. Note that the fake 'this' object we
2049   // manufacture when checking potential constant expressions is conservatively
2050   // assumed to be global here.
2051   if (!IsGlobalLValue(Base)) {
2052     if (Info.getLangOpts().CPlusPlus11) {
2053       const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2054       Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2055         << IsReferenceType << !Designator.Entries.empty()
2056         << !!VD << VD;
2057       NoteLValueLocation(Info, Base);
2058     } else {
2059       Info.FFDiag(Loc);
2060     }
2061     // Don't allow references to temporaries to escape.
2062     return false;
2063   }
2064   assert((Info.checkingPotentialConstantExpression() ||
2065           LVal.getLValueCallIndex() == 0) &&
2066          "have call index for global lvalue");
2067 
2068   if (Base.is<DynamicAllocLValue>()) {
2069     Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2070         << IsReferenceType << !Designator.Entries.empty();
2071     NoteLValueLocation(Info, Base);
2072     return false;
2073   }
2074 
2075   if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
2076     if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
2077       // Check if this is a thread-local variable.
2078       if (Var->getTLSKind())
2079         // FIXME: Diagnostic!
2080         return false;
2081 
2082       // A dllimport variable never acts like a constant.
2083       if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
2084         // FIXME: Diagnostic!
2085         return false;
2086     }
2087     if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
2088       // __declspec(dllimport) must be handled very carefully:
2089       // We must never initialize an expression with the thunk in C++.
2090       // Doing otherwise would allow the same id-expression to yield
2091       // different addresses for the same function in different translation
2092       // units.  However, this means that we must dynamically initialize the
2093       // expression with the contents of the import address table at runtime.
2094       //
2095       // The C language has no notion of ODR; furthermore, it has no notion of
2096       // dynamic initialization.  This means that we are permitted to
2097       // perform initialization with the address of the thunk.
2098       if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
2099           FD->hasAttr<DLLImportAttr>())
2100         // FIXME: Diagnostic!
2101         return false;
2102     }
2103   } else if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(
2104                  Base.dyn_cast<const Expr *>())) {
2105     if (CheckedTemps.insert(MTE).second) {
2106       QualType TempType = getType(Base);
2107       if (TempType.isDestructedType()) {
2108         Info.FFDiag(MTE->getExprLoc(),
2109                     diag::note_constexpr_unsupported_tempoarary_nontrivial_dtor)
2110             << TempType;
2111         return false;
2112       }
2113 
2114       APValue *V = MTE->getOrCreateValue(false);
2115       assert(V && "evasluation result refers to uninitialised temporary");
2116       if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2117                                  Info, MTE->getExprLoc(), TempType, *V,
2118                                  Usage, SourceLocation(), CheckedTemps))
2119         return false;
2120     }
2121   }
2122 
2123   // Allow address constant expressions to be past-the-end pointers. This is
2124   // an extension: the standard requires them to point to an object.
2125   if (!IsReferenceType)
2126     return true;
2127 
2128   // A reference constant expression must refer to an object.
2129   if (!Base) {
2130     // FIXME: diagnostic
2131     Info.CCEDiag(Loc);
2132     return true;
2133   }
2134 
2135   // Does this refer one past the end of some object?
2136   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2137     const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2138     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2139       << !Designator.Entries.empty() << !!VD << VD;
2140     NoteLValueLocation(Info, Base);
2141   }
2142 
2143   return true;
2144 }
2145 
2146 /// Member pointers are constant expressions unless they point to a
2147 /// non-virtual dllimport member function.
2148 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2149                                                  SourceLocation Loc,
2150                                                  QualType Type,
2151                                                  const APValue &Value,
2152                                                  Expr::ConstExprUsage Usage) {
2153   const ValueDecl *Member = Value.getMemberPointerDecl();
2154   const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2155   if (!FD)
2156     return true;
2157   if (FD->isConsteval()) {
2158     Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2159     Info.Note(FD->getLocation(), diag::note_declared_at);
2160     return false;
2161   }
2162   return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
2163          !FD->hasAttr<DLLImportAttr>();
2164 }
2165 
2166 /// Check that this core constant expression is of literal type, and if not,
2167 /// produce an appropriate diagnostic.
2168 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2169                              const LValue *This = nullptr) {
2170   if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
2171     return true;
2172 
2173   // C++1y: A constant initializer for an object o [...] may also invoke
2174   // constexpr constructors for o and its subobjects even if those objects
2175   // are of non-literal class types.
2176   //
2177   // C++11 missed this detail for aggregates, so classes like this:
2178   //   struct foo_t { union { int i; volatile int j; } u; };
2179   // are not (obviously) initializable like so:
2180   //   __attribute__((__require_constant_initialization__))
2181   //   static const foo_t x = {{0}};
2182   // because "i" is a subobject with non-literal initialization (due to the
2183   // volatile member of the union). See:
2184   //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2185   // Therefore, we use the C++1y behavior.
2186   if (This && Info.EvaluatingDecl == This->getLValueBase())
2187     return true;
2188 
2189   // Prvalue constant expressions must be of literal types.
2190   if (Info.getLangOpts().CPlusPlus11)
2191     Info.FFDiag(E, diag::note_constexpr_nonliteral)
2192       << E->getType();
2193   else
2194     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2195   return false;
2196 }
2197 
2198 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2199                                   EvalInfo &Info, SourceLocation DiagLoc,
2200                                   QualType Type, const APValue &Value,
2201                                   Expr::ConstExprUsage Usage,
2202                                   SourceLocation SubobjectLoc,
2203                                   CheckedTemporaries &CheckedTemps) {
2204   if (!Value.hasValue()) {
2205     Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2206       << true << Type;
2207     if (SubobjectLoc.isValid())
2208       Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2209     return false;
2210   }
2211 
2212   // We allow _Atomic(T) to be initialized from anything that T can be
2213   // initialized from.
2214   if (const AtomicType *AT = Type->getAs<AtomicType>())
2215     Type = AT->getValueType();
2216 
2217   // Core issue 1454: For a literal constant expression of array or class type,
2218   // each subobject of its value shall have been initialized by a constant
2219   // expression.
2220   if (Value.isArray()) {
2221     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2222     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2223       if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2224                                  Value.getArrayInitializedElt(I), Usage,
2225                                  SubobjectLoc, CheckedTemps))
2226         return false;
2227     }
2228     if (!Value.hasArrayFiller())
2229       return true;
2230     return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2231                                  Value.getArrayFiller(), Usage, SubobjectLoc,
2232                                  CheckedTemps);
2233   }
2234   if (Value.isUnion() && Value.getUnionField()) {
2235     return CheckEvaluationResult(
2236         CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2237         Value.getUnionValue(), Usage, Value.getUnionField()->getLocation(),
2238         CheckedTemps);
2239   }
2240   if (Value.isStruct()) {
2241     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2242     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2243       unsigned BaseIndex = 0;
2244       for (const CXXBaseSpecifier &BS : CD->bases()) {
2245         if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2246                                    Value.getStructBase(BaseIndex), Usage,
2247                                    BS.getBeginLoc(), CheckedTemps))
2248           return false;
2249         ++BaseIndex;
2250       }
2251     }
2252     for (const auto *I : RD->fields()) {
2253       if (I->isUnnamedBitfield())
2254         continue;
2255 
2256       if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2257                                  Value.getStructField(I->getFieldIndex()),
2258                                  Usage, I->getLocation(), CheckedTemps))
2259         return false;
2260     }
2261   }
2262 
2263   if (Value.isLValue() &&
2264       CERK == CheckEvaluationResultKind::ConstantExpression) {
2265     LValue LVal;
2266     LVal.setFrom(Info.Ctx, Value);
2267     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage,
2268                                          CheckedTemps);
2269   }
2270 
2271   if (Value.isMemberPointer() &&
2272       CERK == CheckEvaluationResultKind::ConstantExpression)
2273     return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
2274 
2275   // Everything else is fine.
2276   return true;
2277 }
2278 
2279 /// Check that this core constant expression value is a valid value for a
2280 /// constant expression. If not, report an appropriate diagnostic. Does not
2281 /// check that the expression is of literal type.
2282 static bool
2283 CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
2284                         const APValue &Value,
2285                         Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
2286   CheckedTemporaries CheckedTemps;
2287   return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2288                                Info, DiagLoc, Type, Value, Usage,
2289                                SourceLocation(), CheckedTemps);
2290 }
2291 
2292 /// Check that this evaluated value is fully-initialized and can be loaded by
2293 /// an lvalue-to-rvalue conversion.
2294 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2295                                   QualType Type, const APValue &Value) {
2296   CheckedTemporaries CheckedTemps;
2297   return CheckEvaluationResult(
2298       CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2299       Expr::EvaluateForCodeGen, SourceLocation(), CheckedTemps);
2300 }
2301 
2302 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2303 /// "the allocated storage is deallocated within the evaluation".
2304 static bool CheckMemoryLeaks(EvalInfo &Info) {
2305   if (!Info.HeapAllocs.empty()) {
2306     // We can still fold to a constant despite a compile-time memory leak,
2307     // so long as the heap allocation isn't referenced in the result (we check
2308     // that in CheckConstantExpression).
2309     Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2310                  diag::note_constexpr_memory_leak)
2311         << unsigned(Info.HeapAllocs.size() - 1);
2312   }
2313   return true;
2314 }
2315 
2316 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2317   // A null base expression indicates a null pointer.  These are always
2318   // evaluatable, and they are false unless the offset is zero.
2319   if (!Value.getLValueBase()) {
2320     Result = !Value.getLValueOffset().isZero();
2321     return true;
2322   }
2323 
2324   // We have a non-null base.  These are generally known to be true, but if it's
2325   // a weak declaration it can be null at runtime.
2326   Result = true;
2327   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2328   return !Decl || !Decl->isWeak();
2329 }
2330 
2331 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2332   switch (Val.getKind()) {
2333   case APValue::None:
2334   case APValue::Indeterminate:
2335     return false;
2336   case APValue::Int:
2337     Result = Val.getInt().getBoolValue();
2338     return true;
2339   case APValue::FixedPoint:
2340     Result = Val.getFixedPoint().getBoolValue();
2341     return true;
2342   case APValue::Float:
2343     Result = !Val.getFloat().isZero();
2344     return true;
2345   case APValue::ComplexInt:
2346     Result = Val.getComplexIntReal().getBoolValue() ||
2347              Val.getComplexIntImag().getBoolValue();
2348     return true;
2349   case APValue::ComplexFloat:
2350     Result = !Val.getComplexFloatReal().isZero() ||
2351              !Val.getComplexFloatImag().isZero();
2352     return true;
2353   case APValue::LValue:
2354     return EvalPointerValueAsBool(Val, Result);
2355   case APValue::MemberPointer:
2356     Result = Val.getMemberPointerDecl();
2357     return true;
2358   case APValue::Vector:
2359   case APValue::Array:
2360   case APValue::Struct:
2361   case APValue::Union:
2362   case APValue::AddrLabelDiff:
2363     return false;
2364   }
2365 
2366   llvm_unreachable("unknown APValue kind");
2367 }
2368 
2369 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2370                                        EvalInfo &Info) {
2371   assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
2372   APValue Val;
2373   if (!Evaluate(Val, Info, E))
2374     return false;
2375   return HandleConversionToBool(Val, Result);
2376 }
2377 
2378 template<typename T>
2379 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2380                            const T &SrcValue, QualType DestType) {
2381   Info.CCEDiag(E, diag::note_constexpr_overflow)
2382     << SrcValue << DestType;
2383   return Info.noteUndefinedBehavior();
2384 }
2385 
2386 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2387                                  QualType SrcType, const APFloat &Value,
2388                                  QualType DestType, APSInt &Result) {
2389   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2390   // Determine whether we are converting to unsigned or signed.
2391   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2392 
2393   Result = APSInt(DestWidth, !DestSigned);
2394   bool ignored;
2395   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2396       & APFloat::opInvalidOp)
2397     return HandleOverflow(Info, E, Value, DestType);
2398   return true;
2399 }
2400 
2401 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2402                                    QualType SrcType, QualType DestType,
2403                                    APFloat &Result) {
2404   APFloat Value = Result;
2405   bool ignored;
2406   Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2407                  APFloat::rmNearestTiesToEven, &ignored);
2408   return true;
2409 }
2410 
2411 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2412                                  QualType DestType, QualType SrcType,
2413                                  const APSInt &Value) {
2414   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2415   // Figure out if this is a truncate, extend or noop cast.
2416   // If the input is signed, do a sign extend, noop, or truncate.
2417   APSInt Result = Value.extOrTrunc(DestWidth);
2418   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2419   if (DestType->isBooleanType())
2420     Result = Value.getBoolValue();
2421   return Result;
2422 }
2423 
2424 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2425                                  QualType SrcType, const APSInt &Value,
2426                                  QualType DestType, APFloat &Result) {
2427   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2428   Result.convertFromAPInt(Value, Value.isSigned(),
2429                           APFloat::rmNearestTiesToEven);
2430   return true;
2431 }
2432 
2433 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2434                                   APValue &Value, const FieldDecl *FD) {
2435   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2436 
2437   if (!Value.isInt()) {
2438     // Trying to store a pointer-cast-to-integer into a bitfield.
2439     // FIXME: In this case, we should provide the diagnostic for casting
2440     // a pointer to an integer.
2441     assert(Value.isLValue() && "integral value neither int nor lvalue?");
2442     Info.FFDiag(E);
2443     return false;
2444   }
2445 
2446   APSInt &Int = Value.getInt();
2447   unsigned OldBitWidth = Int.getBitWidth();
2448   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2449   if (NewBitWidth < OldBitWidth)
2450     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2451   return true;
2452 }
2453 
2454 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2455                                   llvm::APInt &Res) {
2456   APValue SVal;
2457   if (!Evaluate(SVal, Info, E))
2458     return false;
2459   if (SVal.isInt()) {
2460     Res = SVal.getInt();
2461     return true;
2462   }
2463   if (SVal.isFloat()) {
2464     Res = SVal.getFloat().bitcastToAPInt();
2465     return true;
2466   }
2467   if (SVal.isVector()) {
2468     QualType VecTy = E->getType();
2469     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2470     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2471     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2472     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2473     Res = llvm::APInt::getNullValue(VecSize);
2474     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2475       APValue &Elt = SVal.getVectorElt(i);
2476       llvm::APInt EltAsInt;
2477       if (Elt.isInt()) {
2478         EltAsInt = Elt.getInt();
2479       } else if (Elt.isFloat()) {
2480         EltAsInt = Elt.getFloat().bitcastToAPInt();
2481       } else {
2482         // Don't try to handle vectors of anything other than int or float
2483         // (not sure if it's possible to hit this case).
2484         Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2485         return false;
2486       }
2487       unsigned BaseEltSize = EltAsInt.getBitWidth();
2488       if (BigEndian)
2489         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2490       else
2491         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2492     }
2493     return true;
2494   }
2495   // Give up if the input isn't an int, float, or vector.  For example, we
2496   // reject "(v4i16)(intptr_t)&a".
2497   Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2498   return false;
2499 }
2500 
2501 /// Perform the given integer operation, which is known to need at most BitWidth
2502 /// bits, and check for overflow in the original type (if that type was not an
2503 /// unsigned type).
2504 template<typename Operation>
2505 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2506                                  const APSInt &LHS, const APSInt &RHS,
2507                                  unsigned BitWidth, Operation Op,
2508                                  APSInt &Result) {
2509   if (LHS.isUnsigned()) {
2510     Result = Op(LHS, RHS);
2511     return true;
2512   }
2513 
2514   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2515   Result = Value.trunc(LHS.getBitWidth());
2516   if (Result.extend(BitWidth) != Value) {
2517     if (Info.checkingForUndefinedBehavior())
2518       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2519                                        diag::warn_integer_constant_overflow)
2520           << Result.toString(10) << E->getType();
2521     else
2522       return HandleOverflow(Info, E, Value, E->getType());
2523   }
2524   return true;
2525 }
2526 
2527 /// Perform the given binary integer operation.
2528 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2529                               BinaryOperatorKind Opcode, APSInt RHS,
2530                               APSInt &Result) {
2531   switch (Opcode) {
2532   default:
2533     Info.FFDiag(E);
2534     return false;
2535   case BO_Mul:
2536     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2537                                 std::multiplies<APSInt>(), Result);
2538   case BO_Add:
2539     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2540                                 std::plus<APSInt>(), Result);
2541   case BO_Sub:
2542     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2543                                 std::minus<APSInt>(), Result);
2544   case BO_And: Result = LHS & RHS; return true;
2545   case BO_Xor: Result = LHS ^ RHS; return true;
2546   case BO_Or:  Result = LHS | RHS; return true;
2547   case BO_Div:
2548   case BO_Rem:
2549     if (RHS == 0) {
2550       Info.FFDiag(E, diag::note_expr_divide_by_zero);
2551       return false;
2552     }
2553     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2554     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2555     // this operation and gives the two's complement result.
2556     if (RHS.isNegative() && RHS.isAllOnesValue() &&
2557         LHS.isSigned() && LHS.isMinSignedValue())
2558       return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2559                             E->getType());
2560     return true;
2561   case BO_Shl: {
2562     if (Info.getLangOpts().OpenCL)
2563       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2564       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2565                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2566                     RHS.isUnsigned());
2567     else if (RHS.isSigned() && RHS.isNegative()) {
2568       // During constant-folding, a negative shift is an opposite shift. Such
2569       // a shift is not a constant expression.
2570       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2571       RHS = -RHS;
2572       goto shift_right;
2573     }
2574   shift_left:
2575     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2576     // the shifted type.
2577     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2578     if (SA != RHS) {
2579       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2580         << RHS << E->getType() << LHS.getBitWidth();
2581     } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus2a) {
2582       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2583       // operand, and must not overflow the corresponding unsigned type.
2584       // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2585       // E1 x 2^E2 module 2^N.
2586       if (LHS.isNegative())
2587         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2588       else if (LHS.countLeadingZeros() < SA)
2589         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2590     }
2591     Result = LHS << SA;
2592     return true;
2593   }
2594   case BO_Shr: {
2595     if (Info.getLangOpts().OpenCL)
2596       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2597       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2598                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2599                     RHS.isUnsigned());
2600     else if (RHS.isSigned() && RHS.isNegative()) {
2601       // During constant-folding, a negative shift is an opposite shift. Such a
2602       // shift is not a constant expression.
2603       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2604       RHS = -RHS;
2605       goto shift_left;
2606     }
2607   shift_right:
2608     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2609     // shifted type.
2610     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2611     if (SA != RHS)
2612       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2613         << RHS << E->getType() << LHS.getBitWidth();
2614     Result = LHS >> SA;
2615     return true;
2616   }
2617 
2618   case BO_LT: Result = LHS < RHS; return true;
2619   case BO_GT: Result = LHS > RHS; return true;
2620   case BO_LE: Result = LHS <= RHS; return true;
2621   case BO_GE: Result = LHS >= RHS; return true;
2622   case BO_EQ: Result = LHS == RHS; return true;
2623   case BO_NE: Result = LHS != RHS; return true;
2624   case BO_Cmp:
2625     llvm_unreachable("BO_Cmp should be handled elsewhere");
2626   }
2627 }
2628 
2629 /// Perform the given binary floating-point operation, in-place, on LHS.
2630 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2631                                   APFloat &LHS, BinaryOperatorKind Opcode,
2632                                   const APFloat &RHS) {
2633   switch (Opcode) {
2634   default:
2635     Info.FFDiag(E);
2636     return false;
2637   case BO_Mul:
2638     LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2639     break;
2640   case BO_Add:
2641     LHS.add(RHS, APFloat::rmNearestTiesToEven);
2642     break;
2643   case BO_Sub:
2644     LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2645     break;
2646   case BO_Div:
2647     // [expr.mul]p4:
2648     //   If the second operand of / or % is zero the behavior is undefined.
2649     if (RHS.isZero())
2650       Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2651     LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2652     break;
2653   }
2654 
2655   // [expr.pre]p4:
2656   //   If during the evaluation of an expression, the result is not
2657   //   mathematically defined [...], the behavior is undefined.
2658   // FIXME: C++ rules require us to not conform to IEEE 754 here.
2659   if (LHS.isNaN()) {
2660     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2661     return Info.noteUndefinedBehavior();
2662   }
2663   return true;
2664 }
2665 
2666 /// Cast an lvalue referring to a base subobject to a derived class, by
2667 /// truncating the lvalue's path to the given length.
2668 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2669                                const RecordDecl *TruncatedType,
2670                                unsigned TruncatedElements) {
2671   SubobjectDesignator &D = Result.Designator;
2672 
2673   // Check we actually point to a derived class object.
2674   if (TruncatedElements == D.Entries.size())
2675     return true;
2676   assert(TruncatedElements >= D.MostDerivedPathLength &&
2677          "not casting to a derived class");
2678   if (!Result.checkSubobject(Info, E, CSK_Derived))
2679     return false;
2680 
2681   // Truncate the path to the subobject, and remove any derived-to-base offsets.
2682   const RecordDecl *RD = TruncatedType;
2683   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
2684     if (RD->isInvalidDecl()) return false;
2685     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2686     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
2687     if (isVirtualBaseClass(D.Entries[I]))
2688       Result.Offset -= Layout.getVBaseClassOffset(Base);
2689     else
2690       Result.Offset -= Layout.getBaseClassOffset(Base);
2691     RD = Base;
2692   }
2693   D.Entries.resize(TruncatedElements);
2694   return true;
2695 }
2696 
2697 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2698                                    const CXXRecordDecl *Derived,
2699                                    const CXXRecordDecl *Base,
2700                                    const ASTRecordLayout *RL = nullptr) {
2701   if (!RL) {
2702     if (Derived->isInvalidDecl()) return false;
2703     RL = &Info.Ctx.getASTRecordLayout(Derived);
2704   }
2705 
2706   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
2707   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
2708   return true;
2709 }
2710 
2711 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2712                              const CXXRecordDecl *DerivedDecl,
2713                              const CXXBaseSpecifier *Base) {
2714   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2715 
2716   if (!Base->isVirtual())
2717     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
2718 
2719   SubobjectDesignator &D = Obj.Designator;
2720   if (D.Invalid)
2721     return false;
2722 
2723   // Extract most-derived object and corresponding type.
2724   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2725   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2726     return false;
2727 
2728   // Find the virtual base class.
2729   if (DerivedDecl->isInvalidDecl()) return false;
2730   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2731   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
2732   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
2733   return true;
2734 }
2735 
2736 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2737                                  QualType Type, LValue &Result) {
2738   for (CastExpr::path_const_iterator PathI = E->path_begin(),
2739                                      PathE = E->path_end();
2740        PathI != PathE; ++PathI) {
2741     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2742                           *PathI))
2743       return false;
2744     Type = (*PathI)->getType();
2745   }
2746   return true;
2747 }
2748 
2749 /// Cast an lvalue referring to a derived class to a known base subobject.
2750 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
2751                             const CXXRecordDecl *DerivedRD,
2752                             const CXXRecordDecl *BaseRD) {
2753   CXXBasePaths Paths(/*FindAmbiguities=*/false,
2754                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
2755   if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
2756     llvm_unreachable("Class must be derived from the passed in base class!");
2757 
2758   for (CXXBasePathElement &Elem : Paths.front())
2759     if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
2760       return false;
2761   return true;
2762 }
2763 
2764 /// Update LVal to refer to the given field, which must be a member of the type
2765 /// currently described by LVal.
2766 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
2767                                const FieldDecl *FD,
2768                                const ASTRecordLayout *RL = nullptr) {
2769   if (!RL) {
2770     if (FD->getParent()->isInvalidDecl()) return false;
2771     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
2772   }
2773 
2774   unsigned I = FD->getFieldIndex();
2775   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
2776   LVal.addDecl(Info, E, FD);
2777   return true;
2778 }
2779 
2780 /// Update LVal to refer to the given indirect field.
2781 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
2782                                        LValue &LVal,
2783                                        const IndirectFieldDecl *IFD) {
2784   for (const auto *C : IFD->chain())
2785     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
2786       return false;
2787   return true;
2788 }
2789 
2790 /// Get the size of the given type in char units.
2791 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2792                          QualType Type, CharUnits &Size) {
2793   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2794   // extension.
2795   if (Type->isVoidType() || Type->isFunctionType()) {
2796     Size = CharUnits::One();
2797     return true;
2798   }
2799 
2800   if (Type->isDependentType()) {
2801     Info.FFDiag(Loc);
2802     return false;
2803   }
2804 
2805   if (!Type->isConstantSizeType()) {
2806     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2807     // FIXME: Better diagnostic.
2808     Info.FFDiag(Loc);
2809     return false;
2810   }
2811 
2812   Size = Info.Ctx.getTypeSizeInChars(Type);
2813   return true;
2814 }
2815 
2816 /// Update a pointer value to model pointer arithmetic.
2817 /// \param Info - Information about the ongoing evaluation.
2818 /// \param E - The expression being evaluated, for diagnostic purposes.
2819 /// \param LVal - The pointer value to be updated.
2820 /// \param EltTy - The pointee type represented by LVal.
2821 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
2822 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2823                                         LValue &LVal, QualType EltTy,
2824                                         APSInt Adjustment) {
2825   CharUnits SizeOfPointee;
2826   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
2827     return false;
2828 
2829   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
2830   return true;
2831 }
2832 
2833 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2834                                         LValue &LVal, QualType EltTy,
2835                                         int64_t Adjustment) {
2836   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2837                                      APSInt::get(Adjustment));
2838 }
2839 
2840 /// Update an lvalue to refer to a component of a complex number.
2841 /// \param Info - Information about the ongoing evaluation.
2842 /// \param LVal - The lvalue to be updated.
2843 /// \param EltTy - The complex number's component type.
2844 /// \param Imag - False for the real component, true for the imaginary.
2845 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2846                                        LValue &LVal, QualType EltTy,
2847                                        bool Imag) {
2848   if (Imag) {
2849     CharUnits SizeOfComponent;
2850     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2851       return false;
2852     LVal.Offset += SizeOfComponent;
2853   }
2854   LVal.addComplex(Info, E, EltTy, Imag);
2855   return true;
2856 }
2857 
2858 /// Try to evaluate the initializer for a variable declaration.
2859 ///
2860 /// \param Info   Information about the ongoing evaluation.
2861 /// \param E      An expression to be used when printing diagnostics.
2862 /// \param VD     The variable whose initializer should be obtained.
2863 /// \param Frame  The frame in which the variable was created. Must be null
2864 ///               if this variable is not local to the evaluation.
2865 /// \param Result Filled in with a pointer to the value of the variable.
2866 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2867                                 const VarDecl *VD, CallStackFrame *Frame,
2868                                 APValue *&Result, const LValue *LVal) {
2869 
2870   // If this is a parameter to an active constexpr function call, perform
2871   // argument substitution.
2872   if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
2873     // Assume arguments of a potential constant expression are unknown
2874     // constant expressions.
2875     if (Info.checkingPotentialConstantExpression())
2876       return false;
2877     if (!Frame || !Frame->Arguments) {
2878       Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2879       return false;
2880     }
2881     Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
2882     return true;
2883   }
2884 
2885   // If this is a local variable, dig out its value.
2886   if (Frame) {
2887     Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2888                   : Frame->getCurrentTemporary(VD);
2889     if (!Result) {
2890       // Assume variables referenced within a lambda's call operator that were
2891       // not declared within the call operator are captures and during checking
2892       // of a potential constant expression, assume they are unknown constant
2893       // expressions.
2894       assert(isLambdaCallOperator(Frame->Callee) &&
2895              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2896              "missing value for local variable");
2897       if (Info.checkingPotentialConstantExpression())
2898         return false;
2899       // FIXME: implement capture evaluation during constant expr evaluation.
2900       Info.FFDiag(E->getBeginLoc(),
2901                   diag::note_unimplemented_constexpr_lambda_feature_ast)
2902           << "captures not currently allowed";
2903       return false;
2904     }
2905     return true;
2906   }
2907 
2908   // Dig out the initializer, and use the declaration which it's attached to.
2909   const Expr *Init = VD->getAnyInitializer(VD);
2910   if (!Init || Init->isValueDependent()) {
2911     // If we're checking a potential constant expression, the variable could be
2912     // initialized later.
2913     if (!Info.checkingPotentialConstantExpression())
2914       Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2915     return false;
2916   }
2917 
2918   // If we're currently evaluating the initializer of this declaration, use that
2919   // in-flight value.
2920   if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
2921     Result = Info.EvaluatingDeclValue;
2922     return true;
2923   }
2924 
2925   // Never evaluate the initializer of a weak variable. We can't be sure that
2926   // this is the definition which will be used.
2927   if (VD->isWeak()) {
2928     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2929     return false;
2930   }
2931 
2932   // Check that we can fold the initializer. In C++, we will have already done
2933   // this in the cases where it matters for conformance.
2934   SmallVector<PartialDiagnosticAt, 8> Notes;
2935   if (!VD->evaluateValue(Notes)) {
2936     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
2937               Notes.size() + 1) << VD;
2938     Info.Note(VD->getLocation(), diag::note_declared_at);
2939     Info.addNotes(Notes);
2940     return false;
2941   } else if (!VD->checkInitIsICE()) {
2942     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
2943                  Notes.size() + 1) << VD;
2944     Info.Note(VD->getLocation(), diag::note_declared_at);
2945     Info.addNotes(Notes);
2946   }
2947 
2948   Result = VD->getEvaluatedValue();
2949   return true;
2950 }
2951 
2952 static bool IsConstNonVolatile(QualType T) {
2953   Qualifiers Quals = T.getQualifiers();
2954   return Quals.hasConst() && !Quals.hasVolatile();
2955 }
2956 
2957 /// Get the base index of the given base class within an APValue representing
2958 /// the given derived class.
2959 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2960                              const CXXRecordDecl *Base) {
2961   Base = Base->getCanonicalDecl();
2962   unsigned Index = 0;
2963   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2964          E = Derived->bases_end(); I != E; ++I, ++Index) {
2965     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2966       return Index;
2967   }
2968 
2969   llvm_unreachable("base class missing from derived class's bases list");
2970 }
2971 
2972 /// Extract the value of a character from a string literal.
2973 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2974                                             uint64_t Index) {
2975   assert(!isa<SourceLocExpr>(Lit) &&
2976          "SourceLocExpr should have already been converted to a StringLiteral");
2977 
2978   // FIXME: Support MakeStringConstant
2979   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2980     std::string Str;
2981     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2982     assert(Index <= Str.size() && "Index too large");
2983     return APSInt::getUnsigned(Str.c_str()[Index]);
2984   }
2985 
2986   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2987     Lit = PE->getFunctionName();
2988   const StringLiteral *S = cast<StringLiteral>(Lit);
2989   const ConstantArrayType *CAT =
2990       Info.Ctx.getAsConstantArrayType(S->getType());
2991   assert(CAT && "string literal isn't an array");
2992   QualType CharType = CAT->getElementType();
2993   assert(CharType->isIntegerType() && "unexpected character type");
2994 
2995   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2996                CharType->isUnsignedIntegerType());
2997   if (Index < S->getLength())
2998     Value = S->getCodeUnit(Index);
2999   return Value;
3000 }
3001 
3002 // Expand a string literal into an array of characters.
3003 //
3004 // FIXME: This is inefficient; we should probably introduce something similar
3005 // to the LLVM ConstantDataArray to make this cheaper.
3006 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3007                                 APValue &Result,
3008                                 QualType AllocType = QualType()) {
3009   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3010       AllocType.isNull() ? S->getType() : AllocType);
3011   assert(CAT && "string literal isn't an array");
3012   QualType CharType = CAT->getElementType();
3013   assert(CharType->isIntegerType() && "unexpected character type");
3014 
3015   unsigned Elts = CAT->getSize().getZExtValue();
3016   Result = APValue(APValue::UninitArray(),
3017                    std::min(S->getLength(), Elts), Elts);
3018   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3019                CharType->isUnsignedIntegerType());
3020   if (Result.hasArrayFiller())
3021     Result.getArrayFiller() = APValue(Value);
3022   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3023     Value = S->getCodeUnit(I);
3024     Result.getArrayInitializedElt(I) = APValue(Value);
3025   }
3026 }
3027 
3028 // Expand an array so that it has more than Index filled elements.
3029 static void expandArray(APValue &Array, unsigned Index) {
3030   unsigned Size = Array.getArraySize();
3031   assert(Index < Size);
3032 
3033   // Always at least double the number of elements for which we store a value.
3034   unsigned OldElts = Array.getArrayInitializedElts();
3035   unsigned NewElts = std::max(Index+1, OldElts * 2);
3036   NewElts = std::min(Size, std::max(NewElts, 8u));
3037 
3038   // Copy the data across.
3039   APValue NewValue(APValue::UninitArray(), NewElts, Size);
3040   for (unsigned I = 0; I != OldElts; ++I)
3041     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3042   for (unsigned I = OldElts; I != NewElts; ++I)
3043     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3044   if (NewValue.hasArrayFiller())
3045     NewValue.getArrayFiller() = Array.getArrayFiller();
3046   Array.swap(NewValue);
3047 }
3048 
3049 /// Determine whether a type would actually be read by an lvalue-to-rvalue
3050 /// conversion. If it's of class type, we may assume that the copy operation
3051 /// is trivial. Note that this is never true for a union type with fields
3052 /// (because the copy always "reads" the active member) and always true for
3053 /// a non-class type.
3054 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3055 static bool isReadByLvalueToRvalueConversion(QualType T) {
3056   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3057   return !RD || isReadByLvalueToRvalueConversion(RD);
3058 }
3059 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3060   // FIXME: A trivial copy of a union copies the object representation, even if
3061   // the union is empty.
3062   if (RD->isUnion())
3063     return !RD->field_empty();
3064   if (RD->isEmpty())
3065     return false;
3066 
3067   for (auto *Field : RD->fields())
3068     if (!Field->isUnnamedBitfield() &&
3069         isReadByLvalueToRvalueConversion(Field->getType()))
3070       return true;
3071 
3072   for (auto &BaseSpec : RD->bases())
3073     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3074       return true;
3075 
3076   return false;
3077 }
3078 
3079 /// Diagnose an attempt to read from any unreadable field within the specified
3080 /// type, which might be a class type.
3081 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3082                                   QualType T) {
3083   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3084   if (!RD)
3085     return false;
3086 
3087   if (!RD->hasMutableFields())
3088     return false;
3089 
3090   for (auto *Field : RD->fields()) {
3091     // If we're actually going to read this field in some way, then it can't
3092     // be mutable. If we're in a union, then assigning to a mutable field
3093     // (even an empty one) can change the active member, so that's not OK.
3094     // FIXME: Add core issue number for the union case.
3095     if (Field->isMutable() &&
3096         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3097       Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3098       Info.Note(Field->getLocation(), diag::note_declared_at);
3099       return true;
3100     }
3101 
3102     if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3103       return true;
3104   }
3105 
3106   for (auto &BaseSpec : RD->bases())
3107     if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3108       return true;
3109 
3110   // All mutable fields were empty, and thus not actually read.
3111   return false;
3112 }
3113 
3114 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3115                                         APValue::LValueBase Base,
3116                                         bool MutableSubobject = false) {
3117   // A temporary we created.
3118   if (Base.getCallIndex())
3119     return true;
3120 
3121   auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3122   if (!Evaluating)
3123     return false;
3124 
3125   auto *BaseD = Base.dyn_cast<const ValueDecl*>();
3126 
3127   switch (Info.IsEvaluatingDecl) {
3128   case EvalInfo::EvaluatingDeclKind::None:
3129     return false;
3130 
3131   case EvalInfo::EvaluatingDeclKind::Ctor:
3132     // The variable whose initializer we're evaluating.
3133     if (BaseD)
3134       return declaresSameEntity(Evaluating, BaseD);
3135 
3136     // A temporary lifetime-extended by the variable whose initializer we're
3137     // evaluating.
3138     if (auto *BaseE = Base.dyn_cast<const Expr *>())
3139       if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3140         return declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating);
3141     return false;
3142 
3143   case EvalInfo::EvaluatingDeclKind::Dtor:
3144     // C++2a [expr.const]p6:
3145     //   [during constant destruction] the lifetime of a and its non-mutable
3146     //   subobjects (but not its mutable subobjects) [are] considered to start
3147     //   within e.
3148     //
3149     // FIXME: We can meaningfully extend this to cover non-const objects, but
3150     // we will need special handling: we should be able to access only
3151     // subobjects of such objects that are themselves declared const.
3152     if (!BaseD ||
3153         !(BaseD->getType().isConstQualified() ||
3154           BaseD->getType()->isReferenceType()) ||
3155         MutableSubobject)
3156       return false;
3157     return declaresSameEntity(Evaluating, BaseD);
3158   }
3159 
3160   llvm_unreachable("unknown evaluating decl kind");
3161 }
3162 
3163 namespace {
3164 /// A handle to a complete object (an object that is not a subobject of
3165 /// another object).
3166 struct CompleteObject {
3167   /// The identity of the object.
3168   APValue::LValueBase Base;
3169   /// The value of the complete object.
3170   APValue *Value;
3171   /// The type of the complete object.
3172   QualType Type;
3173 
3174   CompleteObject() : Value(nullptr) {}
3175   CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3176       : Base(Base), Value(Value), Type(Type) {}
3177 
3178   bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3179     // If this isn't a "real" access (eg, if it's just accessing the type
3180     // info), allow it. We assume the type doesn't change dynamically for
3181     // subobjects of constexpr objects (even though we'd hit UB here if it
3182     // did). FIXME: Is this right?
3183     if (!isAnyAccess(AK))
3184       return true;
3185 
3186     // In C++14 onwards, it is permitted to read a mutable member whose
3187     // lifetime began within the evaluation.
3188     // FIXME: Should we also allow this in C++11?
3189     if (!Info.getLangOpts().CPlusPlus14)
3190       return false;
3191     return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3192   }
3193 
3194   explicit operator bool() const { return !Type.isNull(); }
3195 };
3196 } // end anonymous namespace
3197 
3198 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3199                                  bool IsMutable = false) {
3200   // C++ [basic.type.qualifier]p1:
3201   // - A const object is an object of type const T or a non-mutable subobject
3202   //   of a const object.
3203   if (ObjType.isConstQualified() && !IsMutable)
3204     SubobjType.addConst();
3205   // - A volatile object is an object of type const T or a subobject of a
3206   //   volatile object.
3207   if (ObjType.isVolatileQualified())
3208     SubobjType.addVolatile();
3209   return SubobjType;
3210 }
3211 
3212 /// Find the designated sub-object of an rvalue.
3213 template<typename SubobjectHandler>
3214 typename SubobjectHandler::result_type
3215 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3216               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3217   if (Sub.Invalid)
3218     // A diagnostic will have already been produced.
3219     return handler.failed();
3220   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3221     if (Info.getLangOpts().CPlusPlus11)
3222       Info.FFDiag(E, Sub.isOnePastTheEnd()
3223                          ? diag::note_constexpr_access_past_end
3224                          : diag::note_constexpr_access_unsized_array)
3225           << handler.AccessKind;
3226     else
3227       Info.FFDiag(E);
3228     return handler.failed();
3229   }
3230 
3231   APValue *O = Obj.Value;
3232   QualType ObjType = Obj.Type;
3233   const FieldDecl *LastField = nullptr;
3234   const FieldDecl *VolatileField = nullptr;
3235 
3236   // Walk the designator's path to find the subobject.
3237   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3238     // Reading an indeterminate value is undefined, but assigning over one is OK.
3239     if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3240         (O->isIndeterminate() &&
3241          !isValidIndeterminateAccess(handler.AccessKind))) {
3242       if (!Info.checkingPotentialConstantExpression())
3243         Info.FFDiag(E, diag::note_constexpr_access_uninit)
3244             << handler.AccessKind << O->isIndeterminate();
3245       return handler.failed();
3246     }
3247 
3248     // C++ [class.ctor]p5, C++ [class.dtor]p5:
3249     //    const and volatile semantics are not applied on an object under
3250     //    {con,de}struction.
3251     if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3252         ObjType->isRecordType() &&
3253         Info.isEvaluatingCtorDtor(
3254             Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3255                                          Sub.Entries.begin() + I)) !=
3256                           ConstructionPhase::None) {
3257       ObjType = Info.Ctx.getCanonicalType(ObjType);
3258       ObjType.removeLocalConst();
3259       ObjType.removeLocalVolatile();
3260     }
3261 
3262     // If this is our last pass, check that the final object type is OK.
3263     if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3264       // Accesses to volatile objects are prohibited.
3265       if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3266         if (Info.getLangOpts().CPlusPlus) {
3267           int DiagKind;
3268           SourceLocation Loc;
3269           const NamedDecl *Decl = nullptr;
3270           if (VolatileField) {
3271             DiagKind = 2;
3272             Loc = VolatileField->getLocation();
3273             Decl = VolatileField;
3274           } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3275             DiagKind = 1;
3276             Loc = VD->getLocation();
3277             Decl = VD;
3278           } else {
3279             DiagKind = 0;
3280             if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3281               Loc = E->getExprLoc();
3282           }
3283           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3284               << handler.AccessKind << DiagKind << Decl;
3285           Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3286         } else {
3287           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3288         }
3289         return handler.failed();
3290       }
3291 
3292       // If we are reading an object of class type, there may still be more
3293       // things we need to check: if there are any mutable subobjects, we
3294       // cannot perform this read. (This only happens when performing a trivial
3295       // copy or assignment.)
3296       if (ObjType->isRecordType() &&
3297           !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3298           diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3299         return handler.failed();
3300     }
3301 
3302     if (I == N) {
3303       if (!handler.found(*O, ObjType))
3304         return false;
3305 
3306       // If we modified a bit-field, truncate it to the right width.
3307       if (isModification(handler.AccessKind) &&
3308           LastField && LastField->isBitField() &&
3309           !truncateBitfieldValue(Info, E, *O, LastField))
3310         return false;
3311 
3312       return true;
3313     }
3314 
3315     LastField = nullptr;
3316     if (ObjType->isArrayType()) {
3317       // Next subobject is an array element.
3318       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3319       assert(CAT && "vla in literal type?");
3320       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3321       if (CAT->getSize().ule(Index)) {
3322         // Note, it should not be possible to form a pointer with a valid
3323         // designator which points more than one past the end of the array.
3324         if (Info.getLangOpts().CPlusPlus11)
3325           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3326             << handler.AccessKind;
3327         else
3328           Info.FFDiag(E);
3329         return handler.failed();
3330       }
3331 
3332       ObjType = CAT->getElementType();
3333 
3334       if (O->getArrayInitializedElts() > Index)
3335         O = &O->getArrayInitializedElt(Index);
3336       else if (!isRead(handler.AccessKind)) {
3337         expandArray(*O, Index);
3338         O = &O->getArrayInitializedElt(Index);
3339       } else
3340         O = &O->getArrayFiller();
3341     } else if (ObjType->isAnyComplexType()) {
3342       // Next subobject is a complex number.
3343       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3344       if (Index > 1) {
3345         if (Info.getLangOpts().CPlusPlus11)
3346           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3347             << handler.AccessKind;
3348         else
3349           Info.FFDiag(E);
3350         return handler.failed();
3351       }
3352 
3353       ObjType = getSubobjectType(
3354           ObjType, ObjType->castAs<ComplexType>()->getElementType());
3355 
3356       assert(I == N - 1 && "extracting subobject of scalar?");
3357       if (O->isComplexInt()) {
3358         return handler.found(Index ? O->getComplexIntImag()
3359                                    : O->getComplexIntReal(), ObjType);
3360       } else {
3361         assert(O->isComplexFloat());
3362         return handler.found(Index ? O->getComplexFloatImag()
3363                                    : O->getComplexFloatReal(), ObjType);
3364       }
3365     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3366       if (Field->isMutable() &&
3367           !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3368         Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3369           << handler.AccessKind << Field;
3370         Info.Note(Field->getLocation(), diag::note_declared_at);
3371         return handler.failed();
3372       }
3373 
3374       // Next subobject is a class, struct or union field.
3375       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3376       if (RD->isUnion()) {
3377         const FieldDecl *UnionField = O->getUnionField();
3378         if (!UnionField ||
3379             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3380           if (I == N - 1 && handler.AccessKind == AK_Construct) {
3381             // Placement new onto an inactive union member makes it active.
3382             O->setUnion(Field, APValue());
3383           } else {
3384             // FIXME: If O->getUnionValue() is absent, report that there's no
3385             // active union member rather than reporting the prior active union
3386             // member. We'll need to fix nullptr_t to not use APValue() as its
3387             // representation first.
3388             Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3389                 << handler.AccessKind << Field << !UnionField << UnionField;
3390             return handler.failed();
3391           }
3392         }
3393         O = &O->getUnionValue();
3394       } else
3395         O = &O->getStructField(Field->getFieldIndex());
3396 
3397       ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3398       LastField = Field;
3399       if (Field->getType().isVolatileQualified())
3400         VolatileField = Field;
3401     } else {
3402       // Next subobject is a base class.
3403       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3404       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3405       O = &O->getStructBase(getBaseIndex(Derived, Base));
3406 
3407       ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3408     }
3409   }
3410 }
3411 
3412 namespace {
3413 struct ExtractSubobjectHandler {
3414   EvalInfo &Info;
3415   const Expr *E;
3416   APValue &Result;
3417   const AccessKinds AccessKind;
3418 
3419   typedef bool result_type;
3420   bool failed() { return false; }
3421   bool found(APValue &Subobj, QualType SubobjType) {
3422     Result = Subobj;
3423     if (AccessKind == AK_ReadObjectRepresentation)
3424       return true;
3425     return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3426   }
3427   bool found(APSInt &Value, QualType SubobjType) {
3428     Result = APValue(Value);
3429     return true;
3430   }
3431   bool found(APFloat &Value, QualType SubobjType) {
3432     Result = APValue(Value);
3433     return true;
3434   }
3435 };
3436 } // end anonymous namespace
3437 
3438 /// Extract the designated sub-object of an rvalue.
3439 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3440                              const CompleteObject &Obj,
3441                              const SubobjectDesignator &Sub, APValue &Result,
3442                              AccessKinds AK = AK_Read) {
3443   assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3444   ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3445   return findSubobject(Info, E, Obj, Sub, Handler);
3446 }
3447 
3448 namespace {
3449 struct ModifySubobjectHandler {
3450   EvalInfo &Info;
3451   APValue &NewVal;
3452   const Expr *E;
3453 
3454   typedef bool result_type;
3455   static const AccessKinds AccessKind = AK_Assign;
3456 
3457   bool checkConst(QualType QT) {
3458     // Assigning to a const object has undefined behavior.
3459     if (QT.isConstQualified()) {
3460       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3461       return false;
3462     }
3463     return true;
3464   }
3465 
3466   bool failed() { return false; }
3467   bool found(APValue &Subobj, QualType SubobjType) {
3468     if (!checkConst(SubobjType))
3469       return false;
3470     // We've been given ownership of NewVal, so just swap it in.
3471     Subobj.swap(NewVal);
3472     return true;
3473   }
3474   bool found(APSInt &Value, QualType SubobjType) {
3475     if (!checkConst(SubobjType))
3476       return false;
3477     if (!NewVal.isInt()) {
3478       // Maybe trying to write a cast pointer value into a complex?
3479       Info.FFDiag(E);
3480       return false;
3481     }
3482     Value = NewVal.getInt();
3483     return true;
3484   }
3485   bool found(APFloat &Value, QualType SubobjType) {
3486     if (!checkConst(SubobjType))
3487       return false;
3488     Value = NewVal.getFloat();
3489     return true;
3490   }
3491 };
3492 } // end anonymous namespace
3493 
3494 const AccessKinds ModifySubobjectHandler::AccessKind;
3495 
3496 /// Update the designated sub-object of an rvalue to the given value.
3497 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3498                             const CompleteObject &Obj,
3499                             const SubobjectDesignator &Sub,
3500                             APValue &NewVal) {
3501   ModifySubobjectHandler Handler = { Info, NewVal, E };
3502   return findSubobject(Info, E, Obj, Sub, Handler);
3503 }
3504 
3505 /// Find the position where two subobject designators diverge, or equivalently
3506 /// the length of the common initial subsequence.
3507 static unsigned FindDesignatorMismatch(QualType ObjType,
3508                                        const SubobjectDesignator &A,
3509                                        const SubobjectDesignator &B,
3510                                        bool &WasArrayIndex) {
3511   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3512   for (/**/; I != N; ++I) {
3513     if (!ObjType.isNull() &&
3514         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3515       // Next subobject is an array element.
3516       if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3517         WasArrayIndex = true;
3518         return I;
3519       }
3520       if (ObjType->isAnyComplexType())
3521         ObjType = ObjType->castAs<ComplexType>()->getElementType();
3522       else
3523         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3524     } else {
3525       if (A.Entries[I].getAsBaseOrMember() !=
3526           B.Entries[I].getAsBaseOrMember()) {
3527         WasArrayIndex = false;
3528         return I;
3529       }
3530       if (const FieldDecl *FD = getAsField(A.Entries[I]))
3531         // Next subobject is a field.
3532         ObjType = FD->getType();
3533       else
3534         // Next subobject is a base class.
3535         ObjType = QualType();
3536     }
3537   }
3538   WasArrayIndex = false;
3539   return I;
3540 }
3541 
3542 /// Determine whether the given subobject designators refer to elements of the
3543 /// same array object.
3544 static bool AreElementsOfSameArray(QualType ObjType,
3545                                    const SubobjectDesignator &A,
3546                                    const SubobjectDesignator &B) {
3547   if (A.Entries.size() != B.Entries.size())
3548     return false;
3549 
3550   bool IsArray = A.MostDerivedIsArrayElement;
3551   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3552     // A is a subobject of the array element.
3553     return false;
3554 
3555   // If A (and B) designates an array element, the last entry will be the array
3556   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3557   // of length 1' case, and the entire path must match.
3558   bool WasArrayIndex;
3559   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3560   return CommonLength >= A.Entries.size() - IsArray;
3561 }
3562 
3563 /// Find the complete object to which an LValue refers.
3564 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3565                                          AccessKinds AK, const LValue &LVal,
3566                                          QualType LValType) {
3567   if (LVal.InvalidBase) {
3568     Info.FFDiag(E);
3569     return CompleteObject();
3570   }
3571 
3572   if (!LVal.Base) {
3573     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3574     return CompleteObject();
3575   }
3576 
3577   CallStackFrame *Frame = nullptr;
3578   unsigned Depth = 0;
3579   if (LVal.getLValueCallIndex()) {
3580     std::tie(Frame, Depth) =
3581         Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3582     if (!Frame) {
3583       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3584         << AK << LVal.Base.is<const ValueDecl*>();
3585       NoteLValueLocation(Info, LVal.Base);
3586       return CompleteObject();
3587     }
3588   }
3589 
3590   bool IsAccess = isAnyAccess(AK);
3591 
3592   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3593   // is not a constant expression (even if the object is non-volatile). We also
3594   // apply this rule to C++98, in order to conform to the expected 'volatile'
3595   // semantics.
3596   if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
3597     if (Info.getLangOpts().CPlusPlus)
3598       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3599         << AK << LValType;
3600     else
3601       Info.FFDiag(E);
3602     return CompleteObject();
3603   }
3604 
3605   // Compute value storage location and type of base object.
3606   APValue *BaseVal = nullptr;
3607   QualType BaseType = getType(LVal.Base);
3608 
3609   if (const ConstantExpr *CE =
3610           dyn_cast_or_null<ConstantExpr>(LVal.Base.dyn_cast<const Expr *>())) {
3611     /// Nested immediate invocation have been previously removed so if we found
3612     /// a ConstantExpr it can only be the EvaluatingDecl.
3613     assert(CE->isImmediateInvocation() && CE == Info.EvaluatingDecl);
3614     (void)CE;
3615     BaseVal = Info.EvaluatingDeclValue;
3616   } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
3617     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3618     // In C++11, constexpr, non-volatile variables initialized with constant
3619     // expressions are constant expressions too. Inside constexpr functions,
3620     // parameters are constant expressions even if they're non-const.
3621     // In C++1y, objects local to a constant expression (those with a Frame) are
3622     // both readable and writable inside constant expressions.
3623     // In C, such things can also be folded, although they are not ICEs.
3624     const VarDecl *VD = dyn_cast<VarDecl>(D);
3625     if (VD) {
3626       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3627         VD = VDef;
3628     }
3629     if (!VD || VD->isInvalidDecl()) {
3630       Info.FFDiag(E);
3631       return CompleteObject();
3632     }
3633 
3634     // Unless we're looking at a local variable or argument in a constexpr call,
3635     // the variable we're reading must be const.
3636     if (!Frame) {
3637       if (Info.getLangOpts().CPlusPlus14 &&
3638           lifetimeStartedInEvaluation(Info, LVal.Base)) {
3639         // OK, we can read and modify an object if we're in the process of
3640         // evaluating its initializer, because its lifetime began in this
3641         // evaluation.
3642       } else if (isModification(AK)) {
3643         // All the remaining cases do not permit modification of the object.
3644         Info.FFDiag(E, diag::note_constexpr_modify_global);
3645         return CompleteObject();
3646       } else if (VD->isConstexpr()) {
3647         // OK, we can read this variable.
3648       } else if (BaseType->isIntegralOrEnumerationType()) {
3649         // In OpenCL if a variable is in constant address space it is a const
3650         // value.
3651         if (!(BaseType.isConstQualified() ||
3652               (Info.getLangOpts().OpenCL &&
3653                BaseType.getAddressSpace() == LangAS::opencl_constant))) {
3654           if (!IsAccess)
3655             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3656           if (Info.getLangOpts().CPlusPlus) {
3657             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
3658             Info.Note(VD->getLocation(), diag::note_declared_at);
3659           } else {
3660             Info.FFDiag(E);
3661           }
3662           return CompleteObject();
3663         }
3664       } else if (!IsAccess) {
3665         return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3666       } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3667         // We support folding of const floating-point types, in order to make
3668         // static const data members of such types (supported as an extension)
3669         // more useful.
3670         if (Info.getLangOpts().CPlusPlus11) {
3671           Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3672           Info.Note(VD->getLocation(), diag::note_declared_at);
3673         } else {
3674           Info.CCEDiag(E);
3675         }
3676       } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3677         Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3678         // Keep evaluating to see what we can do.
3679       } else {
3680         // FIXME: Allow folding of values of any literal type in all languages.
3681         if (Info.checkingPotentialConstantExpression() &&
3682             VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3683           // The definition of this variable could be constexpr. We can't
3684           // access it right now, but may be able to in future.
3685         } else if (Info.getLangOpts().CPlusPlus11) {
3686           Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3687           Info.Note(VD->getLocation(), diag::note_declared_at);
3688         } else {
3689           Info.FFDiag(E);
3690         }
3691         return CompleteObject();
3692       }
3693     }
3694 
3695     if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
3696       return CompleteObject();
3697   } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
3698     Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
3699     if (!Alloc) {
3700       Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
3701       return CompleteObject();
3702     }
3703     return CompleteObject(LVal.Base, &(*Alloc)->Value,
3704                           LVal.Base.getDynamicAllocType());
3705   } else {
3706     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3707 
3708     if (!Frame) {
3709       if (const MaterializeTemporaryExpr *MTE =
3710               dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
3711         assert(MTE->getStorageDuration() == SD_Static &&
3712                "should have a frame for a non-global materialized temporary");
3713 
3714         // Per C++1y [expr.const]p2:
3715         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3716         //   - a [...] glvalue of integral or enumeration type that refers to
3717         //     a non-volatile const object [...]
3718         //   [...]
3719         //   - a [...] glvalue of literal type that refers to a non-volatile
3720         //     object whose lifetime began within the evaluation of e.
3721         //
3722         // C++11 misses the 'began within the evaluation of e' check and
3723         // instead allows all temporaries, including things like:
3724         //   int &&r = 1;
3725         //   int x = ++r;
3726         //   constexpr int k = r;
3727         // Therefore we use the C++14 rules in C++11 too.
3728         //
3729         // Note that temporaries whose lifetimes began while evaluating a
3730         // variable's constructor are not usable while evaluating the
3731         // corresponding destructor, not even if they're of const-qualified
3732         // types.
3733         if (!(BaseType.isConstQualified() &&
3734               BaseType->isIntegralOrEnumerationType()) &&
3735             !lifetimeStartedInEvaluation(Info, LVal.Base)) {
3736           if (!IsAccess)
3737             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3738           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
3739           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3740           return CompleteObject();
3741         }
3742 
3743         BaseVal = MTE->getOrCreateValue(false);
3744         assert(BaseVal && "got reference to unevaluated temporary");
3745       } else {
3746         if (!IsAccess)
3747           return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3748         APValue Val;
3749         LVal.moveInto(Val);
3750         Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
3751             << AK
3752             << Val.getAsString(Info.Ctx,
3753                                Info.Ctx.getLValueReferenceType(LValType));
3754         NoteLValueLocation(Info, LVal.Base);
3755         return CompleteObject();
3756       }
3757     } else {
3758       BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
3759       assert(BaseVal && "missing value for temporary");
3760     }
3761   }
3762 
3763   // In C++14, we can't safely access any mutable state when we might be
3764   // evaluating after an unmodeled side effect.
3765   //
3766   // FIXME: Not all local state is mutable. Allow local constant subobjects
3767   // to be read here (but take care with 'mutable' fields).
3768   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3769        Info.EvalStatus.HasSideEffects) ||
3770       (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth))
3771     return CompleteObject();
3772 
3773   return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
3774 }
3775 
3776 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
3777 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3778 /// glvalue referred to by an entity of reference type.
3779 ///
3780 /// \param Info - Information about the ongoing evaluation.
3781 /// \param Conv - The expression for which we are performing the conversion.
3782 ///               Used for diagnostics.
3783 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3784 ///               case of a non-class type).
3785 /// \param LVal - The glvalue on which we are attempting to perform this action.
3786 /// \param RVal - The produced value will be placed here.
3787 /// \param WantObjectRepresentation - If true, we're looking for the object
3788 ///               representation rather than the value, and in particular,
3789 ///               there is no requirement that the result be fully initialized.
3790 static bool
3791 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
3792                                const LValue &LVal, APValue &RVal,
3793                                bool WantObjectRepresentation = false) {
3794   if (LVal.Designator.Invalid)
3795     return false;
3796 
3797   // Check for special cases where there is no existing APValue to look at.
3798   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3799 
3800   AccessKinds AK =
3801       WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
3802 
3803   if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
3804     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3805       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3806       // initializer until now for such expressions. Such an expression can't be
3807       // an ICE in C, so this only matters for fold.
3808       if (Type.isVolatileQualified()) {
3809         Info.FFDiag(Conv);
3810         return false;
3811       }
3812       APValue Lit;
3813       if (!Evaluate(Lit, Info, CLE->getInitializer()))
3814         return false;
3815       CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
3816       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
3817     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
3818       // Special-case character extraction so we don't have to construct an
3819       // APValue for the whole string.
3820       assert(LVal.Designator.Entries.size() <= 1 &&
3821              "Can only read characters from string literals");
3822       if (LVal.Designator.Entries.empty()) {
3823         // Fail for now for LValue to RValue conversion of an array.
3824         // (This shouldn't show up in C/C++, but it could be triggered by a
3825         // weird EvaluateAsRValue call from a tool.)
3826         Info.FFDiag(Conv);
3827         return false;
3828       }
3829       if (LVal.Designator.isOnePastTheEnd()) {
3830         if (Info.getLangOpts().CPlusPlus11)
3831           Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
3832         else
3833           Info.FFDiag(Conv);
3834         return false;
3835       }
3836       uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
3837       RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
3838       return true;
3839     }
3840   }
3841 
3842   CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
3843   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
3844 }
3845 
3846 /// Perform an assignment of Val to LVal. Takes ownership of Val.
3847 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
3848                              QualType LValType, APValue &Val) {
3849   if (LVal.Designator.Invalid)
3850     return false;
3851 
3852   if (!Info.getLangOpts().CPlusPlus14) {
3853     Info.FFDiag(E);
3854     return false;
3855   }
3856 
3857   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3858   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3859 }
3860 
3861 namespace {
3862 struct CompoundAssignSubobjectHandler {
3863   EvalInfo &Info;
3864   const Expr *E;
3865   QualType PromotedLHSType;
3866   BinaryOperatorKind Opcode;
3867   const APValue &RHS;
3868 
3869   static const AccessKinds AccessKind = AK_Assign;
3870 
3871   typedef bool result_type;
3872 
3873   bool checkConst(QualType QT) {
3874     // Assigning to a const object has undefined behavior.
3875     if (QT.isConstQualified()) {
3876       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3877       return false;
3878     }
3879     return true;
3880   }
3881 
3882   bool failed() { return false; }
3883   bool found(APValue &Subobj, QualType SubobjType) {
3884     switch (Subobj.getKind()) {
3885     case APValue::Int:
3886       return found(Subobj.getInt(), SubobjType);
3887     case APValue::Float:
3888       return found(Subobj.getFloat(), SubobjType);
3889     case APValue::ComplexInt:
3890     case APValue::ComplexFloat:
3891       // FIXME: Implement complex compound assignment.
3892       Info.FFDiag(E);
3893       return false;
3894     case APValue::LValue:
3895       return foundPointer(Subobj, SubobjType);
3896     default:
3897       // FIXME: can this happen?
3898       Info.FFDiag(E);
3899       return false;
3900     }
3901   }
3902   bool found(APSInt &Value, QualType SubobjType) {
3903     if (!checkConst(SubobjType))
3904       return false;
3905 
3906     if (!SubobjType->isIntegerType()) {
3907       // We don't support compound assignment on integer-cast-to-pointer
3908       // values.
3909       Info.FFDiag(E);
3910       return false;
3911     }
3912 
3913     if (RHS.isInt()) {
3914       APSInt LHS =
3915           HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
3916       if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3917         return false;
3918       Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3919       return true;
3920     } else if (RHS.isFloat()) {
3921       APFloat FValue(0.0);
3922       return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
3923                                   FValue) &&
3924              handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
3925              HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
3926                                   Value);
3927     }
3928 
3929     Info.FFDiag(E);
3930     return false;
3931   }
3932   bool found(APFloat &Value, QualType SubobjType) {
3933     return checkConst(SubobjType) &&
3934            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3935                                   Value) &&
3936            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3937            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
3938   }
3939   bool foundPointer(APValue &Subobj, QualType SubobjType) {
3940     if (!checkConst(SubobjType))
3941       return false;
3942 
3943     QualType PointeeType;
3944     if (const PointerType *PT = SubobjType->getAs<PointerType>())
3945       PointeeType = PT->getPointeeType();
3946 
3947     if (PointeeType.isNull() || !RHS.isInt() ||
3948         (Opcode != BO_Add && Opcode != BO_Sub)) {
3949       Info.FFDiag(E);
3950       return false;
3951     }
3952 
3953     APSInt Offset = RHS.getInt();
3954     if (Opcode == BO_Sub)
3955       negateAsSigned(Offset);
3956 
3957     LValue LVal;
3958     LVal.setFrom(Info.Ctx, Subobj);
3959     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3960       return false;
3961     LVal.moveInto(Subobj);
3962     return true;
3963   }
3964 };
3965 } // end anonymous namespace
3966 
3967 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3968 
3969 /// Perform a compound assignment of LVal <op>= RVal.
3970 static bool handleCompoundAssignment(
3971     EvalInfo &Info, const Expr *E,
3972     const LValue &LVal, QualType LValType, QualType PromotedLValType,
3973     BinaryOperatorKind Opcode, const APValue &RVal) {
3974   if (LVal.Designator.Invalid)
3975     return false;
3976 
3977   if (!Info.getLangOpts().CPlusPlus14) {
3978     Info.FFDiag(E);
3979     return false;
3980   }
3981 
3982   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3983   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3984                                              RVal };
3985   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3986 }
3987 
3988 namespace {
3989 struct IncDecSubobjectHandler {
3990   EvalInfo &Info;
3991   const UnaryOperator *E;
3992   AccessKinds AccessKind;
3993   APValue *Old;
3994 
3995   typedef bool result_type;
3996 
3997   bool checkConst(QualType QT) {
3998     // Assigning to a const object has undefined behavior.
3999     if (QT.isConstQualified()) {
4000       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4001       return false;
4002     }
4003     return true;
4004   }
4005 
4006   bool failed() { return false; }
4007   bool found(APValue &Subobj, QualType SubobjType) {
4008     // Stash the old value. Also clear Old, so we don't clobber it later
4009     // if we're post-incrementing a complex.
4010     if (Old) {
4011       *Old = Subobj;
4012       Old = nullptr;
4013     }
4014 
4015     switch (Subobj.getKind()) {
4016     case APValue::Int:
4017       return found(Subobj.getInt(), SubobjType);
4018     case APValue::Float:
4019       return found(Subobj.getFloat(), SubobjType);
4020     case APValue::ComplexInt:
4021       return found(Subobj.getComplexIntReal(),
4022                    SubobjType->castAs<ComplexType>()->getElementType()
4023                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4024     case APValue::ComplexFloat:
4025       return found(Subobj.getComplexFloatReal(),
4026                    SubobjType->castAs<ComplexType>()->getElementType()
4027                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4028     case APValue::LValue:
4029       return foundPointer(Subobj, SubobjType);
4030     default:
4031       // FIXME: can this happen?
4032       Info.FFDiag(E);
4033       return false;
4034     }
4035   }
4036   bool found(APSInt &Value, QualType SubobjType) {
4037     if (!checkConst(SubobjType))
4038       return false;
4039 
4040     if (!SubobjType->isIntegerType()) {
4041       // We don't support increment / decrement on integer-cast-to-pointer
4042       // values.
4043       Info.FFDiag(E);
4044       return false;
4045     }
4046 
4047     if (Old) *Old = APValue(Value);
4048 
4049     // bool arithmetic promotes to int, and the conversion back to bool
4050     // doesn't reduce mod 2^n, so special-case it.
4051     if (SubobjType->isBooleanType()) {
4052       if (AccessKind == AK_Increment)
4053         Value = 1;
4054       else
4055         Value = !Value;
4056       return true;
4057     }
4058 
4059     bool WasNegative = Value.isNegative();
4060     if (AccessKind == AK_Increment) {
4061       ++Value;
4062 
4063       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4064         APSInt ActualValue(Value, /*IsUnsigned*/true);
4065         return HandleOverflow(Info, E, ActualValue, SubobjType);
4066       }
4067     } else {
4068       --Value;
4069 
4070       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4071         unsigned BitWidth = Value.getBitWidth();
4072         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4073         ActualValue.setBit(BitWidth);
4074         return HandleOverflow(Info, E, ActualValue, SubobjType);
4075       }
4076     }
4077     return true;
4078   }
4079   bool found(APFloat &Value, QualType SubobjType) {
4080     if (!checkConst(SubobjType))
4081       return false;
4082 
4083     if (Old) *Old = APValue(Value);
4084 
4085     APFloat One(Value.getSemantics(), 1);
4086     if (AccessKind == AK_Increment)
4087       Value.add(One, APFloat::rmNearestTiesToEven);
4088     else
4089       Value.subtract(One, APFloat::rmNearestTiesToEven);
4090     return true;
4091   }
4092   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4093     if (!checkConst(SubobjType))
4094       return false;
4095 
4096     QualType PointeeType;
4097     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4098       PointeeType = PT->getPointeeType();
4099     else {
4100       Info.FFDiag(E);
4101       return false;
4102     }
4103 
4104     LValue LVal;
4105     LVal.setFrom(Info.Ctx, Subobj);
4106     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4107                                      AccessKind == AK_Increment ? 1 : -1))
4108       return false;
4109     LVal.moveInto(Subobj);
4110     return true;
4111   }
4112 };
4113 } // end anonymous namespace
4114 
4115 /// Perform an increment or decrement on LVal.
4116 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4117                          QualType LValType, bool IsIncrement, APValue *Old) {
4118   if (LVal.Designator.Invalid)
4119     return false;
4120 
4121   if (!Info.getLangOpts().CPlusPlus14) {
4122     Info.FFDiag(E);
4123     return false;
4124   }
4125 
4126   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4127   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4128   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4129   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4130 }
4131 
4132 /// Build an lvalue for the object argument of a member function call.
4133 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4134                                    LValue &This) {
4135   if (Object->getType()->isPointerType() && Object->isRValue())
4136     return EvaluatePointer(Object, This, Info);
4137 
4138   if (Object->isGLValue())
4139     return EvaluateLValue(Object, This, Info);
4140 
4141   if (Object->getType()->isLiteralType(Info.Ctx))
4142     return EvaluateTemporary(Object, This, Info);
4143 
4144   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4145   return false;
4146 }
4147 
4148 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
4149 /// lvalue referring to the result.
4150 ///
4151 /// \param Info - Information about the ongoing evaluation.
4152 /// \param LV - An lvalue referring to the base of the member pointer.
4153 /// \param RHS - The member pointer expression.
4154 /// \param IncludeMember - Specifies whether the member itself is included in
4155 ///        the resulting LValue subobject designator. This is not possible when
4156 ///        creating a bound member function.
4157 /// \return The field or method declaration to which the member pointer refers,
4158 ///         or 0 if evaluation fails.
4159 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4160                                                   QualType LVType,
4161                                                   LValue &LV,
4162                                                   const Expr *RHS,
4163                                                   bool IncludeMember = true) {
4164   MemberPtr MemPtr;
4165   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4166     return nullptr;
4167 
4168   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4169   // member value, the behavior is undefined.
4170   if (!MemPtr.getDecl()) {
4171     // FIXME: Specific diagnostic.
4172     Info.FFDiag(RHS);
4173     return nullptr;
4174   }
4175 
4176   if (MemPtr.isDerivedMember()) {
4177     // This is a member of some derived class. Truncate LV appropriately.
4178     // The end of the derived-to-base path for the base object must match the
4179     // derived-to-base path for the member pointer.
4180     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4181         LV.Designator.Entries.size()) {
4182       Info.FFDiag(RHS);
4183       return nullptr;
4184     }
4185     unsigned PathLengthToMember =
4186         LV.Designator.Entries.size() - MemPtr.Path.size();
4187     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4188       const CXXRecordDecl *LVDecl = getAsBaseClass(
4189           LV.Designator.Entries[PathLengthToMember + I]);
4190       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4191       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4192         Info.FFDiag(RHS);
4193         return nullptr;
4194       }
4195     }
4196 
4197     // Truncate the lvalue to the appropriate derived class.
4198     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4199                             PathLengthToMember))
4200       return nullptr;
4201   } else if (!MemPtr.Path.empty()) {
4202     // Extend the LValue path with the member pointer's path.
4203     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4204                                   MemPtr.Path.size() + IncludeMember);
4205 
4206     // Walk down to the appropriate base class.
4207     if (const PointerType *PT = LVType->getAs<PointerType>())
4208       LVType = PT->getPointeeType();
4209     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4210     assert(RD && "member pointer access on non-class-type expression");
4211     // The first class in the path is that of the lvalue.
4212     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4213       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4214       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4215         return nullptr;
4216       RD = Base;
4217     }
4218     // Finally cast to the class containing the member.
4219     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4220                                 MemPtr.getContainingRecord()))
4221       return nullptr;
4222   }
4223 
4224   // Add the member. Note that we cannot build bound member functions here.
4225   if (IncludeMember) {
4226     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4227       if (!HandleLValueMember(Info, RHS, LV, FD))
4228         return nullptr;
4229     } else if (const IndirectFieldDecl *IFD =
4230                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4231       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4232         return nullptr;
4233     } else {
4234       llvm_unreachable("can't construct reference to bound member function");
4235     }
4236   }
4237 
4238   return MemPtr.getDecl();
4239 }
4240 
4241 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4242                                                   const BinaryOperator *BO,
4243                                                   LValue &LV,
4244                                                   bool IncludeMember = true) {
4245   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4246 
4247   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4248     if (Info.noteFailure()) {
4249       MemberPtr MemPtr;
4250       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4251     }
4252     return nullptr;
4253   }
4254 
4255   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4256                                    BO->getRHS(), IncludeMember);
4257 }
4258 
4259 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4260 /// the provided lvalue, which currently refers to the base object.
4261 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4262                                     LValue &Result) {
4263   SubobjectDesignator &D = Result.Designator;
4264   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4265     return false;
4266 
4267   QualType TargetQT = E->getType();
4268   if (const PointerType *PT = TargetQT->getAs<PointerType>())
4269     TargetQT = PT->getPointeeType();
4270 
4271   // Check this cast lands within the final derived-to-base subobject path.
4272   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4273     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4274       << D.MostDerivedType << TargetQT;
4275     return false;
4276   }
4277 
4278   // Check the type of the final cast. We don't need to check the path,
4279   // since a cast can only be formed if the path is unique.
4280   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4281   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4282   const CXXRecordDecl *FinalType;
4283   if (NewEntriesSize == D.MostDerivedPathLength)
4284     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4285   else
4286     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4287   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4288     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4289       << D.MostDerivedType << TargetQT;
4290     return false;
4291   }
4292 
4293   // Truncate the lvalue to the appropriate derived class.
4294   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4295 }
4296 
4297 /// Get the value to use for a default-initialized object of type T.
4298 static APValue getDefaultInitValue(QualType T) {
4299   if (auto *RD = T->getAsCXXRecordDecl()) {
4300     if (RD->isUnion())
4301       return APValue((const FieldDecl*)nullptr);
4302 
4303     APValue Struct(APValue::UninitStruct(), RD->getNumBases(),
4304                    std::distance(RD->field_begin(), RD->field_end()));
4305 
4306     unsigned Index = 0;
4307     for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4308            End = RD->bases_end(); I != End; ++I, ++Index)
4309       Struct.getStructBase(Index) = getDefaultInitValue(I->getType());
4310 
4311     for (const auto *I : RD->fields()) {
4312       if (I->isUnnamedBitfield())
4313         continue;
4314       Struct.getStructField(I->getFieldIndex()) =
4315           getDefaultInitValue(I->getType());
4316     }
4317     return Struct;
4318   }
4319 
4320   if (auto *AT =
4321           dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4322     APValue Array(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4323     if (Array.hasArrayFiller())
4324       Array.getArrayFiller() = getDefaultInitValue(AT->getElementType());
4325     return Array;
4326   }
4327 
4328   return APValue::IndeterminateValue();
4329 }
4330 
4331 namespace {
4332 enum EvalStmtResult {
4333   /// Evaluation failed.
4334   ESR_Failed,
4335   /// Hit a 'return' statement.
4336   ESR_Returned,
4337   /// Evaluation succeeded.
4338   ESR_Succeeded,
4339   /// Hit a 'continue' statement.
4340   ESR_Continue,
4341   /// Hit a 'break' statement.
4342   ESR_Break,
4343   /// Still scanning for 'case' or 'default' statement.
4344   ESR_CaseNotFound
4345 };
4346 }
4347 
4348 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4349   // We don't need to evaluate the initializer for a static local.
4350   if (!VD->hasLocalStorage())
4351     return true;
4352 
4353   LValue Result;
4354   APValue &Val =
4355       Info.CurrentCall->createTemporary(VD, VD->getType(), true, Result);
4356 
4357   const Expr *InitE = VD->getInit();
4358   if (!InitE) {
4359     Val = getDefaultInitValue(VD->getType());
4360     return true;
4361   }
4362 
4363   if (InitE->isValueDependent())
4364     return false;
4365 
4366   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4367     // Wipe out any partially-computed value, to allow tracking that this
4368     // evaluation failed.
4369     Val = APValue();
4370     return false;
4371   }
4372 
4373   return true;
4374 }
4375 
4376 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4377   bool OK = true;
4378 
4379   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4380     OK &= EvaluateVarDecl(Info, VD);
4381 
4382   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4383     for (auto *BD : DD->bindings())
4384       if (auto *VD = BD->getHoldingVar())
4385         OK &= EvaluateDecl(Info, VD);
4386 
4387   return OK;
4388 }
4389 
4390 
4391 /// Evaluate a condition (either a variable declaration or an expression).
4392 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4393                          const Expr *Cond, bool &Result) {
4394   FullExpressionRAII Scope(Info);
4395   if (CondDecl && !EvaluateDecl(Info, CondDecl))
4396     return false;
4397   if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4398     return false;
4399   return Scope.destroy();
4400 }
4401 
4402 namespace {
4403 /// A location where the result (returned value) of evaluating a
4404 /// statement should be stored.
4405 struct StmtResult {
4406   /// The APValue that should be filled in with the returned value.
4407   APValue &Value;
4408   /// The location containing the result, if any (used to support RVO).
4409   const LValue *Slot;
4410 };
4411 
4412 struct TempVersionRAII {
4413   CallStackFrame &Frame;
4414 
4415   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4416     Frame.pushTempVersion();
4417   }
4418 
4419   ~TempVersionRAII() {
4420     Frame.popTempVersion();
4421   }
4422 };
4423 
4424 }
4425 
4426 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4427                                    const Stmt *S,
4428                                    const SwitchCase *SC = nullptr);
4429 
4430 /// Evaluate the body of a loop, and translate the result as appropriate.
4431 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4432                                        const Stmt *Body,
4433                                        const SwitchCase *Case = nullptr) {
4434   BlockScopeRAII Scope(Info);
4435 
4436   EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4437   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4438     ESR = ESR_Failed;
4439 
4440   switch (ESR) {
4441   case ESR_Break:
4442     return ESR_Succeeded;
4443   case ESR_Succeeded:
4444   case ESR_Continue:
4445     return ESR_Continue;
4446   case ESR_Failed:
4447   case ESR_Returned:
4448   case ESR_CaseNotFound:
4449     return ESR;
4450   }
4451   llvm_unreachable("Invalid EvalStmtResult!");
4452 }
4453 
4454 /// Evaluate a switch statement.
4455 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4456                                      const SwitchStmt *SS) {
4457   BlockScopeRAII Scope(Info);
4458 
4459   // Evaluate the switch condition.
4460   APSInt Value;
4461   {
4462     if (const Stmt *Init = SS->getInit()) {
4463       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4464       if (ESR != ESR_Succeeded) {
4465         if (ESR != ESR_Failed && !Scope.destroy())
4466           ESR = ESR_Failed;
4467         return ESR;
4468       }
4469     }
4470 
4471     FullExpressionRAII CondScope(Info);
4472     if (SS->getConditionVariable() &&
4473         !EvaluateDecl(Info, SS->getConditionVariable()))
4474       return ESR_Failed;
4475     if (!EvaluateInteger(SS->getCond(), Value, Info))
4476       return ESR_Failed;
4477     if (!CondScope.destroy())
4478       return ESR_Failed;
4479   }
4480 
4481   // Find the switch case corresponding to the value of the condition.
4482   // FIXME: Cache this lookup.
4483   const SwitchCase *Found = nullptr;
4484   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4485        SC = SC->getNextSwitchCase()) {
4486     if (isa<DefaultStmt>(SC)) {
4487       Found = SC;
4488       continue;
4489     }
4490 
4491     const CaseStmt *CS = cast<CaseStmt>(SC);
4492     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4493     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4494                               : LHS;
4495     if (LHS <= Value && Value <= RHS) {
4496       Found = SC;
4497       break;
4498     }
4499   }
4500 
4501   if (!Found)
4502     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4503 
4504   // Search the switch body for the switch case and evaluate it from there.
4505   EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
4506   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4507     return ESR_Failed;
4508 
4509   switch (ESR) {
4510   case ESR_Break:
4511     return ESR_Succeeded;
4512   case ESR_Succeeded:
4513   case ESR_Continue:
4514   case ESR_Failed:
4515   case ESR_Returned:
4516     return ESR;
4517   case ESR_CaseNotFound:
4518     // This can only happen if the switch case is nested within a statement
4519     // expression. We have no intention of supporting that.
4520     Info.FFDiag(Found->getBeginLoc(),
4521                 diag::note_constexpr_stmt_expr_unsupported);
4522     return ESR_Failed;
4523   }
4524   llvm_unreachable("Invalid EvalStmtResult!");
4525 }
4526 
4527 // Evaluate a statement.
4528 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4529                                    const Stmt *S, const SwitchCase *Case) {
4530   if (!Info.nextStep(S))
4531     return ESR_Failed;
4532 
4533   // If we're hunting down a 'case' or 'default' label, recurse through
4534   // substatements until we hit the label.
4535   if (Case) {
4536     switch (S->getStmtClass()) {
4537     case Stmt::CompoundStmtClass:
4538       // FIXME: Precompute which substatement of a compound statement we
4539       // would jump to, and go straight there rather than performing a
4540       // linear scan each time.
4541     case Stmt::LabelStmtClass:
4542     case Stmt::AttributedStmtClass:
4543     case Stmt::DoStmtClass:
4544       break;
4545 
4546     case Stmt::CaseStmtClass:
4547     case Stmt::DefaultStmtClass:
4548       if (Case == S)
4549         Case = nullptr;
4550       break;
4551 
4552     case Stmt::IfStmtClass: {
4553       // FIXME: Precompute which side of an 'if' we would jump to, and go
4554       // straight there rather than scanning both sides.
4555       const IfStmt *IS = cast<IfStmt>(S);
4556 
4557       // Wrap the evaluation in a block scope, in case it's a DeclStmt
4558       // preceded by our switch label.
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 = IS->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       // Condition variable must be initialized if it exists.
4572       // FIXME: We can skip evaluating the body if there's a condition
4573       // variable, as there can't be any case labels within it.
4574       // (The same is true for 'for' statements.)
4575 
4576       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
4577       if (ESR == ESR_Failed)
4578         return ESR;
4579       if (ESR != ESR_CaseNotFound)
4580         return Scope.destroy() ? ESR : ESR_Failed;
4581       if (!IS->getElse())
4582         return ESR_CaseNotFound;
4583 
4584       ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
4585       if (ESR == ESR_Failed)
4586         return ESR;
4587       if (ESR != ESR_CaseNotFound)
4588         return Scope.destroy() ? ESR : ESR_Failed;
4589       return ESR_CaseNotFound;
4590     }
4591 
4592     case Stmt::WhileStmtClass: {
4593       EvalStmtResult ESR =
4594           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4595       if (ESR != ESR_Continue)
4596         return ESR;
4597       break;
4598     }
4599 
4600     case Stmt::ForStmtClass: {
4601       const ForStmt *FS = cast<ForStmt>(S);
4602       BlockScopeRAII Scope(Info);
4603 
4604       // Step into the init statement in case it brings an (uninitialized)
4605       // variable into scope.
4606       if (const Stmt *Init = FS->getInit()) {
4607         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
4608         if (ESR != ESR_CaseNotFound) {
4609           assert(ESR != ESR_Succeeded);
4610           return ESR;
4611         }
4612       }
4613 
4614       EvalStmtResult ESR =
4615           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4616       if (ESR != ESR_Continue)
4617         return ESR;
4618       if (FS->getInc()) {
4619         FullExpressionRAII IncScope(Info);
4620         if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
4621           return ESR_Failed;
4622       }
4623       break;
4624     }
4625 
4626     case Stmt::DeclStmtClass: {
4627       // Start the lifetime of any uninitialized variables we encounter. They
4628       // might be used by the selected branch of the switch.
4629       const DeclStmt *DS = cast<DeclStmt>(S);
4630       for (const auto *D : DS->decls()) {
4631         if (const auto *VD = dyn_cast<VarDecl>(D)) {
4632           if (VD->hasLocalStorage() && !VD->getInit())
4633             if (!EvaluateVarDecl(Info, VD))
4634               return ESR_Failed;
4635           // FIXME: If the variable has initialization that can't be jumped
4636           // over, bail out of any immediately-surrounding compound-statement
4637           // too. There can't be any case labels here.
4638         }
4639       }
4640       return ESR_CaseNotFound;
4641     }
4642 
4643     default:
4644       return ESR_CaseNotFound;
4645     }
4646   }
4647 
4648   switch (S->getStmtClass()) {
4649   default:
4650     if (const Expr *E = dyn_cast<Expr>(S)) {
4651       // Don't bother evaluating beyond an expression-statement which couldn't
4652       // be evaluated.
4653       // FIXME: Do we need the FullExpressionRAII object here?
4654       // VisitExprWithCleanups should create one when necessary.
4655       FullExpressionRAII Scope(Info);
4656       if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
4657         return ESR_Failed;
4658       return ESR_Succeeded;
4659     }
4660 
4661     Info.FFDiag(S->getBeginLoc());
4662     return ESR_Failed;
4663 
4664   case Stmt::NullStmtClass:
4665     return ESR_Succeeded;
4666 
4667   case Stmt::DeclStmtClass: {
4668     const DeclStmt *DS = cast<DeclStmt>(S);
4669     for (const auto *D : DS->decls()) {
4670       // Each declaration initialization is its own full-expression.
4671       FullExpressionRAII Scope(Info);
4672       if (!EvaluateDecl(Info, D) && !Info.noteFailure())
4673         return ESR_Failed;
4674       if (!Scope.destroy())
4675         return ESR_Failed;
4676     }
4677     return ESR_Succeeded;
4678   }
4679 
4680   case Stmt::ReturnStmtClass: {
4681     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
4682     FullExpressionRAII Scope(Info);
4683     if (RetExpr &&
4684         !(Result.Slot
4685               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4686               : Evaluate(Result.Value, Info, RetExpr)))
4687       return ESR_Failed;
4688     return Scope.destroy() ? ESR_Returned : ESR_Failed;
4689   }
4690 
4691   case Stmt::CompoundStmtClass: {
4692     BlockScopeRAII Scope(Info);
4693 
4694     const CompoundStmt *CS = cast<CompoundStmt>(S);
4695     for (const auto *BI : CS->body()) {
4696       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
4697       if (ESR == ESR_Succeeded)
4698         Case = nullptr;
4699       else if (ESR != ESR_CaseNotFound) {
4700         if (ESR != ESR_Failed && !Scope.destroy())
4701           return ESR_Failed;
4702         return ESR;
4703       }
4704     }
4705     if (Case)
4706       return ESR_CaseNotFound;
4707     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4708   }
4709 
4710   case Stmt::IfStmtClass: {
4711     const IfStmt *IS = cast<IfStmt>(S);
4712 
4713     // Evaluate the condition, as either a var decl or as an expression.
4714     BlockScopeRAII Scope(Info);
4715     if (const Stmt *Init = IS->getInit()) {
4716       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4717       if (ESR != ESR_Succeeded) {
4718         if (ESR != ESR_Failed && !Scope.destroy())
4719           return ESR_Failed;
4720         return ESR;
4721       }
4722     }
4723     bool Cond;
4724     if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
4725       return ESR_Failed;
4726 
4727     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4728       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4729       if (ESR != ESR_Succeeded) {
4730         if (ESR != ESR_Failed && !Scope.destroy())
4731           return ESR_Failed;
4732         return ESR;
4733       }
4734     }
4735     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4736   }
4737 
4738   case Stmt::WhileStmtClass: {
4739     const WhileStmt *WS = cast<WhileStmt>(S);
4740     while (true) {
4741       BlockScopeRAII Scope(Info);
4742       bool Continue;
4743       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4744                         Continue))
4745         return ESR_Failed;
4746       if (!Continue)
4747         break;
4748 
4749       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4750       if (ESR != ESR_Continue) {
4751         if (ESR != ESR_Failed && !Scope.destroy())
4752           return ESR_Failed;
4753         return ESR;
4754       }
4755       if (!Scope.destroy())
4756         return ESR_Failed;
4757     }
4758     return ESR_Succeeded;
4759   }
4760 
4761   case Stmt::DoStmtClass: {
4762     const DoStmt *DS = cast<DoStmt>(S);
4763     bool Continue;
4764     do {
4765       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
4766       if (ESR != ESR_Continue)
4767         return ESR;
4768       Case = nullptr;
4769 
4770       FullExpressionRAII CondScope(Info);
4771       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
4772           !CondScope.destroy())
4773         return ESR_Failed;
4774     } while (Continue);
4775     return ESR_Succeeded;
4776   }
4777 
4778   case Stmt::ForStmtClass: {
4779     const ForStmt *FS = cast<ForStmt>(S);
4780     BlockScopeRAII ForScope(Info);
4781     if (FS->getInit()) {
4782       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4783       if (ESR != ESR_Succeeded) {
4784         if (ESR != ESR_Failed && !ForScope.destroy())
4785           return ESR_Failed;
4786         return ESR;
4787       }
4788     }
4789     while (true) {
4790       BlockScopeRAII IterScope(Info);
4791       bool Continue = true;
4792       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4793                                          FS->getCond(), Continue))
4794         return ESR_Failed;
4795       if (!Continue)
4796         break;
4797 
4798       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4799       if (ESR != ESR_Continue) {
4800         if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
4801           return ESR_Failed;
4802         return ESR;
4803       }
4804 
4805       if (FS->getInc()) {
4806         FullExpressionRAII IncScope(Info);
4807         if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
4808           return ESR_Failed;
4809       }
4810 
4811       if (!IterScope.destroy())
4812         return ESR_Failed;
4813     }
4814     return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
4815   }
4816 
4817   case Stmt::CXXForRangeStmtClass: {
4818     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
4819     BlockScopeRAII Scope(Info);
4820 
4821     // Evaluate the init-statement if present.
4822     if (FS->getInit()) {
4823       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4824       if (ESR != ESR_Succeeded) {
4825         if (ESR != ESR_Failed && !Scope.destroy())
4826           return ESR_Failed;
4827         return ESR;
4828       }
4829     }
4830 
4831     // Initialize the __range variable.
4832     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4833     if (ESR != ESR_Succeeded) {
4834       if (ESR != ESR_Failed && !Scope.destroy())
4835         return ESR_Failed;
4836       return ESR;
4837     }
4838 
4839     // Create the __begin and __end iterators.
4840     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4841     if (ESR != ESR_Succeeded) {
4842       if (ESR != ESR_Failed && !Scope.destroy())
4843         return ESR_Failed;
4844       return ESR;
4845     }
4846     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
4847     if (ESR != ESR_Succeeded) {
4848       if (ESR != ESR_Failed && !Scope.destroy())
4849         return ESR_Failed;
4850       return ESR;
4851     }
4852 
4853     while (true) {
4854       // Condition: __begin != __end.
4855       {
4856         bool Continue = true;
4857         FullExpressionRAII CondExpr(Info);
4858         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4859           return ESR_Failed;
4860         if (!Continue)
4861           break;
4862       }
4863 
4864       // User's variable declaration, initialized by *__begin.
4865       BlockScopeRAII InnerScope(Info);
4866       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4867       if (ESR != ESR_Succeeded) {
4868         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
4869           return ESR_Failed;
4870         return ESR;
4871       }
4872 
4873       // Loop body.
4874       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4875       if (ESR != ESR_Continue) {
4876         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
4877           return ESR_Failed;
4878         return ESR;
4879       }
4880 
4881       // Increment: ++__begin
4882       if (!EvaluateIgnoredValue(Info, FS->getInc()))
4883         return ESR_Failed;
4884 
4885       if (!InnerScope.destroy())
4886         return ESR_Failed;
4887     }
4888 
4889     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4890   }
4891 
4892   case Stmt::SwitchStmtClass:
4893     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4894 
4895   case Stmt::ContinueStmtClass:
4896     return ESR_Continue;
4897 
4898   case Stmt::BreakStmtClass:
4899     return ESR_Break;
4900 
4901   case Stmt::LabelStmtClass:
4902     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4903 
4904   case Stmt::AttributedStmtClass:
4905     // As a general principle, C++11 attributes can be ignored without
4906     // any semantic impact.
4907     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4908                         Case);
4909 
4910   case Stmt::CaseStmtClass:
4911   case Stmt::DefaultStmtClass:
4912     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
4913   case Stmt::CXXTryStmtClass:
4914     // Evaluate try blocks by evaluating all sub statements.
4915     return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
4916   }
4917 }
4918 
4919 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4920 /// default constructor. If so, we'll fold it whether or not it's marked as
4921 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
4922 /// so we need special handling.
4923 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
4924                                            const CXXConstructorDecl *CD,
4925                                            bool IsValueInitialization) {
4926   if (!CD->isTrivial() || !CD->isDefaultConstructor())
4927     return false;
4928 
4929   // Value-initialization does not call a trivial default constructor, so such a
4930   // call is a core constant expression whether or not the constructor is
4931   // constexpr.
4932   if (!CD->isConstexpr() && !IsValueInitialization) {
4933     if (Info.getLangOpts().CPlusPlus11) {
4934       // FIXME: If DiagDecl is an implicitly-declared special member function,
4935       // we should be much more explicit about why it's not constexpr.
4936       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4937         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4938       Info.Note(CD->getLocation(), diag::note_declared_at);
4939     } else {
4940       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4941     }
4942   }
4943   return true;
4944 }
4945 
4946 /// CheckConstexprFunction - Check that a function can be called in a constant
4947 /// expression.
4948 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4949                                    const FunctionDecl *Declaration,
4950                                    const FunctionDecl *Definition,
4951                                    const Stmt *Body) {
4952   // Potential constant expressions can contain calls to declared, but not yet
4953   // defined, constexpr functions.
4954   if (Info.checkingPotentialConstantExpression() && !Definition &&
4955       Declaration->isConstexpr())
4956     return false;
4957 
4958   // Bail out if the function declaration itself is invalid.  We will
4959   // have produced a relevant diagnostic while parsing it, so just
4960   // note the problematic sub-expression.
4961   if (Declaration->isInvalidDecl()) {
4962     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4963     return false;
4964   }
4965 
4966   // DR1872: An instantiated virtual constexpr function can't be called in a
4967   // constant expression (prior to C++20). We can still constant-fold such a
4968   // call.
4969   if (!Info.Ctx.getLangOpts().CPlusPlus2a && isa<CXXMethodDecl>(Declaration) &&
4970       cast<CXXMethodDecl>(Declaration)->isVirtual())
4971     Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
4972 
4973   if (Definition && Definition->isInvalidDecl()) {
4974     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4975     return false;
4976   }
4977 
4978   // Can we evaluate this function call?
4979   if (Definition && Definition->isConstexpr() && Body)
4980     return true;
4981 
4982   if (Info.getLangOpts().CPlusPlus11) {
4983     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
4984 
4985     // If this function is not constexpr because it is an inherited
4986     // non-constexpr constructor, diagnose that directly.
4987     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4988     if (CD && CD->isInheritingConstructor()) {
4989       auto *Inherited = CD->getInheritedConstructor().getConstructor();
4990       if (!Inherited->isConstexpr())
4991         DiagDecl = CD = Inherited;
4992     }
4993 
4994     // FIXME: If DiagDecl is an implicitly-declared special member function
4995     // or an inheriting constructor, we should be much more explicit about why
4996     // it's not constexpr.
4997     if (CD && CD->isInheritingConstructor())
4998       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
4999         << CD->getInheritedConstructor().getConstructor()->getParent();
5000     else
5001       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5002         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5003     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5004   } else {
5005     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5006   }
5007   return false;
5008 }
5009 
5010 namespace {
5011 struct CheckDynamicTypeHandler {
5012   AccessKinds AccessKind;
5013   typedef bool result_type;
5014   bool failed() { return false; }
5015   bool found(APValue &Subobj, QualType SubobjType) { return true; }
5016   bool found(APSInt &Value, QualType SubobjType) { return true; }
5017   bool found(APFloat &Value, QualType SubobjType) { return true; }
5018 };
5019 } // end anonymous namespace
5020 
5021 /// Check that we can access the notional vptr of an object / determine its
5022 /// dynamic type.
5023 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5024                              AccessKinds AK, bool Polymorphic) {
5025   if (This.Designator.Invalid)
5026     return false;
5027 
5028   CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5029 
5030   if (!Obj)
5031     return false;
5032 
5033   if (!Obj.Value) {
5034     // The object is not usable in constant expressions, so we can't inspect
5035     // its value to see if it's in-lifetime or what the active union members
5036     // are. We can still check for a one-past-the-end lvalue.
5037     if (This.Designator.isOnePastTheEnd() ||
5038         This.Designator.isMostDerivedAnUnsizedArray()) {
5039       Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5040                          ? diag::note_constexpr_access_past_end
5041                          : diag::note_constexpr_access_unsized_array)
5042           << AK;
5043       return false;
5044     } else if (Polymorphic) {
5045       // Conservatively refuse to perform a polymorphic operation if we would
5046       // not be able to read a notional 'vptr' value.
5047       APValue Val;
5048       This.moveInto(Val);
5049       QualType StarThisType =
5050           Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5051       Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5052           << AK << Val.getAsString(Info.Ctx, StarThisType);
5053       return false;
5054     }
5055     return true;
5056   }
5057 
5058   CheckDynamicTypeHandler Handler{AK};
5059   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5060 }
5061 
5062 /// Check that the pointee of the 'this' pointer in a member function call is
5063 /// either within its lifetime or in its period of construction or destruction.
5064 static bool
5065 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5066                                      const LValue &This,
5067                                      const CXXMethodDecl *NamedMember) {
5068   return checkDynamicType(
5069       Info, E, This,
5070       isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5071 }
5072 
5073 struct DynamicType {
5074   /// The dynamic class type of the object.
5075   const CXXRecordDecl *Type;
5076   /// The corresponding path length in the lvalue.
5077   unsigned PathLength;
5078 };
5079 
5080 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5081                                              unsigned PathLength) {
5082   assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5083       Designator.Entries.size() && "invalid path length");
5084   return (PathLength == Designator.MostDerivedPathLength)
5085              ? Designator.MostDerivedType->getAsCXXRecordDecl()
5086              : getAsBaseClass(Designator.Entries[PathLength - 1]);
5087 }
5088 
5089 /// Determine the dynamic type of an object.
5090 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
5091                                                 LValue &This, AccessKinds AK) {
5092   // If we don't have an lvalue denoting an object of class type, there is no
5093   // meaningful dynamic type. (We consider objects of non-class type to have no
5094   // dynamic type.)
5095   if (!checkDynamicType(Info, E, This, AK, true))
5096     return None;
5097 
5098   // Refuse to compute a dynamic type in the presence of virtual bases. This
5099   // shouldn't happen other than in constant-folding situations, since literal
5100   // types can't have virtual bases.
5101   //
5102   // Note that consumers of DynamicType assume that the type has no virtual
5103   // bases, and will need modifications if this restriction is relaxed.
5104   const CXXRecordDecl *Class =
5105       This.Designator.MostDerivedType->getAsCXXRecordDecl();
5106   if (!Class || Class->getNumVBases()) {
5107     Info.FFDiag(E);
5108     return None;
5109   }
5110 
5111   // FIXME: For very deep class hierarchies, it might be beneficial to use a
5112   // binary search here instead. But the overwhelmingly common case is that
5113   // we're not in the middle of a constructor, so it probably doesn't matter
5114   // in practice.
5115   ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5116   for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5117        PathLength <= Path.size(); ++PathLength) {
5118     switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5119                                       Path.slice(0, PathLength))) {
5120     case ConstructionPhase::Bases:
5121     case ConstructionPhase::DestroyingBases:
5122       // We're constructing or destroying a base class. This is not the dynamic
5123       // type.
5124       break;
5125 
5126     case ConstructionPhase::None:
5127     case ConstructionPhase::AfterBases:
5128     case ConstructionPhase::AfterFields:
5129     case ConstructionPhase::Destroying:
5130       // We've finished constructing the base classes and not yet started
5131       // destroying them again, so this is the dynamic type.
5132       return DynamicType{getBaseClassType(This.Designator, PathLength),
5133                          PathLength};
5134     }
5135   }
5136 
5137   // CWG issue 1517: we're constructing a base class of the object described by
5138   // 'This', so that object has not yet begun its period of construction and
5139   // any polymorphic operation on it results in undefined behavior.
5140   Info.FFDiag(E);
5141   return None;
5142 }
5143 
5144 /// Perform virtual dispatch.
5145 static const CXXMethodDecl *HandleVirtualDispatch(
5146     EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5147     llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5148   Optional<DynamicType> DynType = ComputeDynamicType(
5149       Info, E, This,
5150       isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5151   if (!DynType)
5152     return nullptr;
5153 
5154   // Find the final overrider. It must be declared in one of the classes on the
5155   // path from the dynamic type to the static type.
5156   // FIXME: If we ever allow literal types to have virtual base classes, that
5157   // won't be true.
5158   const CXXMethodDecl *Callee = Found;
5159   unsigned PathLength = DynType->PathLength;
5160   for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5161     const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5162     const CXXMethodDecl *Overrider =
5163         Found->getCorrespondingMethodDeclaredInClass(Class, false);
5164     if (Overrider) {
5165       Callee = Overrider;
5166       break;
5167     }
5168   }
5169 
5170   // C++2a [class.abstract]p6:
5171   //   the effect of making a virtual call to a pure virtual function [...] is
5172   //   undefined
5173   if (Callee->isPure()) {
5174     Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5175     Info.Note(Callee->getLocation(), diag::note_declared_at);
5176     return nullptr;
5177   }
5178 
5179   // If necessary, walk the rest of the path to determine the sequence of
5180   // covariant adjustment steps to apply.
5181   if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5182                                        Found->getReturnType())) {
5183     CovariantAdjustmentPath.push_back(Callee->getReturnType());
5184     for (unsigned CovariantPathLength = PathLength + 1;
5185          CovariantPathLength != This.Designator.Entries.size();
5186          ++CovariantPathLength) {
5187       const CXXRecordDecl *NextClass =
5188           getBaseClassType(This.Designator, CovariantPathLength);
5189       const CXXMethodDecl *Next =
5190           Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5191       if (Next && !Info.Ctx.hasSameUnqualifiedType(
5192                       Next->getReturnType(), CovariantAdjustmentPath.back()))
5193         CovariantAdjustmentPath.push_back(Next->getReturnType());
5194     }
5195     if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5196                                          CovariantAdjustmentPath.back()))
5197       CovariantAdjustmentPath.push_back(Found->getReturnType());
5198   }
5199 
5200   // Perform 'this' adjustment.
5201   if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5202     return nullptr;
5203 
5204   return Callee;
5205 }
5206 
5207 /// Perform the adjustment from a value returned by a virtual function to
5208 /// a value of the statically expected type, which may be a pointer or
5209 /// reference to a base class of the returned type.
5210 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5211                                             APValue &Result,
5212                                             ArrayRef<QualType> Path) {
5213   assert(Result.isLValue() &&
5214          "unexpected kind of APValue for covariant return");
5215   if (Result.isNullPointer())
5216     return true;
5217 
5218   LValue LVal;
5219   LVal.setFrom(Info.Ctx, Result);
5220 
5221   const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5222   for (unsigned I = 1; I != Path.size(); ++I) {
5223     const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5224     assert(OldClass && NewClass && "unexpected kind of covariant return");
5225     if (OldClass != NewClass &&
5226         !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5227       return false;
5228     OldClass = NewClass;
5229   }
5230 
5231   LVal.moveInto(Result);
5232   return true;
5233 }
5234 
5235 /// Determine whether \p Base, which is known to be a direct base class of
5236 /// \p Derived, is a public base class.
5237 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5238                               const CXXRecordDecl *Base) {
5239   for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5240     auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5241     if (BaseClass && declaresSameEntity(BaseClass, Base))
5242       return BaseSpec.getAccessSpecifier() == AS_public;
5243   }
5244   llvm_unreachable("Base is not a direct base of Derived");
5245 }
5246 
5247 /// Apply the given dynamic cast operation on the provided lvalue.
5248 ///
5249 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
5250 /// to find a suitable target subobject.
5251 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5252                               LValue &Ptr) {
5253   // We can't do anything with a non-symbolic pointer value.
5254   SubobjectDesignator &D = Ptr.Designator;
5255   if (D.Invalid)
5256     return false;
5257 
5258   // C++ [expr.dynamic.cast]p6:
5259   //   If v is a null pointer value, the result is a null pointer value.
5260   if (Ptr.isNullPointer() && !E->isGLValue())
5261     return true;
5262 
5263   // For all the other cases, we need the pointer to point to an object within
5264   // its lifetime / period of construction / destruction, and we need to know
5265   // its dynamic type.
5266   Optional<DynamicType> DynType =
5267       ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5268   if (!DynType)
5269     return false;
5270 
5271   // C++ [expr.dynamic.cast]p7:
5272   //   If T is "pointer to cv void", then the result is a pointer to the most
5273   //   derived object
5274   if (E->getType()->isVoidPointerType())
5275     return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5276 
5277   const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5278   assert(C && "dynamic_cast target is not void pointer nor class");
5279   CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5280 
5281   auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5282     // C++ [expr.dynamic.cast]p9:
5283     if (!E->isGLValue()) {
5284       //   The value of a failed cast to pointer type is the null pointer value
5285       //   of the required result type.
5286       Ptr.setNull(Info.Ctx, E->getType());
5287       return true;
5288     }
5289 
5290     //   A failed cast to reference type throws [...] std::bad_cast.
5291     unsigned DiagKind;
5292     if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5293                    DynType->Type->isDerivedFrom(C)))
5294       DiagKind = 0;
5295     else if (!Paths || Paths->begin() == Paths->end())
5296       DiagKind = 1;
5297     else if (Paths->isAmbiguous(CQT))
5298       DiagKind = 2;
5299     else {
5300       assert(Paths->front().Access != AS_public && "why did the cast fail?");
5301       DiagKind = 3;
5302     }
5303     Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5304         << DiagKind << Ptr.Designator.getType(Info.Ctx)
5305         << Info.Ctx.getRecordType(DynType->Type)
5306         << E->getType().getUnqualifiedType();
5307     return false;
5308   };
5309 
5310   // Runtime check, phase 1:
5311   //   Walk from the base subobject towards the derived object looking for the
5312   //   target type.
5313   for (int PathLength = Ptr.Designator.Entries.size();
5314        PathLength >= (int)DynType->PathLength; --PathLength) {
5315     const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5316     if (declaresSameEntity(Class, C))
5317       return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5318     // We can only walk across public inheritance edges.
5319     if (PathLength > (int)DynType->PathLength &&
5320         !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5321                            Class))
5322       return RuntimeCheckFailed(nullptr);
5323   }
5324 
5325   // Runtime check, phase 2:
5326   //   Search the dynamic type for an unambiguous public base of type C.
5327   CXXBasePaths Paths(/*FindAmbiguities=*/true,
5328                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
5329   if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5330       Paths.front().Access == AS_public) {
5331     // Downcast to the dynamic type...
5332     if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5333       return false;
5334     // ... then upcast to the chosen base class subobject.
5335     for (CXXBasePathElement &Elem : Paths.front())
5336       if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5337         return false;
5338     return true;
5339   }
5340 
5341   // Otherwise, the runtime check fails.
5342   return RuntimeCheckFailed(&Paths);
5343 }
5344 
5345 namespace {
5346 struct StartLifetimeOfUnionMemberHandler {
5347   EvalInfo &Info;
5348   const Expr *LHSExpr;
5349   const FieldDecl *Field;
5350   bool DuringInit;
5351 
5352   static const AccessKinds AccessKind = AK_Assign;
5353 
5354   typedef bool result_type;
5355   bool failed() { return false; }
5356   bool found(APValue &Subobj, QualType SubobjType) {
5357     // We are supposed to perform no initialization but begin the lifetime of
5358     // the object. We interpret that as meaning to do what default
5359     // initialization of the object would do if all constructors involved were
5360     // trivial:
5361     //  * All base, non-variant member, and array element subobjects' lifetimes
5362     //    begin
5363     //  * No variant members' lifetimes begin
5364     //  * All scalar subobjects whose lifetimes begin have indeterminate values
5365     assert(SubobjType->isUnionType());
5366     if (declaresSameEntity(Subobj.getUnionField(), Field)) {
5367       // This union member is already active. If it's also in-lifetime, there's
5368       // nothing to do.
5369       if (Subobj.getUnionValue().hasValue())
5370         return true;
5371     } else if (DuringInit) {
5372       // We're currently in the process of initializing a different union
5373       // member.  If we carried on, that initialization would attempt to
5374       // store to an inactive union member, resulting in undefined behavior.
5375       Info.FFDiag(LHSExpr,
5376                   diag::note_constexpr_union_member_change_during_init);
5377       return false;
5378     }
5379 
5380     Subobj.setUnion(Field, getDefaultInitValue(Field->getType()));
5381     return true;
5382   }
5383   bool found(APSInt &Value, QualType SubobjType) {
5384     llvm_unreachable("wrong value kind for union object");
5385   }
5386   bool found(APFloat &Value, QualType SubobjType) {
5387     llvm_unreachable("wrong value kind for union object");
5388   }
5389 };
5390 } // end anonymous namespace
5391 
5392 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5393 
5394 /// Handle a builtin simple-assignment or a call to a trivial assignment
5395 /// operator whose left-hand side might involve a union member access. If it
5396 /// does, implicitly start the lifetime of any accessed union elements per
5397 /// C++20 [class.union]5.
5398 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5399                                           const LValue &LHS) {
5400   if (LHS.InvalidBase || LHS.Designator.Invalid)
5401     return false;
5402 
5403   llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5404   // C++ [class.union]p5:
5405   //   define the set S(E) of subexpressions of E as follows:
5406   unsigned PathLength = LHS.Designator.Entries.size();
5407   for (const Expr *E = LHSExpr; E != nullptr;) {
5408     //   -- If E is of the form A.B, S(E) contains the elements of S(A)...
5409     if (auto *ME = dyn_cast<MemberExpr>(E)) {
5410       auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5411       // Note that we can't implicitly start the lifetime of a reference,
5412       // so we don't need to proceed any further if we reach one.
5413       if (!FD || FD->getType()->isReferenceType())
5414         break;
5415 
5416       //    ... and also contains A.B if B names a union member ...
5417       if (FD->getParent()->isUnion()) {
5418         //    ... of a non-class, non-array type, or of a class type with a
5419         //    trivial default constructor that is not deleted, or an array of
5420         //    such types.
5421         auto *RD =
5422             FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5423         if (!RD || RD->hasTrivialDefaultConstructor())
5424           UnionPathLengths.push_back({PathLength - 1, FD});
5425       }
5426 
5427       E = ME->getBase();
5428       --PathLength;
5429       assert(declaresSameEntity(FD,
5430                                 LHS.Designator.Entries[PathLength]
5431                                     .getAsBaseOrMember().getPointer()));
5432 
5433       //   -- If E is of the form A[B] and is interpreted as a built-in array
5434       //      subscripting operator, S(E) is [S(the array operand, if any)].
5435     } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5436       // Step over an ArrayToPointerDecay implicit cast.
5437       auto *Base = ASE->getBase()->IgnoreImplicit();
5438       if (!Base->getType()->isArrayType())
5439         break;
5440 
5441       E = Base;
5442       --PathLength;
5443 
5444     } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5445       // Step over a derived-to-base conversion.
5446       E = ICE->getSubExpr();
5447       if (ICE->getCastKind() == CK_NoOp)
5448         continue;
5449       if (ICE->getCastKind() != CK_DerivedToBase &&
5450           ICE->getCastKind() != CK_UncheckedDerivedToBase)
5451         break;
5452       // Walk path backwards as we walk up from the base to the derived class.
5453       for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
5454         --PathLength;
5455         (void)Elt;
5456         assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
5457                                   LHS.Designator.Entries[PathLength]
5458                                       .getAsBaseOrMember().getPointer()));
5459       }
5460 
5461     //   -- Otherwise, S(E) is empty.
5462     } else {
5463       break;
5464     }
5465   }
5466 
5467   // Common case: no unions' lifetimes are started.
5468   if (UnionPathLengths.empty())
5469     return true;
5470 
5471   //   if modification of X [would access an inactive union member], an object
5472   //   of the type of X is implicitly created
5473   CompleteObject Obj =
5474       findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
5475   if (!Obj)
5476     return false;
5477   for (std::pair<unsigned, const FieldDecl *> LengthAndField :
5478            llvm::reverse(UnionPathLengths)) {
5479     // Form a designator for the union object.
5480     SubobjectDesignator D = LHS.Designator;
5481     D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
5482 
5483     bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
5484                       ConstructionPhase::AfterBases;
5485     StartLifetimeOfUnionMemberHandler StartLifetime{
5486         Info, LHSExpr, LengthAndField.second, DuringInit};
5487     if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
5488       return false;
5489   }
5490 
5491   return true;
5492 }
5493 
5494 namespace {
5495 typedef SmallVector<APValue, 8> ArgVector;
5496 }
5497 
5498 /// EvaluateArgs - Evaluate the arguments to a function call.
5499 static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues,
5500                          EvalInfo &Info, const FunctionDecl *Callee) {
5501   bool Success = true;
5502   llvm::SmallBitVector ForbiddenNullArgs;
5503   if (Callee->hasAttr<NonNullAttr>()) {
5504     ForbiddenNullArgs.resize(Args.size());
5505     for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
5506       if (!Attr->args_size()) {
5507         ForbiddenNullArgs.set();
5508         break;
5509       } else
5510         for (auto Idx : Attr->args()) {
5511           unsigned ASTIdx = Idx.getASTIndex();
5512           if (ASTIdx >= Args.size())
5513             continue;
5514           ForbiddenNullArgs[ASTIdx] = 1;
5515         }
5516     }
5517   }
5518   // FIXME: This is the wrong evaluation order for an assignment operator
5519   // called via operator syntax.
5520   for (unsigned Idx = 0; Idx < Args.size(); Idx++) {
5521     if (!Evaluate(ArgValues[Idx], Info, Args[Idx])) {
5522       // If we're checking for a potential constant expression, evaluate all
5523       // initializers even if some of them fail.
5524       if (!Info.noteFailure())
5525         return false;
5526       Success = false;
5527     } else if (!ForbiddenNullArgs.empty() &&
5528                ForbiddenNullArgs[Idx] &&
5529                ArgValues[Idx].isLValue() &&
5530                ArgValues[Idx].isNullPointer()) {
5531       Info.CCEDiag(Args[Idx], diag::note_non_null_attribute_failed);
5532       if (!Info.noteFailure())
5533         return false;
5534       Success = false;
5535     }
5536   }
5537   return Success;
5538 }
5539 
5540 /// Evaluate a function call.
5541 static bool HandleFunctionCall(SourceLocation CallLoc,
5542                                const FunctionDecl *Callee, const LValue *This,
5543                                ArrayRef<const Expr*> Args, const Stmt *Body,
5544                                EvalInfo &Info, APValue &Result,
5545                                const LValue *ResultSlot) {
5546   ArgVector ArgValues(Args.size());
5547   if (!EvaluateArgs(Args, ArgValues, Info, Callee))
5548     return false;
5549 
5550   if (!Info.CheckCallLimit(CallLoc))
5551     return false;
5552 
5553   CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
5554 
5555   // For a trivial copy or move assignment, perform an APValue copy. This is
5556   // essential for unions, where the operations performed by the assignment
5557   // operator cannot be represented as statements.
5558   //
5559   // Skip this for non-union classes with no fields; in that case, the defaulted
5560   // copy/move does not actually read the object.
5561   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
5562   if (MD && MD->isDefaulted() &&
5563       (MD->getParent()->isUnion() ||
5564        (MD->isTrivial() &&
5565         isReadByLvalueToRvalueConversion(MD->getParent())))) {
5566     assert(This &&
5567            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
5568     LValue RHS;
5569     RHS.setFrom(Info.Ctx, ArgValues[0]);
5570     APValue RHSValue;
5571     if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), RHS,
5572                                         RHSValue, MD->getParent()->isUnion()))
5573       return false;
5574     if (Info.getLangOpts().CPlusPlus2a && MD->isTrivial() &&
5575         !HandleUnionActiveMemberChange(Info, Args[0], *This))
5576       return false;
5577     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
5578                           RHSValue))
5579       return false;
5580     This->moveInto(Result);
5581     return true;
5582   } else if (MD && isLambdaCallOperator(MD)) {
5583     // We're in a lambda; determine the lambda capture field maps unless we're
5584     // just constexpr checking a lambda's call operator. constexpr checking is
5585     // done before the captures have been added to the closure object (unless
5586     // we're inferring constexpr-ness), so we don't have access to them in this
5587     // case. But since we don't need the captures to constexpr check, we can
5588     // just ignore them.
5589     if (!Info.checkingPotentialConstantExpression())
5590       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
5591                                         Frame.LambdaThisCaptureField);
5592   }
5593 
5594   StmtResult Ret = {Result, ResultSlot};
5595   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
5596   if (ESR == ESR_Succeeded) {
5597     if (Callee->getReturnType()->isVoidType())
5598       return true;
5599     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
5600   }
5601   return ESR == ESR_Returned;
5602 }
5603 
5604 /// Evaluate a constructor call.
5605 static bool HandleConstructorCall(const Expr *E, const LValue &This,
5606                                   APValue *ArgValues,
5607                                   const CXXConstructorDecl *Definition,
5608                                   EvalInfo &Info, APValue &Result) {
5609   SourceLocation CallLoc = E->getExprLoc();
5610   if (!Info.CheckCallLimit(CallLoc))
5611     return false;
5612 
5613   const CXXRecordDecl *RD = Definition->getParent();
5614   if (RD->getNumVBases()) {
5615     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
5616     return false;
5617   }
5618 
5619   EvalInfo::EvaluatingConstructorRAII EvalObj(
5620       Info,
5621       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
5622       RD->getNumBases());
5623   CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
5624 
5625   // FIXME: Creating an APValue just to hold a nonexistent return value is
5626   // wasteful.
5627   APValue RetVal;
5628   StmtResult Ret = {RetVal, nullptr};
5629 
5630   // If it's a delegating constructor, delegate.
5631   if (Definition->isDelegatingConstructor()) {
5632     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
5633     {
5634       FullExpressionRAII InitScope(Info);
5635       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
5636           !InitScope.destroy())
5637         return false;
5638     }
5639     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
5640   }
5641 
5642   // For a trivial copy or move constructor, perform an APValue copy. This is
5643   // essential for unions (or classes with anonymous union members), where the
5644   // operations performed by the constructor cannot be represented by
5645   // ctor-initializers.
5646   //
5647   // Skip this for empty non-union classes; we should not perform an
5648   // lvalue-to-rvalue conversion on them because their copy constructor does not
5649   // actually read them.
5650   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
5651       (Definition->getParent()->isUnion() ||
5652        (Definition->isTrivial() &&
5653         isReadByLvalueToRvalueConversion(Definition->getParent())))) {
5654     LValue RHS;
5655     RHS.setFrom(Info.Ctx, ArgValues[0]);
5656     return handleLValueToRValueConversion(
5657         Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
5658         RHS, Result, Definition->getParent()->isUnion());
5659   }
5660 
5661   // Reserve space for the struct members.
5662   if (!Result.hasValue()) {
5663     if (!RD->isUnion())
5664       Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
5665                        std::distance(RD->field_begin(), RD->field_end()));
5666     else
5667       // A union starts with no active member.
5668       Result = APValue((const FieldDecl*)nullptr);
5669   }
5670 
5671   if (RD->isInvalidDecl()) return false;
5672   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5673 
5674   // A scope for temporaries lifetime-extended by reference members.
5675   BlockScopeRAII LifetimeExtendedScope(Info);
5676 
5677   bool Success = true;
5678   unsigned BasesSeen = 0;
5679 #ifndef NDEBUG
5680   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
5681 #endif
5682   CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
5683   auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
5684     // We might be initializing the same field again if this is an indirect
5685     // field initialization.
5686     if (FieldIt == RD->field_end() ||
5687         FieldIt->getFieldIndex() > FD->getFieldIndex()) {
5688       assert(Indirect && "fields out of order?");
5689       return;
5690     }
5691 
5692     // Default-initialize any fields with no explicit initializer.
5693     for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
5694       assert(FieldIt != RD->field_end() && "missing field?");
5695       if (!FieldIt->isUnnamedBitfield())
5696         Result.getStructField(FieldIt->getFieldIndex()) =
5697             getDefaultInitValue(FieldIt->getType());
5698     }
5699     ++FieldIt;
5700   };
5701   for (const auto *I : Definition->inits()) {
5702     LValue Subobject = This;
5703     LValue SubobjectParent = This;
5704     APValue *Value = &Result;
5705 
5706     // Determine the subobject to initialize.
5707     FieldDecl *FD = nullptr;
5708     if (I->isBaseInitializer()) {
5709       QualType BaseType(I->getBaseClass(), 0);
5710 #ifndef NDEBUG
5711       // Non-virtual base classes are initialized in the order in the class
5712       // definition. We have already checked for virtual base classes.
5713       assert(!BaseIt->isVirtual() && "virtual base for literal type");
5714       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
5715              "base class initializers not in expected order");
5716       ++BaseIt;
5717 #endif
5718       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
5719                                   BaseType->getAsCXXRecordDecl(), &Layout))
5720         return false;
5721       Value = &Result.getStructBase(BasesSeen++);
5722     } else if ((FD = I->getMember())) {
5723       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
5724         return false;
5725       if (RD->isUnion()) {
5726         Result = APValue(FD);
5727         Value = &Result.getUnionValue();
5728       } else {
5729         SkipToField(FD, false);
5730         Value = &Result.getStructField(FD->getFieldIndex());
5731       }
5732     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
5733       // Walk the indirect field decl's chain to find the object to initialize,
5734       // and make sure we've initialized every step along it.
5735       auto IndirectFieldChain = IFD->chain();
5736       for (auto *C : IndirectFieldChain) {
5737         FD = cast<FieldDecl>(C);
5738         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
5739         // Switch the union field if it differs. This happens if we had
5740         // preceding zero-initialization, and we're now initializing a union
5741         // subobject other than the first.
5742         // FIXME: In this case, the values of the other subobjects are
5743         // specified, since zero-initialization sets all padding bits to zero.
5744         if (!Value->hasValue() ||
5745             (Value->isUnion() && Value->getUnionField() != FD)) {
5746           if (CD->isUnion())
5747             *Value = APValue(FD);
5748           else
5749             // FIXME: This immediately starts the lifetime of all members of an
5750             // anonymous struct. It would be preferable to strictly start member
5751             // lifetime in initialization order.
5752             *Value = getDefaultInitValue(Info.Ctx.getRecordType(CD));
5753         }
5754         // Store Subobject as its parent before updating it for the last element
5755         // in the chain.
5756         if (C == IndirectFieldChain.back())
5757           SubobjectParent = Subobject;
5758         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
5759           return false;
5760         if (CD->isUnion())
5761           Value = &Value->getUnionValue();
5762         else {
5763           if (C == IndirectFieldChain.front() && !RD->isUnion())
5764             SkipToField(FD, true);
5765           Value = &Value->getStructField(FD->getFieldIndex());
5766         }
5767       }
5768     } else {
5769       llvm_unreachable("unknown base initializer kind");
5770     }
5771 
5772     // Need to override This for implicit field initializers as in this case
5773     // This refers to innermost anonymous struct/union containing initializer,
5774     // not to currently constructed class.
5775     const Expr *Init = I->getInit();
5776     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
5777                                   isa<CXXDefaultInitExpr>(Init));
5778     FullExpressionRAII InitScope(Info);
5779     if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
5780         (FD && FD->isBitField() &&
5781          !truncateBitfieldValue(Info, Init, *Value, FD))) {
5782       // If we're checking for a potential constant expression, evaluate all
5783       // initializers even if some of them fail.
5784       if (!Info.noteFailure())
5785         return false;
5786       Success = false;
5787     }
5788 
5789     // This is the point at which the dynamic type of the object becomes this
5790     // class type.
5791     if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
5792       EvalObj.finishedConstructingBases();
5793   }
5794 
5795   // Default-initialize any remaining fields.
5796   if (!RD->isUnion()) {
5797     for (; FieldIt != RD->field_end(); ++FieldIt) {
5798       if (!FieldIt->isUnnamedBitfield())
5799         Result.getStructField(FieldIt->getFieldIndex()) =
5800             getDefaultInitValue(FieldIt->getType());
5801     }
5802   }
5803 
5804   EvalObj.finishedConstructingFields();
5805 
5806   return Success &&
5807          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
5808          LifetimeExtendedScope.destroy();
5809 }
5810 
5811 static bool HandleConstructorCall(const Expr *E, const LValue &This,
5812                                   ArrayRef<const Expr*> Args,
5813                                   const CXXConstructorDecl *Definition,
5814                                   EvalInfo &Info, APValue &Result) {
5815   ArgVector ArgValues(Args.size());
5816   if (!EvaluateArgs(Args, ArgValues, Info, Definition))
5817     return false;
5818 
5819   return HandleConstructorCall(E, This, ArgValues.data(), Definition,
5820                                Info, Result);
5821 }
5822 
5823 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
5824                                   const LValue &This, APValue &Value,
5825                                   QualType T) {
5826   // Objects can only be destroyed while they're within their lifetimes.
5827   // FIXME: We have no representation for whether an object of type nullptr_t
5828   // is in its lifetime; it usually doesn't matter. Perhaps we should model it
5829   // as indeterminate instead?
5830   if (Value.isAbsent() && !T->isNullPtrType()) {
5831     APValue Printable;
5832     This.moveInto(Printable);
5833     Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
5834       << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
5835     return false;
5836   }
5837 
5838   // Invent an expression for location purposes.
5839   // FIXME: We shouldn't need to do this.
5840   OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue);
5841 
5842   // For arrays, destroy elements right-to-left.
5843   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
5844     uint64_t Size = CAT->getSize().getZExtValue();
5845     QualType ElemT = CAT->getElementType();
5846 
5847     LValue ElemLV = This;
5848     ElemLV.addArray(Info, &LocE, CAT);
5849     if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
5850       return false;
5851 
5852     // Ensure that we have actual array elements available to destroy; the
5853     // destructors might mutate the value, so we can't run them on the array
5854     // filler.
5855     if (Size && Size > Value.getArrayInitializedElts())
5856       expandArray(Value, Value.getArraySize() - 1);
5857 
5858     for (; Size != 0; --Size) {
5859       APValue &Elem = Value.getArrayInitializedElt(Size - 1);
5860       if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
5861           !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
5862         return false;
5863     }
5864 
5865     // End the lifetime of this array now.
5866     Value = APValue();
5867     return true;
5868   }
5869 
5870   const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
5871   if (!RD) {
5872     if (T.isDestructedType()) {
5873       Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
5874       return false;
5875     }
5876 
5877     Value = APValue();
5878     return true;
5879   }
5880 
5881   if (RD->getNumVBases()) {
5882     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
5883     return false;
5884   }
5885 
5886   const CXXDestructorDecl *DD = RD->getDestructor();
5887   if (!DD && !RD->hasTrivialDestructor()) {
5888     Info.FFDiag(CallLoc);
5889     return false;
5890   }
5891 
5892   if (!DD || DD->isTrivial() ||
5893       (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
5894     // A trivial destructor just ends the lifetime of the object. Check for
5895     // this case before checking for a body, because we might not bother
5896     // building a body for a trivial destructor. Note that it doesn't matter
5897     // whether the destructor is constexpr in this case; all trivial
5898     // destructors are constexpr.
5899     //
5900     // If an anonymous union would be destroyed, some enclosing destructor must
5901     // have been explicitly defined, and the anonymous union destruction should
5902     // have no effect.
5903     Value = APValue();
5904     return true;
5905   }
5906 
5907   if (!Info.CheckCallLimit(CallLoc))
5908     return false;
5909 
5910   const FunctionDecl *Definition = nullptr;
5911   const Stmt *Body = DD->getBody(Definition);
5912 
5913   if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
5914     return false;
5915 
5916   CallStackFrame Frame(Info, CallLoc, Definition, &This, nullptr);
5917 
5918   // We're now in the period of destruction of this object.
5919   unsigned BasesLeft = RD->getNumBases();
5920   EvalInfo::EvaluatingDestructorRAII EvalObj(
5921       Info,
5922       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
5923   if (!EvalObj.DidInsert) {
5924     // C++2a [class.dtor]p19:
5925     //   the behavior is undefined if the destructor is invoked for an object
5926     //   whose lifetime has ended
5927     // (Note that formally the lifetime ends when the period of destruction
5928     // begins, even though certain uses of the object remain valid until the
5929     // period of destruction ends.)
5930     Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
5931     return false;
5932   }
5933 
5934   // FIXME: Creating an APValue just to hold a nonexistent return value is
5935   // wasteful.
5936   APValue RetVal;
5937   StmtResult Ret = {RetVal, nullptr};
5938   if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
5939     return false;
5940 
5941   // A union destructor does not implicitly destroy its members.
5942   if (RD->isUnion())
5943     return true;
5944 
5945   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5946 
5947   // We don't have a good way to iterate fields in reverse, so collect all the
5948   // fields first and then walk them backwards.
5949   SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
5950   for (const FieldDecl *FD : llvm::reverse(Fields)) {
5951     if (FD->isUnnamedBitfield())
5952       continue;
5953 
5954     LValue Subobject = This;
5955     if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
5956       return false;
5957 
5958     APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
5959     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
5960                                FD->getType()))
5961       return false;
5962   }
5963 
5964   if (BasesLeft != 0)
5965     EvalObj.startedDestroyingBases();
5966 
5967   // Destroy base classes in reverse order.
5968   for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
5969     --BasesLeft;
5970 
5971     QualType BaseType = Base.getType();
5972     LValue Subobject = This;
5973     if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
5974                                 BaseType->getAsCXXRecordDecl(), &Layout))
5975       return false;
5976 
5977     APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
5978     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
5979                                BaseType))
5980       return false;
5981   }
5982   assert(BasesLeft == 0 && "NumBases was wrong?");
5983 
5984   // The period of destruction ends now. The object is gone.
5985   Value = APValue();
5986   return true;
5987 }
5988 
5989 namespace {
5990 struct DestroyObjectHandler {
5991   EvalInfo &Info;
5992   const Expr *E;
5993   const LValue &This;
5994   const AccessKinds AccessKind;
5995 
5996   typedef bool result_type;
5997   bool failed() { return false; }
5998   bool found(APValue &Subobj, QualType SubobjType) {
5999     return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
6000                                  SubobjType);
6001   }
6002   bool found(APSInt &Value, QualType SubobjType) {
6003     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6004     return false;
6005   }
6006   bool found(APFloat &Value, QualType SubobjType) {
6007     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6008     return false;
6009   }
6010 };
6011 }
6012 
6013 /// Perform a destructor or pseudo-destructor call on the given object, which
6014 /// might in general not be a complete object.
6015 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6016                               const LValue &This, QualType ThisType) {
6017   CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6018   DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6019   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6020 }
6021 
6022 /// Destroy and end the lifetime of the given complete object.
6023 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6024                               APValue::LValueBase LVBase, APValue &Value,
6025                               QualType T) {
6026   // If we've had an unmodeled side-effect, we can't rely on mutable state
6027   // (such as the object we're about to destroy) being correct.
6028   if (Info.EvalStatus.HasSideEffects)
6029     return false;
6030 
6031   LValue LV;
6032   LV.set({LVBase});
6033   return HandleDestructionImpl(Info, Loc, LV, Value, T);
6034 }
6035 
6036 /// Perform a call to 'perator new' or to `__builtin_operator_new'.
6037 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6038                                   LValue &Result) {
6039   if (Info.checkingPotentialConstantExpression() ||
6040       Info.SpeculativeEvaluationDepth)
6041     return false;
6042 
6043   // This is permitted only within a call to std::allocator<T>::allocate.
6044   auto Caller = Info.getStdAllocatorCaller("allocate");
6045   if (!Caller) {
6046     Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus2a
6047                                      ? diag::note_constexpr_new_untyped
6048                                      : diag::note_constexpr_new);
6049     return false;
6050   }
6051 
6052   QualType ElemType = Caller.ElemType;
6053   if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6054     Info.FFDiag(E->getExprLoc(),
6055                 diag::note_constexpr_new_not_complete_object_type)
6056         << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6057     return false;
6058   }
6059 
6060   APSInt ByteSize;
6061   if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6062     return false;
6063   bool IsNothrow = false;
6064   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6065     EvaluateIgnoredValue(Info, E->getArg(I));
6066     IsNothrow |= E->getType()->isNothrowT();
6067   }
6068 
6069   CharUnits ElemSize;
6070   if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6071     return false;
6072   APInt Size, Remainder;
6073   APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6074   APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6075   if (Remainder != 0) {
6076     // This likely indicates a bug in the implementation of 'std::allocator'.
6077     Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6078         << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6079     return false;
6080   }
6081 
6082   if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
6083     if (IsNothrow) {
6084       Result.setNull(Info.Ctx, E->getType());
6085       return true;
6086     }
6087 
6088     Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
6089     return false;
6090   }
6091 
6092   QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
6093                                                      ArrayType::Normal, 0);
6094   APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6095   *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6096   Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6097   return true;
6098 }
6099 
6100 static bool hasVirtualDestructor(QualType T) {
6101   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6102     if (CXXDestructorDecl *DD = RD->getDestructor())
6103       return DD->isVirtual();
6104   return false;
6105 }
6106 
6107 static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6108   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6109     if (CXXDestructorDecl *DD = RD->getDestructor())
6110       return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6111   return nullptr;
6112 }
6113 
6114 /// Check that the given object is a suitable pointer to a heap allocation that
6115 /// still exists and is of the right kind for the purpose of a deletion.
6116 ///
6117 /// On success, returns the heap allocation to deallocate. On failure, produces
6118 /// a diagnostic and returns None.
6119 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6120                                             const LValue &Pointer,
6121                                             DynAlloc::Kind DeallocKind) {
6122   auto PointerAsString = [&] {
6123     return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6124   };
6125 
6126   DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6127   if (!DA) {
6128     Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6129         << PointerAsString();
6130     if (Pointer.Base)
6131       NoteLValueLocation(Info, Pointer.Base);
6132     return None;
6133   }
6134 
6135   Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6136   if (!Alloc) {
6137     Info.FFDiag(E, diag::note_constexpr_double_delete);
6138     return None;
6139   }
6140 
6141   QualType AllocType = Pointer.Base.getDynamicAllocType();
6142   if (DeallocKind != (*Alloc)->getKind()) {
6143     Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6144         << DeallocKind << (*Alloc)->getKind() << AllocType;
6145     NoteLValueLocation(Info, Pointer.Base);
6146     return None;
6147   }
6148 
6149   bool Subobject = false;
6150   if (DeallocKind == DynAlloc::New) {
6151     Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6152                 Pointer.Designator.isOnePastTheEnd();
6153   } else {
6154     Subobject = Pointer.Designator.Entries.size() != 1 ||
6155                 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6156   }
6157   if (Subobject) {
6158     Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6159         << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6160     return None;
6161   }
6162 
6163   return Alloc;
6164 }
6165 
6166 // Perform a call to 'operator delete' or '__builtin_operator_delete'.
6167 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6168   if (Info.checkingPotentialConstantExpression() ||
6169       Info.SpeculativeEvaluationDepth)
6170     return false;
6171 
6172   // This is permitted only within a call to std::allocator<T>::deallocate.
6173   if (!Info.getStdAllocatorCaller("deallocate")) {
6174     Info.FFDiag(E->getExprLoc());
6175     return true;
6176   }
6177 
6178   LValue Pointer;
6179   if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6180     return false;
6181   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6182     EvaluateIgnoredValue(Info, E->getArg(I));
6183 
6184   if (Pointer.Designator.Invalid)
6185     return false;
6186 
6187   // Deleting a null pointer has no effect.
6188   if (Pointer.isNullPointer())
6189     return true;
6190 
6191   if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6192     return false;
6193 
6194   Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6195   return true;
6196 }
6197 
6198 //===----------------------------------------------------------------------===//
6199 // Generic Evaluation
6200 //===----------------------------------------------------------------------===//
6201 namespace {
6202 
6203 class BitCastBuffer {
6204   // FIXME: We're going to need bit-level granularity when we support
6205   // bit-fields.
6206   // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6207   // we don't support a host or target where that is the case. Still, we should
6208   // use a more generic type in case we ever do.
6209   SmallVector<Optional<unsigned char>, 32> Bytes;
6210 
6211   static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6212                 "Need at least 8 bit unsigned char");
6213 
6214   bool TargetIsLittleEndian;
6215 
6216 public:
6217   BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6218       : Bytes(Width.getQuantity()),
6219         TargetIsLittleEndian(TargetIsLittleEndian) {}
6220 
6221   LLVM_NODISCARD
6222   bool readObject(CharUnits Offset, CharUnits Width,
6223                   SmallVectorImpl<unsigned char> &Output) const {
6224     for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6225       // If a byte of an integer is uninitialized, then the whole integer is
6226       // uninitalized.
6227       if (!Bytes[I.getQuantity()])
6228         return false;
6229       Output.push_back(*Bytes[I.getQuantity()]);
6230     }
6231     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6232       std::reverse(Output.begin(), Output.end());
6233     return true;
6234   }
6235 
6236   void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6237     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6238       std::reverse(Input.begin(), Input.end());
6239 
6240     size_t Index = 0;
6241     for (unsigned char Byte : Input) {
6242       assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
6243       Bytes[Offset.getQuantity() + Index] = Byte;
6244       ++Index;
6245     }
6246   }
6247 
6248   size_t size() { return Bytes.size(); }
6249 };
6250 
6251 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6252 /// target would represent the value at runtime.
6253 class APValueToBufferConverter {
6254   EvalInfo &Info;
6255   BitCastBuffer Buffer;
6256   const CastExpr *BCE;
6257 
6258   APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6259                            const CastExpr *BCE)
6260       : Info(Info),
6261         Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6262         BCE(BCE) {}
6263 
6264   bool visit(const APValue &Val, QualType Ty) {
6265     return visit(Val, Ty, CharUnits::fromQuantity(0));
6266   }
6267 
6268   // Write out Val with type Ty into Buffer starting at Offset.
6269   bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6270     assert((size_t)Offset.getQuantity() <= Buffer.size());
6271 
6272     // As a special case, nullptr_t has an indeterminate value.
6273     if (Ty->isNullPtrType())
6274       return true;
6275 
6276     // Dig through Src to find the byte at SrcOffset.
6277     switch (Val.getKind()) {
6278     case APValue::Indeterminate:
6279     case APValue::None:
6280       return true;
6281 
6282     case APValue::Int:
6283       return visitInt(Val.getInt(), Ty, Offset);
6284     case APValue::Float:
6285       return visitFloat(Val.getFloat(), Ty, Offset);
6286     case APValue::Array:
6287       return visitArray(Val, Ty, Offset);
6288     case APValue::Struct:
6289       return visitRecord(Val, Ty, Offset);
6290 
6291     case APValue::ComplexInt:
6292     case APValue::ComplexFloat:
6293     case APValue::Vector:
6294     case APValue::FixedPoint:
6295       // FIXME: We should support these.
6296 
6297     case APValue::Union:
6298     case APValue::MemberPointer:
6299     case APValue::AddrLabelDiff: {
6300       Info.FFDiag(BCE->getBeginLoc(),
6301                   diag::note_constexpr_bit_cast_unsupported_type)
6302           << Ty;
6303       return false;
6304     }
6305 
6306     case APValue::LValue:
6307       llvm_unreachable("LValue subobject in bit_cast?");
6308     }
6309     llvm_unreachable("Unhandled APValue::ValueKind");
6310   }
6311 
6312   bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
6313     const RecordDecl *RD = Ty->getAsRecordDecl();
6314     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6315 
6316     // Visit the base classes.
6317     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6318       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6319         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6320         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6321 
6322         if (!visitRecord(Val.getStructBase(I), BS.getType(),
6323                          Layout.getBaseClassOffset(BaseDecl) + Offset))
6324           return false;
6325       }
6326     }
6327 
6328     // Visit the fields.
6329     unsigned FieldIdx = 0;
6330     for (FieldDecl *FD : RD->fields()) {
6331       if (FD->isBitField()) {
6332         Info.FFDiag(BCE->getBeginLoc(),
6333                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6334         return false;
6335       }
6336 
6337       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6338 
6339       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
6340              "only bit-fields can have sub-char alignment");
6341       CharUnits FieldOffset =
6342           Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
6343       QualType FieldTy = FD->getType();
6344       if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
6345         return false;
6346       ++FieldIdx;
6347     }
6348 
6349     return true;
6350   }
6351 
6352   bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
6353     const auto *CAT =
6354         dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
6355     if (!CAT)
6356       return false;
6357 
6358     CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
6359     unsigned NumInitializedElts = Val.getArrayInitializedElts();
6360     unsigned ArraySize = Val.getArraySize();
6361     // First, initialize the initialized elements.
6362     for (unsigned I = 0; I != NumInitializedElts; ++I) {
6363       const APValue &SubObj = Val.getArrayInitializedElt(I);
6364       if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
6365         return false;
6366     }
6367 
6368     // Next, initialize the rest of the array using the filler.
6369     if (Val.hasArrayFiller()) {
6370       const APValue &Filler = Val.getArrayFiller();
6371       for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
6372         if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
6373           return false;
6374       }
6375     }
6376 
6377     return true;
6378   }
6379 
6380   bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
6381     CharUnits Width = Info.Ctx.getTypeSizeInChars(Ty);
6382     SmallVector<unsigned char, 8> Bytes(Width.getQuantity());
6383     llvm::StoreIntToMemory(Val, &*Bytes.begin(), Width.getQuantity());
6384     Buffer.writeObject(Offset, Bytes);
6385     return true;
6386   }
6387 
6388   bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
6389     APSInt AsInt(Val.bitcastToAPInt());
6390     return visitInt(AsInt, Ty, Offset);
6391   }
6392 
6393 public:
6394   static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
6395                                          const CastExpr *BCE) {
6396     CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
6397     APValueToBufferConverter Converter(Info, DstSize, BCE);
6398     if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
6399       return None;
6400     return Converter.Buffer;
6401   }
6402 };
6403 
6404 /// Write an BitCastBuffer into an APValue.
6405 class BufferToAPValueConverter {
6406   EvalInfo &Info;
6407   const BitCastBuffer &Buffer;
6408   const CastExpr *BCE;
6409 
6410   BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
6411                            const CastExpr *BCE)
6412       : Info(Info), Buffer(Buffer), BCE(BCE) {}
6413 
6414   // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
6415   // with an invalid type, so anything left is a deficiency on our part (FIXME).
6416   // Ideally this will be unreachable.
6417   llvm::NoneType unsupportedType(QualType Ty) {
6418     Info.FFDiag(BCE->getBeginLoc(),
6419                 diag::note_constexpr_bit_cast_unsupported_type)
6420         << Ty;
6421     return None;
6422   }
6423 
6424   Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
6425                           const EnumType *EnumSugar = nullptr) {
6426     if (T->isNullPtrType()) {
6427       uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
6428       return APValue((Expr *)nullptr,
6429                      /*Offset=*/CharUnits::fromQuantity(NullValue),
6430                      APValue::NoLValuePath{}, /*IsNullPtr=*/true);
6431     }
6432 
6433     CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
6434     SmallVector<uint8_t, 8> Bytes;
6435     if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
6436       // If this is std::byte or unsigned char, then its okay to store an
6437       // indeterminate value.
6438       bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
6439       bool IsUChar =
6440           !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
6441                          T->isSpecificBuiltinType(BuiltinType::Char_U));
6442       if (!IsStdByte && !IsUChar) {
6443         QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
6444         Info.FFDiag(BCE->getExprLoc(),
6445                     diag::note_constexpr_bit_cast_indet_dest)
6446             << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
6447         return None;
6448       }
6449 
6450       return APValue::IndeterminateValue();
6451     }
6452 
6453     APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
6454     llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
6455 
6456     if (T->isIntegralOrEnumerationType()) {
6457       Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
6458       return APValue(Val);
6459     }
6460 
6461     if (T->isRealFloatingType()) {
6462       const llvm::fltSemantics &Semantics =
6463           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
6464       return APValue(APFloat(Semantics, Val));
6465     }
6466 
6467     return unsupportedType(QualType(T, 0));
6468   }
6469 
6470   Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
6471     const RecordDecl *RD = RTy->getAsRecordDecl();
6472     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6473 
6474     unsigned NumBases = 0;
6475     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6476       NumBases = CXXRD->getNumBases();
6477 
6478     APValue ResultVal(APValue::UninitStruct(), NumBases,
6479                       std::distance(RD->field_begin(), RD->field_end()));
6480 
6481     // Visit the base classes.
6482     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6483       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6484         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6485         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6486         if (BaseDecl->isEmpty() ||
6487             Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
6488           continue;
6489 
6490         Optional<APValue> SubObj = visitType(
6491             BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
6492         if (!SubObj)
6493           return None;
6494         ResultVal.getStructBase(I) = *SubObj;
6495       }
6496     }
6497 
6498     // Visit the fields.
6499     unsigned FieldIdx = 0;
6500     for (FieldDecl *FD : RD->fields()) {
6501       // FIXME: We don't currently support bit-fields. A lot of the logic for
6502       // this is in CodeGen, so we need to factor it around.
6503       if (FD->isBitField()) {
6504         Info.FFDiag(BCE->getBeginLoc(),
6505                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6506         return None;
6507       }
6508 
6509       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6510       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
6511 
6512       CharUnits FieldOffset =
6513           CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
6514           Offset;
6515       QualType FieldTy = FD->getType();
6516       Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
6517       if (!SubObj)
6518         return None;
6519       ResultVal.getStructField(FieldIdx) = *SubObj;
6520       ++FieldIdx;
6521     }
6522 
6523     return ResultVal;
6524   }
6525 
6526   Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
6527     QualType RepresentationType = Ty->getDecl()->getIntegerType();
6528     assert(!RepresentationType.isNull() &&
6529            "enum forward decl should be caught by Sema");
6530     const auto *AsBuiltin =
6531         RepresentationType.getCanonicalType()->castAs<BuiltinType>();
6532     // Recurse into the underlying type. Treat std::byte transparently as
6533     // unsigned char.
6534     return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
6535   }
6536 
6537   Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
6538     size_t Size = Ty->getSize().getLimitedValue();
6539     CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
6540 
6541     APValue ArrayValue(APValue::UninitArray(), Size, Size);
6542     for (size_t I = 0; I != Size; ++I) {
6543       Optional<APValue> ElementValue =
6544           visitType(Ty->getElementType(), Offset + I * ElementWidth);
6545       if (!ElementValue)
6546         return None;
6547       ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
6548     }
6549 
6550     return ArrayValue;
6551   }
6552 
6553   Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
6554     return unsupportedType(QualType(Ty, 0));
6555   }
6556 
6557   Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
6558     QualType Can = Ty.getCanonicalType();
6559 
6560     switch (Can->getTypeClass()) {
6561 #define TYPE(Class, Base)                                                      \
6562   case Type::Class:                                                            \
6563     return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
6564 #define ABSTRACT_TYPE(Class, Base)
6565 #define NON_CANONICAL_TYPE(Class, Base)                                        \
6566   case Type::Class:                                                            \
6567     llvm_unreachable("non-canonical type should be impossible!");
6568 #define DEPENDENT_TYPE(Class, Base)                                            \
6569   case Type::Class:                                                            \
6570     llvm_unreachable(                                                          \
6571         "dependent types aren't supported in the constant evaluator!");
6572 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)                            \
6573   case Type::Class:                                                            \
6574     llvm_unreachable("either dependent or not canonical!");
6575 #include "clang/AST/TypeNodes.inc"
6576     }
6577     llvm_unreachable("Unhandled Type::TypeClass");
6578   }
6579 
6580 public:
6581   // Pull out a full value of type DstType.
6582   static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
6583                                    const CastExpr *BCE) {
6584     BufferToAPValueConverter Converter(Info, Buffer, BCE);
6585     return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
6586   }
6587 };
6588 
6589 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
6590                                                  QualType Ty, EvalInfo *Info,
6591                                                  const ASTContext &Ctx,
6592                                                  bool CheckingDest) {
6593   Ty = Ty.getCanonicalType();
6594 
6595   auto diag = [&](int Reason) {
6596     if (Info)
6597       Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
6598           << CheckingDest << (Reason == 4) << Reason;
6599     return false;
6600   };
6601   auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
6602     if (Info)
6603       Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
6604           << NoteTy << Construct << Ty;
6605     return false;
6606   };
6607 
6608   if (Ty->isUnionType())
6609     return diag(0);
6610   if (Ty->isPointerType())
6611     return diag(1);
6612   if (Ty->isMemberPointerType())
6613     return diag(2);
6614   if (Ty.isVolatileQualified())
6615     return diag(3);
6616 
6617   if (RecordDecl *Record = Ty->getAsRecordDecl()) {
6618     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
6619       for (CXXBaseSpecifier &BS : CXXRD->bases())
6620         if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
6621                                                   CheckingDest))
6622           return note(1, BS.getType(), BS.getBeginLoc());
6623     }
6624     for (FieldDecl *FD : Record->fields()) {
6625       if (FD->getType()->isReferenceType())
6626         return diag(4);
6627       if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
6628                                                 CheckingDest))
6629         return note(0, FD->getType(), FD->getBeginLoc());
6630     }
6631   }
6632 
6633   if (Ty->isArrayType() &&
6634       !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
6635                                             Info, Ctx, CheckingDest))
6636     return false;
6637 
6638   return true;
6639 }
6640 
6641 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
6642                                              const ASTContext &Ctx,
6643                                              const CastExpr *BCE) {
6644   bool DestOK = checkBitCastConstexprEligibilityType(
6645       BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
6646   bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
6647                                 BCE->getBeginLoc(),
6648                                 BCE->getSubExpr()->getType(), Info, Ctx, false);
6649   return SourceOK;
6650 }
6651 
6652 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
6653                                         APValue &SourceValue,
6654                                         const CastExpr *BCE) {
6655   assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
6656          "no host or target supports non 8-bit chars");
6657   assert(SourceValue.isLValue() &&
6658          "LValueToRValueBitcast requires an lvalue operand!");
6659 
6660   if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
6661     return false;
6662 
6663   LValue SourceLValue;
6664   APValue SourceRValue;
6665   SourceLValue.setFrom(Info.Ctx, SourceValue);
6666   if (!handleLValueToRValueConversion(
6667           Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
6668           SourceRValue, /*WantObjectRepresentation=*/true))
6669     return false;
6670 
6671   // Read out SourceValue into a char buffer.
6672   Optional<BitCastBuffer> Buffer =
6673       APValueToBufferConverter::convert(Info, SourceRValue, BCE);
6674   if (!Buffer)
6675     return false;
6676 
6677   // Write out the buffer into a new APValue.
6678   Optional<APValue> MaybeDestValue =
6679       BufferToAPValueConverter::convert(Info, *Buffer, BCE);
6680   if (!MaybeDestValue)
6681     return false;
6682 
6683   DestValue = std::move(*MaybeDestValue);
6684   return true;
6685 }
6686 
6687 template <class Derived>
6688 class ExprEvaluatorBase
6689   : public ConstStmtVisitor<Derived, bool> {
6690 private:
6691   Derived &getDerived() { return static_cast<Derived&>(*this); }
6692   bool DerivedSuccess(const APValue &V, const Expr *E) {
6693     return getDerived().Success(V, E);
6694   }
6695   bool DerivedZeroInitialization(const Expr *E) {
6696     return getDerived().ZeroInitialization(E);
6697   }
6698 
6699   // Check whether a conditional operator with a non-constant condition is a
6700   // potential constant expression. If neither arm is a potential constant
6701   // expression, then the conditional operator is not either.
6702   template<typename ConditionalOperator>
6703   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
6704     assert(Info.checkingPotentialConstantExpression());
6705 
6706     // Speculatively evaluate both arms.
6707     SmallVector<PartialDiagnosticAt, 8> Diag;
6708     {
6709       SpeculativeEvaluationRAII Speculate(Info, &Diag);
6710       StmtVisitorTy::Visit(E->getFalseExpr());
6711       if (Diag.empty())
6712         return;
6713     }
6714 
6715     {
6716       SpeculativeEvaluationRAII Speculate(Info, &Diag);
6717       Diag.clear();
6718       StmtVisitorTy::Visit(E->getTrueExpr());
6719       if (Diag.empty())
6720         return;
6721     }
6722 
6723     Error(E, diag::note_constexpr_conditional_never_const);
6724   }
6725 
6726 
6727   template<typename ConditionalOperator>
6728   bool HandleConditionalOperator(const ConditionalOperator *E) {
6729     bool BoolResult;
6730     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
6731       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
6732         CheckPotentialConstantConditional(E);
6733         return false;
6734       }
6735       if (Info.noteFailure()) {
6736         StmtVisitorTy::Visit(E->getTrueExpr());
6737         StmtVisitorTy::Visit(E->getFalseExpr());
6738       }
6739       return false;
6740     }
6741 
6742     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
6743     return StmtVisitorTy::Visit(EvalExpr);
6744   }
6745 
6746 protected:
6747   EvalInfo &Info;
6748   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
6749   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
6750 
6751   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
6752     return Info.CCEDiag(E, D);
6753   }
6754 
6755   bool ZeroInitialization(const Expr *E) { return Error(E); }
6756 
6757 public:
6758   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
6759 
6760   EvalInfo &getEvalInfo() { return Info; }
6761 
6762   /// Report an evaluation error. This should only be called when an error is
6763   /// first discovered. When propagating an error, just return false.
6764   bool Error(const Expr *E, diag::kind D) {
6765     Info.FFDiag(E, D);
6766     return false;
6767   }
6768   bool Error(const Expr *E) {
6769     return Error(E, diag::note_invalid_subexpr_in_const_expr);
6770   }
6771 
6772   bool VisitStmt(const Stmt *) {
6773     llvm_unreachable("Expression evaluator should not be called on stmts");
6774   }
6775   bool VisitExpr(const Expr *E) {
6776     return Error(E);
6777   }
6778 
6779   bool VisitConstantExpr(const ConstantExpr *E) {
6780     if (E->hasAPValueResult())
6781       return DerivedSuccess(E->getAPValueResult(), E);
6782 
6783     return StmtVisitorTy::Visit(E->getSubExpr());
6784   }
6785 
6786   bool VisitParenExpr(const ParenExpr *E)
6787     { return StmtVisitorTy::Visit(E->getSubExpr()); }
6788   bool VisitUnaryExtension(const UnaryOperator *E)
6789     { return StmtVisitorTy::Visit(E->getSubExpr()); }
6790   bool VisitUnaryPlus(const UnaryOperator *E)
6791     { return StmtVisitorTy::Visit(E->getSubExpr()); }
6792   bool VisitChooseExpr(const ChooseExpr *E)
6793     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
6794   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
6795     { return StmtVisitorTy::Visit(E->getResultExpr()); }
6796   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
6797     { return StmtVisitorTy::Visit(E->getReplacement()); }
6798   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
6799     TempVersionRAII RAII(*Info.CurrentCall);
6800     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
6801     return StmtVisitorTy::Visit(E->getExpr());
6802   }
6803   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
6804     TempVersionRAII RAII(*Info.CurrentCall);
6805     // The initializer may not have been parsed yet, or might be erroneous.
6806     if (!E->getExpr())
6807       return Error(E);
6808     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
6809     return StmtVisitorTy::Visit(E->getExpr());
6810   }
6811 
6812   bool VisitExprWithCleanups(const ExprWithCleanups *E) {
6813     FullExpressionRAII Scope(Info);
6814     return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
6815   }
6816 
6817   // Temporaries are registered when created, so we don't care about
6818   // CXXBindTemporaryExpr.
6819   bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
6820     return StmtVisitorTy::Visit(E->getSubExpr());
6821   }
6822 
6823   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
6824     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
6825     return static_cast<Derived*>(this)->VisitCastExpr(E);
6826   }
6827   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
6828     if (!Info.Ctx.getLangOpts().CPlusPlus2a)
6829       CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
6830     return static_cast<Derived*>(this)->VisitCastExpr(E);
6831   }
6832   bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
6833     return static_cast<Derived*>(this)->VisitCastExpr(E);
6834   }
6835 
6836   bool VisitBinaryOperator(const BinaryOperator *E) {
6837     switch (E->getOpcode()) {
6838     default:
6839       return Error(E);
6840 
6841     case BO_Comma:
6842       VisitIgnoredValue(E->getLHS());
6843       return StmtVisitorTy::Visit(E->getRHS());
6844 
6845     case BO_PtrMemD:
6846     case BO_PtrMemI: {
6847       LValue Obj;
6848       if (!HandleMemberPointerAccess(Info, E, Obj))
6849         return false;
6850       APValue Result;
6851       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
6852         return false;
6853       return DerivedSuccess(Result, E);
6854     }
6855     }
6856   }
6857 
6858   bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
6859     return StmtVisitorTy::Visit(E->getSemanticForm());
6860   }
6861 
6862   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
6863     // Evaluate and cache the common expression. We treat it as a temporary,
6864     // even though it's not quite the same thing.
6865     LValue CommonLV;
6866     if (!Evaluate(Info.CurrentCall->createTemporary(
6867                       E->getOpaqueValue(),
6868                       getStorageType(Info.Ctx, E->getOpaqueValue()), false,
6869                       CommonLV),
6870                   Info, E->getCommon()))
6871       return false;
6872 
6873     return HandleConditionalOperator(E);
6874   }
6875 
6876   bool VisitConditionalOperator(const ConditionalOperator *E) {
6877     bool IsBcpCall = false;
6878     // If the condition (ignoring parens) is a __builtin_constant_p call,
6879     // the result is a constant expression if it can be folded without
6880     // side-effects. This is an important GNU extension. See GCC PR38377
6881     // for discussion.
6882     if (const CallExpr *CallCE =
6883           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
6884       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
6885         IsBcpCall = true;
6886 
6887     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
6888     // constant expression; we can't check whether it's potentially foldable.
6889     // FIXME: We should instead treat __builtin_constant_p as non-constant if
6890     // it would return 'false' in this mode.
6891     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
6892       return false;
6893 
6894     FoldConstant Fold(Info, IsBcpCall);
6895     if (!HandleConditionalOperator(E)) {
6896       Fold.keepDiagnostics();
6897       return false;
6898     }
6899 
6900     return true;
6901   }
6902 
6903   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
6904     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
6905       return DerivedSuccess(*Value, E);
6906 
6907     const Expr *Source = E->getSourceExpr();
6908     if (!Source)
6909       return Error(E);
6910     if (Source == E) { // sanity checking.
6911       assert(0 && "OpaqueValueExpr recursively refers to itself");
6912       return Error(E);
6913     }
6914     return StmtVisitorTy::Visit(Source);
6915   }
6916 
6917   bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
6918     for (const Expr *SemE : E->semantics()) {
6919       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
6920         // FIXME: We can't handle the case where an OpaqueValueExpr is also the
6921         // result expression: there could be two different LValues that would
6922         // refer to the same object in that case, and we can't model that.
6923         if (SemE == E->getResultExpr())
6924           return Error(E);
6925 
6926         // Unique OVEs get evaluated if and when we encounter them when
6927         // emitting the rest of the semantic form, rather than eagerly.
6928         if (OVE->isUnique())
6929           continue;
6930 
6931         LValue LV;
6932         if (!Evaluate(Info.CurrentCall->createTemporary(
6933                           OVE, getStorageType(Info.Ctx, OVE), false, LV),
6934                       Info, OVE->getSourceExpr()))
6935           return false;
6936       } else if (SemE == E->getResultExpr()) {
6937         if (!StmtVisitorTy::Visit(SemE))
6938           return false;
6939       } else {
6940         if (!EvaluateIgnoredValue(Info, SemE))
6941           return false;
6942       }
6943     }
6944     return true;
6945   }
6946 
6947   bool VisitCallExpr(const CallExpr *E) {
6948     APValue Result;
6949     if (!handleCallExpr(E, Result, nullptr))
6950       return false;
6951     return DerivedSuccess(Result, E);
6952   }
6953 
6954   bool handleCallExpr(const CallExpr *E, APValue &Result,
6955                      const LValue *ResultSlot) {
6956     const Expr *Callee = E->getCallee()->IgnoreParens();
6957     QualType CalleeType = Callee->getType();
6958 
6959     const FunctionDecl *FD = nullptr;
6960     LValue *This = nullptr, ThisVal;
6961     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
6962     bool HasQualifier = false;
6963 
6964     // Extract function decl and 'this' pointer from the callee.
6965     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
6966       const CXXMethodDecl *Member = nullptr;
6967       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
6968         // Explicit bound member calls, such as x.f() or p->g();
6969         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
6970           return false;
6971         Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
6972         if (!Member)
6973           return Error(Callee);
6974         This = &ThisVal;
6975         HasQualifier = ME->hasQualifier();
6976       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
6977         // Indirect bound member calls ('.*' or '->*').
6978         const ValueDecl *D =
6979             HandleMemberPointerAccess(Info, BE, ThisVal, false);
6980         if (!D)
6981           return false;
6982         Member = dyn_cast<CXXMethodDecl>(D);
6983         if (!Member)
6984           return Error(Callee);
6985         This = &ThisVal;
6986       } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
6987         if (!Info.getLangOpts().CPlusPlus2a)
6988           Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
6989         return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
6990                HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
6991       } else
6992         return Error(Callee);
6993       FD = Member;
6994     } else if (CalleeType->isFunctionPointerType()) {
6995       LValue Call;
6996       if (!EvaluatePointer(Callee, Call, Info))
6997         return false;
6998 
6999       if (!Call.getLValueOffset().isZero())
7000         return Error(Callee);
7001       FD = dyn_cast_or_null<FunctionDecl>(
7002                              Call.getLValueBase().dyn_cast<const ValueDecl*>());
7003       if (!FD)
7004         return Error(Callee);
7005       // Don't call function pointers which have been cast to some other type.
7006       // Per DR (no number yet), the caller and callee can differ in noexcept.
7007       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7008         CalleeType->getPointeeType(), FD->getType())) {
7009         return Error(E);
7010       }
7011 
7012       // Overloaded operator calls to member functions are represented as normal
7013       // calls with '*this' as the first argument.
7014       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7015       if (MD && !MD->isStatic()) {
7016         // FIXME: When selecting an implicit conversion for an overloaded
7017         // operator delete, we sometimes try to evaluate calls to conversion
7018         // operators without a 'this' parameter!
7019         if (Args.empty())
7020           return Error(E);
7021 
7022         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7023           return false;
7024         This = &ThisVal;
7025         Args = Args.slice(1);
7026       } else if (MD && MD->isLambdaStaticInvoker()) {
7027         // Map the static invoker for the lambda back to the call operator.
7028         // Conveniently, we don't have to slice out the 'this' argument (as is
7029         // being done for the non-static case), since a static member function
7030         // doesn't have an implicit argument passed in.
7031         const CXXRecordDecl *ClosureClass = MD->getParent();
7032         assert(
7033             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7034             "Number of captures must be zero for conversion to function-ptr");
7035 
7036         const CXXMethodDecl *LambdaCallOp =
7037             ClosureClass->getLambdaCallOperator();
7038 
7039         // Set 'FD', the function that will be called below, to the call
7040         // operator.  If the closure object represents a generic lambda, find
7041         // the corresponding specialization of the call operator.
7042 
7043         if (ClosureClass->isGenericLambda()) {
7044           assert(MD->isFunctionTemplateSpecialization() &&
7045                  "A generic lambda's static-invoker function must be a "
7046                  "template specialization");
7047           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7048           FunctionTemplateDecl *CallOpTemplate =
7049               LambdaCallOp->getDescribedFunctionTemplate();
7050           void *InsertPos = nullptr;
7051           FunctionDecl *CorrespondingCallOpSpecialization =
7052               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7053           assert(CorrespondingCallOpSpecialization &&
7054                  "We must always have a function call operator specialization "
7055                  "that corresponds to our static invoker specialization");
7056           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7057         } else
7058           FD = LambdaCallOp;
7059       } else if (FD->isReplaceableGlobalAllocationFunction()) {
7060         if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7061             FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7062           LValue Ptr;
7063           if (!HandleOperatorNewCall(Info, E, Ptr))
7064             return false;
7065           Ptr.moveInto(Result);
7066           return true;
7067         } else {
7068           return HandleOperatorDeleteCall(Info, E);
7069         }
7070       }
7071     } else
7072       return Error(E);
7073 
7074     SmallVector<QualType, 4> CovariantAdjustmentPath;
7075     if (This) {
7076       auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7077       if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
7078         // Perform virtual dispatch, if necessary.
7079         FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
7080                                    CovariantAdjustmentPath);
7081         if (!FD)
7082           return false;
7083       } else {
7084         // Check that the 'this' pointer points to an object of the right type.
7085         // FIXME: If this is an assignment operator call, we may need to change
7086         // the active union member before we check this.
7087         if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
7088           return false;
7089       }
7090     }
7091 
7092     // Destructor calls are different enough that they have their own codepath.
7093     if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
7094       assert(This && "no 'this' pointer for destructor call");
7095       return HandleDestruction(Info, E, *This,
7096                                Info.Ctx.getRecordType(DD->getParent()));
7097     }
7098 
7099     const FunctionDecl *Definition = nullptr;
7100     Stmt *Body = FD->getBody(Definition);
7101 
7102     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
7103         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
7104                             Result, ResultSlot))
7105       return false;
7106 
7107     if (!CovariantAdjustmentPath.empty() &&
7108         !HandleCovariantReturnAdjustment(Info, E, Result,
7109                                          CovariantAdjustmentPath))
7110       return false;
7111 
7112     return true;
7113   }
7114 
7115   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7116     return StmtVisitorTy::Visit(E->getInitializer());
7117   }
7118   bool VisitInitListExpr(const InitListExpr *E) {
7119     if (E->getNumInits() == 0)
7120       return DerivedZeroInitialization(E);
7121     if (E->getNumInits() == 1)
7122       return StmtVisitorTy::Visit(E->getInit(0));
7123     return Error(E);
7124   }
7125   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
7126     return DerivedZeroInitialization(E);
7127   }
7128   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
7129     return DerivedZeroInitialization(E);
7130   }
7131   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
7132     return DerivedZeroInitialization(E);
7133   }
7134 
7135   /// A member expression where the object is a prvalue is itself a prvalue.
7136   bool VisitMemberExpr(const MemberExpr *E) {
7137     assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
7138            "missing temporary materialization conversion");
7139     assert(!E->isArrow() && "missing call to bound member function?");
7140 
7141     APValue Val;
7142     if (!Evaluate(Val, Info, E->getBase()))
7143       return false;
7144 
7145     QualType BaseTy = E->getBase()->getType();
7146 
7147     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
7148     if (!FD) return Error(E);
7149     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
7150     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7151            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7152 
7153     // Note: there is no lvalue base here. But this case should only ever
7154     // happen in C or in C++98, where we cannot be evaluating a constexpr
7155     // constructor, which is the only case the base matters.
7156     CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
7157     SubobjectDesignator Designator(BaseTy);
7158     Designator.addDeclUnchecked(FD);
7159 
7160     APValue Result;
7161     return extractSubobject(Info, E, Obj, Designator, Result) &&
7162            DerivedSuccess(Result, E);
7163   }
7164 
7165   bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
7166     APValue Val;
7167     if (!Evaluate(Val, Info, E->getBase()))
7168       return false;
7169 
7170     if (Val.isVector()) {
7171       SmallVector<uint32_t, 4> Indices;
7172       E->getEncodedElementAccess(Indices);
7173       if (Indices.size() == 1) {
7174         // Return scalar.
7175         return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
7176       } else {
7177         // Construct new APValue vector.
7178         SmallVector<APValue, 4> Elts;
7179         for (unsigned I = 0; I < Indices.size(); ++I) {
7180           Elts.push_back(Val.getVectorElt(Indices[I]));
7181         }
7182         APValue VecResult(Elts.data(), Indices.size());
7183         return DerivedSuccess(VecResult, E);
7184       }
7185     }
7186 
7187     return false;
7188   }
7189 
7190   bool VisitCastExpr(const CastExpr *E) {
7191     switch (E->getCastKind()) {
7192     default:
7193       break;
7194 
7195     case CK_AtomicToNonAtomic: {
7196       APValue AtomicVal;
7197       // This does not need to be done in place even for class/array types:
7198       // atomic-to-non-atomic conversion implies copying the object
7199       // representation.
7200       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
7201         return false;
7202       return DerivedSuccess(AtomicVal, E);
7203     }
7204 
7205     case CK_NoOp:
7206     case CK_UserDefinedConversion:
7207       return StmtVisitorTy::Visit(E->getSubExpr());
7208 
7209     case CK_LValueToRValue: {
7210       LValue LVal;
7211       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
7212         return false;
7213       APValue RVal;
7214       // Note, we use the subexpression's type in order to retain cv-qualifiers.
7215       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7216                                           LVal, RVal))
7217         return false;
7218       return DerivedSuccess(RVal, E);
7219     }
7220     case CK_LValueToRValueBitCast: {
7221       APValue DestValue, SourceValue;
7222       if (!Evaluate(SourceValue, Info, E->getSubExpr()))
7223         return false;
7224       if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
7225         return false;
7226       return DerivedSuccess(DestValue, E);
7227     }
7228 
7229     case CK_AddressSpaceConversion: {
7230       APValue Value;
7231       if (!Evaluate(Value, Info, E->getSubExpr()))
7232         return false;
7233       return DerivedSuccess(Value, E);
7234     }
7235     }
7236 
7237     return Error(E);
7238   }
7239 
7240   bool VisitUnaryPostInc(const UnaryOperator *UO) {
7241     return VisitUnaryPostIncDec(UO);
7242   }
7243   bool VisitUnaryPostDec(const UnaryOperator *UO) {
7244     return VisitUnaryPostIncDec(UO);
7245   }
7246   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
7247     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7248       return Error(UO);
7249 
7250     LValue LVal;
7251     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
7252       return false;
7253     APValue RVal;
7254     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
7255                       UO->isIncrementOp(), &RVal))
7256       return false;
7257     return DerivedSuccess(RVal, UO);
7258   }
7259 
7260   bool VisitStmtExpr(const StmtExpr *E) {
7261     // We will have checked the full-expressions inside the statement expression
7262     // when they were completed, and don't need to check them again now.
7263     if (Info.checkingForUndefinedBehavior())
7264       return Error(E);
7265 
7266     const CompoundStmt *CS = E->getSubStmt();
7267     if (CS->body_empty())
7268       return true;
7269 
7270     BlockScopeRAII Scope(Info);
7271     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
7272                                            BE = CS->body_end();
7273          /**/; ++BI) {
7274       if (BI + 1 == BE) {
7275         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
7276         if (!FinalExpr) {
7277           Info.FFDiag((*BI)->getBeginLoc(),
7278                       diag::note_constexpr_stmt_expr_unsupported);
7279           return false;
7280         }
7281         return this->Visit(FinalExpr) && Scope.destroy();
7282       }
7283 
7284       APValue ReturnValue;
7285       StmtResult Result = { ReturnValue, nullptr };
7286       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
7287       if (ESR != ESR_Succeeded) {
7288         // FIXME: If the statement-expression terminated due to 'return',
7289         // 'break', or 'continue', it would be nice to propagate that to
7290         // the outer statement evaluation rather than bailing out.
7291         if (ESR != ESR_Failed)
7292           Info.FFDiag((*BI)->getBeginLoc(),
7293                       diag::note_constexpr_stmt_expr_unsupported);
7294         return false;
7295       }
7296     }
7297 
7298     llvm_unreachable("Return from function from the loop above.");
7299   }
7300 
7301   /// Visit a value which is evaluated, but whose value is ignored.
7302   void VisitIgnoredValue(const Expr *E) {
7303     EvaluateIgnoredValue(Info, E);
7304   }
7305 
7306   /// Potentially visit a MemberExpr's base expression.
7307   void VisitIgnoredBaseExpression(const Expr *E) {
7308     // While MSVC doesn't evaluate the base expression, it does diagnose the
7309     // presence of side-effecting behavior.
7310     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
7311       return;
7312     VisitIgnoredValue(E);
7313   }
7314 };
7315 
7316 } // namespace
7317 
7318 //===----------------------------------------------------------------------===//
7319 // Common base class for lvalue and temporary evaluation.
7320 //===----------------------------------------------------------------------===//
7321 namespace {
7322 template<class Derived>
7323 class LValueExprEvaluatorBase
7324   : public ExprEvaluatorBase<Derived> {
7325 protected:
7326   LValue &Result;
7327   bool InvalidBaseOK;
7328   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
7329   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
7330 
7331   bool Success(APValue::LValueBase B) {
7332     Result.set(B);
7333     return true;
7334   }
7335 
7336   bool evaluatePointer(const Expr *E, LValue &Result) {
7337     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
7338   }
7339 
7340 public:
7341   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
7342       : ExprEvaluatorBaseTy(Info), Result(Result),
7343         InvalidBaseOK(InvalidBaseOK) {}
7344 
7345   bool Success(const APValue &V, const Expr *E) {
7346     Result.setFrom(this->Info.Ctx, V);
7347     return true;
7348   }
7349 
7350   bool VisitMemberExpr(const MemberExpr *E) {
7351     // Handle non-static data members.
7352     QualType BaseTy;
7353     bool EvalOK;
7354     if (E->isArrow()) {
7355       EvalOK = evaluatePointer(E->getBase(), Result);
7356       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
7357     } else if (E->getBase()->isRValue()) {
7358       assert(E->getBase()->getType()->isRecordType());
7359       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
7360       BaseTy = E->getBase()->getType();
7361     } else {
7362       EvalOK = this->Visit(E->getBase());
7363       BaseTy = E->getBase()->getType();
7364     }
7365     if (!EvalOK) {
7366       if (!InvalidBaseOK)
7367         return false;
7368       Result.setInvalid(E);
7369       return true;
7370     }
7371 
7372     const ValueDecl *MD = E->getMemberDecl();
7373     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
7374       assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7375              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7376       (void)BaseTy;
7377       if (!HandleLValueMember(this->Info, E, Result, FD))
7378         return false;
7379     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
7380       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
7381         return false;
7382     } else
7383       return this->Error(E);
7384 
7385     if (MD->getType()->isReferenceType()) {
7386       APValue RefValue;
7387       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
7388                                           RefValue))
7389         return false;
7390       return Success(RefValue, E);
7391     }
7392     return true;
7393   }
7394 
7395   bool VisitBinaryOperator(const BinaryOperator *E) {
7396     switch (E->getOpcode()) {
7397     default:
7398       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7399 
7400     case BO_PtrMemD:
7401     case BO_PtrMemI:
7402       return HandleMemberPointerAccess(this->Info, E, Result);
7403     }
7404   }
7405 
7406   bool VisitCastExpr(const CastExpr *E) {
7407     switch (E->getCastKind()) {
7408     default:
7409       return ExprEvaluatorBaseTy::VisitCastExpr(E);
7410 
7411     case CK_DerivedToBase:
7412     case CK_UncheckedDerivedToBase:
7413       if (!this->Visit(E->getSubExpr()))
7414         return false;
7415 
7416       // Now figure out the necessary offset to add to the base LV to get from
7417       // the derived class to the base class.
7418       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
7419                                   Result);
7420     }
7421   }
7422 };
7423 }
7424 
7425 //===----------------------------------------------------------------------===//
7426 // LValue Evaluation
7427 //
7428 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
7429 // function designators (in C), decl references to void objects (in C), and
7430 // temporaries (if building with -Wno-address-of-temporary).
7431 //
7432 // LValue evaluation produces values comprising a base expression of one of the
7433 // following types:
7434 // - Declarations
7435 //  * VarDecl
7436 //  * FunctionDecl
7437 // - Literals
7438 //  * CompoundLiteralExpr in C (and in global scope in C++)
7439 //  * StringLiteral
7440 //  * PredefinedExpr
7441 //  * ObjCStringLiteralExpr
7442 //  * ObjCEncodeExpr
7443 //  * AddrLabelExpr
7444 //  * BlockExpr
7445 //  * CallExpr for a MakeStringConstant builtin
7446 // - typeid(T) expressions, as TypeInfoLValues
7447 // - Locals and temporaries
7448 //  * MaterializeTemporaryExpr
7449 //  * Any Expr, with a CallIndex indicating the function in which the temporary
7450 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
7451 //    from the AST (FIXME).
7452 //  * A MaterializeTemporaryExpr that has static storage duration, with no
7453 //    CallIndex, for a lifetime-extended temporary.
7454 //  * The ConstantExpr that is currently being evaluated during evaluation of an
7455 //    immediate invocation.
7456 // plus an offset in bytes.
7457 //===----------------------------------------------------------------------===//
7458 namespace {
7459 class LValueExprEvaluator
7460   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
7461 public:
7462   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
7463     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
7464 
7465   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
7466   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
7467 
7468   bool VisitDeclRefExpr(const DeclRefExpr *E);
7469   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
7470   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
7471   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
7472   bool VisitMemberExpr(const MemberExpr *E);
7473   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
7474   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
7475   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
7476   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
7477   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
7478   bool VisitUnaryDeref(const UnaryOperator *E);
7479   bool VisitUnaryReal(const UnaryOperator *E);
7480   bool VisitUnaryImag(const UnaryOperator *E);
7481   bool VisitUnaryPreInc(const UnaryOperator *UO) {
7482     return VisitUnaryPreIncDec(UO);
7483   }
7484   bool VisitUnaryPreDec(const UnaryOperator *UO) {
7485     return VisitUnaryPreIncDec(UO);
7486   }
7487   bool VisitBinAssign(const BinaryOperator *BO);
7488   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
7489 
7490   bool VisitCastExpr(const CastExpr *E) {
7491     switch (E->getCastKind()) {
7492     default:
7493       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
7494 
7495     case CK_LValueBitCast:
7496       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7497       if (!Visit(E->getSubExpr()))
7498         return false;
7499       Result.Designator.setInvalid();
7500       return true;
7501 
7502     case CK_BaseToDerived:
7503       if (!Visit(E->getSubExpr()))
7504         return false;
7505       return HandleBaseToDerivedCast(Info, E, Result);
7506 
7507     case CK_Dynamic:
7508       if (!Visit(E->getSubExpr()))
7509         return false;
7510       return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
7511     }
7512   }
7513 };
7514 } // end anonymous namespace
7515 
7516 /// Evaluate an expression as an lvalue. This can be legitimately called on
7517 /// expressions which are not glvalues, in three cases:
7518 ///  * function designators in C, and
7519 ///  * "extern void" objects
7520 ///  * @selector() expressions in Objective-C
7521 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
7522                            bool InvalidBaseOK) {
7523   assert(E->isGLValue() || E->getType()->isFunctionType() ||
7524          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
7525   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
7526 }
7527 
7528 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
7529   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
7530     return Success(FD);
7531   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
7532     return VisitVarDecl(E, VD);
7533   if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
7534     return Visit(BD->getBinding());
7535   return Error(E);
7536 }
7537 
7538 
7539 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
7540 
7541   // If we are within a lambda's call operator, check whether the 'VD' referred
7542   // to within 'E' actually represents a lambda-capture that maps to a
7543   // data-member/field within the closure object, and if so, evaluate to the
7544   // field or what the field refers to.
7545   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
7546       isa<DeclRefExpr>(E) &&
7547       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
7548     // We don't always have a complete capture-map when checking or inferring if
7549     // the function call operator meets the requirements of a constexpr function
7550     // - but we don't need to evaluate the captures to determine constexprness
7551     // (dcl.constexpr C++17).
7552     if (Info.checkingPotentialConstantExpression())
7553       return false;
7554 
7555     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
7556       // Start with 'Result' referring to the complete closure object...
7557       Result = *Info.CurrentCall->This;
7558       // ... then update it to refer to the field of the closure object
7559       // that represents the capture.
7560       if (!HandleLValueMember(Info, E, Result, FD))
7561         return false;
7562       // And if the field is of reference type, update 'Result' to refer to what
7563       // the field refers to.
7564       if (FD->getType()->isReferenceType()) {
7565         APValue RVal;
7566         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
7567                                             RVal))
7568           return false;
7569         Result.setFrom(Info.Ctx, RVal);
7570       }
7571       return true;
7572     }
7573   }
7574   CallStackFrame *Frame = nullptr;
7575   if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
7576     // Only if a local variable was declared in the function currently being
7577     // evaluated, do we expect to be able to find its value in the current
7578     // frame. (Otherwise it was likely declared in an enclosing context and
7579     // could either have a valid evaluatable value (for e.g. a constexpr
7580     // variable) or be ill-formed (and trigger an appropriate evaluation
7581     // diagnostic)).
7582     if (Info.CurrentCall->Callee &&
7583         Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
7584       Frame = Info.CurrentCall;
7585     }
7586   }
7587 
7588   if (!VD->getType()->isReferenceType()) {
7589     if (Frame) {
7590       Result.set({VD, Frame->Index,
7591                   Info.CurrentCall->getCurrentTemporaryVersion(VD)});
7592       return true;
7593     }
7594     return Success(VD);
7595   }
7596 
7597   APValue *V;
7598   if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
7599     return false;
7600   if (!V->hasValue()) {
7601     // FIXME: Is it possible for V to be indeterminate here? If so, we should
7602     // adjust the diagnostic to say that.
7603     if (!Info.checkingPotentialConstantExpression())
7604       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
7605     return false;
7606   }
7607   return Success(*V, E);
7608 }
7609 
7610 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
7611     const MaterializeTemporaryExpr *E) {
7612   // Walk through the expression to find the materialized temporary itself.
7613   SmallVector<const Expr *, 2> CommaLHSs;
7614   SmallVector<SubobjectAdjustment, 2> Adjustments;
7615   const Expr *Inner =
7616       E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
7617 
7618   // If we passed any comma operators, evaluate their LHSs.
7619   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
7620     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
7621       return false;
7622 
7623   // A materialized temporary with static storage duration can appear within the
7624   // result of a constant expression evaluation, so we need to preserve its
7625   // value for use outside this evaluation.
7626   APValue *Value;
7627   if (E->getStorageDuration() == SD_Static) {
7628     Value = E->getOrCreateValue(true);
7629     *Value = APValue();
7630     Result.set(E);
7631   } else {
7632     Value = &Info.CurrentCall->createTemporary(
7633         E, E->getType(), E->getStorageDuration() == SD_Automatic, Result);
7634   }
7635 
7636   QualType Type = Inner->getType();
7637 
7638   // Materialize the temporary itself.
7639   if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
7640     *Value = APValue();
7641     return false;
7642   }
7643 
7644   // Adjust our lvalue to refer to the desired subobject.
7645   for (unsigned I = Adjustments.size(); I != 0; /**/) {
7646     --I;
7647     switch (Adjustments[I].Kind) {
7648     case SubobjectAdjustment::DerivedToBaseAdjustment:
7649       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
7650                                 Type, Result))
7651         return false;
7652       Type = Adjustments[I].DerivedToBase.BasePath->getType();
7653       break;
7654 
7655     case SubobjectAdjustment::FieldAdjustment:
7656       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
7657         return false;
7658       Type = Adjustments[I].Field->getType();
7659       break;
7660 
7661     case SubobjectAdjustment::MemberPointerAdjustment:
7662       if (!HandleMemberPointerAccess(this->Info, Type, Result,
7663                                      Adjustments[I].Ptr.RHS))
7664         return false;
7665       Type = Adjustments[I].Ptr.MPT->getPointeeType();
7666       break;
7667     }
7668   }
7669 
7670   return true;
7671 }
7672 
7673 bool
7674 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7675   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
7676          "lvalue compound literal in c++?");
7677   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
7678   // only see this when folding in C, so there's no standard to follow here.
7679   return Success(E);
7680 }
7681 
7682 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
7683   TypeInfoLValue TypeInfo;
7684 
7685   if (!E->isPotentiallyEvaluated()) {
7686     if (E->isTypeOperand())
7687       TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
7688     else
7689       TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
7690   } else {
7691     if (!Info.Ctx.getLangOpts().CPlusPlus2a) {
7692       Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
7693         << E->getExprOperand()->getType()
7694         << E->getExprOperand()->getSourceRange();
7695     }
7696 
7697     if (!Visit(E->getExprOperand()))
7698       return false;
7699 
7700     Optional<DynamicType> DynType =
7701         ComputeDynamicType(Info, E, Result, AK_TypeId);
7702     if (!DynType)
7703       return false;
7704 
7705     TypeInfo =
7706         TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
7707   }
7708 
7709   return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
7710 }
7711 
7712 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
7713   return Success(E);
7714 }
7715 
7716 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
7717   // Handle static data members.
7718   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
7719     VisitIgnoredBaseExpression(E->getBase());
7720     return VisitVarDecl(E, VD);
7721   }
7722 
7723   // Handle static member functions.
7724   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
7725     if (MD->isStatic()) {
7726       VisitIgnoredBaseExpression(E->getBase());
7727       return Success(MD);
7728     }
7729   }
7730 
7731   // Handle non-static data members.
7732   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
7733 }
7734 
7735 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
7736   // FIXME: Deal with vectors as array subscript bases.
7737   if (E->getBase()->getType()->isVectorType())
7738     return Error(E);
7739 
7740   bool Success = true;
7741   if (!evaluatePointer(E->getBase(), Result)) {
7742     if (!Info.noteFailure())
7743       return false;
7744     Success = false;
7745   }
7746 
7747   APSInt Index;
7748   if (!EvaluateInteger(E->getIdx(), Index, Info))
7749     return false;
7750 
7751   return Success &&
7752          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
7753 }
7754 
7755 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
7756   return evaluatePointer(E->getSubExpr(), Result);
7757 }
7758 
7759 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7760   if (!Visit(E->getSubExpr()))
7761     return false;
7762   // __real is a no-op on scalar lvalues.
7763   if (E->getSubExpr()->getType()->isAnyComplexType())
7764     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
7765   return true;
7766 }
7767 
7768 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
7769   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
7770          "lvalue __imag__ on scalar?");
7771   if (!Visit(E->getSubExpr()))
7772     return false;
7773   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
7774   return true;
7775 }
7776 
7777 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
7778   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7779     return Error(UO);
7780 
7781   if (!this->Visit(UO->getSubExpr()))
7782     return false;
7783 
7784   return handleIncDec(
7785       this->Info, UO, Result, UO->getSubExpr()->getType(),
7786       UO->isIncrementOp(), nullptr);
7787 }
7788 
7789 bool LValueExprEvaluator::VisitCompoundAssignOperator(
7790     const CompoundAssignOperator *CAO) {
7791   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7792     return Error(CAO);
7793 
7794   APValue RHS;
7795 
7796   // The overall lvalue result is the result of evaluating the LHS.
7797   if (!this->Visit(CAO->getLHS())) {
7798     if (Info.noteFailure())
7799       Evaluate(RHS, this->Info, CAO->getRHS());
7800     return false;
7801   }
7802 
7803   if (!Evaluate(RHS, this->Info, CAO->getRHS()))
7804     return false;
7805 
7806   return handleCompoundAssignment(
7807       this->Info, CAO,
7808       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
7809       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
7810 }
7811 
7812 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
7813   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7814     return Error(E);
7815 
7816   APValue NewVal;
7817 
7818   if (!this->Visit(E->getLHS())) {
7819     if (Info.noteFailure())
7820       Evaluate(NewVal, this->Info, E->getRHS());
7821     return false;
7822   }
7823 
7824   if (!Evaluate(NewVal, this->Info, E->getRHS()))
7825     return false;
7826 
7827   if (Info.getLangOpts().CPlusPlus2a &&
7828       !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
7829     return false;
7830 
7831   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
7832                           NewVal);
7833 }
7834 
7835 //===----------------------------------------------------------------------===//
7836 // Pointer Evaluation
7837 //===----------------------------------------------------------------------===//
7838 
7839 /// Attempts to compute the number of bytes available at the pointer
7840 /// returned by a function with the alloc_size attribute. Returns true if we
7841 /// were successful. Places an unsigned number into `Result`.
7842 ///
7843 /// This expects the given CallExpr to be a call to a function with an
7844 /// alloc_size attribute.
7845 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
7846                                             const CallExpr *Call,
7847                                             llvm::APInt &Result) {
7848   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
7849 
7850   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
7851   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
7852   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
7853   if (Call->getNumArgs() <= SizeArgNo)
7854     return false;
7855 
7856   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
7857     Expr::EvalResult ExprResult;
7858     if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
7859       return false;
7860     Into = ExprResult.Val.getInt();
7861     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
7862       return false;
7863     Into = Into.zextOrSelf(BitsInSizeT);
7864     return true;
7865   };
7866 
7867   APSInt SizeOfElem;
7868   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
7869     return false;
7870 
7871   if (!AllocSize->getNumElemsParam().isValid()) {
7872     Result = std::move(SizeOfElem);
7873     return true;
7874   }
7875 
7876   APSInt NumberOfElems;
7877   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
7878   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
7879     return false;
7880 
7881   bool Overflow;
7882   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
7883   if (Overflow)
7884     return false;
7885 
7886   Result = std::move(BytesAvailable);
7887   return true;
7888 }
7889 
7890 /// Convenience function. LVal's base must be a call to an alloc_size
7891 /// function.
7892 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
7893                                             const LValue &LVal,
7894                                             llvm::APInt &Result) {
7895   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7896          "Can't get the size of a non alloc_size function");
7897   const auto *Base = LVal.getLValueBase().get<const Expr *>();
7898   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
7899   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
7900 }
7901 
7902 /// Attempts to evaluate the given LValueBase as the result of a call to
7903 /// a function with the alloc_size attribute. If it was possible to do so, this
7904 /// function will return true, make Result's Base point to said function call,
7905 /// and mark Result's Base as invalid.
7906 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
7907                                       LValue &Result) {
7908   if (Base.isNull())
7909     return false;
7910 
7911   // Because we do no form of static analysis, we only support const variables.
7912   //
7913   // Additionally, we can't support parameters, nor can we support static
7914   // variables (in the latter case, use-before-assign isn't UB; in the former,
7915   // we have no clue what they'll be assigned to).
7916   const auto *VD =
7917       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
7918   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
7919     return false;
7920 
7921   const Expr *Init = VD->getAnyInitializer();
7922   if (!Init)
7923     return false;
7924 
7925   const Expr *E = Init->IgnoreParens();
7926   if (!tryUnwrapAllocSizeCall(E))
7927     return false;
7928 
7929   // Store E instead of E unwrapped so that the type of the LValue's base is
7930   // what the user wanted.
7931   Result.setInvalid(E);
7932 
7933   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
7934   Result.addUnsizedArray(Info, E, Pointee);
7935   return true;
7936 }
7937 
7938 namespace {
7939 class PointerExprEvaluator
7940   : public ExprEvaluatorBase<PointerExprEvaluator> {
7941   LValue &Result;
7942   bool InvalidBaseOK;
7943 
7944   bool Success(const Expr *E) {
7945     Result.set(E);
7946     return true;
7947   }
7948 
7949   bool evaluateLValue(const Expr *E, LValue &Result) {
7950     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
7951   }
7952 
7953   bool evaluatePointer(const Expr *E, LValue &Result) {
7954     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
7955   }
7956 
7957   bool visitNonBuiltinCallExpr(const CallExpr *E);
7958 public:
7959 
7960   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
7961       : ExprEvaluatorBaseTy(info), Result(Result),
7962         InvalidBaseOK(InvalidBaseOK) {}
7963 
7964   bool Success(const APValue &V, const Expr *E) {
7965     Result.setFrom(Info.Ctx, V);
7966     return true;
7967   }
7968   bool ZeroInitialization(const Expr *E) {
7969     Result.setNull(Info.Ctx, E->getType());
7970     return true;
7971   }
7972 
7973   bool VisitBinaryOperator(const BinaryOperator *E);
7974   bool VisitCastExpr(const CastExpr* E);
7975   bool VisitUnaryAddrOf(const UnaryOperator *E);
7976   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
7977       { return Success(E); }
7978   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
7979     if (E->isExpressibleAsConstantInitializer())
7980       return Success(E);
7981     if (Info.noteFailure())
7982       EvaluateIgnoredValue(Info, E->getSubExpr());
7983     return Error(E);
7984   }
7985   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
7986       { return Success(E); }
7987   bool VisitCallExpr(const CallExpr *E);
7988   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
7989   bool VisitBlockExpr(const BlockExpr *E) {
7990     if (!E->getBlockDecl()->hasCaptures())
7991       return Success(E);
7992     return Error(E);
7993   }
7994   bool VisitCXXThisExpr(const CXXThisExpr *E) {
7995     // Can't look at 'this' when checking a potential constant expression.
7996     if (Info.checkingPotentialConstantExpression())
7997       return false;
7998     if (!Info.CurrentCall->This) {
7999       if (Info.getLangOpts().CPlusPlus11)
8000         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
8001       else
8002         Info.FFDiag(E);
8003       return false;
8004     }
8005     Result = *Info.CurrentCall->This;
8006     // If we are inside a lambda's call operator, the 'this' expression refers
8007     // to the enclosing '*this' object (either by value or reference) which is
8008     // either copied into the closure object's field that represents the '*this'
8009     // or refers to '*this'.
8010     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
8011       // Ensure we actually have captured 'this'. (an error will have
8012       // been previously reported if not).
8013       if (!Info.CurrentCall->LambdaThisCaptureField)
8014         return false;
8015 
8016       // Update 'Result' to refer to the data member/field of the closure object
8017       // that represents the '*this' capture.
8018       if (!HandleLValueMember(Info, E, Result,
8019                              Info.CurrentCall->LambdaThisCaptureField))
8020         return false;
8021       // If we captured '*this' by reference, replace the field with its referent.
8022       if (Info.CurrentCall->LambdaThisCaptureField->getType()
8023               ->isPointerType()) {
8024         APValue RVal;
8025         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
8026                                             RVal))
8027           return false;
8028 
8029         Result.setFrom(Info.Ctx, RVal);
8030       }
8031     }
8032     return true;
8033   }
8034 
8035   bool VisitCXXNewExpr(const CXXNewExpr *E);
8036 
8037   bool VisitSourceLocExpr(const SourceLocExpr *E) {
8038     assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
8039     APValue LValResult = E->EvaluateInContext(
8040         Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8041     Result.setFrom(Info.Ctx, LValResult);
8042     return true;
8043   }
8044 
8045   // FIXME: Missing: @protocol, @selector
8046 };
8047 } // end anonymous namespace
8048 
8049 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
8050                             bool InvalidBaseOK) {
8051   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
8052   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8053 }
8054 
8055 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8056   if (E->getOpcode() != BO_Add &&
8057       E->getOpcode() != BO_Sub)
8058     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8059 
8060   const Expr *PExp = E->getLHS();
8061   const Expr *IExp = E->getRHS();
8062   if (IExp->getType()->isPointerType())
8063     std::swap(PExp, IExp);
8064 
8065   bool EvalPtrOK = evaluatePointer(PExp, Result);
8066   if (!EvalPtrOK && !Info.noteFailure())
8067     return false;
8068 
8069   llvm::APSInt Offset;
8070   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
8071     return false;
8072 
8073   if (E->getOpcode() == BO_Sub)
8074     negateAsSigned(Offset);
8075 
8076   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
8077   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
8078 }
8079 
8080 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8081   return evaluateLValue(E->getSubExpr(), Result);
8082 }
8083 
8084 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8085   const Expr *SubExpr = E->getSubExpr();
8086 
8087   switch (E->getCastKind()) {
8088   default:
8089     break;
8090   case CK_BitCast:
8091   case CK_CPointerToObjCPointerCast:
8092   case CK_BlockPointerToObjCPointerCast:
8093   case CK_AnyPointerToBlockPointerCast:
8094   case CK_AddressSpaceConversion:
8095     if (!Visit(SubExpr))
8096       return false;
8097     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
8098     // permitted in constant expressions in C++11. Bitcasts from cv void* are
8099     // also static_casts, but we disallow them as a resolution to DR1312.
8100     if (!E->getType()->isVoidPointerType()) {
8101       if (!Result.InvalidBase && !Result.Designator.Invalid &&
8102           !Result.IsNullPtr &&
8103           Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
8104                                           E->getType()->getPointeeType()) &&
8105           Info.getStdAllocatorCaller("allocate")) {
8106         // Inside a call to std::allocator::allocate and friends, we permit
8107         // casting from void* back to cv1 T* for a pointer that points to a
8108         // cv2 T.
8109       } else {
8110         Result.Designator.setInvalid();
8111         if (SubExpr->getType()->isVoidPointerType())
8112           CCEDiag(E, diag::note_constexpr_invalid_cast)
8113             << 3 << SubExpr->getType();
8114         else
8115           CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8116       }
8117     }
8118     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
8119       ZeroInitialization(E);
8120     return true;
8121 
8122   case CK_DerivedToBase:
8123   case CK_UncheckedDerivedToBase:
8124     if (!evaluatePointer(E->getSubExpr(), Result))
8125       return false;
8126     if (!Result.Base && Result.Offset.isZero())
8127       return true;
8128 
8129     // Now figure out the necessary offset to add to the base LV to get from
8130     // the derived class to the base class.
8131     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
8132                                   castAs<PointerType>()->getPointeeType(),
8133                                 Result);
8134 
8135   case CK_BaseToDerived:
8136     if (!Visit(E->getSubExpr()))
8137       return false;
8138     if (!Result.Base && Result.Offset.isZero())
8139       return true;
8140     return HandleBaseToDerivedCast(Info, E, Result);
8141 
8142   case CK_Dynamic:
8143     if (!Visit(E->getSubExpr()))
8144       return false;
8145     return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8146 
8147   case CK_NullToPointer:
8148     VisitIgnoredValue(E->getSubExpr());
8149     return ZeroInitialization(E);
8150 
8151   case CK_IntegralToPointer: {
8152     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8153 
8154     APValue Value;
8155     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
8156       break;
8157 
8158     if (Value.isInt()) {
8159       unsigned Size = Info.Ctx.getTypeSize(E->getType());
8160       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
8161       Result.Base = (Expr*)nullptr;
8162       Result.InvalidBase = false;
8163       Result.Offset = CharUnits::fromQuantity(N);
8164       Result.Designator.setInvalid();
8165       Result.IsNullPtr = false;
8166       return true;
8167     } else {
8168       // Cast is of an lvalue, no need to change value.
8169       Result.setFrom(Info.Ctx, Value);
8170       return true;
8171     }
8172   }
8173 
8174   case CK_ArrayToPointerDecay: {
8175     if (SubExpr->isGLValue()) {
8176       if (!evaluateLValue(SubExpr, Result))
8177         return false;
8178     } else {
8179       APValue &Value = Info.CurrentCall->createTemporary(
8180           SubExpr, SubExpr->getType(), false, Result);
8181       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
8182         return false;
8183     }
8184     // The result is a pointer to the first element of the array.
8185     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
8186     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
8187       Result.addArray(Info, E, CAT);
8188     else
8189       Result.addUnsizedArray(Info, E, AT->getElementType());
8190     return true;
8191   }
8192 
8193   case CK_FunctionToPointerDecay:
8194     return evaluateLValue(SubExpr, Result);
8195 
8196   case CK_LValueToRValue: {
8197     LValue LVal;
8198     if (!evaluateLValue(E->getSubExpr(), LVal))
8199       return false;
8200 
8201     APValue RVal;
8202     // Note, we use the subexpression's type in order to retain cv-qualifiers.
8203     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8204                                         LVal, RVal))
8205       return InvalidBaseOK &&
8206              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
8207     return Success(RVal, E);
8208   }
8209   }
8210 
8211   return ExprEvaluatorBaseTy::VisitCastExpr(E);
8212 }
8213 
8214 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
8215                                 UnaryExprOrTypeTrait ExprKind) {
8216   // C++ [expr.alignof]p3:
8217   //     When alignof is applied to a reference type, the result is the
8218   //     alignment of the referenced type.
8219   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
8220     T = Ref->getPointeeType();
8221 
8222   if (T.getQualifiers().hasUnaligned())
8223     return CharUnits::One();
8224 
8225   const bool AlignOfReturnsPreferred =
8226       Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
8227 
8228   // __alignof is defined to return the preferred alignment.
8229   // Before 8, clang returned the preferred alignment for alignof and _Alignof
8230   // as well.
8231   if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
8232     return Info.Ctx.toCharUnitsFromBits(
8233       Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
8234   // alignof and _Alignof are defined to return the ABI alignment.
8235   else if (ExprKind == UETT_AlignOf)
8236     return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
8237   else
8238     llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
8239 }
8240 
8241 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
8242                                 UnaryExprOrTypeTrait ExprKind) {
8243   E = E->IgnoreParens();
8244 
8245   // The kinds of expressions that we have special-case logic here for
8246   // should be kept up to date with the special checks for those
8247   // expressions in Sema.
8248 
8249   // alignof decl is always accepted, even if it doesn't make sense: we default
8250   // to 1 in those cases.
8251   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8252     return Info.Ctx.getDeclAlign(DRE->getDecl(),
8253                                  /*RefAsPointee*/true);
8254 
8255   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
8256     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
8257                                  /*RefAsPointee*/true);
8258 
8259   return GetAlignOfType(Info, E->getType(), ExprKind);
8260 }
8261 
8262 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
8263   if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
8264     return Info.Ctx.getDeclAlign(VD);
8265   if (const auto *E = Value.Base.dyn_cast<const Expr *>())
8266     return GetAlignOfExpr(Info, E, UETT_AlignOf);
8267   return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
8268 }
8269 
8270 /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
8271 /// __builtin_is_aligned and __builtin_assume_aligned.
8272 static bool getAlignmentArgument(const Expr *E, QualType ForType,
8273                                  EvalInfo &Info, APSInt &Alignment) {
8274   if (!EvaluateInteger(E, Alignment, Info))
8275     return false;
8276   if (Alignment < 0 || !Alignment.isPowerOf2()) {
8277     Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
8278     return false;
8279   }
8280   unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
8281   APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
8282   if (APSInt::compareValues(Alignment, MaxValue) > 0) {
8283     Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
8284         << MaxValue << ForType << Alignment;
8285     return false;
8286   }
8287   // Ensure both alignment and source value have the same bit width so that we
8288   // don't assert when computing the resulting value.
8289   APSInt ExtAlignment =
8290       APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
8291   assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
8292          "Alignment should not be changed by ext/trunc");
8293   Alignment = ExtAlignment;
8294   assert(Alignment.getBitWidth() == SrcWidth);
8295   return true;
8296 }
8297 
8298 // To be clear: this happily visits unsupported builtins. Better name welcomed.
8299 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
8300   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
8301     return true;
8302 
8303   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
8304     return false;
8305 
8306   Result.setInvalid(E);
8307   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
8308   Result.addUnsizedArray(Info, E, PointeeTy);
8309   return true;
8310 }
8311 
8312 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
8313   if (IsStringLiteralCall(E))
8314     return Success(E);
8315 
8316   if (unsigned BuiltinOp = E->getBuiltinCallee())
8317     return VisitBuiltinCallExpr(E, BuiltinOp);
8318 
8319   return visitNonBuiltinCallExpr(E);
8320 }
8321 
8322 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8323                                                 unsigned BuiltinOp) {
8324   switch (BuiltinOp) {
8325   case Builtin::BI__builtin_addressof:
8326     return evaluateLValue(E->getArg(0), Result);
8327   case Builtin::BI__builtin_assume_aligned: {
8328     // We need to be very careful here because: if the pointer does not have the
8329     // asserted alignment, then the behavior is undefined, and undefined
8330     // behavior is non-constant.
8331     if (!evaluatePointer(E->getArg(0), Result))
8332       return false;
8333 
8334     LValue OffsetResult(Result);
8335     APSInt Alignment;
8336     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
8337                               Alignment))
8338       return false;
8339     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
8340 
8341     if (E->getNumArgs() > 2) {
8342       APSInt Offset;
8343       if (!EvaluateInteger(E->getArg(2), Offset, Info))
8344         return false;
8345 
8346       int64_t AdditionalOffset = -Offset.getZExtValue();
8347       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
8348     }
8349 
8350     // If there is a base object, then it must have the correct alignment.
8351     if (OffsetResult.Base) {
8352       CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
8353 
8354       if (BaseAlignment < Align) {
8355         Result.Designator.setInvalid();
8356         // FIXME: Add support to Diagnostic for long / long long.
8357         CCEDiag(E->getArg(0),
8358                 diag::note_constexpr_baa_insufficient_alignment) << 0
8359           << (unsigned)BaseAlignment.getQuantity()
8360           << (unsigned)Align.getQuantity();
8361         return false;
8362       }
8363     }
8364 
8365     // The offset must also have the correct alignment.
8366     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
8367       Result.Designator.setInvalid();
8368 
8369       (OffsetResult.Base
8370            ? CCEDiag(E->getArg(0),
8371                      diag::note_constexpr_baa_insufficient_alignment) << 1
8372            : CCEDiag(E->getArg(0),
8373                      diag::note_constexpr_baa_value_insufficient_alignment))
8374         << (int)OffsetResult.Offset.getQuantity()
8375         << (unsigned)Align.getQuantity();
8376       return false;
8377     }
8378 
8379     return true;
8380   }
8381   case Builtin::BI__builtin_align_up:
8382   case Builtin::BI__builtin_align_down: {
8383     if (!evaluatePointer(E->getArg(0), Result))
8384       return false;
8385     APSInt Alignment;
8386     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
8387                               Alignment))
8388       return false;
8389     CharUnits BaseAlignment = getBaseAlignment(Info, Result);
8390     CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
8391     // For align_up/align_down, we can return the same value if the alignment
8392     // is known to be greater or equal to the requested value.
8393     if (PtrAlign.getQuantity() >= Alignment)
8394       return true;
8395 
8396     // The alignment could be greater than the minimum at run-time, so we cannot
8397     // infer much about the resulting pointer value. One case is possible:
8398     // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
8399     // can infer the correct index if the requested alignment is smaller than
8400     // the base alignment so we can perform the computation on the offset.
8401     if (BaseAlignment.getQuantity() >= Alignment) {
8402       assert(Alignment.getBitWidth() <= 64 &&
8403              "Cannot handle > 64-bit address-space");
8404       uint64_t Alignment64 = Alignment.getZExtValue();
8405       CharUnits NewOffset = CharUnits::fromQuantity(
8406           BuiltinOp == Builtin::BI__builtin_align_down
8407               ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
8408               : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
8409       Result.adjustOffset(NewOffset - Result.Offset);
8410       // TODO: diagnose out-of-bounds values/only allow for arrays?
8411       return true;
8412     }
8413     // Otherwise, we cannot constant-evaluate the result.
8414     Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
8415         << Alignment;
8416     return false;
8417   }
8418   case Builtin::BI__builtin_operator_new:
8419     return HandleOperatorNewCall(Info, E, Result);
8420   case Builtin::BI__builtin_launder:
8421     return evaluatePointer(E->getArg(0), Result);
8422   case Builtin::BIstrchr:
8423   case Builtin::BIwcschr:
8424   case Builtin::BImemchr:
8425   case Builtin::BIwmemchr:
8426     if (Info.getLangOpts().CPlusPlus11)
8427       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8428         << /*isConstexpr*/0 << /*isConstructor*/0
8429         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
8430     else
8431       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
8432     LLVM_FALLTHROUGH;
8433   case Builtin::BI__builtin_strchr:
8434   case Builtin::BI__builtin_wcschr:
8435   case Builtin::BI__builtin_memchr:
8436   case Builtin::BI__builtin_char_memchr:
8437   case Builtin::BI__builtin_wmemchr: {
8438     if (!Visit(E->getArg(0)))
8439       return false;
8440     APSInt Desired;
8441     if (!EvaluateInteger(E->getArg(1), Desired, Info))
8442       return false;
8443     uint64_t MaxLength = uint64_t(-1);
8444     if (BuiltinOp != Builtin::BIstrchr &&
8445         BuiltinOp != Builtin::BIwcschr &&
8446         BuiltinOp != Builtin::BI__builtin_strchr &&
8447         BuiltinOp != Builtin::BI__builtin_wcschr) {
8448       APSInt N;
8449       if (!EvaluateInteger(E->getArg(2), N, Info))
8450         return false;
8451       MaxLength = N.getExtValue();
8452     }
8453     // We cannot find the value if there are no candidates to match against.
8454     if (MaxLength == 0u)
8455       return ZeroInitialization(E);
8456     if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
8457         Result.Designator.Invalid)
8458       return false;
8459     QualType CharTy = Result.Designator.getType(Info.Ctx);
8460     bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
8461                      BuiltinOp == Builtin::BI__builtin_memchr;
8462     assert(IsRawByte ||
8463            Info.Ctx.hasSameUnqualifiedType(
8464                CharTy, E->getArg(0)->getType()->getPointeeType()));
8465     // Pointers to const void may point to objects of incomplete type.
8466     if (IsRawByte && CharTy->isIncompleteType()) {
8467       Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
8468       return false;
8469     }
8470     // Give up on byte-oriented matching against multibyte elements.
8471     // FIXME: We can compare the bytes in the correct order.
8472     if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One())
8473       return false;
8474     // Figure out what value we're actually looking for (after converting to
8475     // the corresponding unsigned type if necessary).
8476     uint64_t DesiredVal;
8477     bool StopAtNull = false;
8478     switch (BuiltinOp) {
8479     case Builtin::BIstrchr:
8480     case Builtin::BI__builtin_strchr:
8481       // strchr compares directly to the passed integer, and therefore
8482       // always fails if given an int that is not a char.
8483       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
8484                                                   E->getArg(1)->getType(),
8485                                                   Desired),
8486                                Desired))
8487         return ZeroInitialization(E);
8488       StopAtNull = true;
8489       LLVM_FALLTHROUGH;
8490     case Builtin::BImemchr:
8491     case Builtin::BI__builtin_memchr:
8492     case Builtin::BI__builtin_char_memchr:
8493       // memchr compares by converting both sides to unsigned char. That's also
8494       // correct for strchr if we get this far (to cope with plain char being
8495       // unsigned in the strchr case).
8496       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
8497       break;
8498 
8499     case Builtin::BIwcschr:
8500     case Builtin::BI__builtin_wcschr:
8501       StopAtNull = true;
8502       LLVM_FALLTHROUGH;
8503     case Builtin::BIwmemchr:
8504     case Builtin::BI__builtin_wmemchr:
8505       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
8506       DesiredVal = Desired.getZExtValue();
8507       break;
8508     }
8509 
8510     for (; MaxLength; --MaxLength) {
8511       APValue Char;
8512       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
8513           !Char.isInt())
8514         return false;
8515       if (Char.getInt().getZExtValue() == DesiredVal)
8516         return true;
8517       if (StopAtNull && !Char.getInt())
8518         break;
8519       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
8520         return false;
8521     }
8522     // Not found: return nullptr.
8523     return ZeroInitialization(E);
8524   }
8525 
8526   case Builtin::BImemcpy:
8527   case Builtin::BImemmove:
8528   case Builtin::BIwmemcpy:
8529   case Builtin::BIwmemmove:
8530     if (Info.getLangOpts().CPlusPlus11)
8531       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8532         << /*isConstexpr*/0 << /*isConstructor*/0
8533         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
8534     else
8535       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
8536     LLVM_FALLTHROUGH;
8537   case Builtin::BI__builtin_memcpy:
8538   case Builtin::BI__builtin_memmove:
8539   case Builtin::BI__builtin_wmemcpy:
8540   case Builtin::BI__builtin_wmemmove: {
8541     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
8542                  BuiltinOp == Builtin::BIwmemmove ||
8543                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
8544                  BuiltinOp == Builtin::BI__builtin_wmemmove;
8545     bool Move = BuiltinOp == Builtin::BImemmove ||
8546                 BuiltinOp == Builtin::BIwmemmove ||
8547                 BuiltinOp == Builtin::BI__builtin_memmove ||
8548                 BuiltinOp == Builtin::BI__builtin_wmemmove;
8549 
8550     // The result of mem* is the first argument.
8551     if (!Visit(E->getArg(0)))
8552       return false;
8553     LValue Dest = Result;
8554 
8555     LValue Src;
8556     if (!EvaluatePointer(E->getArg(1), Src, Info))
8557       return false;
8558 
8559     APSInt N;
8560     if (!EvaluateInteger(E->getArg(2), N, Info))
8561       return false;
8562     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
8563 
8564     // If the size is zero, we treat this as always being a valid no-op.
8565     // (Even if one of the src and dest pointers is null.)
8566     if (!N)
8567       return true;
8568 
8569     // Otherwise, if either of the operands is null, we can't proceed. Don't
8570     // try to determine the type of the copied objects, because there aren't
8571     // any.
8572     if (!Src.Base || !Dest.Base) {
8573       APValue Val;
8574       (!Src.Base ? Src : Dest).moveInto(Val);
8575       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
8576           << Move << WChar << !!Src.Base
8577           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
8578       return false;
8579     }
8580     if (Src.Designator.Invalid || Dest.Designator.Invalid)
8581       return false;
8582 
8583     // We require that Src and Dest are both pointers to arrays of
8584     // trivially-copyable type. (For the wide version, the designator will be
8585     // invalid if the designated object is not a wchar_t.)
8586     QualType T = Dest.Designator.getType(Info.Ctx);
8587     QualType SrcT = Src.Designator.getType(Info.Ctx);
8588     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
8589       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
8590       return false;
8591     }
8592     if (T->isIncompleteType()) {
8593       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
8594       return false;
8595     }
8596     if (!T.isTriviallyCopyableType(Info.Ctx)) {
8597       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
8598       return false;
8599     }
8600 
8601     // Figure out how many T's we're copying.
8602     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
8603     if (!WChar) {
8604       uint64_t Remainder;
8605       llvm::APInt OrigN = N;
8606       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
8607       if (Remainder) {
8608         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
8609             << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
8610             << (unsigned)TSize;
8611         return false;
8612       }
8613     }
8614 
8615     // Check that the copying will remain within the arrays, just so that we
8616     // can give a more meaningful diagnostic. This implicitly also checks that
8617     // N fits into 64 bits.
8618     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
8619     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
8620     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
8621       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
8622           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
8623           << N.toString(10, /*Signed*/false);
8624       return false;
8625     }
8626     uint64_t NElems = N.getZExtValue();
8627     uint64_t NBytes = NElems * TSize;
8628 
8629     // Check for overlap.
8630     int Direction = 1;
8631     if (HasSameBase(Src, Dest)) {
8632       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
8633       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
8634       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
8635         // Dest is inside the source region.
8636         if (!Move) {
8637           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
8638           return false;
8639         }
8640         // For memmove and friends, copy backwards.
8641         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
8642             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
8643           return false;
8644         Direction = -1;
8645       } else if (!Move && SrcOffset >= DestOffset &&
8646                  SrcOffset - DestOffset < NBytes) {
8647         // Src is inside the destination region for memcpy: invalid.
8648         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
8649         return false;
8650       }
8651     }
8652 
8653     while (true) {
8654       APValue Val;
8655       // FIXME: Set WantObjectRepresentation to true if we're copying a
8656       // char-like type?
8657       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
8658           !handleAssignment(Info, E, Dest, T, Val))
8659         return false;
8660       // Do not iterate past the last element; if we're copying backwards, that
8661       // might take us off the start of the array.
8662       if (--NElems == 0)
8663         return true;
8664       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
8665           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
8666         return false;
8667     }
8668   }
8669 
8670   default:
8671     break;
8672   }
8673 
8674   return visitNonBuiltinCallExpr(E);
8675 }
8676 
8677 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
8678                                      APValue &Result, const InitListExpr *ILE,
8679                                      QualType AllocType);
8680 
8681 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
8682   if (!Info.getLangOpts().CPlusPlus2a)
8683     Info.CCEDiag(E, diag::note_constexpr_new);
8684 
8685   // We cannot speculatively evaluate a delete expression.
8686   if (Info.SpeculativeEvaluationDepth)
8687     return false;
8688 
8689   FunctionDecl *OperatorNew = E->getOperatorNew();
8690 
8691   bool IsNothrow = false;
8692   bool IsPlacement = false;
8693   if (OperatorNew->isReservedGlobalPlacementOperator() &&
8694       Info.CurrentCall->isStdFunction() && !E->isArray()) {
8695     // FIXME Support array placement new.
8696     assert(E->getNumPlacementArgs() == 1);
8697     if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
8698       return false;
8699     if (Result.Designator.Invalid)
8700       return false;
8701     IsPlacement = true;
8702   } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
8703     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
8704         << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
8705     return false;
8706   } else if (E->getNumPlacementArgs()) {
8707     // The only new-placement list we support is of the form (std::nothrow).
8708     //
8709     // FIXME: There is no restriction on this, but it's not clear that any
8710     // other form makes any sense. We get here for cases such as:
8711     //
8712     //   new (std::align_val_t{N}) X(int)
8713     //
8714     // (which should presumably be valid only if N is a multiple of
8715     // alignof(int), and in any case can't be deallocated unless N is
8716     // alignof(X) and X has new-extended alignment).
8717     if (E->getNumPlacementArgs() != 1 ||
8718         !E->getPlacementArg(0)->getType()->isNothrowT())
8719       return Error(E, diag::note_constexpr_new_placement);
8720 
8721     LValue Nothrow;
8722     if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
8723       return false;
8724     IsNothrow = true;
8725   }
8726 
8727   const Expr *Init = E->getInitializer();
8728   const InitListExpr *ResizedArrayILE = nullptr;
8729 
8730   QualType AllocType = E->getAllocatedType();
8731   if (Optional<const Expr*> ArraySize = E->getArraySize()) {
8732     const Expr *Stripped = *ArraySize;
8733     for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
8734          Stripped = ICE->getSubExpr())
8735       if (ICE->getCastKind() != CK_NoOp &&
8736           ICE->getCastKind() != CK_IntegralCast)
8737         break;
8738 
8739     llvm::APSInt ArrayBound;
8740     if (!EvaluateInteger(Stripped, ArrayBound, Info))
8741       return false;
8742 
8743     // C++ [expr.new]p9:
8744     //   The expression is erroneous if:
8745     //   -- [...] its value before converting to size_t [or] applying the
8746     //      second standard conversion sequence is less than zero
8747     if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
8748       if (IsNothrow)
8749         return ZeroInitialization(E);
8750 
8751       Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
8752           << ArrayBound << (*ArraySize)->getSourceRange();
8753       return false;
8754     }
8755 
8756     //   -- its value is such that the size of the allocated object would
8757     //      exceed the implementation-defined limit
8758     if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
8759                                                 ArrayBound) >
8760         ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
8761       if (IsNothrow)
8762         return ZeroInitialization(E);
8763 
8764       Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
8765         << ArrayBound << (*ArraySize)->getSourceRange();
8766       return false;
8767     }
8768 
8769     //   -- the new-initializer is a braced-init-list and the number of
8770     //      array elements for which initializers are provided [...]
8771     //      exceeds the number of elements to initialize
8772     if (Init) {
8773       auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
8774       assert(CAT && "unexpected type for array initializer");
8775 
8776       unsigned Bits =
8777           std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
8778       llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits);
8779       llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits);
8780       if (InitBound.ugt(AllocBound)) {
8781         if (IsNothrow)
8782           return ZeroInitialization(E);
8783 
8784         Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
8785             << AllocBound.toString(10, /*Signed=*/false)
8786             << InitBound.toString(10, /*Signed=*/false)
8787             << (*ArraySize)->getSourceRange();
8788         return false;
8789       }
8790 
8791       // If the sizes differ, we must have an initializer list, and we need
8792       // special handling for this case when we initialize.
8793       if (InitBound != AllocBound)
8794         ResizedArrayILE = cast<InitListExpr>(Init);
8795     }
8796 
8797     AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
8798                                               ArrayType::Normal, 0);
8799   } else {
8800     assert(!AllocType->isArrayType() &&
8801            "array allocation with non-array new");
8802   }
8803 
8804   APValue *Val;
8805   if (IsPlacement) {
8806     AccessKinds AK = AK_Construct;
8807     struct FindObjectHandler {
8808       EvalInfo &Info;
8809       const Expr *E;
8810       QualType AllocType;
8811       const AccessKinds AccessKind;
8812       APValue *Value;
8813 
8814       typedef bool result_type;
8815       bool failed() { return false; }
8816       bool found(APValue &Subobj, QualType SubobjType) {
8817         // FIXME: Reject the cases where [basic.life]p8 would not permit the
8818         // old name of the object to be used to name the new object.
8819         if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
8820           Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
8821             SubobjType << AllocType;
8822           return false;
8823         }
8824         Value = &Subobj;
8825         return true;
8826       }
8827       bool found(APSInt &Value, QualType SubobjType) {
8828         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
8829         return false;
8830       }
8831       bool found(APFloat &Value, QualType SubobjType) {
8832         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
8833         return false;
8834       }
8835     } Handler = {Info, E, AllocType, AK, nullptr};
8836 
8837     CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
8838     if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
8839       return false;
8840 
8841     Val = Handler.Value;
8842 
8843     // [basic.life]p1:
8844     //   The lifetime of an object o of type T ends when [...] the storage
8845     //   which the object occupies is [...] reused by an object that is not
8846     //   nested within o (6.6.2).
8847     *Val = APValue();
8848   } else {
8849     // Perform the allocation and obtain a pointer to the resulting object.
8850     Val = Info.createHeapAlloc(E, AllocType, Result);
8851     if (!Val)
8852       return false;
8853   }
8854 
8855   if (ResizedArrayILE) {
8856     if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
8857                                   AllocType))
8858       return false;
8859   } else if (Init) {
8860     if (!EvaluateInPlace(*Val, Info, Result, Init))
8861       return false;
8862   } else {
8863     *Val = getDefaultInitValue(AllocType);
8864   }
8865 
8866   // Array new returns a pointer to the first element, not a pointer to the
8867   // array.
8868   if (auto *AT = AllocType->getAsArrayTypeUnsafe())
8869     Result.addArray(Info, E, cast<ConstantArrayType>(AT));
8870 
8871   return true;
8872 }
8873 //===----------------------------------------------------------------------===//
8874 // Member Pointer Evaluation
8875 //===----------------------------------------------------------------------===//
8876 
8877 namespace {
8878 class MemberPointerExprEvaluator
8879   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
8880   MemberPtr &Result;
8881 
8882   bool Success(const ValueDecl *D) {
8883     Result = MemberPtr(D);
8884     return true;
8885   }
8886 public:
8887 
8888   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
8889     : ExprEvaluatorBaseTy(Info), Result(Result) {}
8890 
8891   bool Success(const APValue &V, const Expr *E) {
8892     Result.setFrom(V);
8893     return true;
8894   }
8895   bool ZeroInitialization(const Expr *E) {
8896     return Success((const ValueDecl*)nullptr);
8897   }
8898 
8899   bool VisitCastExpr(const CastExpr *E);
8900   bool VisitUnaryAddrOf(const UnaryOperator *E);
8901 };
8902 } // end anonymous namespace
8903 
8904 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
8905                                   EvalInfo &Info) {
8906   assert(E->isRValue() && E->getType()->isMemberPointerType());
8907   return MemberPointerExprEvaluator(Info, Result).Visit(E);
8908 }
8909 
8910 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8911   switch (E->getCastKind()) {
8912   default:
8913     return ExprEvaluatorBaseTy::VisitCastExpr(E);
8914 
8915   case CK_NullToMemberPointer:
8916     VisitIgnoredValue(E->getSubExpr());
8917     return ZeroInitialization(E);
8918 
8919   case CK_BaseToDerivedMemberPointer: {
8920     if (!Visit(E->getSubExpr()))
8921       return false;
8922     if (E->path_empty())
8923       return true;
8924     // Base-to-derived member pointer casts store the path in derived-to-base
8925     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
8926     // the wrong end of the derived->base arc, so stagger the path by one class.
8927     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
8928     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
8929          PathI != PathE; ++PathI) {
8930       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
8931       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
8932       if (!Result.castToDerived(Derived))
8933         return Error(E);
8934     }
8935     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
8936     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
8937       return Error(E);
8938     return true;
8939   }
8940 
8941   case CK_DerivedToBaseMemberPointer:
8942     if (!Visit(E->getSubExpr()))
8943       return false;
8944     for (CastExpr::path_const_iterator PathI = E->path_begin(),
8945          PathE = E->path_end(); PathI != PathE; ++PathI) {
8946       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
8947       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
8948       if (!Result.castToBase(Base))
8949         return Error(E);
8950     }
8951     return true;
8952   }
8953 }
8954 
8955 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8956   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
8957   // member can be formed.
8958   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
8959 }
8960 
8961 //===----------------------------------------------------------------------===//
8962 // Record Evaluation
8963 //===----------------------------------------------------------------------===//
8964 
8965 namespace {
8966   class RecordExprEvaluator
8967   : public ExprEvaluatorBase<RecordExprEvaluator> {
8968     const LValue &This;
8969     APValue &Result;
8970   public:
8971 
8972     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
8973       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
8974 
8975     bool Success(const APValue &V, const Expr *E) {
8976       Result = V;
8977       return true;
8978     }
8979     bool ZeroInitialization(const Expr *E) {
8980       return ZeroInitialization(E, E->getType());
8981     }
8982     bool ZeroInitialization(const Expr *E, QualType T);
8983 
8984     bool VisitCallExpr(const CallExpr *E) {
8985       return handleCallExpr(E, Result, &This);
8986     }
8987     bool VisitCastExpr(const CastExpr *E);
8988     bool VisitInitListExpr(const InitListExpr *E);
8989     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
8990       return VisitCXXConstructExpr(E, E->getType());
8991     }
8992     bool VisitLambdaExpr(const LambdaExpr *E);
8993     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
8994     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
8995     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
8996     bool VisitBinCmp(const BinaryOperator *E);
8997   };
8998 }
8999 
9000 /// Perform zero-initialization on an object of non-union class type.
9001 /// C++11 [dcl.init]p5:
9002 ///  To zero-initialize an object or reference of type T means:
9003 ///    [...]
9004 ///    -- if T is a (possibly cv-qualified) non-union class type,
9005 ///       each non-static data member and each base-class subobject is
9006 ///       zero-initialized
9007 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
9008                                           const RecordDecl *RD,
9009                                           const LValue &This, APValue &Result) {
9010   assert(!RD->isUnion() && "Expected non-union class type");
9011   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
9012   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
9013                    std::distance(RD->field_begin(), RD->field_end()));
9014 
9015   if (RD->isInvalidDecl()) return false;
9016   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9017 
9018   if (CD) {
9019     unsigned Index = 0;
9020     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
9021            End = CD->bases_end(); I != End; ++I, ++Index) {
9022       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
9023       LValue Subobject = This;
9024       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
9025         return false;
9026       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
9027                                          Result.getStructBase(Index)))
9028         return false;
9029     }
9030   }
9031 
9032   for (const auto *I : RD->fields()) {
9033     // -- if T is a reference type, no initialization is performed.
9034     if (I->getType()->isReferenceType())
9035       continue;
9036 
9037     LValue Subobject = This;
9038     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
9039       return false;
9040 
9041     ImplicitValueInitExpr VIE(I->getType());
9042     if (!EvaluateInPlace(
9043           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
9044       return false;
9045   }
9046 
9047   return true;
9048 }
9049 
9050 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
9051   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
9052   if (RD->isInvalidDecl()) return false;
9053   if (RD->isUnion()) {
9054     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
9055     // object's first non-static named data member is zero-initialized
9056     RecordDecl::field_iterator I = RD->field_begin();
9057     if (I == RD->field_end()) {
9058       Result = APValue((const FieldDecl*)nullptr);
9059       return true;
9060     }
9061 
9062     LValue Subobject = This;
9063     if (!HandleLValueMember(Info, E, Subobject, *I))
9064       return false;
9065     Result = APValue(*I);
9066     ImplicitValueInitExpr VIE(I->getType());
9067     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
9068   }
9069 
9070   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
9071     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
9072     return false;
9073   }
9074 
9075   return HandleClassZeroInitialization(Info, E, RD, This, Result);
9076 }
9077 
9078 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
9079   switch (E->getCastKind()) {
9080   default:
9081     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9082 
9083   case CK_ConstructorConversion:
9084     return Visit(E->getSubExpr());
9085 
9086   case CK_DerivedToBase:
9087   case CK_UncheckedDerivedToBase: {
9088     APValue DerivedObject;
9089     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
9090       return false;
9091     if (!DerivedObject.isStruct())
9092       return Error(E->getSubExpr());
9093 
9094     // Derived-to-base rvalue conversion: just slice off the derived part.
9095     APValue *Value = &DerivedObject;
9096     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
9097     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9098          PathE = E->path_end(); PathI != PathE; ++PathI) {
9099       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
9100       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9101       Value = &Value->getStructBase(getBaseIndex(RD, Base));
9102       RD = Base;
9103     }
9104     Result = *Value;
9105     return true;
9106   }
9107   }
9108 }
9109 
9110 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9111   if (E->isTransparent())
9112     return Visit(E->getInit(0));
9113 
9114   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
9115   if (RD->isInvalidDecl()) return false;
9116   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9117   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
9118 
9119   EvalInfo::EvaluatingConstructorRAII EvalObj(
9120       Info,
9121       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
9122       CXXRD && CXXRD->getNumBases());
9123 
9124   if (RD->isUnion()) {
9125     const FieldDecl *Field = E->getInitializedFieldInUnion();
9126     Result = APValue(Field);
9127     if (!Field)
9128       return true;
9129 
9130     // If the initializer list for a union does not contain any elements, the
9131     // first element of the union is value-initialized.
9132     // FIXME: The element should be initialized from an initializer list.
9133     //        Is this difference ever observable for initializer lists which
9134     //        we don't build?
9135     ImplicitValueInitExpr VIE(Field->getType());
9136     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
9137 
9138     LValue Subobject = This;
9139     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
9140       return false;
9141 
9142     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9143     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9144                                   isa<CXXDefaultInitExpr>(InitExpr));
9145 
9146     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
9147   }
9148 
9149   if (!Result.hasValue())
9150     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
9151                      std::distance(RD->field_begin(), RD->field_end()));
9152   unsigned ElementNo = 0;
9153   bool Success = true;
9154 
9155   // Initialize base classes.
9156   if (CXXRD && CXXRD->getNumBases()) {
9157     for (const auto &Base : CXXRD->bases()) {
9158       assert(ElementNo < E->getNumInits() && "missing init for base class");
9159       const Expr *Init = E->getInit(ElementNo);
9160 
9161       LValue Subobject = This;
9162       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
9163         return false;
9164 
9165       APValue &FieldVal = Result.getStructBase(ElementNo);
9166       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
9167         if (!Info.noteFailure())
9168           return false;
9169         Success = false;
9170       }
9171       ++ElementNo;
9172     }
9173 
9174     EvalObj.finishedConstructingBases();
9175   }
9176 
9177   // Initialize members.
9178   for (const auto *Field : RD->fields()) {
9179     // Anonymous bit-fields are not considered members of the class for
9180     // purposes of aggregate initialization.
9181     if (Field->isUnnamedBitfield())
9182       continue;
9183 
9184     LValue Subobject = This;
9185 
9186     bool HaveInit = ElementNo < E->getNumInits();
9187 
9188     // FIXME: Diagnostics here should point to the end of the initializer
9189     // list, not the start.
9190     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
9191                             Subobject, Field, &Layout))
9192       return false;
9193 
9194     // Perform an implicit value-initialization for members beyond the end of
9195     // the initializer list.
9196     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
9197     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
9198 
9199     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9200     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9201                                   isa<CXXDefaultInitExpr>(Init));
9202 
9203     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9204     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
9205         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
9206                                                        FieldVal, Field))) {
9207       if (!Info.noteFailure())
9208         return false;
9209       Success = false;
9210     }
9211   }
9212 
9213   EvalObj.finishedConstructingFields();
9214 
9215   return Success;
9216 }
9217 
9218 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
9219                                                 QualType T) {
9220   // Note that E's type is not necessarily the type of our class here; we might
9221   // be initializing an array element instead.
9222   const CXXConstructorDecl *FD = E->getConstructor();
9223   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
9224 
9225   bool ZeroInit = E->requiresZeroInitialization();
9226   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
9227     // If we've already performed zero-initialization, we're already done.
9228     if (Result.hasValue())
9229       return true;
9230 
9231     if (ZeroInit)
9232       return ZeroInitialization(E, T);
9233 
9234     Result = getDefaultInitValue(T);
9235     return true;
9236   }
9237 
9238   const FunctionDecl *Definition = nullptr;
9239   auto Body = FD->getBody(Definition);
9240 
9241   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9242     return false;
9243 
9244   // Avoid materializing a temporary for an elidable copy/move constructor.
9245   if (E->isElidable() && !ZeroInit)
9246     if (const MaterializeTemporaryExpr *ME
9247           = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
9248       return Visit(ME->getSubExpr());
9249 
9250   if (ZeroInit && !ZeroInitialization(E, T))
9251     return false;
9252 
9253   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
9254   return HandleConstructorCall(E, This, Args,
9255                                cast<CXXConstructorDecl>(Definition), Info,
9256                                Result);
9257 }
9258 
9259 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
9260     const CXXInheritedCtorInitExpr *E) {
9261   if (!Info.CurrentCall) {
9262     assert(Info.checkingPotentialConstantExpression());
9263     return false;
9264   }
9265 
9266   const CXXConstructorDecl *FD = E->getConstructor();
9267   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
9268     return false;
9269 
9270   const FunctionDecl *Definition = nullptr;
9271   auto Body = FD->getBody(Definition);
9272 
9273   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9274     return false;
9275 
9276   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
9277                                cast<CXXConstructorDecl>(Definition), Info,
9278                                Result);
9279 }
9280 
9281 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
9282     const CXXStdInitializerListExpr *E) {
9283   const ConstantArrayType *ArrayType =
9284       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
9285 
9286   LValue Array;
9287   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
9288     return false;
9289 
9290   // Get a pointer to the first element of the array.
9291   Array.addArray(Info, E, ArrayType);
9292 
9293   // FIXME: Perform the checks on the field types in SemaInit.
9294   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
9295   RecordDecl::field_iterator Field = Record->field_begin();
9296   if (Field == Record->field_end())
9297     return Error(E);
9298 
9299   // Start pointer.
9300   if (!Field->getType()->isPointerType() ||
9301       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
9302                             ArrayType->getElementType()))
9303     return Error(E);
9304 
9305   // FIXME: What if the initializer_list type has base classes, etc?
9306   Result = APValue(APValue::UninitStruct(), 0, 2);
9307   Array.moveInto(Result.getStructField(0));
9308 
9309   if (++Field == Record->field_end())
9310     return Error(E);
9311 
9312   if (Field->getType()->isPointerType() &&
9313       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
9314                            ArrayType->getElementType())) {
9315     // End pointer.
9316     if (!HandleLValueArrayAdjustment(Info, E, Array,
9317                                      ArrayType->getElementType(),
9318                                      ArrayType->getSize().getZExtValue()))
9319       return false;
9320     Array.moveInto(Result.getStructField(1));
9321   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
9322     // Length.
9323     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
9324   else
9325     return Error(E);
9326 
9327   if (++Field != Record->field_end())
9328     return Error(E);
9329 
9330   return true;
9331 }
9332 
9333 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
9334   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
9335   if (ClosureClass->isInvalidDecl())
9336     return false;
9337 
9338   const size_t NumFields =
9339       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
9340 
9341   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
9342                                             E->capture_init_end()) &&
9343          "The number of lambda capture initializers should equal the number of "
9344          "fields within the closure type");
9345 
9346   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
9347   // Iterate through all the lambda's closure object's fields and initialize
9348   // them.
9349   auto *CaptureInitIt = E->capture_init_begin();
9350   const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
9351   bool Success = true;
9352   for (const auto *Field : ClosureClass->fields()) {
9353     assert(CaptureInitIt != E->capture_init_end());
9354     // Get the initializer for this field
9355     Expr *const CurFieldInit = *CaptureInitIt++;
9356 
9357     // If there is no initializer, either this is a VLA or an error has
9358     // occurred.
9359     if (!CurFieldInit)
9360       return Error(E);
9361 
9362     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9363     if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
9364       if (!Info.keepEvaluatingAfterFailure())
9365         return false;
9366       Success = false;
9367     }
9368     ++CaptureIt;
9369   }
9370   return Success;
9371 }
9372 
9373 static bool EvaluateRecord(const Expr *E, const LValue &This,
9374                            APValue &Result, EvalInfo &Info) {
9375   assert(E->isRValue() && E->getType()->isRecordType() &&
9376          "can't evaluate expression as a record rvalue");
9377   return RecordExprEvaluator(Info, This, Result).Visit(E);
9378 }
9379 
9380 //===----------------------------------------------------------------------===//
9381 // Temporary Evaluation
9382 //
9383 // Temporaries are represented in the AST as rvalues, but generally behave like
9384 // lvalues. The full-object of which the temporary is a subobject is implicitly
9385 // materialized so that a reference can bind to it.
9386 //===----------------------------------------------------------------------===//
9387 namespace {
9388 class TemporaryExprEvaluator
9389   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
9390 public:
9391   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
9392     LValueExprEvaluatorBaseTy(Info, Result, false) {}
9393 
9394   /// Visit an expression which constructs the value of this temporary.
9395   bool VisitConstructExpr(const Expr *E) {
9396     APValue &Value =
9397         Info.CurrentCall->createTemporary(E, E->getType(), false, Result);
9398     return EvaluateInPlace(Value, Info, Result, E);
9399   }
9400 
9401   bool VisitCastExpr(const CastExpr *E) {
9402     switch (E->getCastKind()) {
9403     default:
9404       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
9405 
9406     case CK_ConstructorConversion:
9407       return VisitConstructExpr(E->getSubExpr());
9408     }
9409   }
9410   bool VisitInitListExpr(const InitListExpr *E) {
9411     return VisitConstructExpr(E);
9412   }
9413   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9414     return VisitConstructExpr(E);
9415   }
9416   bool VisitCallExpr(const CallExpr *E) {
9417     return VisitConstructExpr(E);
9418   }
9419   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
9420     return VisitConstructExpr(E);
9421   }
9422   bool VisitLambdaExpr(const LambdaExpr *E) {
9423     return VisitConstructExpr(E);
9424   }
9425 };
9426 } // end anonymous namespace
9427 
9428 /// Evaluate an expression of record type as a temporary.
9429 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
9430   assert(E->isRValue() && E->getType()->isRecordType());
9431   return TemporaryExprEvaluator(Info, Result).Visit(E);
9432 }
9433 
9434 //===----------------------------------------------------------------------===//
9435 // Vector Evaluation
9436 //===----------------------------------------------------------------------===//
9437 
9438 namespace {
9439   class VectorExprEvaluator
9440   : public ExprEvaluatorBase<VectorExprEvaluator> {
9441     APValue &Result;
9442   public:
9443 
9444     VectorExprEvaluator(EvalInfo &info, APValue &Result)
9445       : ExprEvaluatorBaseTy(info), Result(Result) {}
9446 
9447     bool Success(ArrayRef<APValue> V, const Expr *E) {
9448       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
9449       // FIXME: remove this APValue copy.
9450       Result = APValue(V.data(), V.size());
9451       return true;
9452     }
9453     bool Success(const APValue &V, const Expr *E) {
9454       assert(V.isVector());
9455       Result = V;
9456       return true;
9457     }
9458     bool ZeroInitialization(const Expr *E);
9459 
9460     bool VisitUnaryReal(const UnaryOperator *E)
9461       { return Visit(E->getSubExpr()); }
9462     bool VisitCastExpr(const CastExpr* E);
9463     bool VisitInitListExpr(const InitListExpr *E);
9464     bool VisitUnaryImag(const UnaryOperator *E);
9465     // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
9466     //                 binary comparisons, binary and/or/xor,
9467     //                 conditional operator (for GNU conditional select),
9468     //                 shufflevector, ExtVectorElementExpr
9469   };
9470 } // end anonymous namespace
9471 
9472 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
9473   assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
9474   return VectorExprEvaluator(Info, Result).Visit(E);
9475 }
9476 
9477 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
9478   const VectorType *VTy = E->getType()->castAs<VectorType>();
9479   unsigned NElts = VTy->getNumElements();
9480 
9481   const Expr *SE = E->getSubExpr();
9482   QualType SETy = SE->getType();
9483 
9484   switch (E->getCastKind()) {
9485   case CK_VectorSplat: {
9486     APValue Val = APValue();
9487     if (SETy->isIntegerType()) {
9488       APSInt IntResult;
9489       if (!EvaluateInteger(SE, IntResult, Info))
9490         return false;
9491       Val = APValue(std::move(IntResult));
9492     } else if (SETy->isRealFloatingType()) {
9493       APFloat FloatResult(0.0);
9494       if (!EvaluateFloat(SE, FloatResult, Info))
9495         return false;
9496       Val = APValue(std::move(FloatResult));
9497     } else {
9498       return Error(E);
9499     }
9500 
9501     // Splat and create vector APValue.
9502     SmallVector<APValue, 4> Elts(NElts, Val);
9503     return Success(Elts, E);
9504   }
9505   case CK_BitCast: {
9506     // Evaluate the operand into an APInt we can extract from.
9507     llvm::APInt SValInt;
9508     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
9509       return false;
9510     // Extract the elements
9511     QualType EltTy = VTy->getElementType();
9512     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
9513     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
9514     SmallVector<APValue, 4> Elts;
9515     if (EltTy->isRealFloatingType()) {
9516       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
9517       unsigned FloatEltSize = EltSize;
9518       if (&Sem == &APFloat::x87DoubleExtended())
9519         FloatEltSize = 80;
9520       for (unsigned i = 0; i < NElts; i++) {
9521         llvm::APInt Elt;
9522         if (BigEndian)
9523           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
9524         else
9525           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
9526         Elts.push_back(APValue(APFloat(Sem, Elt)));
9527       }
9528     } else if (EltTy->isIntegerType()) {
9529       for (unsigned i = 0; i < NElts; i++) {
9530         llvm::APInt Elt;
9531         if (BigEndian)
9532           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
9533         else
9534           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
9535         Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
9536       }
9537     } else {
9538       return Error(E);
9539     }
9540     return Success(Elts, E);
9541   }
9542   default:
9543     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9544   }
9545 }
9546 
9547 bool
9548 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9549   const VectorType *VT = E->getType()->castAs<VectorType>();
9550   unsigned NumInits = E->getNumInits();
9551   unsigned NumElements = VT->getNumElements();
9552 
9553   QualType EltTy = VT->getElementType();
9554   SmallVector<APValue, 4> Elements;
9555 
9556   // The number of initializers can be less than the number of
9557   // vector elements. For OpenCL, this can be due to nested vector
9558   // initialization. For GCC compatibility, missing trailing elements
9559   // should be initialized with zeroes.
9560   unsigned CountInits = 0, CountElts = 0;
9561   while (CountElts < NumElements) {
9562     // Handle nested vector initialization.
9563     if (CountInits < NumInits
9564         && E->getInit(CountInits)->getType()->isVectorType()) {
9565       APValue v;
9566       if (!EvaluateVector(E->getInit(CountInits), v, Info))
9567         return Error(E);
9568       unsigned vlen = v.getVectorLength();
9569       for (unsigned j = 0; j < vlen; j++)
9570         Elements.push_back(v.getVectorElt(j));
9571       CountElts += vlen;
9572     } else if (EltTy->isIntegerType()) {
9573       llvm::APSInt sInt(32);
9574       if (CountInits < NumInits) {
9575         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
9576           return false;
9577       } else // trailing integer zero.
9578         sInt = Info.Ctx.MakeIntValue(0, EltTy);
9579       Elements.push_back(APValue(sInt));
9580       CountElts++;
9581     } else {
9582       llvm::APFloat f(0.0);
9583       if (CountInits < NumInits) {
9584         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
9585           return false;
9586       } else // trailing float zero.
9587         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
9588       Elements.push_back(APValue(f));
9589       CountElts++;
9590     }
9591     CountInits++;
9592   }
9593   return Success(Elements, E);
9594 }
9595 
9596 bool
9597 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
9598   const auto *VT = E->getType()->castAs<VectorType>();
9599   QualType EltTy = VT->getElementType();
9600   APValue ZeroElement;
9601   if (EltTy->isIntegerType())
9602     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
9603   else
9604     ZeroElement =
9605         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
9606 
9607   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
9608   return Success(Elements, E);
9609 }
9610 
9611 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9612   VisitIgnoredValue(E->getSubExpr());
9613   return ZeroInitialization(E);
9614 }
9615 
9616 //===----------------------------------------------------------------------===//
9617 // Array Evaluation
9618 //===----------------------------------------------------------------------===//
9619 
9620 namespace {
9621   class ArrayExprEvaluator
9622   : public ExprEvaluatorBase<ArrayExprEvaluator> {
9623     const LValue &This;
9624     APValue &Result;
9625   public:
9626 
9627     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
9628       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
9629 
9630     bool Success(const APValue &V, const Expr *E) {
9631       assert(V.isArray() && "expected array");
9632       Result = V;
9633       return true;
9634     }
9635 
9636     bool ZeroInitialization(const Expr *E) {
9637       const ConstantArrayType *CAT =
9638           Info.Ctx.getAsConstantArrayType(E->getType());
9639       if (!CAT)
9640         return Error(E);
9641 
9642       Result = APValue(APValue::UninitArray(), 0,
9643                        CAT->getSize().getZExtValue());
9644       if (!Result.hasArrayFiller()) return true;
9645 
9646       // Zero-initialize all elements.
9647       LValue Subobject = This;
9648       Subobject.addArray(Info, E, CAT);
9649       ImplicitValueInitExpr VIE(CAT->getElementType());
9650       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
9651     }
9652 
9653     bool VisitCallExpr(const CallExpr *E) {
9654       return handleCallExpr(E, Result, &This);
9655     }
9656     bool VisitInitListExpr(const InitListExpr *E,
9657                            QualType AllocType = QualType());
9658     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
9659     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
9660     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
9661                                const LValue &Subobject,
9662                                APValue *Value, QualType Type);
9663     bool VisitStringLiteral(const StringLiteral *E,
9664                             QualType AllocType = QualType()) {
9665       expandStringLiteral(Info, E, Result, AllocType);
9666       return true;
9667     }
9668   };
9669 } // end anonymous namespace
9670 
9671 static bool EvaluateArray(const Expr *E, const LValue &This,
9672                           APValue &Result, EvalInfo &Info) {
9673   assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
9674   return ArrayExprEvaluator(Info, This, Result).Visit(E);
9675 }
9676 
9677 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9678                                      APValue &Result, const InitListExpr *ILE,
9679                                      QualType AllocType) {
9680   assert(ILE->isRValue() && ILE->getType()->isArrayType() &&
9681          "not an array rvalue");
9682   return ArrayExprEvaluator(Info, This, Result)
9683       .VisitInitListExpr(ILE, AllocType);
9684 }
9685 
9686 // Return true iff the given array filler may depend on the element index.
9687 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
9688   // For now, just whitelist non-class value-initialization and initialization
9689   // lists comprised of them.
9690   if (isa<ImplicitValueInitExpr>(FillerExpr))
9691     return false;
9692   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
9693     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
9694       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
9695         return true;
9696     }
9697     return false;
9698   }
9699   return true;
9700 }
9701 
9702 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
9703                                            QualType AllocType) {
9704   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
9705       AllocType.isNull() ? E->getType() : AllocType);
9706   if (!CAT)
9707     return Error(E);
9708 
9709   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
9710   // an appropriately-typed string literal enclosed in braces.
9711   if (E->isStringLiteralInit()) {
9712     auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens());
9713     // FIXME: Support ObjCEncodeExpr here once we support it in
9714     // ArrayExprEvaluator generally.
9715     if (!SL)
9716       return Error(E);
9717     return VisitStringLiteral(SL, AllocType);
9718   }
9719 
9720   bool Success = true;
9721 
9722   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
9723          "zero-initialized array shouldn't have any initialized elts");
9724   APValue Filler;
9725   if (Result.isArray() && Result.hasArrayFiller())
9726     Filler = Result.getArrayFiller();
9727 
9728   unsigned NumEltsToInit = E->getNumInits();
9729   unsigned NumElts = CAT->getSize().getZExtValue();
9730   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
9731 
9732   // If the initializer might depend on the array index, run it for each
9733   // array element.
9734   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
9735     NumEltsToInit = NumElts;
9736 
9737   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
9738                           << NumEltsToInit << ".\n");
9739 
9740   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
9741 
9742   // If the array was previously zero-initialized, preserve the
9743   // zero-initialized values.
9744   if (Filler.hasValue()) {
9745     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
9746       Result.getArrayInitializedElt(I) = Filler;
9747     if (Result.hasArrayFiller())
9748       Result.getArrayFiller() = Filler;
9749   }
9750 
9751   LValue Subobject = This;
9752   Subobject.addArray(Info, E, CAT);
9753   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
9754     const Expr *Init =
9755         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
9756     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
9757                          Info, Subobject, Init) ||
9758         !HandleLValueArrayAdjustment(Info, Init, Subobject,
9759                                      CAT->getElementType(), 1)) {
9760       if (!Info.noteFailure())
9761         return false;
9762       Success = false;
9763     }
9764   }
9765 
9766   if (!Result.hasArrayFiller())
9767     return Success;
9768 
9769   // If we get here, we have a trivial filler, which we can just evaluate
9770   // once and splat over the rest of the array elements.
9771   assert(FillerExpr && "no array filler for incomplete init list");
9772   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
9773                          FillerExpr) && Success;
9774 }
9775 
9776 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
9777   LValue CommonLV;
9778   if (E->getCommonExpr() &&
9779       !Evaluate(Info.CurrentCall->createTemporary(
9780                     E->getCommonExpr(),
9781                     getStorageType(Info.Ctx, E->getCommonExpr()), false,
9782                     CommonLV),
9783                 Info, E->getCommonExpr()->getSourceExpr()))
9784     return false;
9785 
9786   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
9787 
9788   uint64_t Elements = CAT->getSize().getZExtValue();
9789   Result = APValue(APValue::UninitArray(), Elements, Elements);
9790 
9791   LValue Subobject = This;
9792   Subobject.addArray(Info, E, CAT);
9793 
9794   bool Success = true;
9795   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
9796     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
9797                          Info, Subobject, E->getSubExpr()) ||
9798         !HandleLValueArrayAdjustment(Info, E, Subobject,
9799                                      CAT->getElementType(), 1)) {
9800       if (!Info.noteFailure())
9801         return false;
9802       Success = false;
9803     }
9804   }
9805 
9806   return Success;
9807 }
9808 
9809 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
9810   return VisitCXXConstructExpr(E, This, &Result, E->getType());
9811 }
9812 
9813 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
9814                                                const LValue &Subobject,
9815                                                APValue *Value,
9816                                                QualType Type) {
9817   bool HadZeroInit = Value->hasValue();
9818 
9819   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
9820     unsigned N = CAT->getSize().getZExtValue();
9821 
9822     // Preserve the array filler if we had prior zero-initialization.
9823     APValue Filler =
9824       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
9825                                              : APValue();
9826 
9827     *Value = APValue(APValue::UninitArray(), N, N);
9828 
9829     if (HadZeroInit)
9830       for (unsigned I = 0; I != N; ++I)
9831         Value->getArrayInitializedElt(I) = Filler;
9832 
9833     // Initialize the elements.
9834     LValue ArrayElt = Subobject;
9835     ArrayElt.addArray(Info, E, CAT);
9836     for (unsigned I = 0; I != N; ++I)
9837       if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
9838                                  CAT->getElementType()) ||
9839           !HandleLValueArrayAdjustment(Info, E, ArrayElt,
9840                                        CAT->getElementType(), 1))
9841         return false;
9842 
9843     return true;
9844   }
9845 
9846   if (!Type->isRecordType())
9847     return Error(E);
9848 
9849   return RecordExprEvaluator(Info, Subobject, *Value)
9850              .VisitCXXConstructExpr(E, Type);
9851 }
9852 
9853 //===----------------------------------------------------------------------===//
9854 // Integer Evaluation
9855 //
9856 // As a GNU extension, we support casting pointers to sufficiently-wide integer
9857 // types and back in constant folding. Integer values are thus represented
9858 // either as an integer-valued APValue, or as an lvalue-valued APValue.
9859 //===----------------------------------------------------------------------===//
9860 
9861 namespace {
9862 class IntExprEvaluator
9863         : public ExprEvaluatorBase<IntExprEvaluator> {
9864   APValue &Result;
9865 public:
9866   IntExprEvaluator(EvalInfo &info, APValue &result)
9867       : ExprEvaluatorBaseTy(info), Result(result) {}
9868 
9869   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
9870     assert(E->getType()->isIntegralOrEnumerationType() &&
9871            "Invalid evaluation result.");
9872     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
9873            "Invalid evaluation result.");
9874     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
9875            "Invalid evaluation result.");
9876     Result = APValue(SI);
9877     return true;
9878   }
9879   bool Success(const llvm::APSInt &SI, const Expr *E) {
9880     return Success(SI, E, Result);
9881   }
9882 
9883   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
9884     assert(E->getType()->isIntegralOrEnumerationType() &&
9885            "Invalid evaluation result.");
9886     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
9887            "Invalid evaluation result.");
9888     Result = APValue(APSInt(I));
9889     Result.getInt().setIsUnsigned(
9890                             E->getType()->isUnsignedIntegerOrEnumerationType());
9891     return true;
9892   }
9893   bool Success(const llvm::APInt &I, const Expr *E) {
9894     return Success(I, E, Result);
9895   }
9896 
9897   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
9898     assert(E->getType()->isIntegralOrEnumerationType() &&
9899            "Invalid evaluation result.");
9900     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
9901     return true;
9902   }
9903   bool Success(uint64_t Value, const Expr *E) {
9904     return Success(Value, E, Result);
9905   }
9906 
9907   bool Success(CharUnits Size, const Expr *E) {
9908     return Success(Size.getQuantity(), E);
9909   }
9910 
9911   bool Success(const APValue &V, const Expr *E) {
9912     if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
9913       Result = V;
9914       return true;
9915     }
9916     return Success(V.getInt(), E);
9917   }
9918 
9919   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
9920 
9921   //===--------------------------------------------------------------------===//
9922   //                            Visitor Methods
9923   //===--------------------------------------------------------------------===//
9924 
9925   bool VisitConstantExpr(const ConstantExpr *E);
9926 
9927   bool VisitIntegerLiteral(const IntegerLiteral *E) {
9928     return Success(E->getValue(), E);
9929   }
9930   bool VisitCharacterLiteral(const CharacterLiteral *E) {
9931     return Success(E->getValue(), E);
9932   }
9933 
9934   bool CheckReferencedDecl(const Expr *E, const Decl *D);
9935   bool VisitDeclRefExpr(const DeclRefExpr *E) {
9936     if (CheckReferencedDecl(E, E->getDecl()))
9937       return true;
9938 
9939     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
9940   }
9941   bool VisitMemberExpr(const MemberExpr *E) {
9942     if (CheckReferencedDecl(E, E->getMemberDecl())) {
9943       VisitIgnoredBaseExpression(E->getBase());
9944       return true;
9945     }
9946 
9947     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
9948   }
9949 
9950   bool VisitCallExpr(const CallExpr *E);
9951   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
9952   bool VisitBinaryOperator(const BinaryOperator *E);
9953   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
9954   bool VisitUnaryOperator(const UnaryOperator *E);
9955 
9956   bool VisitCastExpr(const CastExpr* E);
9957   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
9958 
9959   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
9960     return Success(E->getValue(), E);
9961   }
9962 
9963   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
9964     return Success(E->getValue(), E);
9965   }
9966 
9967   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
9968     if (Info.ArrayInitIndex == uint64_t(-1)) {
9969       // We were asked to evaluate this subexpression independent of the
9970       // enclosing ArrayInitLoopExpr. We can't do that.
9971       Info.FFDiag(E);
9972       return false;
9973     }
9974     return Success(Info.ArrayInitIndex, E);
9975   }
9976 
9977   // Note, GNU defines __null as an integer, not a pointer.
9978   bool VisitGNUNullExpr(const GNUNullExpr *E) {
9979     return ZeroInitialization(E);
9980   }
9981 
9982   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
9983     return Success(E->getValue(), E);
9984   }
9985 
9986   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
9987     return Success(E->getValue(), E);
9988   }
9989 
9990   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
9991     return Success(E->getValue(), E);
9992   }
9993 
9994   bool VisitUnaryReal(const UnaryOperator *E);
9995   bool VisitUnaryImag(const UnaryOperator *E);
9996 
9997   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
9998   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
9999   bool VisitSourceLocExpr(const SourceLocExpr *E);
10000   bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
10001   bool VisitRequiresExpr(const RequiresExpr *E);
10002   // FIXME: Missing: array subscript of vector, member of vector
10003 };
10004 
10005 class FixedPointExprEvaluator
10006     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
10007   APValue &Result;
10008 
10009  public:
10010   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
10011       : ExprEvaluatorBaseTy(info), Result(result) {}
10012 
10013   bool Success(const llvm::APInt &I, const Expr *E) {
10014     return Success(
10015         APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10016   }
10017 
10018   bool Success(uint64_t Value, const Expr *E) {
10019     return Success(
10020         APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10021   }
10022 
10023   bool Success(const APValue &V, const Expr *E) {
10024     return Success(V.getFixedPoint(), E);
10025   }
10026 
10027   bool Success(const APFixedPoint &V, const Expr *E) {
10028     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
10029     assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10030            "Invalid evaluation result.");
10031     Result = APValue(V);
10032     return true;
10033   }
10034 
10035   //===--------------------------------------------------------------------===//
10036   //                            Visitor Methods
10037   //===--------------------------------------------------------------------===//
10038 
10039   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
10040     return Success(E->getValue(), E);
10041   }
10042 
10043   bool VisitCastExpr(const CastExpr *E);
10044   bool VisitUnaryOperator(const UnaryOperator *E);
10045   bool VisitBinaryOperator(const BinaryOperator *E);
10046 };
10047 } // end anonymous namespace
10048 
10049 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
10050 /// produce either the integer value or a pointer.
10051 ///
10052 /// GCC has a heinous extension which folds casts between pointer types and
10053 /// pointer-sized integral types. We support this by allowing the evaluation of
10054 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
10055 /// Some simple arithmetic on such values is supported (they are treated much
10056 /// like char*).
10057 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
10058                                     EvalInfo &Info) {
10059   assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
10060   return IntExprEvaluator(Info, Result).Visit(E);
10061 }
10062 
10063 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
10064   APValue Val;
10065   if (!EvaluateIntegerOrLValue(E, Val, Info))
10066     return false;
10067   if (!Val.isInt()) {
10068     // FIXME: It would be better to produce the diagnostic for casting
10069     //        a pointer to an integer.
10070     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10071     return false;
10072   }
10073   Result = Val.getInt();
10074   return true;
10075 }
10076 
10077 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
10078   APValue Evaluated = E->EvaluateInContext(
10079       Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
10080   return Success(Evaluated, E);
10081 }
10082 
10083 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
10084                                EvalInfo &Info) {
10085   if (E->getType()->isFixedPointType()) {
10086     APValue Val;
10087     if (!FixedPointExprEvaluator(Info, Val).Visit(E))
10088       return false;
10089     if (!Val.isFixedPoint())
10090       return false;
10091 
10092     Result = Val.getFixedPoint();
10093     return true;
10094   }
10095   return false;
10096 }
10097 
10098 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
10099                                         EvalInfo &Info) {
10100   if (E->getType()->isIntegerType()) {
10101     auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
10102     APSInt Val;
10103     if (!EvaluateInteger(E, Val, Info))
10104       return false;
10105     Result = APFixedPoint(Val, FXSema);
10106     return true;
10107   } else if (E->getType()->isFixedPointType()) {
10108     return EvaluateFixedPoint(E, Result, Info);
10109   }
10110   return false;
10111 }
10112 
10113 /// Check whether the given declaration can be directly converted to an integral
10114 /// rvalue. If not, no diagnostic is produced; there are other things we can
10115 /// try.
10116 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
10117   // Enums are integer constant exprs.
10118   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
10119     // Check for signedness/width mismatches between E type and ECD value.
10120     bool SameSign = (ECD->getInitVal().isSigned()
10121                      == E->getType()->isSignedIntegerOrEnumerationType());
10122     bool SameWidth = (ECD->getInitVal().getBitWidth()
10123                       == Info.Ctx.getIntWidth(E->getType()));
10124     if (SameSign && SameWidth)
10125       return Success(ECD->getInitVal(), E);
10126     else {
10127       // Get rid of mismatch (otherwise Success assertions will fail)
10128       // by computing a new value matching the type of E.
10129       llvm::APSInt Val = ECD->getInitVal();
10130       if (!SameSign)
10131         Val.setIsSigned(!ECD->getInitVal().isSigned());
10132       if (!SameWidth)
10133         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
10134       return Success(Val, E);
10135     }
10136   }
10137   return false;
10138 }
10139 
10140 /// Values returned by __builtin_classify_type, chosen to match the values
10141 /// produced by GCC's builtin.
10142 enum class GCCTypeClass {
10143   None = -1,
10144   Void = 0,
10145   Integer = 1,
10146   // GCC reserves 2 for character types, but instead classifies them as
10147   // integers.
10148   Enum = 3,
10149   Bool = 4,
10150   Pointer = 5,
10151   // GCC reserves 6 for references, but appears to never use it (because
10152   // expressions never have reference type, presumably).
10153   PointerToDataMember = 7,
10154   RealFloat = 8,
10155   Complex = 9,
10156   // GCC reserves 10 for functions, but does not use it since GCC version 6 due
10157   // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
10158   // GCC claims to reserve 11 for pointers to member functions, but *actually*
10159   // uses 12 for that purpose, same as for a class or struct. Maybe it
10160   // internally implements a pointer to member as a struct?  Who knows.
10161   PointerToMemberFunction = 12, // Not a bug, see above.
10162   ClassOrStruct = 12,
10163   Union = 13,
10164   // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
10165   // decay to pointer. (Prior to version 6 it was only used in C++ mode).
10166   // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
10167   // literals.
10168 };
10169 
10170 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
10171 /// as GCC.
10172 static GCCTypeClass
10173 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
10174   assert(!T->isDependentType() && "unexpected dependent type");
10175 
10176   QualType CanTy = T.getCanonicalType();
10177   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
10178 
10179   switch (CanTy->getTypeClass()) {
10180 #define TYPE(ID, BASE)
10181 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
10182 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
10183 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
10184 #include "clang/AST/TypeNodes.inc"
10185   case Type::Auto:
10186   case Type::DeducedTemplateSpecialization:
10187       llvm_unreachable("unexpected non-canonical or dependent type");
10188 
10189   case Type::Builtin:
10190     switch (BT->getKind()) {
10191 #define BUILTIN_TYPE(ID, SINGLETON_ID)
10192 #define SIGNED_TYPE(ID, SINGLETON_ID) \
10193     case BuiltinType::ID: return GCCTypeClass::Integer;
10194 #define FLOATING_TYPE(ID, SINGLETON_ID) \
10195     case BuiltinType::ID: return GCCTypeClass::RealFloat;
10196 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
10197     case BuiltinType::ID: break;
10198 #include "clang/AST/BuiltinTypes.def"
10199     case BuiltinType::Void:
10200       return GCCTypeClass::Void;
10201 
10202     case BuiltinType::Bool:
10203       return GCCTypeClass::Bool;
10204 
10205     case BuiltinType::Char_U:
10206     case BuiltinType::UChar:
10207     case BuiltinType::WChar_U:
10208     case BuiltinType::Char8:
10209     case BuiltinType::Char16:
10210     case BuiltinType::Char32:
10211     case BuiltinType::UShort:
10212     case BuiltinType::UInt:
10213     case BuiltinType::ULong:
10214     case BuiltinType::ULongLong:
10215     case BuiltinType::UInt128:
10216       return GCCTypeClass::Integer;
10217 
10218     case BuiltinType::UShortAccum:
10219     case BuiltinType::UAccum:
10220     case BuiltinType::ULongAccum:
10221     case BuiltinType::UShortFract:
10222     case BuiltinType::UFract:
10223     case BuiltinType::ULongFract:
10224     case BuiltinType::SatUShortAccum:
10225     case BuiltinType::SatUAccum:
10226     case BuiltinType::SatULongAccum:
10227     case BuiltinType::SatUShortFract:
10228     case BuiltinType::SatUFract:
10229     case BuiltinType::SatULongFract:
10230       return GCCTypeClass::None;
10231 
10232     case BuiltinType::NullPtr:
10233 
10234     case BuiltinType::ObjCId:
10235     case BuiltinType::ObjCClass:
10236     case BuiltinType::ObjCSel:
10237 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
10238     case BuiltinType::Id:
10239 #include "clang/Basic/OpenCLImageTypes.def"
10240 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
10241     case BuiltinType::Id:
10242 #include "clang/Basic/OpenCLExtensionTypes.def"
10243     case BuiltinType::OCLSampler:
10244     case BuiltinType::OCLEvent:
10245     case BuiltinType::OCLClkEvent:
10246     case BuiltinType::OCLQueue:
10247     case BuiltinType::OCLReserveID:
10248 #define SVE_TYPE(Name, Id, SingletonId) \
10249     case BuiltinType::Id:
10250 #include "clang/Basic/AArch64SVEACLETypes.def"
10251       return GCCTypeClass::None;
10252 
10253     case BuiltinType::Dependent:
10254       llvm_unreachable("unexpected dependent type");
10255     };
10256     llvm_unreachable("unexpected placeholder type");
10257 
10258   case Type::Enum:
10259     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
10260 
10261   case Type::Pointer:
10262   case Type::ConstantArray:
10263   case Type::VariableArray:
10264   case Type::IncompleteArray:
10265   case Type::FunctionNoProto:
10266   case Type::FunctionProto:
10267     return GCCTypeClass::Pointer;
10268 
10269   case Type::MemberPointer:
10270     return CanTy->isMemberDataPointerType()
10271                ? GCCTypeClass::PointerToDataMember
10272                : GCCTypeClass::PointerToMemberFunction;
10273 
10274   case Type::Complex:
10275     return GCCTypeClass::Complex;
10276 
10277   case Type::Record:
10278     return CanTy->isUnionType() ? GCCTypeClass::Union
10279                                 : GCCTypeClass::ClassOrStruct;
10280 
10281   case Type::Atomic:
10282     // GCC classifies _Atomic T the same as T.
10283     return EvaluateBuiltinClassifyType(
10284         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
10285 
10286   case Type::BlockPointer:
10287   case Type::Vector:
10288   case Type::ExtVector:
10289   case Type::ObjCObject:
10290   case Type::ObjCInterface:
10291   case Type::ObjCObjectPointer:
10292   case Type::Pipe:
10293     // GCC classifies vectors as None. We follow its lead and classify all
10294     // other types that don't fit into the regular classification the same way.
10295     return GCCTypeClass::None;
10296 
10297   case Type::LValueReference:
10298   case Type::RValueReference:
10299     llvm_unreachable("invalid type for expression");
10300   }
10301 
10302   llvm_unreachable("unexpected type class");
10303 }
10304 
10305 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
10306 /// as GCC.
10307 static GCCTypeClass
10308 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
10309   // If no argument was supplied, default to None. This isn't
10310   // ideal, however it is what gcc does.
10311   if (E->getNumArgs() == 0)
10312     return GCCTypeClass::None;
10313 
10314   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
10315   // being an ICE, but still folds it to a constant using the type of the first
10316   // argument.
10317   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
10318 }
10319 
10320 /// EvaluateBuiltinConstantPForLValue - Determine the result of
10321 /// __builtin_constant_p when applied to the given pointer.
10322 ///
10323 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
10324 /// or it points to the first character of a string literal.
10325 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
10326   APValue::LValueBase Base = LV.getLValueBase();
10327   if (Base.isNull()) {
10328     // A null base is acceptable.
10329     return true;
10330   } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
10331     if (!isa<StringLiteral>(E))
10332       return false;
10333     return LV.getLValueOffset().isZero();
10334   } else if (Base.is<TypeInfoLValue>()) {
10335     // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
10336     // evaluate to true.
10337     return true;
10338   } else {
10339     // Any other base is not constant enough for GCC.
10340     return false;
10341   }
10342 }
10343 
10344 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
10345 /// GCC as we can manage.
10346 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
10347   // This evaluation is not permitted to have side-effects, so evaluate it in
10348   // a speculative evaluation context.
10349   SpeculativeEvaluationRAII SpeculativeEval(Info);
10350 
10351   // Constant-folding is always enabled for the operand of __builtin_constant_p
10352   // (even when the enclosing evaluation context otherwise requires a strict
10353   // language-specific constant expression).
10354   FoldConstant Fold(Info, true);
10355 
10356   QualType ArgType = Arg->getType();
10357 
10358   // __builtin_constant_p always has one operand. The rules which gcc follows
10359   // are not precisely documented, but are as follows:
10360   //
10361   //  - If the operand is of integral, floating, complex or enumeration type,
10362   //    and can be folded to a known value of that type, it returns 1.
10363   //  - If the operand can be folded to a pointer to the first character
10364   //    of a string literal (or such a pointer cast to an integral type)
10365   //    or to a null pointer or an integer cast to a pointer, it returns 1.
10366   //
10367   // Otherwise, it returns 0.
10368   //
10369   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
10370   // its support for this did not work prior to GCC 9 and is not yet well
10371   // understood.
10372   if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
10373       ArgType->isAnyComplexType() || ArgType->isPointerType() ||
10374       ArgType->isNullPtrType()) {
10375     APValue V;
10376     if (!::EvaluateAsRValue(Info, Arg, V)) {
10377       Fold.keepDiagnostics();
10378       return false;
10379     }
10380 
10381     // For a pointer (possibly cast to integer), there are special rules.
10382     if (V.getKind() == APValue::LValue)
10383       return EvaluateBuiltinConstantPForLValue(V);
10384 
10385     // Otherwise, any constant value is good enough.
10386     return V.hasValue();
10387   }
10388 
10389   // Anything else isn't considered to be sufficiently constant.
10390   return false;
10391 }
10392 
10393 /// Retrieves the "underlying object type" of the given expression,
10394 /// as used by __builtin_object_size.
10395 static QualType getObjectType(APValue::LValueBase B) {
10396   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
10397     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
10398       return VD->getType();
10399   } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
10400     if (isa<CompoundLiteralExpr>(E))
10401       return E->getType();
10402   } else if (B.is<TypeInfoLValue>()) {
10403     return B.getTypeInfoType();
10404   } else if (B.is<DynamicAllocLValue>()) {
10405     return B.getDynamicAllocType();
10406   }
10407 
10408   return QualType();
10409 }
10410 
10411 /// A more selective version of E->IgnoreParenCasts for
10412 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
10413 /// to change the type of E.
10414 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
10415 ///
10416 /// Always returns an RValue with a pointer representation.
10417 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
10418   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
10419 
10420   auto *NoParens = E->IgnoreParens();
10421   auto *Cast = dyn_cast<CastExpr>(NoParens);
10422   if (Cast == nullptr)
10423     return NoParens;
10424 
10425   // We only conservatively allow a few kinds of casts, because this code is
10426   // inherently a simple solution that seeks to support the common case.
10427   auto CastKind = Cast->getCastKind();
10428   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
10429       CastKind != CK_AddressSpaceConversion)
10430     return NoParens;
10431 
10432   auto *SubExpr = Cast->getSubExpr();
10433   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
10434     return NoParens;
10435   return ignorePointerCastsAndParens(SubExpr);
10436 }
10437 
10438 /// Checks to see if the given LValue's Designator is at the end of the LValue's
10439 /// record layout. e.g.
10440 ///   struct { struct { int a, b; } fst, snd; } obj;
10441 ///   obj.fst   // no
10442 ///   obj.snd   // yes
10443 ///   obj.fst.a // no
10444 ///   obj.fst.b // no
10445 ///   obj.snd.a // no
10446 ///   obj.snd.b // yes
10447 ///
10448 /// Please note: this function is specialized for how __builtin_object_size
10449 /// views "objects".
10450 ///
10451 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
10452 /// correct result, it will always return true.
10453 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
10454   assert(!LVal.Designator.Invalid);
10455 
10456   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
10457     const RecordDecl *Parent = FD->getParent();
10458     Invalid = Parent->isInvalidDecl();
10459     if (Invalid || Parent->isUnion())
10460       return true;
10461     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
10462     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
10463   };
10464 
10465   auto &Base = LVal.getLValueBase();
10466   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
10467     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
10468       bool Invalid;
10469       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
10470         return Invalid;
10471     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
10472       for (auto *FD : IFD->chain()) {
10473         bool Invalid;
10474         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
10475           return Invalid;
10476       }
10477     }
10478   }
10479 
10480   unsigned I = 0;
10481   QualType BaseType = getType(Base);
10482   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
10483     // If we don't know the array bound, conservatively assume we're looking at
10484     // the final array element.
10485     ++I;
10486     if (BaseType->isIncompleteArrayType())
10487       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
10488     else
10489       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
10490   }
10491 
10492   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
10493     const auto &Entry = LVal.Designator.Entries[I];
10494     if (BaseType->isArrayType()) {
10495       // Because __builtin_object_size treats arrays as objects, we can ignore
10496       // the index iff this is the last array in the Designator.
10497       if (I + 1 == E)
10498         return true;
10499       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
10500       uint64_t Index = Entry.getAsArrayIndex();
10501       if (Index + 1 != CAT->getSize())
10502         return false;
10503       BaseType = CAT->getElementType();
10504     } else if (BaseType->isAnyComplexType()) {
10505       const auto *CT = BaseType->castAs<ComplexType>();
10506       uint64_t Index = Entry.getAsArrayIndex();
10507       if (Index != 1)
10508         return false;
10509       BaseType = CT->getElementType();
10510     } else if (auto *FD = getAsField(Entry)) {
10511       bool Invalid;
10512       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
10513         return Invalid;
10514       BaseType = FD->getType();
10515     } else {
10516       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
10517       return false;
10518     }
10519   }
10520   return true;
10521 }
10522 
10523 /// Tests to see if the LValue has a user-specified designator (that isn't
10524 /// necessarily valid). Note that this always returns 'true' if the LValue has
10525 /// an unsized array as its first designator entry, because there's currently no
10526 /// way to tell if the user typed *foo or foo[0].
10527 static bool refersToCompleteObject(const LValue &LVal) {
10528   if (LVal.Designator.Invalid)
10529     return false;
10530 
10531   if (!LVal.Designator.Entries.empty())
10532     return LVal.Designator.isMostDerivedAnUnsizedArray();
10533 
10534   if (!LVal.InvalidBase)
10535     return true;
10536 
10537   // If `E` is a MemberExpr, then the first part of the designator is hiding in
10538   // the LValueBase.
10539   const auto *E = LVal.Base.dyn_cast<const Expr *>();
10540   return !E || !isa<MemberExpr>(E);
10541 }
10542 
10543 /// Attempts to detect a user writing into a piece of memory that's impossible
10544 /// to figure out the size of by just using types.
10545 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
10546   const SubobjectDesignator &Designator = LVal.Designator;
10547   // Notes:
10548   // - Users can only write off of the end when we have an invalid base. Invalid
10549   //   bases imply we don't know where the memory came from.
10550   // - We used to be a bit more aggressive here; we'd only be conservative if
10551   //   the array at the end was flexible, or if it had 0 or 1 elements. This
10552   //   broke some common standard library extensions (PR30346), but was
10553   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
10554   //   with some sort of whitelist. OTOH, it seems that GCC is always
10555   //   conservative with the last element in structs (if it's an array), so our
10556   //   current behavior is more compatible than a whitelisting approach would
10557   //   be.
10558   return LVal.InvalidBase &&
10559          Designator.Entries.size() == Designator.MostDerivedPathLength &&
10560          Designator.MostDerivedIsArrayElement &&
10561          isDesignatorAtObjectEnd(Ctx, LVal);
10562 }
10563 
10564 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
10565 /// Fails if the conversion would cause loss of precision.
10566 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
10567                                             CharUnits &Result) {
10568   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
10569   if (Int.ugt(CharUnitsMax))
10570     return false;
10571   Result = CharUnits::fromQuantity(Int.getZExtValue());
10572   return true;
10573 }
10574 
10575 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
10576 /// determine how many bytes exist from the beginning of the object to either
10577 /// the end of the current subobject, or the end of the object itself, depending
10578 /// on what the LValue looks like + the value of Type.
10579 ///
10580 /// If this returns false, the value of Result is undefined.
10581 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
10582                                unsigned Type, const LValue &LVal,
10583                                CharUnits &EndOffset) {
10584   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
10585 
10586   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
10587     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
10588       return false;
10589     return HandleSizeof(Info, ExprLoc, Ty, Result);
10590   };
10591 
10592   // We want to evaluate the size of the entire object. This is a valid fallback
10593   // for when Type=1 and the designator is invalid, because we're asked for an
10594   // upper-bound.
10595   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
10596     // Type=3 wants a lower bound, so we can't fall back to this.
10597     if (Type == 3 && !DetermineForCompleteObject)
10598       return false;
10599 
10600     llvm::APInt APEndOffset;
10601     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
10602         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
10603       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
10604 
10605     if (LVal.InvalidBase)
10606       return false;
10607 
10608     QualType BaseTy = getObjectType(LVal.getLValueBase());
10609     return CheckedHandleSizeof(BaseTy, EndOffset);
10610   }
10611 
10612   // We want to evaluate the size of a subobject.
10613   const SubobjectDesignator &Designator = LVal.Designator;
10614 
10615   // The following is a moderately common idiom in C:
10616   //
10617   // struct Foo { int a; char c[1]; };
10618   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
10619   // strcpy(&F->c[0], Bar);
10620   //
10621   // In order to not break too much legacy code, we need to support it.
10622   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
10623     // If we can resolve this to an alloc_size call, we can hand that back,
10624     // because we know for certain how many bytes there are to write to.
10625     llvm::APInt APEndOffset;
10626     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
10627         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
10628       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
10629 
10630     // If we cannot determine the size of the initial allocation, then we can't
10631     // given an accurate upper-bound. However, we are still able to give
10632     // conservative lower-bounds for Type=3.
10633     if (Type == 1)
10634       return false;
10635   }
10636 
10637   CharUnits BytesPerElem;
10638   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
10639     return false;
10640 
10641   // According to the GCC documentation, we want the size of the subobject
10642   // denoted by the pointer. But that's not quite right -- what we actually
10643   // want is the size of the immediately-enclosing array, if there is one.
10644   int64_t ElemsRemaining;
10645   if (Designator.MostDerivedIsArrayElement &&
10646       Designator.Entries.size() == Designator.MostDerivedPathLength) {
10647     uint64_t ArraySize = Designator.getMostDerivedArraySize();
10648     uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
10649     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
10650   } else {
10651     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
10652   }
10653 
10654   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
10655   return true;
10656 }
10657 
10658 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
10659 /// returns true and stores the result in @p Size.
10660 ///
10661 /// If @p WasError is non-null, this will report whether the failure to evaluate
10662 /// is to be treated as an Error in IntExprEvaluator.
10663 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
10664                                          EvalInfo &Info, uint64_t &Size) {
10665   // Determine the denoted object.
10666   LValue LVal;
10667   {
10668     // The operand of __builtin_object_size is never evaluated for side-effects.
10669     // If there are any, but we can determine the pointed-to object anyway, then
10670     // ignore the side-effects.
10671     SpeculativeEvaluationRAII SpeculativeEval(Info);
10672     IgnoreSideEffectsRAII Fold(Info);
10673 
10674     if (E->isGLValue()) {
10675       // It's possible for us to be given GLValues if we're called via
10676       // Expr::tryEvaluateObjectSize.
10677       APValue RVal;
10678       if (!EvaluateAsRValue(Info, E, RVal))
10679         return false;
10680       LVal.setFrom(Info.Ctx, RVal);
10681     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
10682                                 /*InvalidBaseOK=*/true))
10683       return false;
10684   }
10685 
10686   // If we point to before the start of the object, there are no accessible
10687   // bytes.
10688   if (LVal.getLValueOffset().isNegative()) {
10689     Size = 0;
10690     return true;
10691   }
10692 
10693   CharUnits EndOffset;
10694   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
10695     return false;
10696 
10697   // If we've fallen outside of the end offset, just pretend there's nothing to
10698   // write to/read from.
10699   if (EndOffset <= LVal.getLValueOffset())
10700     Size = 0;
10701   else
10702     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
10703   return true;
10704 }
10705 
10706 bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
10707   llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
10708   if (E->getResultAPValueKind() != APValue::None)
10709     return Success(E->getAPValueResult(), E);
10710   return ExprEvaluatorBaseTy::VisitConstantExpr(E);
10711 }
10712 
10713 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
10714   if (unsigned BuiltinOp = E->getBuiltinCallee())
10715     return VisitBuiltinCallExpr(E, BuiltinOp);
10716 
10717   return ExprEvaluatorBaseTy::VisitCallExpr(E);
10718 }
10719 
10720 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
10721                                      APValue &Val, APSInt &Alignment) {
10722   QualType SrcTy = E->getArg(0)->getType();
10723   if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
10724     return false;
10725   // Even though we are evaluating integer expressions we could get a pointer
10726   // argument for the __builtin_is_aligned() case.
10727   if (SrcTy->isPointerType()) {
10728     LValue Ptr;
10729     if (!EvaluatePointer(E->getArg(0), Ptr, Info))
10730       return false;
10731     Ptr.moveInto(Val);
10732   } else if (!SrcTy->isIntegralOrEnumerationType()) {
10733     Info.FFDiag(E->getArg(0));
10734     return false;
10735   } else {
10736     APSInt SrcInt;
10737     if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
10738       return false;
10739     assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
10740            "Bit widths must be the same");
10741     Val = APValue(SrcInt);
10742   }
10743   assert(Val.hasValue());
10744   return true;
10745 }
10746 
10747 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
10748                                             unsigned BuiltinOp) {
10749   switch (BuiltinOp) {
10750   default:
10751     return ExprEvaluatorBaseTy::VisitCallExpr(E);
10752 
10753   case Builtin::BI__builtin_dynamic_object_size:
10754   case Builtin::BI__builtin_object_size: {
10755     // The type was checked when we built the expression.
10756     unsigned Type =
10757         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
10758     assert(Type <= 3 && "unexpected type");
10759 
10760     uint64_t Size;
10761     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
10762       return Success(Size, E);
10763 
10764     if (E->getArg(0)->HasSideEffects(Info.Ctx))
10765       return Success((Type & 2) ? 0 : -1, E);
10766 
10767     // Expression had no side effects, but we couldn't statically determine the
10768     // size of the referenced object.
10769     switch (Info.EvalMode) {
10770     case EvalInfo::EM_ConstantExpression:
10771     case EvalInfo::EM_ConstantFold:
10772     case EvalInfo::EM_IgnoreSideEffects:
10773       // Leave it to IR generation.
10774       return Error(E);
10775     case EvalInfo::EM_ConstantExpressionUnevaluated:
10776       // Reduce it to a constant now.
10777       return Success((Type & 2) ? 0 : -1, E);
10778     }
10779 
10780     llvm_unreachable("unexpected EvalMode");
10781   }
10782 
10783   case Builtin::BI__builtin_os_log_format_buffer_size: {
10784     analyze_os_log::OSLogBufferLayout Layout;
10785     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
10786     return Success(Layout.size().getQuantity(), E);
10787   }
10788 
10789   case Builtin::BI__builtin_is_aligned: {
10790     APValue Src;
10791     APSInt Alignment;
10792     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
10793       return false;
10794     if (Src.isLValue()) {
10795       // If we evaluated a pointer, check the minimum known alignment.
10796       LValue Ptr;
10797       Ptr.setFrom(Info.Ctx, Src);
10798       CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
10799       CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
10800       // We can return true if the known alignment at the computed offset is
10801       // greater than the requested alignment.
10802       assert(PtrAlign.isPowerOfTwo());
10803       assert(Alignment.isPowerOf2());
10804       if (PtrAlign.getQuantity() >= Alignment)
10805         return Success(1, E);
10806       // If the alignment is not known to be sufficient, some cases could still
10807       // be aligned at run time. However, if the requested alignment is less or
10808       // equal to the base alignment and the offset is not aligned, we know that
10809       // the run-time value can never be aligned.
10810       if (BaseAlignment.getQuantity() >= Alignment &&
10811           PtrAlign.getQuantity() < Alignment)
10812         return Success(0, E);
10813       // Otherwise we can't infer whether the value is sufficiently aligned.
10814       // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
10815       //  in cases where we can't fully evaluate the pointer.
10816       Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
10817           << Alignment;
10818       return false;
10819     }
10820     assert(Src.isInt());
10821     return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
10822   }
10823   case Builtin::BI__builtin_align_up: {
10824     APValue Src;
10825     APSInt Alignment;
10826     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
10827       return false;
10828     if (!Src.isInt())
10829       return Error(E);
10830     APSInt AlignedVal =
10831         APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
10832                Src.getInt().isUnsigned());
10833     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
10834     return Success(AlignedVal, E);
10835   }
10836   case Builtin::BI__builtin_align_down: {
10837     APValue Src;
10838     APSInt Alignment;
10839     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
10840       return false;
10841     if (!Src.isInt())
10842       return Error(E);
10843     APSInt AlignedVal =
10844         APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
10845     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
10846     return Success(AlignedVal, E);
10847   }
10848 
10849   case Builtin::BI__builtin_bswap16:
10850   case Builtin::BI__builtin_bswap32:
10851   case Builtin::BI__builtin_bswap64: {
10852     APSInt Val;
10853     if (!EvaluateInteger(E->getArg(0), Val, Info))
10854       return false;
10855 
10856     return Success(Val.byteSwap(), E);
10857   }
10858 
10859   case Builtin::BI__builtin_classify_type:
10860     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
10861 
10862   case Builtin::BI__builtin_clrsb:
10863   case Builtin::BI__builtin_clrsbl:
10864   case Builtin::BI__builtin_clrsbll: {
10865     APSInt Val;
10866     if (!EvaluateInteger(E->getArg(0), Val, Info))
10867       return false;
10868 
10869     return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
10870   }
10871 
10872   case Builtin::BI__builtin_clz:
10873   case Builtin::BI__builtin_clzl:
10874   case Builtin::BI__builtin_clzll:
10875   case Builtin::BI__builtin_clzs: {
10876     APSInt Val;
10877     if (!EvaluateInteger(E->getArg(0), Val, Info))
10878       return false;
10879     if (!Val)
10880       return Error(E);
10881 
10882     return Success(Val.countLeadingZeros(), E);
10883   }
10884 
10885   case Builtin::BI__builtin_constant_p: {
10886     const Expr *Arg = E->getArg(0);
10887     if (EvaluateBuiltinConstantP(Info, Arg))
10888       return Success(true, E);
10889     if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
10890       // Outside a constant context, eagerly evaluate to false in the presence
10891       // of side-effects in order to avoid -Wunsequenced false-positives in
10892       // a branch on __builtin_constant_p(expr).
10893       return Success(false, E);
10894     }
10895     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10896     return false;
10897   }
10898 
10899   case Builtin::BI__builtin_is_constant_evaluated: {
10900     const auto *Callee = Info.CurrentCall->getCallee();
10901     if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
10902         (Info.CallStackDepth == 1 ||
10903          (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
10904           Callee->getIdentifier() &&
10905           Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
10906       // FIXME: Find a better way to avoid duplicated diagnostics.
10907       if (Info.EvalStatus.Diag)
10908         Info.report((Info.CallStackDepth == 1) ? E->getExprLoc()
10909                                                : Info.CurrentCall->CallLoc,
10910                     diag::warn_is_constant_evaluated_always_true_constexpr)
10911             << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
10912                                          : "std::is_constant_evaluated");
10913     }
10914 
10915     return Success(Info.InConstantContext, E);
10916   }
10917 
10918   case Builtin::BI__builtin_ctz:
10919   case Builtin::BI__builtin_ctzl:
10920   case Builtin::BI__builtin_ctzll:
10921   case Builtin::BI__builtin_ctzs: {
10922     APSInt Val;
10923     if (!EvaluateInteger(E->getArg(0), Val, Info))
10924       return false;
10925     if (!Val)
10926       return Error(E);
10927 
10928     return Success(Val.countTrailingZeros(), E);
10929   }
10930 
10931   case Builtin::BI__builtin_eh_return_data_regno: {
10932     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
10933     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
10934     return Success(Operand, E);
10935   }
10936 
10937   case Builtin::BI__builtin_expect:
10938     return Visit(E->getArg(0));
10939 
10940   case Builtin::BI__builtin_ffs:
10941   case Builtin::BI__builtin_ffsl:
10942   case Builtin::BI__builtin_ffsll: {
10943     APSInt Val;
10944     if (!EvaluateInteger(E->getArg(0), Val, Info))
10945       return false;
10946 
10947     unsigned N = Val.countTrailingZeros();
10948     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
10949   }
10950 
10951   case Builtin::BI__builtin_fpclassify: {
10952     APFloat Val(0.0);
10953     if (!EvaluateFloat(E->getArg(5), Val, Info))
10954       return false;
10955     unsigned Arg;
10956     switch (Val.getCategory()) {
10957     case APFloat::fcNaN: Arg = 0; break;
10958     case APFloat::fcInfinity: Arg = 1; break;
10959     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
10960     case APFloat::fcZero: Arg = 4; break;
10961     }
10962     return Visit(E->getArg(Arg));
10963   }
10964 
10965   case Builtin::BI__builtin_isinf_sign: {
10966     APFloat Val(0.0);
10967     return EvaluateFloat(E->getArg(0), Val, Info) &&
10968            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
10969   }
10970 
10971   case Builtin::BI__builtin_isinf: {
10972     APFloat Val(0.0);
10973     return EvaluateFloat(E->getArg(0), Val, Info) &&
10974            Success(Val.isInfinity() ? 1 : 0, E);
10975   }
10976 
10977   case Builtin::BI__builtin_isfinite: {
10978     APFloat Val(0.0);
10979     return EvaluateFloat(E->getArg(0), Val, Info) &&
10980            Success(Val.isFinite() ? 1 : 0, E);
10981   }
10982 
10983   case Builtin::BI__builtin_isnan: {
10984     APFloat Val(0.0);
10985     return EvaluateFloat(E->getArg(0), Val, Info) &&
10986            Success(Val.isNaN() ? 1 : 0, E);
10987   }
10988 
10989   case Builtin::BI__builtin_isnormal: {
10990     APFloat Val(0.0);
10991     return EvaluateFloat(E->getArg(0), Val, Info) &&
10992            Success(Val.isNormal() ? 1 : 0, E);
10993   }
10994 
10995   case Builtin::BI__builtin_parity:
10996   case Builtin::BI__builtin_parityl:
10997   case Builtin::BI__builtin_parityll: {
10998     APSInt Val;
10999     if (!EvaluateInteger(E->getArg(0), Val, Info))
11000       return false;
11001 
11002     return Success(Val.countPopulation() % 2, E);
11003   }
11004 
11005   case Builtin::BI__builtin_popcount:
11006   case Builtin::BI__builtin_popcountl:
11007   case Builtin::BI__builtin_popcountll: {
11008     APSInt Val;
11009     if (!EvaluateInteger(E->getArg(0), Val, Info))
11010       return false;
11011 
11012     return Success(Val.countPopulation(), E);
11013   }
11014 
11015   case Builtin::BIstrlen:
11016   case Builtin::BIwcslen:
11017     // A call to strlen is not a constant expression.
11018     if (Info.getLangOpts().CPlusPlus11)
11019       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11020         << /*isConstexpr*/0 << /*isConstructor*/0
11021         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11022     else
11023       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11024     LLVM_FALLTHROUGH;
11025   case Builtin::BI__builtin_strlen:
11026   case Builtin::BI__builtin_wcslen: {
11027     // As an extension, we support __builtin_strlen() as a constant expression,
11028     // and support folding strlen() to a constant.
11029     LValue String;
11030     if (!EvaluatePointer(E->getArg(0), String, Info))
11031       return false;
11032 
11033     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
11034 
11035     // Fast path: if it's a string literal, search the string value.
11036     if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
11037             String.getLValueBase().dyn_cast<const Expr *>())) {
11038       // The string literal may have embedded null characters. Find the first
11039       // one and truncate there.
11040       StringRef Str = S->getBytes();
11041       int64_t Off = String.Offset.getQuantity();
11042       if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
11043           S->getCharByteWidth() == 1 &&
11044           // FIXME: Add fast-path for wchar_t too.
11045           Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
11046         Str = Str.substr(Off);
11047 
11048         StringRef::size_type Pos = Str.find(0);
11049         if (Pos != StringRef::npos)
11050           Str = Str.substr(0, Pos);
11051 
11052         return Success(Str.size(), E);
11053       }
11054 
11055       // Fall through to slow path to issue appropriate diagnostic.
11056     }
11057 
11058     // Slow path: scan the bytes of the string looking for the terminating 0.
11059     for (uint64_t Strlen = 0; /**/; ++Strlen) {
11060       APValue Char;
11061       if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
11062           !Char.isInt())
11063         return false;
11064       if (!Char.getInt())
11065         return Success(Strlen, E);
11066       if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
11067         return false;
11068     }
11069   }
11070 
11071   case Builtin::BIstrcmp:
11072   case Builtin::BIwcscmp:
11073   case Builtin::BIstrncmp:
11074   case Builtin::BIwcsncmp:
11075   case Builtin::BImemcmp:
11076   case Builtin::BIbcmp:
11077   case Builtin::BIwmemcmp:
11078     // A call to strlen is not a constant expression.
11079     if (Info.getLangOpts().CPlusPlus11)
11080       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11081         << /*isConstexpr*/0 << /*isConstructor*/0
11082         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11083     else
11084       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11085     LLVM_FALLTHROUGH;
11086   case Builtin::BI__builtin_strcmp:
11087   case Builtin::BI__builtin_wcscmp:
11088   case Builtin::BI__builtin_strncmp:
11089   case Builtin::BI__builtin_wcsncmp:
11090   case Builtin::BI__builtin_memcmp:
11091   case Builtin::BI__builtin_bcmp:
11092   case Builtin::BI__builtin_wmemcmp: {
11093     LValue String1, String2;
11094     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
11095         !EvaluatePointer(E->getArg(1), String2, Info))
11096       return false;
11097 
11098     uint64_t MaxLength = uint64_t(-1);
11099     if (BuiltinOp != Builtin::BIstrcmp &&
11100         BuiltinOp != Builtin::BIwcscmp &&
11101         BuiltinOp != Builtin::BI__builtin_strcmp &&
11102         BuiltinOp != Builtin::BI__builtin_wcscmp) {
11103       APSInt N;
11104       if (!EvaluateInteger(E->getArg(2), N, Info))
11105         return false;
11106       MaxLength = N.getExtValue();
11107     }
11108 
11109     // Empty substrings compare equal by definition.
11110     if (MaxLength == 0u)
11111       return Success(0, E);
11112 
11113     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11114         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11115         String1.Designator.Invalid || String2.Designator.Invalid)
11116       return false;
11117 
11118     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
11119     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
11120 
11121     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
11122                      BuiltinOp == Builtin::BIbcmp ||
11123                      BuiltinOp == Builtin::BI__builtin_memcmp ||
11124                      BuiltinOp == Builtin::BI__builtin_bcmp;
11125 
11126     assert(IsRawByte ||
11127            (Info.Ctx.hasSameUnqualifiedType(
11128                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
11129             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
11130 
11131     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
11132       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
11133              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
11134              Char1.isInt() && Char2.isInt();
11135     };
11136     const auto &AdvanceElems = [&] {
11137       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
11138              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
11139     };
11140 
11141     if (IsRawByte) {
11142       uint64_t BytesRemaining = MaxLength;
11143       // Pointers to const void may point to objects of incomplete type.
11144       if (CharTy1->isIncompleteType()) {
11145         Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1;
11146         return false;
11147       }
11148       if (CharTy2->isIncompleteType()) {
11149         Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2;
11150         return false;
11151       }
11152       uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)};
11153       CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width);
11154       // Give up on comparing between elements with disparate widths.
11155       if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2))
11156         return false;
11157       uint64_t BytesPerElement = CharTy1Size.getQuantity();
11158       assert(BytesRemaining && "BytesRemaining should not be zero: the "
11159                                "following loop considers at least one element");
11160       while (true) {
11161         APValue Char1, Char2;
11162         if (!ReadCurElems(Char1, Char2))
11163           return false;
11164         // We have compatible in-memory widths, but a possible type and
11165         // (for `bool`) internal representation mismatch.
11166         // Assuming two's complement representation, including 0 for `false` and
11167         // 1 for `true`, we can check an appropriate number of elements for
11168         // equality even if they are not byte-sized.
11169         APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width);
11170         APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width);
11171         if (Char1InMem.ne(Char2InMem)) {
11172           // If the elements are byte-sized, then we can produce a three-way
11173           // comparison result in a straightforward manner.
11174           if (BytesPerElement == 1u) {
11175             // memcmp always compares unsigned chars.
11176             return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E);
11177           }
11178           // The result is byte-order sensitive, and we have multibyte elements.
11179           // FIXME: We can compare the remaining bytes in the correct order.
11180           return false;
11181         }
11182         if (!AdvanceElems())
11183           return false;
11184         if (BytesRemaining <= BytesPerElement)
11185           break;
11186         BytesRemaining -= BytesPerElement;
11187       }
11188       // Enough elements are equal to account for the memcmp limit.
11189       return Success(0, E);
11190     }
11191 
11192     bool StopAtNull =
11193         (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
11194          BuiltinOp != Builtin::BIwmemcmp &&
11195          BuiltinOp != Builtin::BI__builtin_memcmp &&
11196          BuiltinOp != Builtin::BI__builtin_bcmp &&
11197          BuiltinOp != Builtin::BI__builtin_wmemcmp);
11198     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
11199                   BuiltinOp == Builtin::BIwcsncmp ||
11200                   BuiltinOp == Builtin::BIwmemcmp ||
11201                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
11202                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
11203                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
11204 
11205     for (; MaxLength; --MaxLength) {
11206       APValue Char1, Char2;
11207       if (!ReadCurElems(Char1, Char2))
11208         return false;
11209       if (Char1.getInt() != Char2.getInt()) {
11210         if (IsWide) // wmemcmp compares with wchar_t signedness.
11211           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
11212         // memcmp always compares unsigned chars.
11213         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
11214       }
11215       if (StopAtNull && !Char1.getInt())
11216         return Success(0, E);
11217       assert(!(StopAtNull && !Char2.getInt()));
11218       if (!AdvanceElems())
11219         return false;
11220     }
11221     // We hit the strncmp / memcmp limit.
11222     return Success(0, E);
11223   }
11224 
11225   case Builtin::BI__atomic_always_lock_free:
11226   case Builtin::BI__atomic_is_lock_free:
11227   case Builtin::BI__c11_atomic_is_lock_free: {
11228     APSInt SizeVal;
11229     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
11230       return false;
11231 
11232     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
11233     // of two less than the maximum inline atomic width, we know it is
11234     // lock-free.  If the size isn't a power of two, or greater than the
11235     // maximum alignment where we promote atomics, we know it is not lock-free
11236     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
11237     // the answer can only be determined at runtime; for example, 16-byte
11238     // atomics have lock-free implementations on some, but not all,
11239     // x86-64 processors.
11240 
11241     // Check power-of-two.
11242     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
11243     if (Size.isPowerOfTwo()) {
11244       // Check against inlining width.
11245       unsigned InlineWidthBits =
11246           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
11247       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
11248         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
11249             Size == CharUnits::One() ||
11250             E->getArg(1)->isNullPointerConstant(Info.Ctx,
11251                                                 Expr::NPC_NeverValueDependent))
11252           // OK, we will inline appropriately-aligned operations of this size,
11253           // and _Atomic(T) is appropriately-aligned.
11254           return Success(1, E);
11255 
11256         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
11257           castAs<PointerType>()->getPointeeType();
11258         if (!PointeeType->isIncompleteType() &&
11259             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
11260           // OK, we will inline operations on this object.
11261           return Success(1, E);
11262         }
11263       }
11264     }
11265 
11266     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
11267         Success(0, E) : Error(E);
11268   }
11269   case Builtin::BIomp_is_initial_device:
11270     // We can decide statically which value the runtime would return if called.
11271     return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
11272   case Builtin::BI__builtin_add_overflow:
11273   case Builtin::BI__builtin_sub_overflow:
11274   case Builtin::BI__builtin_mul_overflow:
11275   case Builtin::BI__builtin_sadd_overflow:
11276   case Builtin::BI__builtin_uadd_overflow:
11277   case Builtin::BI__builtin_uaddl_overflow:
11278   case Builtin::BI__builtin_uaddll_overflow:
11279   case Builtin::BI__builtin_usub_overflow:
11280   case Builtin::BI__builtin_usubl_overflow:
11281   case Builtin::BI__builtin_usubll_overflow:
11282   case Builtin::BI__builtin_umul_overflow:
11283   case Builtin::BI__builtin_umull_overflow:
11284   case Builtin::BI__builtin_umulll_overflow:
11285   case Builtin::BI__builtin_saddl_overflow:
11286   case Builtin::BI__builtin_saddll_overflow:
11287   case Builtin::BI__builtin_ssub_overflow:
11288   case Builtin::BI__builtin_ssubl_overflow:
11289   case Builtin::BI__builtin_ssubll_overflow:
11290   case Builtin::BI__builtin_smul_overflow:
11291   case Builtin::BI__builtin_smull_overflow:
11292   case Builtin::BI__builtin_smulll_overflow: {
11293     LValue ResultLValue;
11294     APSInt LHS, RHS;
11295 
11296     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
11297     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
11298         !EvaluateInteger(E->getArg(1), RHS, Info) ||
11299         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
11300       return false;
11301 
11302     APSInt Result;
11303     bool DidOverflow = false;
11304 
11305     // If the types don't have to match, enlarge all 3 to the largest of them.
11306     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
11307         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
11308         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
11309       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
11310                       ResultType->isSignedIntegerOrEnumerationType();
11311       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
11312                       ResultType->isSignedIntegerOrEnumerationType();
11313       uint64_t LHSSize = LHS.getBitWidth();
11314       uint64_t RHSSize = RHS.getBitWidth();
11315       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
11316       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
11317 
11318       // Add an additional bit if the signedness isn't uniformly agreed to. We
11319       // could do this ONLY if there is a signed and an unsigned that both have
11320       // MaxBits, but the code to check that is pretty nasty.  The issue will be
11321       // caught in the shrink-to-result later anyway.
11322       if (IsSigned && !AllSigned)
11323         ++MaxBits;
11324 
11325       LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
11326       RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
11327       Result = APSInt(MaxBits, !IsSigned);
11328     }
11329 
11330     // Find largest int.
11331     switch (BuiltinOp) {
11332     default:
11333       llvm_unreachable("Invalid value for BuiltinOp");
11334     case Builtin::BI__builtin_add_overflow:
11335     case Builtin::BI__builtin_sadd_overflow:
11336     case Builtin::BI__builtin_saddl_overflow:
11337     case Builtin::BI__builtin_saddll_overflow:
11338     case Builtin::BI__builtin_uadd_overflow:
11339     case Builtin::BI__builtin_uaddl_overflow:
11340     case Builtin::BI__builtin_uaddll_overflow:
11341       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
11342                               : LHS.uadd_ov(RHS, DidOverflow);
11343       break;
11344     case Builtin::BI__builtin_sub_overflow:
11345     case Builtin::BI__builtin_ssub_overflow:
11346     case Builtin::BI__builtin_ssubl_overflow:
11347     case Builtin::BI__builtin_ssubll_overflow:
11348     case Builtin::BI__builtin_usub_overflow:
11349     case Builtin::BI__builtin_usubl_overflow:
11350     case Builtin::BI__builtin_usubll_overflow:
11351       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
11352                               : LHS.usub_ov(RHS, DidOverflow);
11353       break;
11354     case Builtin::BI__builtin_mul_overflow:
11355     case Builtin::BI__builtin_smul_overflow:
11356     case Builtin::BI__builtin_smull_overflow:
11357     case Builtin::BI__builtin_smulll_overflow:
11358     case Builtin::BI__builtin_umul_overflow:
11359     case Builtin::BI__builtin_umull_overflow:
11360     case Builtin::BI__builtin_umulll_overflow:
11361       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
11362                               : LHS.umul_ov(RHS, DidOverflow);
11363       break;
11364     }
11365 
11366     // In the case where multiple sizes are allowed, truncate and see if
11367     // the values are the same.
11368     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
11369         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
11370         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
11371       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
11372       // since it will give us the behavior of a TruncOrSelf in the case where
11373       // its parameter <= its size.  We previously set Result to be at least the
11374       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
11375       // will work exactly like TruncOrSelf.
11376       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
11377       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
11378 
11379       if (!APSInt::isSameValue(Temp, Result))
11380         DidOverflow = true;
11381       Result = Temp;
11382     }
11383 
11384     APValue APV{Result};
11385     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
11386       return false;
11387     return Success(DidOverflow, E);
11388   }
11389   }
11390 }
11391 
11392 /// Determine whether this is a pointer past the end of the complete
11393 /// object referred to by the lvalue.
11394 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
11395                                             const LValue &LV) {
11396   // A null pointer can be viewed as being "past the end" but we don't
11397   // choose to look at it that way here.
11398   if (!LV.getLValueBase())
11399     return false;
11400 
11401   // If the designator is valid and refers to a subobject, we're not pointing
11402   // past the end.
11403   if (!LV.getLValueDesignator().Invalid &&
11404       !LV.getLValueDesignator().isOnePastTheEnd())
11405     return false;
11406 
11407   // A pointer to an incomplete type might be past-the-end if the type's size is
11408   // zero.  We cannot tell because the type is incomplete.
11409   QualType Ty = getType(LV.getLValueBase());
11410   if (Ty->isIncompleteType())
11411     return true;
11412 
11413   // We're a past-the-end pointer if we point to the byte after the object,
11414   // no matter what our type or path is.
11415   auto Size = Ctx.getTypeSizeInChars(Ty);
11416   return LV.getLValueOffset() == Size;
11417 }
11418 
11419 namespace {
11420 
11421 /// Data recursive integer evaluator of certain binary operators.
11422 ///
11423 /// We use a data recursive algorithm for binary operators so that we are able
11424 /// to handle extreme cases of chained binary operators without causing stack
11425 /// overflow.
11426 class DataRecursiveIntBinOpEvaluator {
11427   struct EvalResult {
11428     APValue Val;
11429     bool Failed;
11430 
11431     EvalResult() : Failed(false) { }
11432 
11433     void swap(EvalResult &RHS) {
11434       Val.swap(RHS.Val);
11435       Failed = RHS.Failed;
11436       RHS.Failed = false;
11437     }
11438   };
11439 
11440   struct Job {
11441     const Expr *E;
11442     EvalResult LHSResult; // meaningful only for binary operator expression.
11443     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
11444 
11445     Job() = default;
11446     Job(Job &&) = default;
11447 
11448     void startSpeculativeEval(EvalInfo &Info) {
11449       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
11450     }
11451 
11452   private:
11453     SpeculativeEvaluationRAII SpecEvalRAII;
11454   };
11455 
11456   SmallVector<Job, 16> Queue;
11457 
11458   IntExprEvaluator &IntEval;
11459   EvalInfo &Info;
11460   APValue &FinalResult;
11461 
11462 public:
11463   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
11464     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
11465 
11466   /// True if \param E is a binary operator that we are going to handle
11467   /// data recursively.
11468   /// We handle binary operators that are comma, logical, or that have operands
11469   /// with integral or enumeration type.
11470   static bool shouldEnqueue(const BinaryOperator *E) {
11471     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
11472            (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
11473             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
11474             E->getRHS()->getType()->isIntegralOrEnumerationType());
11475   }
11476 
11477   bool Traverse(const BinaryOperator *E) {
11478     enqueue(E);
11479     EvalResult PrevResult;
11480     while (!Queue.empty())
11481       process(PrevResult);
11482 
11483     if (PrevResult.Failed) return false;
11484 
11485     FinalResult.swap(PrevResult.Val);
11486     return true;
11487   }
11488 
11489 private:
11490   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
11491     return IntEval.Success(Value, E, Result);
11492   }
11493   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
11494     return IntEval.Success(Value, E, Result);
11495   }
11496   bool Error(const Expr *E) {
11497     return IntEval.Error(E);
11498   }
11499   bool Error(const Expr *E, diag::kind D) {
11500     return IntEval.Error(E, D);
11501   }
11502 
11503   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
11504     return Info.CCEDiag(E, D);
11505   }
11506 
11507   // Returns true if visiting the RHS is necessary, false otherwise.
11508   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
11509                          bool &SuppressRHSDiags);
11510 
11511   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
11512                   const BinaryOperator *E, APValue &Result);
11513 
11514   void EvaluateExpr(const Expr *E, EvalResult &Result) {
11515     Result.Failed = !Evaluate(Result.Val, Info, E);
11516     if (Result.Failed)
11517       Result.Val = APValue();
11518   }
11519 
11520   void process(EvalResult &Result);
11521 
11522   void enqueue(const Expr *E) {
11523     E = E->IgnoreParens();
11524     Queue.resize(Queue.size()+1);
11525     Queue.back().E = E;
11526     Queue.back().Kind = Job::AnyExprKind;
11527   }
11528 };
11529 
11530 }
11531 
11532 bool DataRecursiveIntBinOpEvaluator::
11533        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
11534                          bool &SuppressRHSDiags) {
11535   if (E->getOpcode() == BO_Comma) {
11536     // Ignore LHS but note if we could not evaluate it.
11537     if (LHSResult.Failed)
11538       return Info.noteSideEffect();
11539     return true;
11540   }
11541 
11542   if (E->isLogicalOp()) {
11543     bool LHSAsBool;
11544     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
11545       // We were able to evaluate the LHS, see if we can get away with not
11546       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
11547       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
11548         Success(LHSAsBool, E, LHSResult.Val);
11549         return false; // Ignore RHS
11550       }
11551     } else {
11552       LHSResult.Failed = true;
11553 
11554       // Since we weren't able to evaluate the left hand side, it
11555       // might have had side effects.
11556       if (!Info.noteSideEffect())
11557         return false;
11558 
11559       // We can't evaluate the LHS; however, sometimes the result
11560       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
11561       // Don't ignore RHS and suppress diagnostics from this arm.
11562       SuppressRHSDiags = true;
11563     }
11564 
11565     return true;
11566   }
11567 
11568   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
11569          E->getRHS()->getType()->isIntegralOrEnumerationType());
11570 
11571   if (LHSResult.Failed && !Info.noteFailure())
11572     return false; // Ignore RHS;
11573 
11574   return true;
11575 }
11576 
11577 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
11578                                     bool IsSub) {
11579   // Compute the new offset in the appropriate width, wrapping at 64 bits.
11580   // FIXME: When compiling for a 32-bit target, we should use 32-bit
11581   // offsets.
11582   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
11583   CharUnits &Offset = LVal.getLValueOffset();
11584   uint64_t Offset64 = Offset.getQuantity();
11585   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
11586   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
11587                                          : Offset64 + Index64);
11588 }
11589 
11590 bool DataRecursiveIntBinOpEvaluator::
11591        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
11592                   const BinaryOperator *E, APValue &Result) {
11593   if (E->getOpcode() == BO_Comma) {
11594     if (RHSResult.Failed)
11595       return false;
11596     Result = RHSResult.Val;
11597     return true;
11598   }
11599 
11600   if (E->isLogicalOp()) {
11601     bool lhsResult, rhsResult;
11602     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
11603     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
11604 
11605     if (LHSIsOK) {
11606       if (RHSIsOK) {
11607         if (E->getOpcode() == BO_LOr)
11608           return Success(lhsResult || rhsResult, E, Result);
11609         else
11610           return Success(lhsResult && rhsResult, E, Result);
11611       }
11612     } else {
11613       if (RHSIsOK) {
11614         // We can't evaluate the LHS; however, sometimes the result
11615         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
11616         if (rhsResult == (E->getOpcode() == BO_LOr))
11617           return Success(rhsResult, E, Result);
11618       }
11619     }
11620 
11621     return false;
11622   }
11623 
11624   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
11625          E->getRHS()->getType()->isIntegralOrEnumerationType());
11626 
11627   if (LHSResult.Failed || RHSResult.Failed)
11628     return false;
11629 
11630   const APValue &LHSVal = LHSResult.Val;
11631   const APValue &RHSVal = RHSResult.Val;
11632 
11633   // Handle cases like (unsigned long)&a + 4.
11634   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
11635     Result = LHSVal;
11636     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
11637     return true;
11638   }
11639 
11640   // Handle cases like 4 + (unsigned long)&a
11641   if (E->getOpcode() == BO_Add &&
11642       RHSVal.isLValue() && LHSVal.isInt()) {
11643     Result = RHSVal;
11644     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
11645     return true;
11646   }
11647 
11648   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
11649     // Handle (intptr_t)&&A - (intptr_t)&&B.
11650     if (!LHSVal.getLValueOffset().isZero() ||
11651         !RHSVal.getLValueOffset().isZero())
11652       return false;
11653     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
11654     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
11655     if (!LHSExpr || !RHSExpr)
11656       return false;
11657     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
11658     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
11659     if (!LHSAddrExpr || !RHSAddrExpr)
11660       return false;
11661     // Make sure both labels come from the same function.
11662     if (LHSAddrExpr->getLabel()->getDeclContext() !=
11663         RHSAddrExpr->getLabel()->getDeclContext())
11664       return false;
11665     Result = APValue(LHSAddrExpr, RHSAddrExpr);
11666     return true;
11667   }
11668 
11669   // All the remaining cases expect both operands to be an integer
11670   if (!LHSVal.isInt() || !RHSVal.isInt())
11671     return Error(E);
11672 
11673   // Set up the width and signedness manually, in case it can't be deduced
11674   // from the operation we're performing.
11675   // FIXME: Don't do this in the cases where we can deduce it.
11676   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
11677                E->getType()->isUnsignedIntegerOrEnumerationType());
11678   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
11679                          RHSVal.getInt(), Value))
11680     return false;
11681   return Success(Value, E, Result);
11682 }
11683 
11684 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
11685   Job &job = Queue.back();
11686 
11687   switch (job.Kind) {
11688     case Job::AnyExprKind: {
11689       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
11690         if (shouldEnqueue(Bop)) {
11691           job.Kind = Job::BinOpKind;
11692           enqueue(Bop->getLHS());
11693           return;
11694         }
11695       }
11696 
11697       EvaluateExpr(job.E, Result);
11698       Queue.pop_back();
11699       return;
11700     }
11701 
11702     case Job::BinOpKind: {
11703       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
11704       bool SuppressRHSDiags = false;
11705       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
11706         Queue.pop_back();
11707         return;
11708       }
11709       if (SuppressRHSDiags)
11710         job.startSpeculativeEval(Info);
11711       job.LHSResult.swap(Result);
11712       job.Kind = Job::BinOpVisitedLHSKind;
11713       enqueue(Bop->getRHS());
11714       return;
11715     }
11716 
11717     case Job::BinOpVisitedLHSKind: {
11718       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
11719       EvalResult RHS;
11720       RHS.swap(Result);
11721       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
11722       Queue.pop_back();
11723       return;
11724     }
11725   }
11726 
11727   llvm_unreachable("Invalid Job::Kind!");
11728 }
11729 
11730 namespace {
11731 /// Used when we determine that we should fail, but can keep evaluating prior to
11732 /// noting that we had a failure.
11733 class DelayedNoteFailureRAII {
11734   EvalInfo &Info;
11735   bool NoteFailure;
11736 
11737 public:
11738   DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
11739       : Info(Info), NoteFailure(NoteFailure) {}
11740   ~DelayedNoteFailureRAII() {
11741     if (NoteFailure) {
11742       bool ContinueAfterFailure = Info.noteFailure();
11743       (void)ContinueAfterFailure;
11744       assert(ContinueAfterFailure &&
11745              "Shouldn't have kept evaluating on failure.");
11746     }
11747   }
11748 };
11749 
11750 enum class CmpResult {
11751   Unequal,
11752   Less,
11753   Equal,
11754   Greater,
11755   Unordered,
11756 };
11757 }
11758 
11759 template <class SuccessCB, class AfterCB>
11760 static bool
11761 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
11762                                  SuccessCB &&Success, AfterCB &&DoAfter) {
11763   assert(E->isComparisonOp() && "expected comparison operator");
11764   assert((E->getOpcode() == BO_Cmp ||
11765           E->getType()->isIntegralOrEnumerationType()) &&
11766          "unsupported binary expression evaluation");
11767   auto Error = [&](const Expr *E) {
11768     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11769     return false;
11770   };
11771 
11772   bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
11773   bool IsEquality = E->isEqualityOp();
11774 
11775   QualType LHSTy = E->getLHS()->getType();
11776   QualType RHSTy = E->getRHS()->getType();
11777 
11778   if (LHSTy->isIntegralOrEnumerationType() &&
11779       RHSTy->isIntegralOrEnumerationType()) {
11780     APSInt LHS, RHS;
11781     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
11782     if (!LHSOK && !Info.noteFailure())
11783       return false;
11784     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
11785       return false;
11786     if (LHS < RHS)
11787       return Success(CmpResult::Less, E);
11788     if (LHS > RHS)
11789       return Success(CmpResult::Greater, E);
11790     return Success(CmpResult::Equal, E);
11791   }
11792 
11793   if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
11794     APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
11795     APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
11796 
11797     bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
11798     if (!LHSOK && !Info.noteFailure())
11799       return false;
11800     if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
11801       return false;
11802     if (LHSFX < RHSFX)
11803       return Success(CmpResult::Less, E);
11804     if (LHSFX > RHSFX)
11805       return Success(CmpResult::Greater, E);
11806     return Success(CmpResult::Equal, E);
11807   }
11808 
11809   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
11810     ComplexValue LHS, RHS;
11811     bool LHSOK;
11812     if (E->isAssignmentOp()) {
11813       LValue LV;
11814       EvaluateLValue(E->getLHS(), LV, Info);
11815       LHSOK = false;
11816     } else if (LHSTy->isRealFloatingType()) {
11817       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
11818       if (LHSOK) {
11819         LHS.makeComplexFloat();
11820         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
11821       }
11822     } else {
11823       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
11824     }
11825     if (!LHSOK && !Info.noteFailure())
11826       return false;
11827 
11828     if (E->getRHS()->getType()->isRealFloatingType()) {
11829       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
11830         return false;
11831       RHS.makeComplexFloat();
11832       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
11833     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
11834       return false;
11835 
11836     if (LHS.isComplexFloat()) {
11837       APFloat::cmpResult CR_r =
11838         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
11839       APFloat::cmpResult CR_i =
11840         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
11841       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
11842       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
11843     } else {
11844       assert(IsEquality && "invalid complex comparison");
11845       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
11846                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
11847       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
11848     }
11849   }
11850 
11851   if (LHSTy->isRealFloatingType() &&
11852       RHSTy->isRealFloatingType()) {
11853     APFloat RHS(0.0), LHS(0.0);
11854 
11855     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
11856     if (!LHSOK && !Info.noteFailure())
11857       return false;
11858 
11859     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
11860       return false;
11861 
11862     assert(E->isComparisonOp() && "Invalid binary operator!");
11863     auto GetCmpRes = [&]() {
11864       switch (LHS.compare(RHS)) {
11865       case APFloat::cmpEqual:
11866         return CmpResult::Equal;
11867       case APFloat::cmpLessThan:
11868         return CmpResult::Less;
11869       case APFloat::cmpGreaterThan:
11870         return CmpResult::Greater;
11871       case APFloat::cmpUnordered:
11872         return CmpResult::Unordered;
11873       }
11874       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
11875     };
11876     return Success(GetCmpRes(), E);
11877   }
11878 
11879   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
11880     LValue LHSValue, RHSValue;
11881 
11882     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
11883     if (!LHSOK && !Info.noteFailure())
11884       return false;
11885 
11886     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
11887       return false;
11888 
11889     // Reject differing bases from the normal codepath; we special-case
11890     // comparisons to null.
11891     if (!HasSameBase(LHSValue, RHSValue)) {
11892       // Inequalities and subtractions between unrelated pointers have
11893       // unspecified or undefined behavior.
11894       if (!IsEquality) {
11895         Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified);
11896         return false;
11897       }
11898       // A constant address may compare equal to the address of a symbol.
11899       // The one exception is that address of an object cannot compare equal
11900       // to a null pointer constant.
11901       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
11902           (!RHSValue.Base && !RHSValue.Offset.isZero()))
11903         return Error(E);
11904       // It's implementation-defined whether distinct literals will have
11905       // distinct addresses. In clang, the result of such a comparison is
11906       // unspecified, so it is not a constant expression. However, we do know
11907       // that the address of a literal will be non-null.
11908       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
11909           LHSValue.Base && RHSValue.Base)
11910         return Error(E);
11911       // We can't tell whether weak symbols will end up pointing to the same
11912       // object.
11913       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
11914         return Error(E);
11915       // We can't compare the address of the start of one object with the
11916       // past-the-end address of another object, per C++ DR1652.
11917       if ((LHSValue.Base && LHSValue.Offset.isZero() &&
11918            isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
11919           (RHSValue.Base && RHSValue.Offset.isZero() &&
11920            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
11921         return Error(E);
11922       // We can't tell whether an object is at the same address as another
11923       // zero sized object.
11924       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
11925           (LHSValue.Base && isZeroSized(RHSValue)))
11926         return Error(E);
11927       return Success(CmpResult::Unequal, E);
11928     }
11929 
11930     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
11931     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
11932 
11933     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
11934     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
11935 
11936     // C++11 [expr.rel]p3:
11937     //   Pointers to void (after pointer conversions) can be compared, with a
11938     //   result defined as follows: If both pointers represent the same
11939     //   address or are both the null pointer value, the result is true if the
11940     //   operator is <= or >= and false otherwise; otherwise the result is
11941     //   unspecified.
11942     // We interpret this as applying to pointers to *cv* void.
11943     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
11944       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
11945 
11946     // C++11 [expr.rel]p2:
11947     // - If two pointers point to non-static data members of the same object,
11948     //   or to subobjects or array elements fo such members, recursively, the
11949     //   pointer to the later declared member compares greater provided the
11950     //   two members have the same access control and provided their class is
11951     //   not a union.
11952     //   [...]
11953     // - Otherwise pointer comparisons are unspecified.
11954     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
11955       bool WasArrayIndex;
11956       unsigned Mismatch = FindDesignatorMismatch(
11957           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
11958       // At the point where the designators diverge, the comparison has a
11959       // specified value if:
11960       //  - we are comparing array indices
11961       //  - we are comparing fields of a union, or fields with the same access
11962       // Otherwise, the result is unspecified and thus the comparison is not a
11963       // constant expression.
11964       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
11965           Mismatch < RHSDesignator.Entries.size()) {
11966         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
11967         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
11968         if (!LF && !RF)
11969           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
11970         else if (!LF)
11971           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
11972               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
11973               << RF->getParent() << RF;
11974         else if (!RF)
11975           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
11976               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
11977               << LF->getParent() << LF;
11978         else if (!LF->getParent()->isUnion() &&
11979                  LF->getAccess() != RF->getAccess())
11980           Info.CCEDiag(E,
11981                        diag::note_constexpr_pointer_comparison_differing_access)
11982               << LF << LF->getAccess() << RF << RF->getAccess()
11983               << LF->getParent();
11984       }
11985     }
11986 
11987     // The comparison here must be unsigned, and performed with the same
11988     // width as the pointer.
11989     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
11990     uint64_t CompareLHS = LHSOffset.getQuantity();
11991     uint64_t CompareRHS = RHSOffset.getQuantity();
11992     assert(PtrSize <= 64 && "Unexpected pointer width");
11993     uint64_t Mask = ~0ULL >> (64 - PtrSize);
11994     CompareLHS &= Mask;
11995     CompareRHS &= Mask;
11996 
11997     // If there is a base and this is a relational operator, we can only
11998     // compare pointers within the object in question; otherwise, the result
11999     // depends on where the object is located in memory.
12000     if (!LHSValue.Base.isNull() && IsRelational) {
12001       QualType BaseTy = getType(LHSValue.Base);
12002       if (BaseTy->isIncompleteType())
12003         return Error(E);
12004       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
12005       uint64_t OffsetLimit = Size.getQuantity();
12006       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
12007         return Error(E);
12008     }
12009 
12010     if (CompareLHS < CompareRHS)
12011       return Success(CmpResult::Less, E);
12012     if (CompareLHS > CompareRHS)
12013       return Success(CmpResult::Greater, E);
12014     return Success(CmpResult::Equal, E);
12015   }
12016 
12017   if (LHSTy->isMemberPointerType()) {
12018     assert(IsEquality && "unexpected member pointer operation");
12019     assert(RHSTy->isMemberPointerType() && "invalid comparison");
12020 
12021     MemberPtr LHSValue, RHSValue;
12022 
12023     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
12024     if (!LHSOK && !Info.noteFailure())
12025       return false;
12026 
12027     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12028       return false;
12029 
12030     // C++11 [expr.eq]p2:
12031     //   If both operands are null, they compare equal. Otherwise if only one is
12032     //   null, they compare unequal.
12033     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
12034       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
12035       return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12036     }
12037 
12038     //   Otherwise if either is a pointer to a virtual member function, the
12039     //   result is unspecified.
12040     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
12041       if (MD->isVirtual())
12042         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12043     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
12044       if (MD->isVirtual())
12045         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12046 
12047     //   Otherwise they compare equal if and only if they would refer to the
12048     //   same member of the same most derived object or the same subobject if
12049     //   they were dereferenced with a hypothetical object of the associated
12050     //   class type.
12051     bool Equal = LHSValue == RHSValue;
12052     return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12053   }
12054 
12055   if (LHSTy->isNullPtrType()) {
12056     assert(E->isComparisonOp() && "unexpected nullptr operation");
12057     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
12058     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
12059     // are compared, the result is true of the operator is <=, >= or ==, and
12060     // false otherwise.
12061     return Success(CmpResult::Equal, E);
12062   }
12063 
12064   return DoAfter();
12065 }
12066 
12067 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
12068   if (!CheckLiteralType(Info, E))
12069     return false;
12070 
12071   auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12072     ComparisonCategoryResult CCR;
12073     switch (CR) {
12074     case CmpResult::Unequal:
12075       llvm_unreachable("should never produce Unequal for three-way comparison");
12076     case CmpResult::Less:
12077       CCR = ComparisonCategoryResult::Less;
12078       break;
12079     case CmpResult::Equal:
12080       CCR = ComparisonCategoryResult::Equal;
12081       break;
12082     case CmpResult::Greater:
12083       CCR = ComparisonCategoryResult::Greater;
12084       break;
12085     case CmpResult::Unordered:
12086       CCR = ComparisonCategoryResult::Unordered;
12087       break;
12088     }
12089     // Evaluation succeeded. Lookup the information for the comparison category
12090     // type and fetch the VarDecl for the result.
12091     const ComparisonCategoryInfo &CmpInfo =
12092         Info.Ctx.CompCategories.getInfoForType(E->getType());
12093     const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
12094     // Check and evaluate the result as a constant expression.
12095     LValue LV;
12096     LV.set(VD);
12097     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
12098       return false;
12099     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
12100   };
12101   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12102     return ExprEvaluatorBaseTy::VisitBinCmp(E);
12103   });
12104 }
12105 
12106 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12107   // We don't call noteFailure immediately because the assignment happens after
12108   // we evaluate LHS and RHS.
12109   if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
12110     return Error(E);
12111 
12112   DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
12113   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
12114     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
12115 
12116   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
12117           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
12118          "DataRecursiveIntBinOpEvaluator should have handled integral types");
12119 
12120   if (E->isComparisonOp()) {
12121     // Evaluate builtin binary comparisons by evaluating them as three-way
12122     // comparisons and then translating the result.
12123     auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12124       assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
12125              "should only produce Unequal for equality comparisons");
12126       bool IsEqual   = CR == CmpResult::Equal,
12127            IsLess    = CR == CmpResult::Less,
12128            IsGreater = CR == CmpResult::Greater;
12129       auto Op = E->getOpcode();
12130       switch (Op) {
12131       default:
12132         llvm_unreachable("unsupported binary operator");
12133       case BO_EQ:
12134       case BO_NE:
12135         return Success(IsEqual == (Op == BO_EQ), E);
12136       case BO_LT:
12137         return Success(IsLess, E);
12138       case BO_GT:
12139         return Success(IsGreater, E);
12140       case BO_LE:
12141         return Success(IsEqual || IsLess, E);
12142       case BO_GE:
12143         return Success(IsEqual || IsGreater, E);
12144       }
12145     };
12146     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12147       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12148     });
12149   }
12150 
12151   QualType LHSTy = E->getLHS()->getType();
12152   QualType RHSTy = E->getRHS()->getType();
12153 
12154   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
12155       E->getOpcode() == BO_Sub) {
12156     LValue LHSValue, RHSValue;
12157 
12158     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12159     if (!LHSOK && !Info.noteFailure())
12160       return false;
12161 
12162     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12163       return false;
12164 
12165     // Reject differing bases from the normal codepath; we special-case
12166     // comparisons to null.
12167     if (!HasSameBase(LHSValue, RHSValue)) {
12168       // Handle &&A - &&B.
12169       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
12170         return Error(E);
12171       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
12172       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
12173       if (!LHSExpr || !RHSExpr)
12174         return Error(E);
12175       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12176       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12177       if (!LHSAddrExpr || !RHSAddrExpr)
12178         return Error(E);
12179       // Make sure both labels come from the same function.
12180       if (LHSAddrExpr->getLabel()->getDeclContext() !=
12181           RHSAddrExpr->getLabel()->getDeclContext())
12182         return Error(E);
12183       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
12184     }
12185     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12186     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12187 
12188     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12189     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12190 
12191     // C++11 [expr.add]p6:
12192     //   Unless both pointers point to elements of the same array object, or
12193     //   one past the last element of the array object, the behavior is
12194     //   undefined.
12195     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
12196         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
12197                                 RHSDesignator))
12198       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
12199 
12200     QualType Type = E->getLHS()->getType();
12201     QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
12202 
12203     CharUnits ElementSize;
12204     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
12205       return false;
12206 
12207     // As an extension, a type may have zero size (empty struct or union in
12208     // C, array of zero length). Pointer subtraction in such cases has
12209     // undefined behavior, so is not constant.
12210     if (ElementSize.isZero()) {
12211       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
12212           << ElementType;
12213       return false;
12214     }
12215 
12216     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
12217     // and produce incorrect results when it overflows. Such behavior
12218     // appears to be non-conforming, but is common, so perhaps we should
12219     // assume the standard intended for such cases to be undefined behavior
12220     // and check for them.
12221 
12222     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
12223     // overflow in the final conversion to ptrdiff_t.
12224     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
12225     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
12226     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
12227                     false);
12228     APSInt TrueResult = (LHS - RHS) / ElemSize;
12229     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
12230 
12231     if (Result.extend(65) != TrueResult &&
12232         !HandleOverflow(Info, E, TrueResult, E->getType()))
12233       return false;
12234     return Success(Result, E);
12235   }
12236 
12237   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12238 }
12239 
12240 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
12241 /// a result as the expression's type.
12242 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
12243                                     const UnaryExprOrTypeTraitExpr *E) {
12244   switch(E->getKind()) {
12245   case UETT_PreferredAlignOf:
12246   case UETT_AlignOf: {
12247     if (E->isArgumentType())
12248       return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
12249                      E);
12250     else
12251       return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
12252                      E);
12253   }
12254 
12255   case UETT_VecStep: {
12256     QualType Ty = E->getTypeOfArgument();
12257 
12258     if (Ty->isVectorType()) {
12259       unsigned n = Ty->castAs<VectorType>()->getNumElements();
12260 
12261       // The vec_step built-in functions that take a 3-component
12262       // vector return 4. (OpenCL 1.1 spec 6.11.12)
12263       if (n == 3)
12264         n = 4;
12265 
12266       return Success(n, E);
12267     } else
12268       return Success(1, E);
12269   }
12270 
12271   case UETT_SizeOf: {
12272     QualType SrcTy = E->getTypeOfArgument();
12273     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
12274     //   the result is the size of the referenced type."
12275     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
12276       SrcTy = Ref->getPointeeType();
12277 
12278     CharUnits Sizeof;
12279     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
12280       return false;
12281     return Success(Sizeof, E);
12282   }
12283   case UETT_OpenMPRequiredSimdAlign:
12284     assert(E->isArgumentType());
12285     return Success(
12286         Info.Ctx.toCharUnitsFromBits(
12287                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
12288             .getQuantity(),
12289         E);
12290   }
12291 
12292   llvm_unreachable("unknown expr/type trait");
12293 }
12294 
12295 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
12296   CharUnits Result;
12297   unsigned n = OOE->getNumComponents();
12298   if (n == 0)
12299     return Error(OOE);
12300   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
12301   for (unsigned i = 0; i != n; ++i) {
12302     OffsetOfNode ON = OOE->getComponent(i);
12303     switch (ON.getKind()) {
12304     case OffsetOfNode::Array: {
12305       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
12306       APSInt IdxResult;
12307       if (!EvaluateInteger(Idx, IdxResult, Info))
12308         return false;
12309       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
12310       if (!AT)
12311         return Error(OOE);
12312       CurrentType = AT->getElementType();
12313       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
12314       Result += IdxResult.getSExtValue() * ElementSize;
12315       break;
12316     }
12317 
12318     case OffsetOfNode::Field: {
12319       FieldDecl *MemberDecl = ON.getField();
12320       const RecordType *RT = CurrentType->getAs<RecordType>();
12321       if (!RT)
12322         return Error(OOE);
12323       RecordDecl *RD = RT->getDecl();
12324       if (RD->isInvalidDecl()) return false;
12325       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
12326       unsigned i = MemberDecl->getFieldIndex();
12327       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
12328       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
12329       CurrentType = MemberDecl->getType().getNonReferenceType();
12330       break;
12331     }
12332 
12333     case OffsetOfNode::Identifier:
12334       llvm_unreachable("dependent __builtin_offsetof");
12335 
12336     case OffsetOfNode::Base: {
12337       CXXBaseSpecifier *BaseSpec = ON.getBase();
12338       if (BaseSpec->isVirtual())
12339         return Error(OOE);
12340 
12341       // Find the layout of the class whose base we are looking into.
12342       const RecordType *RT = CurrentType->getAs<RecordType>();
12343       if (!RT)
12344         return Error(OOE);
12345       RecordDecl *RD = RT->getDecl();
12346       if (RD->isInvalidDecl()) return false;
12347       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
12348 
12349       // Find the base class itself.
12350       CurrentType = BaseSpec->getType();
12351       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
12352       if (!BaseRT)
12353         return Error(OOE);
12354 
12355       // Add the offset to the base.
12356       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
12357       break;
12358     }
12359     }
12360   }
12361   return Success(Result, OOE);
12362 }
12363 
12364 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12365   switch (E->getOpcode()) {
12366   default:
12367     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
12368     // See C99 6.6p3.
12369     return Error(E);
12370   case UO_Extension:
12371     // FIXME: Should extension allow i-c-e extension expressions in its scope?
12372     // If so, we could clear the diagnostic ID.
12373     return Visit(E->getSubExpr());
12374   case UO_Plus:
12375     // The result is just the value.
12376     return Visit(E->getSubExpr());
12377   case UO_Minus: {
12378     if (!Visit(E->getSubExpr()))
12379       return false;
12380     if (!Result.isInt()) return Error(E);
12381     const APSInt &Value = Result.getInt();
12382     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
12383         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
12384                         E->getType()))
12385       return false;
12386     return Success(-Value, E);
12387   }
12388   case UO_Not: {
12389     if (!Visit(E->getSubExpr()))
12390       return false;
12391     if (!Result.isInt()) return Error(E);
12392     return Success(~Result.getInt(), E);
12393   }
12394   case UO_LNot: {
12395     bool bres;
12396     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
12397       return false;
12398     return Success(!bres, E);
12399   }
12400   }
12401 }
12402 
12403 /// HandleCast - This is used to evaluate implicit or explicit casts where the
12404 /// result type is integer.
12405 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
12406   const Expr *SubExpr = E->getSubExpr();
12407   QualType DestType = E->getType();
12408   QualType SrcType = SubExpr->getType();
12409 
12410   switch (E->getCastKind()) {
12411   case CK_BaseToDerived:
12412   case CK_DerivedToBase:
12413   case CK_UncheckedDerivedToBase:
12414   case CK_Dynamic:
12415   case CK_ToUnion:
12416   case CK_ArrayToPointerDecay:
12417   case CK_FunctionToPointerDecay:
12418   case CK_NullToPointer:
12419   case CK_NullToMemberPointer:
12420   case CK_BaseToDerivedMemberPointer:
12421   case CK_DerivedToBaseMemberPointer:
12422   case CK_ReinterpretMemberPointer:
12423   case CK_ConstructorConversion:
12424   case CK_IntegralToPointer:
12425   case CK_ToVoid:
12426   case CK_VectorSplat:
12427   case CK_IntegralToFloating:
12428   case CK_FloatingCast:
12429   case CK_CPointerToObjCPointerCast:
12430   case CK_BlockPointerToObjCPointerCast:
12431   case CK_AnyPointerToBlockPointerCast:
12432   case CK_ObjCObjectLValueCast:
12433   case CK_FloatingRealToComplex:
12434   case CK_FloatingComplexToReal:
12435   case CK_FloatingComplexCast:
12436   case CK_FloatingComplexToIntegralComplex:
12437   case CK_IntegralRealToComplex:
12438   case CK_IntegralComplexCast:
12439   case CK_IntegralComplexToFloatingComplex:
12440   case CK_BuiltinFnToFnPtr:
12441   case CK_ZeroToOCLOpaqueType:
12442   case CK_NonAtomicToAtomic:
12443   case CK_AddressSpaceConversion:
12444   case CK_IntToOCLSampler:
12445   case CK_FixedPointCast:
12446   case CK_IntegralToFixedPoint:
12447     llvm_unreachable("invalid cast kind for integral value");
12448 
12449   case CK_BitCast:
12450   case CK_Dependent:
12451   case CK_LValueBitCast:
12452   case CK_ARCProduceObject:
12453   case CK_ARCConsumeObject:
12454   case CK_ARCReclaimReturnedObject:
12455   case CK_ARCExtendBlockObject:
12456   case CK_CopyAndAutoreleaseBlockObject:
12457     return Error(E);
12458 
12459   case CK_UserDefinedConversion:
12460   case CK_LValueToRValue:
12461   case CK_AtomicToNonAtomic:
12462   case CK_NoOp:
12463   case CK_LValueToRValueBitCast:
12464     return ExprEvaluatorBaseTy::VisitCastExpr(E);
12465 
12466   case CK_MemberPointerToBoolean:
12467   case CK_PointerToBoolean:
12468   case CK_IntegralToBoolean:
12469   case CK_FloatingToBoolean:
12470   case CK_BooleanToSignedIntegral:
12471   case CK_FloatingComplexToBoolean:
12472   case CK_IntegralComplexToBoolean: {
12473     bool BoolResult;
12474     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
12475       return false;
12476     uint64_t IntResult = BoolResult;
12477     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
12478       IntResult = (uint64_t)-1;
12479     return Success(IntResult, E);
12480   }
12481 
12482   case CK_FixedPointToIntegral: {
12483     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
12484     if (!EvaluateFixedPoint(SubExpr, Src, Info))
12485       return false;
12486     bool Overflowed;
12487     llvm::APSInt Result = Src.convertToInt(
12488         Info.Ctx.getIntWidth(DestType),
12489         DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
12490     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
12491       return false;
12492     return Success(Result, E);
12493   }
12494 
12495   case CK_FixedPointToBoolean: {
12496     // Unsigned padding does not affect this.
12497     APValue Val;
12498     if (!Evaluate(Val, Info, SubExpr))
12499       return false;
12500     return Success(Val.getFixedPoint().getBoolValue(), E);
12501   }
12502 
12503   case CK_IntegralCast: {
12504     if (!Visit(SubExpr))
12505       return false;
12506 
12507     if (!Result.isInt()) {
12508       // Allow casts of address-of-label differences if they are no-ops
12509       // or narrowing.  (The narrowing case isn't actually guaranteed to
12510       // be constant-evaluatable except in some narrow cases which are hard
12511       // to detect here.  We let it through on the assumption the user knows
12512       // what they are doing.)
12513       if (Result.isAddrLabelDiff())
12514         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
12515       // Only allow casts of lvalues if they are lossless.
12516       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
12517     }
12518 
12519     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
12520                                       Result.getInt()), E);
12521   }
12522 
12523   case CK_PointerToIntegral: {
12524     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
12525 
12526     LValue LV;
12527     if (!EvaluatePointer(SubExpr, LV, Info))
12528       return false;
12529 
12530     if (LV.getLValueBase()) {
12531       // Only allow based lvalue casts if they are lossless.
12532       // FIXME: Allow a larger integer size than the pointer size, and allow
12533       // narrowing back down to pointer width in subsequent integral casts.
12534       // FIXME: Check integer type's active bits, not its type size.
12535       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
12536         return Error(E);
12537 
12538       LV.Designator.setInvalid();
12539       LV.moveInto(Result);
12540       return true;
12541     }
12542 
12543     APSInt AsInt;
12544     APValue V;
12545     LV.moveInto(V);
12546     if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
12547       llvm_unreachable("Can't cast this!");
12548 
12549     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
12550   }
12551 
12552   case CK_IntegralComplexToReal: {
12553     ComplexValue C;
12554     if (!EvaluateComplex(SubExpr, C, Info))
12555       return false;
12556     return Success(C.getComplexIntReal(), E);
12557   }
12558 
12559   case CK_FloatingToIntegral: {
12560     APFloat F(0.0);
12561     if (!EvaluateFloat(SubExpr, F, Info))
12562       return false;
12563 
12564     APSInt Value;
12565     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
12566       return false;
12567     return Success(Value, E);
12568   }
12569   }
12570 
12571   llvm_unreachable("unknown cast resulting in integral value");
12572 }
12573 
12574 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
12575   if (E->getSubExpr()->getType()->isAnyComplexType()) {
12576     ComplexValue LV;
12577     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
12578       return false;
12579     if (!LV.isComplexInt())
12580       return Error(E);
12581     return Success(LV.getComplexIntReal(), E);
12582   }
12583 
12584   return Visit(E->getSubExpr());
12585 }
12586 
12587 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
12588   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
12589     ComplexValue LV;
12590     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
12591       return false;
12592     if (!LV.isComplexInt())
12593       return Error(E);
12594     return Success(LV.getComplexIntImag(), E);
12595   }
12596 
12597   VisitIgnoredValue(E->getSubExpr());
12598   return Success(0, E);
12599 }
12600 
12601 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
12602   return Success(E->getPackLength(), E);
12603 }
12604 
12605 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
12606   return Success(E->getValue(), E);
12607 }
12608 
12609 bool IntExprEvaluator::VisitConceptSpecializationExpr(
12610        const ConceptSpecializationExpr *E) {
12611   return Success(E->isSatisfied(), E);
12612 }
12613 
12614 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
12615   return Success(E->isSatisfied(), E);
12616 }
12617 
12618 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12619   switch (E->getOpcode()) {
12620     default:
12621       // Invalid unary operators
12622       return Error(E);
12623     case UO_Plus:
12624       // The result is just the value.
12625       return Visit(E->getSubExpr());
12626     case UO_Minus: {
12627       if (!Visit(E->getSubExpr())) return false;
12628       if (!Result.isFixedPoint())
12629         return Error(E);
12630       bool Overflowed;
12631       APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
12632       if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
12633         return false;
12634       return Success(Negated, E);
12635     }
12636     case UO_LNot: {
12637       bool bres;
12638       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
12639         return false;
12640       return Success(!bres, E);
12641     }
12642   }
12643 }
12644 
12645 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
12646   const Expr *SubExpr = E->getSubExpr();
12647   QualType DestType = E->getType();
12648   assert(DestType->isFixedPointType() &&
12649          "Expected destination type to be a fixed point type");
12650   auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
12651 
12652   switch (E->getCastKind()) {
12653   case CK_FixedPointCast: {
12654     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
12655     if (!EvaluateFixedPoint(SubExpr, Src, Info))
12656       return false;
12657     bool Overflowed;
12658     APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
12659     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
12660       return false;
12661     return Success(Result, E);
12662   }
12663   case CK_IntegralToFixedPoint: {
12664     APSInt Src;
12665     if (!EvaluateInteger(SubExpr, Src, Info))
12666       return false;
12667 
12668     bool Overflowed;
12669     APFixedPoint IntResult = APFixedPoint::getFromIntValue(
12670         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
12671 
12672     if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType))
12673       return false;
12674 
12675     return Success(IntResult, E);
12676   }
12677   case CK_NoOp:
12678   case CK_LValueToRValue:
12679     return ExprEvaluatorBaseTy::VisitCastExpr(E);
12680   default:
12681     return Error(E);
12682   }
12683 }
12684 
12685 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12686   const Expr *LHS = E->getLHS();
12687   const Expr *RHS = E->getRHS();
12688   FixedPointSemantics ResultFXSema =
12689       Info.Ctx.getFixedPointSemantics(E->getType());
12690 
12691   APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
12692   if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
12693     return false;
12694   APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
12695   if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
12696     return false;
12697 
12698   switch (E->getOpcode()) {
12699   case BO_Add: {
12700     bool AddOverflow, ConversionOverflow;
12701     APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow)
12702                               .convert(ResultFXSema, &ConversionOverflow);
12703     if ((AddOverflow || ConversionOverflow) &&
12704         !HandleOverflow(Info, E, Result, E->getType()))
12705       return false;
12706     return Success(Result, E);
12707   }
12708   default:
12709     return false;
12710   }
12711   llvm_unreachable("Should've exited before this");
12712 }
12713 
12714 //===----------------------------------------------------------------------===//
12715 // Float Evaluation
12716 //===----------------------------------------------------------------------===//
12717 
12718 namespace {
12719 class FloatExprEvaluator
12720   : public ExprEvaluatorBase<FloatExprEvaluator> {
12721   APFloat &Result;
12722 public:
12723   FloatExprEvaluator(EvalInfo &info, APFloat &result)
12724     : ExprEvaluatorBaseTy(info), Result(result) {}
12725 
12726   bool Success(const APValue &V, const Expr *e) {
12727     Result = V.getFloat();
12728     return true;
12729   }
12730 
12731   bool ZeroInitialization(const Expr *E) {
12732     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
12733     return true;
12734   }
12735 
12736   bool VisitCallExpr(const CallExpr *E);
12737 
12738   bool VisitUnaryOperator(const UnaryOperator *E);
12739   bool VisitBinaryOperator(const BinaryOperator *E);
12740   bool VisitFloatingLiteral(const FloatingLiteral *E);
12741   bool VisitCastExpr(const CastExpr *E);
12742 
12743   bool VisitUnaryReal(const UnaryOperator *E);
12744   bool VisitUnaryImag(const UnaryOperator *E);
12745 
12746   // FIXME: Missing: array subscript of vector, member of vector
12747 };
12748 } // end anonymous namespace
12749 
12750 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
12751   assert(E->isRValue() && E->getType()->isRealFloatingType());
12752   return FloatExprEvaluator(Info, Result).Visit(E);
12753 }
12754 
12755 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
12756                                   QualType ResultTy,
12757                                   const Expr *Arg,
12758                                   bool SNaN,
12759                                   llvm::APFloat &Result) {
12760   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
12761   if (!S) return false;
12762 
12763   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
12764 
12765   llvm::APInt fill;
12766 
12767   // Treat empty strings as if they were zero.
12768   if (S->getString().empty())
12769     fill = llvm::APInt(32, 0);
12770   else if (S->getString().getAsInteger(0, fill))
12771     return false;
12772 
12773   if (Context.getTargetInfo().isNan2008()) {
12774     if (SNaN)
12775       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
12776     else
12777       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
12778   } else {
12779     // Prior to IEEE 754-2008, architectures were allowed to choose whether
12780     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
12781     // a different encoding to what became a standard in 2008, and for pre-
12782     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
12783     // sNaN. This is now known as "legacy NaN" encoding.
12784     if (SNaN)
12785       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
12786     else
12787       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
12788   }
12789 
12790   return true;
12791 }
12792 
12793 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
12794   switch (E->getBuiltinCallee()) {
12795   default:
12796     return ExprEvaluatorBaseTy::VisitCallExpr(E);
12797 
12798   case Builtin::BI__builtin_huge_val:
12799   case Builtin::BI__builtin_huge_valf:
12800   case Builtin::BI__builtin_huge_vall:
12801   case Builtin::BI__builtin_huge_valf128:
12802   case Builtin::BI__builtin_inf:
12803   case Builtin::BI__builtin_inff:
12804   case Builtin::BI__builtin_infl:
12805   case Builtin::BI__builtin_inff128: {
12806     const llvm::fltSemantics &Sem =
12807       Info.Ctx.getFloatTypeSemantics(E->getType());
12808     Result = llvm::APFloat::getInf(Sem);
12809     return true;
12810   }
12811 
12812   case Builtin::BI__builtin_nans:
12813   case Builtin::BI__builtin_nansf:
12814   case Builtin::BI__builtin_nansl:
12815   case Builtin::BI__builtin_nansf128:
12816     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
12817                                true, Result))
12818       return Error(E);
12819     return true;
12820 
12821   case Builtin::BI__builtin_nan:
12822   case Builtin::BI__builtin_nanf:
12823   case Builtin::BI__builtin_nanl:
12824   case Builtin::BI__builtin_nanf128:
12825     // If this is __builtin_nan() turn this into a nan, otherwise we
12826     // can't constant fold it.
12827     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
12828                                false, Result))
12829       return Error(E);
12830     return true;
12831 
12832   case Builtin::BI__builtin_fabs:
12833   case Builtin::BI__builtin_fabsf:
12834   case Builtin::BI__builtin_fabsl:
12835   case Builtin::BI__builtin_fabsf128:
12836     if (!EvaluateFloat(E->getArg(0), Result, Info))
12837       return false;
12838 
12839     if (Result.isNegative())
12840       Result.changeSign();
12841     return true;
12842 
12843   // FIXME: Builtin::BI__builtin_powi
12844   // FIXME: Builtin::BI__builtin_powif
12845   // FIXME: Builtin::BI__builtin_powil
12846 
12847   case Builtin::BI__builtin_copysign:
12848   case Builtin::BI__builtin_copysignf:
12849   case Builtin::BI__builtin_copysignl:
12850   case Builtin::BI__builtin_copysignf128: {
12851     APFloat RHS(0.);
12852     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
12853         !EvaluateFloat(E->getArg(1), RHS, Info))
12854       return false;
12855     Result.copySign(RHS);
12856     return true;
12857   }
12858   }
12859 }
12860 
12861 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
12862   if (E->getSubExpr()->getType()->isAnyComplexType()) {
12863     ComplexValue CV;
12864     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
12865       return false;
12866     Result = CV.FloatReal;
12867     return true;
12868   }
12869 
12870   return Visit(E->getSubExpr());
12871 }
12872 
12873 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
12874   if (E->getSubExpr()->getType()->isAnyComplexType()) {
12875     ComplexValue CV;
12876     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
12877       return false;
12878     Result = CV.FloatImag;
12879     return true;
12880   }
12881 
12882   VisitIgnoredValue(E->getSubExpr());
12883   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
12884   Result = llvm::APFloat::getZero(Sem);
12885   return true;
12886 }
12887 
12888 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12889   switch (E->getOpcode()) {
12890   default: return Error(E);
12891   case UO_Plus:
12892     return EvaluateFloat(E->getSubExpr(), Result, Info);
12893   case UO_Minus:
12894     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
12895       return false;
12896     Result.changeSign();
12897     return true;
12898   }
12899 }
12900 
12901 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12902   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
12903     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12904 
12905   APFloat RHS(0.0);
12906   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
12907   if (!LHSOK && !Info.noteFailure())
12908     return false;
12909   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
12910          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
12911 }
12912 
12913 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
12914   Result = E->getValue();
12915   return true;
12916 }
12917 
12918 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
12919   const Expr* SubExpr = E->getSubExpr();
12920 
12921   switch (E->getCastKind()) {
12922   default:
12923     return ExprEvaluatorBaseTy::VisitCastExpr(E);
12924 
12925   case CK_IntegralToFloating: {
12926     APSInt IntResult;
12927     return EvaluateInteger(SubExpr, IntResult, Info) &&
12928            HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
12929                                 E->getType(), Result);
12930   }
12931 
12932   case CK_FloatingCast: {
12933     if (!Visit(SubExpr))
12934       return false;
12935     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
12936                                   Result);
12937   }
12938 
12939   case CK_FloatingComplexToReal: {
12940     ComplexValue V;
12941     if (!EvaluateComplex(SubExpr, V, Info))
12942       return false;
12943     Result = V.getComplexFloatReal();
12944     return true;
12945   }
12946   }
12947 }
12948 
12949 //===----------------------------------------------------------------------===//
12950 // Complex Evaluation (for float and integer)
12951 //===----------------------------------------------------------------------===//
12952 
12953 namespace {
12954 class ComplexExprEvaluator
12955   : public ExprEvaluatorBase<ComplexExprEvaluator> {
12956   ComplexValue &Result;
12957 
12958 public:
12959   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
12960     : ExprEvaluatorBaseTy(info), Result(Result) {}
12961 
12962   bool Success(const APValue &V, const Expr *e) {
12963     Result.setFrom(V);
12964     return true;
12965   }
12966 
12967   bool ZeroInitialization(const Expr *E);
12968 
12969   //===--------------------------------------------------------------------===//
12970   //                            Visitor Methods
12971   //===--------------------------------------------------------------------===//
12972 
12973   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
12974   bool VisitCastExpr(const CastExpr *E);
12975   bool VisitBinaryOperator(const BinaryOperator *E);
12976   bool VisitUnaryOperator(const UnaryOperator *E);
12977   bool VisitInitListExpr(const InitListExpr *E);
12978 };
12979 } // end anonymous namespace
12980 
12981 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
12982                             EvalInfo &Info) {
12983   assert(E->isRValue() && E->getType()->isAnyComplexType());
12984   return ComplexExprEvaluator(Info, Result).Visit(E);
12985 }
12986 
12987 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
12988   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
12989   if (ElemTy->isRealFloatingType()) {
12990     Result.makeComplexFloat();
12991     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
12992     Result.FloatReal = Zero;
12993     Result.FloatImag = Zero;
12994   } else {
12995     Result.makeComplexInt();
12996     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
12997     Result.IntReal = Zero;
12998     Result.IntImag = Zero;
12999   }
13000   return true;
13001 }
13002 
13003 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
13004   const Expr* SubExpr = E->getSubExpr();
13005 
13006   if (SubExpr->getType()->isRealFloatingType()) {
13007     Result.makeComplexFloat();
13008     APFloat &Imag = Result.FloatImag;
13009     if (!EvaluateFloat(SubExpr, Imag, Info))
13010       return false;
13011 
13012     Result.FloatReal = APFloat(Imag.getSemantics());
13013     return true;
13014   } else {
13015     assert(SubExpr->getType()->isIntegerType() &&
13016            "Unexpected imaginary literal.");
13017 
13018     Result.makeComplexInt();
13019     APSInt &Imag = Result.IntImag;
13020     if (!EvaluateInteger(SubExpr, Imag, Info))
13021       return false;
13022 
13023     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
13024     return true;
13025   }
13026 }
13027 
13028 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
13029 
13030   switch (E->getCastKind()) {
13031   case CK_BitCast:
13032   case CK_BaseToDerived:
13033   case CK_DerivedToBase:
13034   case CK_UncheckedDerivedToBase:
13035   case CK_Dynamic:
13036   case CK_ToUnion:
13037   case CK_ArrayToPointerDecay:
13038   case CK_FunctionToPointerDecay:
13039   case CK_NullToPointer:
13040   case CK_NullToMemberPointer:
13041   case CK_BaseToDerivedMemberPointer:
13042   case CK_DerivedToBaseMemberPointer:
13043   case CK_MemberPointerToBoolean:
13044   case CK_ReinterpretMemberPointer:
13045   case CK_ConstructorConversion:
13046   case CK_IntegralToPointer:
13047   case CK_PointerToIntegral:
13048   case CK_PointerToBoolean:
13049   case CK_ToVoid:
13050   case CK_VectorSplat:
13051   case CK_IntegralCast:
13052   case CK_BooleanToSignedIntegral:
13053   case CK_IntegralToBoolean:
13054   case CK_IntegralToFloating:
13055   case CK_FloatingToIntegral:
13056   case CK_FloatingToBoolean:
13057   case CK_FloatingCast:
13058   case CK_CPointerToObjCPointerCast:
13059   case CK_BlockPointerToObjCPointerCast:
13060   case CK_AnyPointerToBlockPointerCast:
13061   case CK_ObjCObjectLValueCast:
13062   case CK_FloatingComplexToReal:
13063   case CK_FloatingComplexToBoolean:
13064   case CK_IntegralComplexToReal:
13065   case CK_IntegralComplexToBoolean:
13066   case CK_ARCProduceObject:
13067   case CK_ARCConsumeObject:
13068   case CK_ARCReclaimReturnedObject:
13069   case CK_ARCExtendBlockObject:
13070   case CK_CopyAndAutoreleaseBlockObject:
13071   case CK_BuiltinFnToFnPtr:
13072   case CK_ZeroToOCLOpaqueType:
13073   case CK_NonAtomicToAtomic:
13074   case CK_AddressSpaceConversion:
13075   case CK_IntToOCLSampler:
13076   case CK_FixedPointCast:
13077   case CK_FixedPointToBoolean:
13078   case CK_FixedPointToIntegral:
13079   case CK_IntegralToFixedPoint:
13080     llvm_unreachable("invalid cast kind for complex value");
13081 
13082   case CK_LValueToRValue:
13083   case CK_AtomicToNonAtomic:
13084   case CK_NoOp:
13085   case CK_LValueToRValueBitCast:
13086     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13087 
13088   case CK_Dependent:
13089   case CK_LValueBitCast:
13090   case CK_UserDefinedConversion:
13091     return Error(E);
13092 
13093   case CK_FloatingRealToComplex: {
13094     APFloat &Real = Result.FloatReal;
13095     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
13096       return false;
13097 
13098     Result.makeComplexFloat();
13099     Result.FloatImag = APFloat(Real.getSemantics());
13100     return true;
13101   }
13102 
13103   case CK_FloatingComplexCast: {
13104     if (!Visit(E->getSubExpr()))
13105       return false;
13106 
13107     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13108     QualType From
13109       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13110 
13111     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
13112            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
13113   }
13114 
13115   case CK_FloatingComplexToIntegralComplex: {
13116     if (!Visit(E->getSubExpr()))
13117       return false;
13118 
13119     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13120     QualType From
13121       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13122     Result.makeComplexInt();
13123     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
13124                                 To, Result.IntReal) &&
13125            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
13126                                 To, Result.IntImag);
13127   }
13128 
13129   case CK_IntegralRealToComplex: {
13130     APSInt &Real = Result.IntReal;
13131     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
13132       return false;
13133 
13134     Result.makeComplexInt();
13135     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
13136     return true;
13137   }
13138 
13139   case CK_IntegralComplexCast: {
13140     if (!Visit(E->getSubExpr()))
13141       return false;
13142 
13143     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13144     QualType From
13145       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13146 
13147     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
13148     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
13149     return true;
13150   }
13151 
13152   case CK_IntegralComplexToFloatingComplex: {
13153     if (!Visit(E->getSubExpr()))
13154       return false;
13155 
13156     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13157     QualType From
13158       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13159     Result.makeComplexFloat();
13160     return HandleIntToFloatCast(Info, E, From, Result.IntReal,
13161                                 To, Result.FloatReal) &&
13162            HandleIntToFloatCast(Info, E, From, Result.IntImag,
13163                                 To, Result.FloatImag);
13164   }
13165   }
13166 
13167   llvm_unreachable("unknown cast resulting in complex value");
13168 }
13169 
13170 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13171   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13172     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13173 
13174   // Track whether the LHS or RHS is real at the type system level. When this is
13175   // the case we can simplify our evaluation strategy.
13176   bool LHSReal = false, RHSReal = false;
13177 
13178   bool LHSOK;
13179   if (E->getLHS()->getType()->isRealFloatingType()) {
13180     LHSReal = true;
13181     APFloat &Real = Result.FloatReal;
13182     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
13183     if (LHSOK) {
13184       Result.makeComplexFloat();
13185       Result.FloatImag = APFloat(Real.getSemantics());
13186     }
13187   } else {
13188     LHSOK = Visit(E->getLHS());
13189   }
13190   if (!LHSOK && !Info.noteFailure())
13191     return false;
13192 
13193   ComplexValue RHS;
13194   if (E->getRHS()->getType()->isRealFloatingType()) {
13195     RHSReal = true;
13196     APFloat &Real = RHS.FloatReal;
13197     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
13198       return false;
13199     RHS.makeComplexFloat();
13200     RHS.FloatImag = APFloat(Real.getSemantics());
13201   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
13202     return false;
13203 
13204   assert(!(LHSReal && RHSReal) &&
13205          "Cannot have both operands of a complex operation be real.");
13206   switch (E->getOpcode()) {
13207   default: return Error(E);
13208   case BO_Add:
13209     if (Result.isComplexFloat()) {
13210       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
13211                                        APFloat::rmNearestTiesToEven);
13212       if (LHSReal)
13213         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
13214       else if (!RHSReal)
13215         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
13216                                          APFloat::rmNearestTiesToEven);
13217     } else {
13218       Result.getComplexIntReal() += RHS.getComplexIntReal();
13219       Result.getComplexIntImag() += RHS.getComplexIntImag();
13220     }
13221     break;
13222   case BO_Sub:
13223     if (Result.isComplexFloat()) {
13224       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
13225                                             APFloat::rmNearestTiesToEven);
13226       if (LHSReal) {
13227         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
13228         Result.getComplexFloatImag().changeSign();
13229       } else if (!RHSReal) {
13230         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
13231                                               APFloat::rmNearestTiesToEven);
13232       }
13233     } else {
13234       Result.getComplexIntReal() -= RHS.getComplexIntReal();
13235       Result.getComplexIntImag() -= RHS.getComplexIntImag();
13236     }
13237     break;
13238   case BO_Mul:
13239     if (Result.isComplexFloat()) {
13240       // This is an implementation of complex multiplication according to the
13241       // constraints laid out in C11 Annex G. The implementation uses the
13242       // following naming scheme:
13243       //   (a + ib) * (c + id)
13244       ComplexValue LHS = Result;
13245       APFloat &A = LHS.getComplexFloatReal();
13246       APFloat &B = LHS.getComplexFloatImag();
13247       APFloat &C = RHS.getComplexFloatReal();
13248       APFloat &D = RHS.getComplexFloatImag();
13249       APFloat &ResR = Result.getComplexFloatReal();
13250       APFloat &ResI = Result.getComplexFloatImag();
13251       if (LHSReal) {
13252         assert(!RHSReal && "Cannot have two real operands for a complex op!");
13253         ResR = A * C;
13254         ResI = A * D;
13255       } else if (RHSReal) {
13256         ResR = C * A;
13257         ResI = C * B;
13258       } else {
13259         // In the fully general case, we need to handle NaNs and infinities
13260         // robustly.
13261         APFloat AC = A * C;
13262         APFloat BD = B * D;
13263         APFloat AD = A * D;
13264         APFloat BC = B * C;
13265         ResR = AC - BD;
13266         ResI = AD + BC;
13267         if (ResR.isNaN() && ResI.isNaN()) {
13268           bool Recalc = false;
13269           if (A.isInfinity() || B.isInfinity()) {
13270             A = APFloat::copySign(
13271                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
13272             B = APFloat::copySign(
13273                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
13274             if (C.isNaN())
13275               C = APFloat::copySign(APFloat(C.getSemantics()), C);
13276             if (D.isNaN())
13277               D = APFloat::copySign(APFloat(D.getSemantics()), D);
13278             Recalc = true;
13279           }
13280           if (C.isInfinity() || D.isInfinity()) {
13281             C = APFloat::copySign(
13282                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
13283             D = APFloat::copySign(
13284                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
13285             if (A.isNaN())
13286               A = APFloat::copySign(APFloat(A.getSemantics()), A);
13287             if (B.isNaN())
13288               B = APFloat::copySign(APFloat(B.getSemantics()), B);
13289             Recalc = true;
13290           }
13291           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
13292                           AD.isInfinity() || BC.isInfinity())) {
13293             if (A.isNaN())
13294               A = APFloat::copySign(APFloat(A.getSemantics()), A);
13295             if (B.isNaN())
13296               B = APFloat::copySign(APFloat(B.getSemantics()), B);
13297             if (C.isNaN())
13298               C = APFloat::copySign(APFloat(C.getSemantics()), C);
13299             if (D.isNaN())
13300               D = APFloat::copySign(APFloat(D.getSemantics()), D);
13301             Recalc = true;
13302           }
13303           if (Recalc) {
13304             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
13305             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
13306           }
13307         }
13308       }
13309     } else {
13310       ComplexValue LHS = Result;
13311       Result.getComplexIntReal() =
13312         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
13313          LHS.getComplexIntImag() * RHS.getComplexIntImag());
13314       Result.getComplexIntImag() =
13315         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
13316          LHS.getComplexIntImag() * RHS.getComplexIntReal());
13317     }
13318     break;
13319   case BO_Div:
13320     if (Result.isComplexFloat()) {
13321       // This is an implementation of complex division according to the
13322       // constraints laid out in C11 Annex G. The implementation uses the
13323       // following naming scheme:
13324       //   (a + ib) / (c + id)
13325       ComplexValue LHS = Result;
13326       APFloat &A = LHS.getComplexFloatReal();
13327       APFloat &B = LHS.getComplexFloatImag();
13328       APFloat &C = RHS.getComplexFloatReal();
13329       APFloat &D = RHS.getComplexFloatImag();
13330       APFloat &ResR = Result.getComplexFloatReal();
13331       APFloat &ResI = Result.getComplexFloatImag();
13332       if (RHSReal) {
13333         ResR = A / C;
13334         ResI = B / C;
13335       } else {
13336         if (LHSReal) {
13337           // No real optimizations we can do here, stub out with zero.
13338           B = APFloat::getZero(A.getSemantics());
13339         }
13340         int DenomLogB = 0;
13341         APFloat MaxCD = maxnum(abs(C), abs(D));
13342         if (MaxCD.isFinite()) {
13343           DenomLogB = ilogb(MaxCD);
13344           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
13345           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
13346         }
13347         APFloat Denom = C * C + D * D;
13348         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
13349                       APFloat::rmNearestTiesToEven);
13350         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
13351                       APFloat::rmNearestTiesToEven);
13352         if (ResR.isNaN() && ResI.isNaN()) {
13353           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
13354             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
13355             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
13356           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
13357                      D.isFinite()) {
13358             A = APFloat::copySign(
13359                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
13360             B = APFloat::copySign(
13361                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
13362             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
13363             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
13364           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
13365             C = APFloat::copySign(
13366                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
13367             D = APFloat::copySign(
13368                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
13369             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
13370             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
13371           }
13372         }
13373       }
13374     } else {
13375       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
13376         return Error(E, diag::note_expr_divide_by_zero);
13377 
13378       ComplexValue LHS = Result;
13379       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
13380         RHS.getComplexIntImag() * RHS.getComplexIntImag();
13381       Result.getComplexIntReal() =
13382         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
13383          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
13384       Result.getComplexIntImag() =
13385         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
13386          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
13387     }
13388     break;
13389   }
13390 
13391   return true;
13392 }
13393 
13394 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13395   // Get the operand value into 'Result'.
13396   if (!Visit(E->getSubExpr()))
13397     return false;
13398 
13399   switch (E->getOpcode()) {
13400   default:
13401     return Error(E);
13402   case UO_Extension:
13403     return true;
13404   case UO_Plus:
13405     // The result is always just the subexpr.
13406     return true;
13407   case UO_Minus:
13408     if (Result.isComplexFloat()) {
13409       Result.getComplexFloatReal().changeSign();
13410       Result.getComplexFloatImag().changeSign();
13411     }
13412     else {
13413       Result.getComplexIntReal() = -Result.getComplexIntReal();
13414       Result.getComplexIntImag() = -Result.getComplexIntImag();
13415     }
13416     return true;
13417   case UO_Not:
13418     if (Result.isComplexFloat())
13419       Result.getComplexFloatImag().changeSign();
13420     else
13421       Result.getComplexIntImag() = -Result.getComplexIntImag();
13422     return true;
13423   }
13424 }
13425 
13426 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
13427   if (E->getNumInits() == 2) {
13428     if (E->getType()->isComplexType()) {
13429       Result.makeComplexFloat();
13430       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
13431         return false;
13432       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
13433         return false;
13434     } else {
13435       Result.makeComplexInt();
13436       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
13437         return false;
13438       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
13439         return false;
13440     }
13441     return true;
13442   }
13443   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
13444 }
13445 
13446 //===----------------------------------------------------------------------===//
13447 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
13448 // implicit conversion.
13449 //===----------------------------------------------------------------------===//
13450 
13451 namespace {
13452 class AtomicExprEvaluator :
13453     public ExprEvaluatorBase<AtomicExprEvaluator> {
13454   const LValue *This;
13455   APValue &Result;
13456 public:
13457   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
13458       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
13459 
13460   bool Success(const APValue &V, const Expr *E) {
13461     Result = V;
13462     return true;
13463   }
13464 
13465   bool ZeroInitialization(const Expr *E) {
13466     ImplicitValueInitExpr VIE(
13467         E->getType()->castAs<AtomicType>()->getValueType());
13468     // For atomic-qualified class (and array) types in C++, initialize the
13469     // _Atomic-wrapped subobject directly, in-place.
13470     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
13471                 : Evaluate(Result, Info, &VIE);
13472   }
13473 
13474   bool VisitCastExpr(const CastExpr *E) {
13475     switch (E->getCastKind()) {
13476     default:
13477       return ExprEvaluatorBaseTy::VisitCastExpr(E);
13478     case CK_NonAtomicToAtomic:
13479       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
13480                   : Evaluate(Result, Info, E->getSubExpr());
13481     }
13482   }
13483 };
13484 } // end anonymous namespace
13485 
13486 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
13487                            EvalInfo &Info) {
13488   assert(E->isRValue() && E->getType()->isAtomicType());
13489   return AtomicExprEvaluator(Info, This, Result).Visit(E);
13490 }
13491 
13492 //===----------------------------------------------------------------------===//
13493 // Void expression evaluation, primarily for a cast to void on the LHS of a
13494 // comma operator
13495 //===----------------------------------------------------------------------===//
13496 
13497 namespace {
13498 class VoidExprEvaluator
13499   : public ExprEvaluatorBase<VoidExprEvaluator> {
13500 public:
13501   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
13502 
13503   bool Success(const APValue &V, const Expr *e) { return true; }
13504 
13505   bool ZeroInitialization(const Expr *E) { return true; }
13506 
13507   bool VisitCastExpr(const CastExpr *E) {
13508     switch (E->getCastKind()) {
13509     default:
13510       return ExprEvaluatorBaseTy::VisitCastExpr(E);
13511     case CK_ToVoid:
13512       VisitIgnoredValue(E->getSubExpr());
13513       return true;
13514     }
13515   }
13516 
13517   bool VisitCallExpr(const CallExpr *E) {
13518     switch (E->getBuiltinCallee()) {
13519     case Builtin::BI__assume:
13520     case Builtin::BI__builtin_assume:
13521       // The argument is not evaluated!
13522       return true;
13523 
13524     case Builtin::BI__builtin_operator_delete:
13525       return HandleOperatorDeleteCall(Info, E);
13526 
13527     default:
13528       break;
13529     }
13530 
13531     return ExprEvaluatorBaseTy::VisitCallExpr(E);
13532   }
13533 
13534   bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
13535 };
13536 } // end anonymous namespace
13537 
13538 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
13539   // We cannot speculatively evaluate a delete expression.
13540   if (Info.SpeculativeEvaluationDepth)
13541     return false;
13542 
13543   FunctionDecl *OperatorDelete = E->getOperatorDelete();
13544   if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
13545     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
13546         << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
13547     return false;
13548   }
13549 
13550   const Expr *Arg = E->getArgument();
13551 
13552   LValue Pointer;
13553   if (!EvaluatePointer(Arg, Pointer, Info))
13554     return false;
13555   if (Pointer.Designator.Invalid)
13556     return false;
13557 
13558   // Deleting a null pointer has no effect.
13559   if (Pointer.isNullPointer()) {
13560     // This is the only case where we need to produce an extension warning:
13561     // the only other way we can succeed is if we find a dynamic allocation,
13562     // and we will have warned when we allocated it in that case.
13563     if (!Info.getLangOpts().CPlusPlus2a)
13564       Info.CCEDiag(E, diag::note_constexpr_new);
13565     return true;
13566   }
13567 
13568   Optional<DynAlloc *> Alloc = CheckDeleteKind(
13569       Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
13570   if (!Alloc)
13571     return false;
13572   QualType AllocType = Pointer.Base.getDynamicAllocType();
13573 
13574   // For the non-array case, the designator must be empty if the static type
13575   // does not have a virtual destructor.
13576   if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
13577       !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
13578     Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
13579         << Arg->getType()->getPointeeType() << AllocType;
13580     return false;
13581   }
13582 
13583   // For a class type with a virtual destructor, the selected operator delete
13584   // is the one looked up when building the destructor.
13585   if (!E->isArrayForm() && !E->isGlobalDelete()) {
13586     const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
13587     if (VirtualDelete &&
13588         !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
13589       Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
13590           << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
13591       return false;
13592     }
13593   }
13594 
13595   if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
13596                          (*Alloc)->Value, AllocType))
13597     return false;
13598 
13599   if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
13600     // The element was already erased. This means the destructor call also
13601     // deleted the object.
13602     // FIXME: This probably results in undefined behavior before we get this
13603     // far, and should be diagnosed elsewhere first.
13604     Info.FFDiag(E, diag::note_constexpr_double_delete);
13605     return false;
13606   }
13607 
13608   return true;
13609 }
13610 
13611 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
13612   assert(E->isRValue() && E->getType()->isVoidType());
13613   return VoidExprEvaluator(Info).Visit(E);
13614 }
13615 
13616 //===----------------------------------------------------------------------===//
13617 // Top level Expr::EvaluateAsRValue method.
13618 //===----------------------------------------------------------------------===//
13619 
13620 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
13621   // In C, function designators are not lvalues, but we evaluate them as if they
13622   // are.
13623   QualType T = E->getType();
13624   if (E->isGLValue() || T->isFunctionType()) {
13625     LValue LV;
13626     if (!EvaluateLValue(E, LV, Info))
13627       return false;
13628     LV.moveInto(Result);
13629   } else if (T->isVectorType()) {
13630     if (!EvaluateVector(E, Result, Info))
13631       return false;
13632   } else if (T->isIntegralOrEnumerationType()) {
13633     if (!IntExprEvaluator(Info, Result).Visit(E))
13634       return false;
13635   } else if (T->hasPointerRepresentation()) {
13636     LValue LV;
13637     if (!EvaluatePointer(E, LV, Info))
13638       return false;
13639     LV.moveInto(Result);
13640   } else if (T->isRealFloatingType()) {
13641     llvm::APFloat F(0.0);
13642     if (!EvaluateFloat(E, F, Info))
13643       return false;
13644     Result = APValue(F);
13645   } else if (T->isAnyComplexType()) {
13646     ComplexValue C;
13647     if (!EvaluateComplex(E, C, Info))
13648       return false;
13649     C.moveInto(Result);
13650   } else if (T->isFixedPointType()) {
13651     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
13652   } else if (T->isMemberPointerType()) {
13653     MemberPtr P;
13654     if (!EvaluateMemberPointer(E, P, Info))
13655       return false;
13656     P.moveInto(Result);
13657     return true;
13658   } else if (T->isArrayType()) {
13659     LValue LV;
13660     APValue &Value =
13661         Info.CurrentCall->createTemporary(E, T, false, LV);
13662     if (!EvaluateArray(E, LV, Value, Info))
13663       return false;
13664     Result = Value;
13665   } else if (T->isRecordType()) {
13666     LValue LV;
13667     APValue &Value = Info.CurrentCall->createTemporary(E, T, false, LV);
13668     if (!EvaluateRecord(E, LV, Value, Info))
13669       return false;
13670     Result = Value;
13671   } else if (T->isVoidType()) {
13672     if (!Info.getLangOpts().CPlusPlus11)
13673       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
13674         << E->getType();
13675     if (!EvaluateVoid(E, Info))
13676       return false;
13677   } else if (T->isAtomicType()) {
13678     QualType Unqual = T.getAtomicUnqualifiedType();
13679     if (Unqual->isArrayType() || Unqual->isRecordType()) {
13680       LValue LV;
13681       APValue &Value = Info.CurrentCall->createTemporary(E, Unqual, false, LV);
13682       if (!EvaluateAtomic(E, &LV, Value, Info))
13683         return false;
13684     } else {
13685       if (!EvaluateAtomic(E, nullptr, Result, Info))
13686         return false;
13687     }
13688   } else if (Info.getLangOpts().CPlusPlus11) {
13689     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
13690     return false;
13691   } else {
13692     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
13693     return false;
13694   }
13695 
13696   return true;
13697 }
13698 
13699 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
13700 /// cases, the in-place evaluation is essential, since later initializers for
13701 /// an object can indirectly refer to subobjects which were initialized earlier.
13702 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
13703                             const Expr *E, bool AllowNonLiteralTypes) {
13704   assert(!E->isValueDependent());
13705 
13706   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
13707     return false;
13708 
13709   if (E->isRValue()) {
13710     // Evaluate arrays and record types in-place, so that later initializers can
13711     // refer to earlier-initialized members of the object.
13712     QualType T = E->getType();
13713     if (T->isArrayType())
13714       return EvaluateArray(E, This, Result, Info);
13715     else if (T->isRecordType())
13716       return EvaluateRecord(E, This, Result, Info);
13717     else if (T->isAtomicType()) {
13718       QualType Unqual = T.getAtomicUnqualifiedType();
13719       if (Unqual->isArrayType() || Unqual->isRecordType())
13720         return EvaluateAtomic(E, &This, Result, Info);
13721     }
13722   }
13723 
13724   // For any other type, in-place evaluation is unimportant.
13725   return Evaluate(Result, Info, E);
13726 }
13727 
13728 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
13729 /// lvalue-to-rvalue cast if it is an lvalue.
13730 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
13731   if (Info.EnableNewConstInterp) {
13732     if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
13733       return false;
13734   } else {
13735     if (E->getType().isNull())
13736       return false;
13737 
13738     if (!CheckLiteralType(Info, E))
13739       return false;
13740 
13741     if (!::Evaluate(Result, Info, E))
13742       return false;
13743 
13744     if (E->isGLValue()) {
13745       LValue LV;
13746       LV.setFrom(Info.Ctx, Result);
13747       if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
13748         return false;
13749     }
13750   }
13751 
13752   // Check this core constant expression is a constant expression.
13753   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result) &&
13754          CheckMemoryLeaks(Info);
13755 }
13756 
13757 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
13758                                  const ASTContext &Ctx, bool &IsConst) {
13759   // Fast-path evaluations of integer literals, since we sometimes see files
13760   // containing vast quantities of these.
13761   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
13762     Result.Val = APValue(APSInt(L->getValue(),
13763                                 L->getType()->isUnsignedIntegerType()));
13764     IsConst = true;
13765     return true;
13766   }
13767 
13768   // This case should be rare, but we need to check it before we check on
13769   // the type below.
13770   if (Exp->getType().isNull()) {
13771     IsConst = false;
13772     return true;
13773   }
13774 
13775   // FIXME: Evaluating values of large array and record types can cause
13776   // performance problems. Only do so in C++11 for now.
13777   if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
13778                           Exp->getType()->isRecordType()) &&
13779       !Ctx.getLangOpts().CPlusPlus11) {
13780     IsConst = false;
13781     return true;
13782   }
13783   return false;
13784 }
13785 
13786 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
13787                                       Expr::SideEffectsKind SEK) {
13788   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
13789          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
13790 }
13791 
13792 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
13793                              const ASTContext &Ctx, EvalInfo &Info) {
13794   bool IsConst;
13795   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
13796     return IsConst;
13797 
13798   return EvaluateAsRValue(Info, E, Result.Val);
13799 }
13800 
13801 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
13802                           const ASTContext &Ctx,
13803                           Expr::SideEffectsKind AllowSideEffects,
13804                           EvalInfo &Info) {
13805   if (!E->getType()->isIntegralOrEnumerationType())
13806     return false;
13807 
13808   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
13809       !ExprResult.Val.isInt() ||
13810       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
13811     return false;
13812 
13813   return true;
13814 }
13815 
13816 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
13817                                  const ASTContext &Ctx,
13818                                  Expr::SideEffectsKind AllowSideEffects,
13819                                  EvalInfo &Info) {
13820   if (!E->getType()->isFixedPointType())
13821     return false;
13822 
13823   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
13824     return false;
13825 
13826   if (!ExprResult.Val.isFixedPoint() ||
13827       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
13828     return false;
13829 
13830   return true;
13831 }
13832 
13833 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
13834 /// any crazy technique (that has nothing to do with language standards) that
13835 /// we want to.  If this function returns true, it returns the folded constant
13836 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
13837 /// will be applied to the result.
13838 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
13839                             bool InConstantContext) const {
13840   assert(!isValueDependent() &&
13841          "Expression evaluator can't be called on a dependent expression.");
13842   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
13843   Info.InConstantContext = InConstantContext;
13844   return ::EvaluateAsRValue(this, Result, Ctx, Info);
13845 }
13846 
13847 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
13848                                       bool InConstantContext) const {
13849   assert(!isValueDependent() &&
13850          "Expression evaluator can't be called on a dependent expression.");
13851   EvalResult Scratch;
13852   return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
13853          HandleConversionToBool(Scratch.Val, Result);
13854 }
13855 
13856 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
13857                          SideEffectsKind AllowSideEffects,
13858                          bool InConstantContext) const {
13859   assert(!isValueDependent() &&
13860          "Expression evaluator can't be called on a dependent expression.");
13861   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
13862   Info.InConstantContext = InConstantContext;
13863   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
13864 }
13865 
13866 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
13867                                 SideEffectsKind AllowSideEffects,
13868                                 bool InConstantContext) const {
13869   assert(!isValueDependent() &&
13870          "Expression evaluator can't be called on a dependent expression.");
13871   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
13872   Info.InConstantContext = InConstantContext;
13873   return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
13874 }
13875 
13876 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
13877                            SideEffectsKind AllowSideEffects,
13878                            bool InConstantContext) const {
13879   assert(!isValueDependent() &&
13880          "Expression evaluator can't be called on a dependent expression.");
13881 
13882   if (!getType()->isRealFloatingType())
13883     return false;
13884 
13885   EvalResult ExprResult;
13886   if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
13887       !ExprResult.Val.isFloat() ||
13888       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
13889     return false;
13890 
13891   Result = ExprResult.Val.getFloat();
13892   return true;
13893 }
13894 
13895 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
13896                             bool InConstantContext) const {
13897   assert(!isValueDependent() &&
13898          "Expression evaluator can't be called on a dependent expression.");
13899 
13900   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
13901   Info.InConstantContext = InConstantContext;
13902   LValue LV;
13903   CheckedTemporaries CheckedTemps;
13904   if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
13905       Result.HasSideEffects ||
13906       !CheckLValueConstantExpression(Info, getExprLoc(),
13907                                      Ctx.getLValueReferenceType(getType()), LV,
13908                                      Expr::EvaluateForCodeGen, CheckedTemps))
13909     return false;
13910 
13911   LV.moveInto(Result.Val);
13912   return true;
13913 }
13914 
13915 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
13916                                   const ASTContext &Ctx, bool InPlace) const {
13917   assert(!isValueDependent() &&
13918          "Expression evaluator can't be called on a dependent expression.");
13919 
13920   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
13921   EvalInfo Info(Ctx, Result, EM);
13922   Info.InConstantContext = true;
13923 
13924   if (InPlace) {
13925     Info.setEvaluatingDecl(this, Result.Val);
13926     LValue LVal;
13927     LVal.set(this);
13928     if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
13929         Result.HasSideEffects)
13930       return false;
13931   } else if (!::Evaluate(Result.Val, Info, this) || Result.HasSideEffects)
13932     return false;
13933 
13934   if (!Info.discardCleanups())
13935     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
13936 
13937   return CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
13938                                  Result.Val, Usage) &&
13939          CheckMemoryLeaks(Info);
13940 }
13941 
13942 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
13943                                  const VarDecl *VD,
13944                             SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
13945   assert(!isValueDependent() &&
13946          "Expression evaluator can't be called on a dependent expression.");
13947 
13948   // FIXME: Evaluating initializers for large array and record types can cause
13949   // performance problems. Only do so in C++11 for now.
13950   if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
13951       !Ctx.getLangOpts().CPlusPlus11)
13952     return false;
13953 
13954   Expr::EvalStatus EStatus;
13955   EStatus.Diag = &Notes;
13956 
13957   EvalInfo Info(Ctx, EStatus, VD->isConstexpr()
13958                                       ? EvalInfo::EM_ConstantExpression
13959                                       : EvalInfo::EM_ConstantFold);
13960   Info.setEvaluatingDecl(VD, Value);
13961   Info.InConstantContext = true;
13962 
13963   SourceLocation DeclLoc = VD->getLocation();
13964   QualType DeclTy = VD->getType();
13965 
13966   if (Info.EnableNewConstInterp) {
13967     auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
13968     if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
13969       return false;
13970   } else {
13971     LValue LVal;
13972     LVal.set(VD);
13973 
13974     if (!EvaluateInPlace(Value, Info, LVal, this,
13975                          /*AllowNonLiteralTypes=*/true) ||
13976         EStatus.HasSideEffects)
13977       return false;
13978 
13979     // At this point, any lifetime-extended temporaries are completely
13980     // initialized.
13981     Info.performLifetimeExtension();
13982 
13983     if (!Info.discardCleanups())
13984       llvm_unreachable("Unhandled cleanup; missing full expression marker?");
13985   }
13986   return CheckConstantExpression(Info, DeclLoc, DeclTy, Value) &&
13987          CheckMemoryLeaks(Info);
13988 }
13989 
13990 bool VarDecl::evaluateDestruction(
13991     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
13992   Expr::EvalStatus EStatus;
13993   EStatus.Diag = &Notes;
13994 
13995   // Make a copy of the value for the destructor to mutate, if we know it.
13996   // Otherwise, treat the value as default-initialized; if the destructor works
13997   // anyway, then the destruction is constant (and must be essentially empty).
13998   APValue DestroyedValue =
13999       (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
14000           ? *getEvaluatedValue()
14001           : getDefaultInitValue(getType());
14002 
14003   EvalInfo Info(getASTContext(), EStatus, EvalInfo::EM_ConstantExpression);
14004   Info.setEvaluatingDecl(this, DestroyedValue,
14005                          EvalInfo::EvaluatingDeclKind::Dtor);
14006   Info.InConstantContext = true;
14007 
14008   SourceLocation DeclLoc = getLocation();
14009   QualType DeclTy = getType();
14010 
14011   LValue LVal;
14012   LVal.set(this);
14013 
14014   if (!HandleDestruction(Info, DeclLoc, LVal.Base, DestroyedValue, DeclTy) ||
14015       EStatus.HasSideEffects)
14016     return false;
14017 
14018   if (!Info.discardCleanups())
14019     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14020 
14021   ensureEvaluatedStmt()->HasConstantDestruction = true;
14022   return true;
14023 }
14024 
14025 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
14026 /// constant folded, but discard the result.
14027 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
14028   assert(!isValueDependent() &&
14029          "Expression evaluator can't be called on a dependent expression.");
14030 
14031   EvalResult Result;
14032   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
14033          !hasUnacceptableSideEffect(Result, SEK);
14034 }
14035 
14036 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
14037                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
14038   assert(!isValueDependent() &&
14039          "Expression evaluator can't be called on a dependent expression.");
14040 
14041   EvalResult EVResult;
14042   EVResult.Diag = Diag;
14043   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14044   Info.InConstantContext = true;
14045 
14046   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
14047   (void)Result;
14048   assert(Result && "Could not evaluate expression");
14049   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
14050 
14051   return EVResult.Val.getInt();
14052 }
14053 
14054 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
14055     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
14056   assert(!isValueDependent() &&
14057          "Expression evaluator can't be called on a dependent expression.");
14058 
14059   EvalResult EVResult;
14060   EVResult.Diag = Diag;
14061   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14062   Info.InConstantContext = true;
14063   Info.CheckingForUndefinedBehavior = true;
14064 
14065   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
14066   (void)Result;
14067   assert(Result && "Could not evaluate expression");
14068   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
14069 
14070   return EVResult.Val.getInt();
14071 }
14072 
14073 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
14074   assert(!isValueDependent() &&
14075          "Expression evaluator can't be called on a dependent expression.");
14076 
14077   bool IsConst;
14078   EvalResult EVResult;
14079   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
14080     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14081     Info.CheckingForUndefinedBehavior = true;
14082     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
14083   }
14084 }
14085 
14086 bool Expr::EvalResult::isGlobalLValue() const {
14087   assert(Val.isLValue());
14088   return IsGlobalLValue(Val.getLValueBase());
14089 }
14090 
14091 
14092 /// isIntegerConstantExpr - this recursive routine will test if an expression is
14093 /// an integer constant expression.
14094 
14095 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
14096 /// comma, etc
14097 
14098 // CheckICE - This function does the fundamental ICE checking: the returned
14099 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
14100 // and a (possibly null) SourceLocation indicating the location of the problem.
14101 //
14102 // Note that to reduce code duplication, this helper does no evaluation
14103 // itself; the caller checks whether the expression is evaluatable, and
14104 // in the rare cases where CheckICE actually cares about the evaluated
14105 // value, it calls into Evaluate.
14106 
14107 namespace {
14108 
14109 enum ICEKind {
14110   /// This expression is an ICE.
14111   IK_ICE,
14112   /// This expression is not an ICE, but if it isn't evaluated, it's
14113   /// a legal subexpression for an ICE. This return value is used to handle
14114   /// the comma operator in C99 mode, and non-constant subexpressions.
14115   IK_ICEIfUnevaluated,
14116   /// This expression is not an ICE, and is not a legal subexpression for one.
14117   IK_NotICE
14118 };
14119 
14120 struct ICEDiag {
14121   ICEKind Kind;
14122   SourceLocation Loc;
14123 
14124   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
14125 };
14126 
14127 }
14128 
14129 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
14130 
14131 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
14132 
14133 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
14134   Expr::EvalResult EVResult;
14135   Expr::EvalStatus Status;
14136   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
14137 
14138   Info.InConstantContext = true;
14139   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
14140       !EVResult.Val.isInt())
14141     return ICEDiag(IK_NotICE, E->getBeginLoc());
14142 
14143   return NoDiag();
14144 }
14145 
14146 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
14147   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
14148   if (!E->getType()->isIntegralOrEnumerationType())
14149     return ICEDiag(IK_NotICE, E->getBeginLoc());
14150 
14151   switch (E->getStmtClass()) {
14152 #define ABSTRACT_STMT(Node)
14153 #define STMT(Node, Base) case Expr::Node##Class:
14154 #define EXPR(Node, Base)
14155 #include "clang/AST/StmtNodes.inc"
14156   case Expr::PredefinedExprClass:
14157   case Expr::FloatingLiteralClass:
14158   case Expr::ImaginaryLiteralClass:
14159   case Expr::StringLiteralClass:
14160   case Expr::ArraySubscriptExprClass:
14161   case Expr::OMPArraySectionExprClass:
14162   case Expr::MemberExprClass:
14163   case Expr::CompoundAssignOperatorClass:
14164   case Expr::CompoundLiteralExprClass:
14165   case Expr::ExtVectorElementExprClass:
14166   case Expr::DesignatedInitExprClass:
14167   case Expr::ArrayInitLoopExprClass:
14168   case Expr::ArrayInitIndexExprClass:
14169   case Expr::NoInitExprClass:
14170   case Expr::DesignatedInitUpdateExprClass:
14171   case Expr::ImplicitValueInitExprClass:
14172   case Expr::ParenListExprClass:
14173   case Expr::VAArgExprClass:
14174   case Expr::AddrLabelExprClass:
14175   case Expr::StmtExprClass:
14176   case Expr::CXXMemberCallExprClass:
14177   case Expr::CUDAKernelCallExprClass:
14178   case Expr::CXXDynamicCastExprClass:
14179   case Expr::CXXTypeidExprClass:
14180   case Expr::CXXUuidofExprClass:
14181   case Expr::MSPropertyRefExprClass:
14182   case Expr::MSPropertySubscriptExprClass:
14183   case Expr::CXXNullPtrLiteralExprClass:
14184   case Expr::UserDefinedLiteralClass:
14185   case Expr::CXXThisExprClass:
14186   case Expr::CXXThrowExprClass:
14187   case Expr::CXXNewExprClass:
14188   case Expr::CXXDeleteExprClass:
14189   case Expr::CXXPseudoDestructorExprClass:
14190   case Expr::UnresolvedLookupExprClass:
14191   case Expr::TypoExprClass:
14192   case Expr::RecoveryExprClass:
14193   case Expr::DependentScopeDeclRefExprClass:
14194   case Expr::CXXConstructExprClass:
14195   case Expr::CXXInheritedCtorInitExprClass:
14196   case Expr::CXXStdInitializerListExprClass:
14197   case Expr::CXXBindTemporaryExprClass:
14198   case Expr::ExprWithCleanupsClass:
14199   case Expr::CXXTemporaryObjectExprClass:
14200   case Expr::CXXUnresolvedConstructExprClass:
14201   case Expr::CXXDependentScopeMemberExprClass:
14202   case Expr::UnresolvedMemberExprClass:
14203   case Expr::ObjCStringLiteralClass:
14204   case Expr::ObjCBoxedExprClass:
14205   case Expr::ObjCArrayLiteralClass:
14206   case Expr::ObjCDictionaryLiteralClass:
14207   case Expr::ObjCEncodeExprClass:
14208   case Expr::ObjCMessageExprClass:
14209   case Expr::ObjCSelectorExprClass:
14210   case Expr::ObjCProtocolExprClass:
14211   case Expr::ObjCIvarRefExprClass:
14212   case Expr::ObjCPropertyRefExprClass:
14213   case Expr::ObjCSubscriptRefExprClass:
14214   case Expr::ObjCIsaExprClass:
14215   case Expr::ObjCAvailabilityCheckExprClass:
14216   case Expr::ShuffleVectorExprClass:
14217   case Expr::ConvertVectorExprClass:
14218   case Expr::BlockExprClass:
14219   case Expr::NoStmtClass:
14220   case Expr::OpaqueValueExprClass:
14221   case Expr::PackExpansionExprClass:
14222   case Expr::SubstNonTypeTemplateParmPackExprClass:
14223   case Expr::FunctionParmPackExprClass:
14224   case Expr::AsTypeExprClass:
14225   case Expr::ObjCIndirectCopyRestoreExprClass:
14226   case Expr::MaterializeTemporaryExprClass:
14227   case Expr::PseudoObjectExprClass:
14228   case Expr::AtomicExprClass:
14229   case Expr::LambdaExprClass:
14230   case Expr::CXXFoldExprClass:
14231   case Expr::CoawaitExprClass:
14232   case Expr::DependentCoawaitExprClass:
14233   case Expr::CoyieldExprClass:
14234     return ICEDiag(IK_NotICE, E->getBeginLoc());
14235 
14236   case Expr::InitListExprClass: {
14237     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
14238     // form "T x = { a };" is equivalent to "T x = a;".
14239     // Unless we're initializing a reference, T is a scalar as it is known to be
14240     // of integral or enumeration type.
14241     if (E->isRValue())
14242       if (cast<InitListExpr>(E)->getNumInits() == 1)
14243         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
14244     return ICEDiag(IK_NotICE, E->getBeginLoc());
14245   }
14246 
14247   case Expr::SizeOfPackExprClass:
14248   case Expr::GNUNullExprClass:
14249   case Expr::SourceLocExprClass:
14250     return NoDiag();
14251 
14252   case Expr::SubstNonTypeTemplateParmExprClass:
14253     return
14254       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
14255 
14256   case Expr::ConstantExprClass:
14257     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
14258 
14259   case Expr::ParenExprClass:
14260     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
14261   case Expr::GenericSelectionExprClass:
14262     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
14263   case Expr::IntegerLiteralClass:
14264   case Expr::FixedPointLiteralClass:
14265   case Expr::CharacterLiteralClass:
14266   case Expr::ObjCBoolLiteralExprClass:
14267   case Expr::CXXBoolLiteralExprClass:
14268   case Expr::CXXScalarValueInitExprClass:
14269   case Expr::TypeTraitExprClass:
14270   case Expr::ConceptSpecializationExprClass:
14271   case Expr::RequiresExprClass:
14272   case Expr::ArrayTypeTraitExprClass:
14273   case Expr::ExpressionTraitExprClass:
14274   case Expr::CXXNoexceptExprClass:
14275     return NoDiag();
14276   case Expr::CallExprClass:
14277   case Expr::CXXOperatorCallExprClass: {
14278     // C99 6.6/3 allows function calls within unevaluated subexpressions of
14279     // constant expressions, but they can never be ICEs because an ICE cannot
14280     // contain an operand of (pointer to) function type.
14281     const CallExpr *CE = cast<CallExpr>(E);
14282     if (CE->getBuiltinCallee())
14283       return CheckEvalInICE(E, Ctx);
14284     return ICEDiag(IK_NotICE, E->getBeginLoc());
14285   }
14286   case Expr::CXXRewrittenBinaryOperatorClass:
14287     return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
14288                     Ctx);
14289   case Expr::DeclRefExprClass: {
14290     if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
14291       return NoDiag();
14292     const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
14293     if (Ctx.getLangOpts().CPlusPlus &&
14294         D && IsConstNonVolatile(D->getType())) {
14295       // Parameter variables are never constants.  Without this check,
14296       // getAnyInitializer() can find a default argument, which leads
14297       // to chaos.
14298       if (isa<ParmVarDecl>(D))
14299         return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
14300 
14301       // C++ 7.1.5.1p2
14302       //   A variable of non-volatile const-qualified integral or enumeration
14303       //   type initialized by an ICE can be used in ICEs.
14304       if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
14305         if (!Dcl->getType()->isIntegralOrEnumerationType())
14306           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
14307 
14308         const VarDecl *VD;
14309         // Look for a declaration of this variable that has an initializer, and
14310         // check whether it is an ICE.
14311         if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
14312           return NoDiag();
14313         else
14314           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
14315       }
14316     }
14317     return ICEDiag(IK_NotICE, E->getBeginLoc());
14318   }
14319   case Expr::UnaryOperatorClass: {
14320     const UnaryOperator *Exp = cast<UnaryOperator>(E);
14321     switch (Exp->getOpcode()) {
14322     case UO_PostInc:
14323     case UO_PostDec:
14324     case UO_PreInc:
14325     case UO_PreDec:
14326     case UO_AddrOf:
14327     case UO_Deref:
14328     case UO_Coawait:
14329       // C99 6.6/3 allows increment and decrement within unevaluated
14330       // subexpressions of constant expressions, but they can never be ICEs
14331       // because an ICE cannot contain an lvalue operand.
14332       return ICEDiag(IK_NotICE, E->getBeginLoc());
14333     case UO_Extension:
14334     case UO_LNot:
14335     case UO_Plus:
14336     case UO_Minus:
14337     case UO_Not:
14338     case UO_Real:
14339     case UO_Imag:
14340       return CheckICE(Exp->getSubExpr(), Ctx);
14341     }
14342     llvm_unreachable("invalid unary operator class");
14343   }
14344   case Expr::OffsetOfExprClass: {
14345     // Note that per C99, offsetof must be an ICE. And AFAIK, using
14346     // EvaluateAsRValue matches the proposed gcc behavior for cases like
14347     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
14348     // compliance: we should warn earlier for offsetof expressions with
14349     // array subscripts that aren't ICEs, and if the array subscripts
14350     // are ICEs, the value of the offsetof must be an integer constant.
14351     return CheckEvalInICE(E, Ctx);
14352   }
14353   case Expr::UnaryExprOrTypeTraitExprClass: {
14354     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
14355     if ((Exp->getKind() ==  UETT_SizeOf) &&
14356         Exp->getTypeOfArgument()->isVariableArrayType())
14357       return ICEDiag(IK_NotICE, E->getBeginLoc());
14358     return NoDiag();
14359   }
14360   case Expr::BinaryOperatorClass: {
14361     const BinaryOperator *Exp = cast<BinaryOperator>(E);
14362     switch (Exp->getOpcode()) {
14363     case BO_PtrMemD:
14364     case BO_PtrMemI:
14365     case BO_Assign:
14366     case BO_MulAssign:
14367     case BO_DivAssign:
14368     case BO_RemAssign:
14369     case BO_AddAssign:
14370     case BO_SubAssign:
14371     case BO_ShlAssign:
14372     case BO_ShrAssign:
14373     case BO_AndAssign:
14374     case BO_XorAssign:
14375     case BO_OrAssign:
14376       // C99 6.6/3 allows assignments within unevaluated subexpressions of
14377       // constant expressions, but they can never be ICEs because an ICE cannot
14378       // contain an lvalue operand.
14379       return ICEDiag(IK_NotICE, E->getBeginLoc());
14380 
14381     case BO_Mul:
14382     case BO_Div:
14383     case BO_Rem:
14384     case BO_Add:
14385     case BO_Sub:
14386     case BO_Shl:
14387     case BO_Shr:
14388     case BO_LT:
14389     case BO_GT:
14390     case BO_LE:
14391     case BO_GE:
14392     case BO_EQ:
14393     case BO_NE:
14394     case BO_And:
14395     case BO_Xor:
14396     case BO_Or:
14397     case BO_Comma:
14398     case BO_Cmp: {
14399       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
14400       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
14401       if (Exp->getOpcode() == BO_Div ||
14402           Exp->getOpcode() == BO_Rem) {
14403         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
14404         // we don't evaluate one.
14405         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
14406           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
14407           if (REval == 0)
14408             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
14409           if (REval.isSigned() && REval.isAllOnesValue()) {
14410             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
14411             if (LEval.isMinSignedValue())
14412               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
14413           }
14414         }
14415       }
14416       if (Exp->getOpcode() == BO_Comma) {
14417         if (Ctx.getLangOpts().C99) {
14418           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
14419           // if it isn't evaluated.
14420           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
14421             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
14422         } else {
14423           // In both C89 and C++, commas in ICEs are illegal.
14424           return ICEDiag(IK_NotICE, E->getBeginLoc());
14425         }
14426       }
14427       return Worst(LHSResult, RHSResult);
14428     }
14429     case BO_LAnd:
14430     case BO_LOr: {
14431       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
14432       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
14433       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
14434         // Rare case where the RHS has a comma "side-effect"; we need
14435         // to actually check the condition to see whether the side
14436         // with the comma is evaluated.
14437         if ((Exp->getOpcode() == BO_LAnd) !=
14438             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
14439           return RHSResult;
14440         return NoDiag();
14441       }
14442 
14443       return Worst(LHSResult, RHSResult);
14444     }
14445     }
14446     llvm_unreachable("invalid binary operator kind");
14447   }
14448   case Expr::ImplicitCastExprClass:
14449   case Expr::CStyleCastExprClass:
14450   case Expr::CXXFunctionalCastExprClass:
14451   case Expr::CXXStaticCastExprClass:
14452   case Expr::CXXReinterpretCastExprClass:
14453   case Expr::CXXConstCastExprClass:
14454   case Expr::ObjCBridgedCastExprClass: {
14455     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
14456     if (isa<ExplicitCastExpr>(E)) {
14457       if (const FloatingLiteral *FL
14458             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
14459         unsigned DestWidth = Ctx.getIntWidth(E->getType());
14460         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
14461         APSInt IgnoredVal(DestWidth, !DestSigned);
14462         bool Ignored;
14463         // If the value does not fit in the destination type, the behavior is
14464         // undefined, so we are not required to treat it as a constant
14465         // expression.
14466         if (FL->getValue().convertToInteger(IgnoredVal,
14467                                             llvm::APFloat::rmTowardZero,
14468                                             &Ignored) & APFloat::opInvalidOp)
14469           return ICEDiag(IK_NotICE, E->getBeginLoc());
14470         return NoDiag();
14471       }
14472     }
14473     switch (cast<CastExpr>(E)->getCastKind()) {
14474     case CK_LValueToRValue:
14475     case CK_AtomicToNonAtomic:
14476     case CK_NonAtomicToAtomic:
14477     case CK_NoOp:
14478     case CK_IntegralToBoolean:
14479     case CK_IntegralCast:
14480       return CheckICE(SubExpr, Ctx);
14481     default:
14482       return ICEDiag(IK_NotICE, E->getBeginLoc());
14483     }
14484   }
14485   case Expr::BinaryConditionalOperatorClass: {
14486     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
14487     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
14488     if (CommonResult.Kind == IK_NotICE) return CommonResult;
14489     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
14490     if (FalseResult.Kind == IK_NotICE) return FalseResult;
14491     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
14492     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
14493         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
14494     return FalseResult;
14495   }
14496   case Expr::ConditionalOperatorClass: {
14497     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
14498     // If the condition (ignoring parens) is a __builtin_constant_p call,
14499     // then only the true side is actually considered in an integer constant
14500     // expression, and it is fully evaluated.  This is an important GNU
14501     // extension.  See GCC PR38377 for discussion.
14502     if (const CallExpr *CallCE
14503         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
14504       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
14505         return CheckEvalInICE(E, Ctx);
14506     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
14507     if (CondResult.Kind == IK_NotICE)
14508       return CondResult;
14509 
14510     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
14511     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
14512 
14513     if (TrueResult.Kind == IK_NotICE)
14514       return TrueResult;
14515     if (FalseResult.Kind == IK_NotICE)
14516       return FalseResult;
14517     if (CondResult.Kind == IK_ICEIfUnevaluated)
14518       return CondResult;
14519     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
14520       return NoDiag();
14521     // Rare case where the diagnostics depend on which side is evaluated
14522     // Note that if we get here, CondResult is 0, and at least one of
14523     // TrueResult and FalseResult is non-zero.
14524     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
14525       return FalseResult;
14526     return TrueResult;
14527   }
14528   case Expr::CXXDefaultArgExprClass:
14529     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
14530   case Expr::CXXDefaultInitExprClass:
14531     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
14532   case Expr::ChooseExprClass: {
14533     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
14534   }
14535   case Expr::BuiltinBitCastExprClass: {
14536     if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
14537       return ICEDiag(IK_NotICE, E->getBeginLoc());
14538     return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
14539   }
14540   }
14541 
14542   llvm_unreachable("Invalid StmtClass!");
14543 }
14544 
14545 /// Evaluate an expression as a C++11 integral constant expression.
14546 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
14547                                                     const Expr *E,
14548                                                     llvm::APSInt *Value,
14549                                                     SourceLocation *Loc) {
14550   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
14551     if (Loc) *Loc = E->getExprLoc();
14552     return false;
14553   }
14554 
14555   APValue Result;
14556   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
14557     return false;
14558 
14559   if (!Result.isInt()) {
14560     if (Loc) *Loc = E->getExprLoc();
14561     return false;
14562   }
14563 
14564   if (Value) *Value = Result.getInt();
14565   return true;
14566 }
14567 
14568 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
14569                                  SourceLocation *Loc) const {
14570   assert(!isValueDependent() &&
14571          "Expression evaluator can't be called on a dependent expression.");
14572 
14573   if (Ctx.getLangOpts().CPlusPlus11)
14574     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
14575 
14576   ICEDiag D = CheckICE(this, Ctx);
14577   if (D.Kind != IK_ICE) {
14578     if (Loc) *Loc = D.Loc;
14579     return false;
14580   }
14581   return true;
14582 }
14583 
14584 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
14585                                  SourceLocation *Loc, bool isEvaluated) const {
14586   assert(!isValueDependent() &&
14587          "Expression evaluator can't be called on a dependent expression.");
14588 
14589   if (Ctx.getLangOpts().CPlusPlus11)
14590     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
14591 
14592   if (!isIntegerConstantExpr(Ctx, Loc))
14593     return false;
14594 
14595   // The only possible side-effects here are due to UB discovered in the
14596   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
14597   // required to treat the expression as an ICE, so we produce the folded
14598   // value.
14599   EvalResult ExprResult;
14600   Expr::EvalStatus Status;
14601   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
14602   Info.InConstantContext = true;
14603 
14604   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
14605     llvm_unreachable("ICE cannot be evaluated!");
14606 
14607   Value = ExprResult.Val.getInt();
14608   return true;
14609 }
14610 
14611 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
14612   assert(!isValueDependent() &&
14613          "Expression evaluator can't be called on a dependent expression.");
14614 
14615   return CheckICE(this, Ctx).Kind == IK_ICE;
14616 }
14617 
14618 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
14619                                SourceLocation *Loc) const {
14620   assert(!isValueDependent() &&
14621          "Expression evaluator can't be called on a dependent expression.");
14622 
14623   // We support this checking in C++98 mode in order to diagnose compatibility
14624   // issues.
14625   assert(Ctx.getLangOpts().CPlusPlus);
14626 
14627   // Build evaluation settings.
14628   Expr::EvalStatus Status;
14629   SmallVector<PartialDiagnosticAt, 8> Diags;
14630   Status.Diag = &Diags;
14631   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
14632 
14633   APValue Scratch;
14634   bool IsConstExpr =
14635       ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
14636       // FIXME: We don't produce a diagnostic for this, but the callers that
14637       // call us on arbitrary full-expressions should generally not care.
14638       Info.discardCleanups() && !Status.HasSideEffects;
14639 
14640   if (!Diags.empty()) {
14641     IsConstExpr = false;
14642     if (Loc) *Loc = Diags[0].first;
14643   } else if (!IsConstExpr) {
14644     // FIXME: This shouldn't happen.
14645     if (Loc) *Loc = getExprLoc();
14646   }
14647 
14648   return IsConstExpr;
14649 }
14650 
14651 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
14652                                     const FunctionDecl *Callee,
14653                                     ArrayRef<const Expr*> Args,
14654                                     const Expr *This) const {
14655   assert(!isValueDependent() &&
14656          "Expression evaluator can't be called on a dependent expression.");
14657 
14658   Expr::EvalStatus Status;
14659   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
14660   Info.InConstantContext = true;
14661 
14662   LValue ThisVal;
14663   const LValue *ThisPtr = nullptr;
14664   if (This) {
14665 #ifndef NDEBUG
14666     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
14667     assert(MD && "Don't provide `this` for non-methods.");
14668     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
14669 #endif
14670     if (!This->isValueDependent() &&
14671         EvaluateObjectArgument(Info, This, ThisVal) &&
14672         !Info.EvalStatus.HasSideEffects)
14673       ThisPtr = &ThisVal;
14674 
14675     // Ignore any side-effects from a failed evaluation. This is safe because
14676     // they can't interfere with any other argument evaluation.
14677     Info.EvalStatus.HasSideEffects = false;
14678   }
14679 
14680   ArgVector ArgValues(Args.size());
14681   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
14682        I != E; ++I) {
14683     if ((*I)->isValueDependent() ||
14684         !Evaluate(ArgValues[I - Args.begin()], Info, *I) ||
14685         Info.EvalStatus.HasSideEffects)
14686       // If evaluation fails, throw away the argument entirely.
14687       ArgValues[I - Args.begin()] = APValue();
14688 
14689     // Ignore any side-effects from a failed evaluation. This is safe because
14690     // they can't interfere with any other argument evaluation.
14691     Info.EvalStatus.HasSideEffects = false;
14692   }
14693 
14694   // Parameter cleanups happen in the caller and are not part of this
14695   // evaluation.
14696   Info.discardCleanups();
14697   Info.EvalStatus.HasSideEffects = false;
14698 
14699   // Build fake call to Callee.
14700   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
14701                        ArgValues.data());
14702   // FIXME: Missing ExprWithCleanups in enable_if conditions?
14703   FullExpressionRAII Scope(Info);
14704   return Evaluate(Value, Info, this) && Scope.destroy() &&
14705          !Info.EvalStatus.HasSideEffects;
14706 }
14707 
14708 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
14709                                    SmallVectorImpl<
14710                                      PartialDiagnosticAt> &Diags) {
14711   // FIXME: It would be useful to check constexpr function templates, but at the
14712   // moment the constant expression evaluator cannot cope with the non-rigorous
14713   // ASTs which we build for dependent expressions.
14714   if (FD->isDependentContext())
14715     return true;
14716 
14717   Expr::EvalStatus Status;
14718   Status.Diag = &Diags;
14719 
14720   EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
14721   Info.InConstantContext = true;
14722   Info.CheckingPotentialConstantExpression = true;
14723 
14724   // The constexpr VM attempts to compile all methods to bytecode here.
14725   if (Info.EnableNewConstInterp) {
14726     Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
14727     return Diags.empty();
14728   }
14729 
14730   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
14731   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
14732 
14733   // Fabricate an arbitrary expression on the stack and pretend that it
14734   // is a temporary being used as the 'this' pointer.
14735   LValue This;
14736   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
14737   This.set({&VIE, Info.CurrentCall->Index});
14738 
14739   ArrayRef<const Expr*> Args;
14740 
14741   APValue Scratch;
14742   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
14743     // Evaluate the call as a constant initializer, to allow the construction
14744     // of objects of non-literal types.
14745     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
14746     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
14747   } else {
14748     SourceLocation Loc = FD->getLocation();
14749     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
14750                        Args, FD->getBody(), Info, Scratch, nullptr);
14751   }
14752 
14753   return Diags.empty();
14754 }
14755 
14756 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
14757                                               const FunctionDecl *FD,
14758                                               SmallVectorImpl<
14759                                                 PartialDiagnosticAt> &Diags) {
14760   assert(!E->isValueDependent() &&
14761          "Expression evaluator can't be called on a dependent expression.");
14762 
14763   Expr::EvalStatus Status;
14764   Status.Diag = &Diags;
14765 
14766   EvalInfo Info(FD->getASTContext(), Status,
14767                 EvalInfo::EM_ConstantExpressionUnevaluated);
14768   Info.InConstantContext = true;
14769   Info.CheckingPotentialConstantExpression = true;
14770 
14771   // Fabricate a call stack frame to give the arguments a plausible cover story.
14772   ArrayRef<const Expr*> Args;
14773   ArgVector ArgValues(0);
14774   bool Success = EvaluateArgs(Args, ArgValues, Info, FD);
14775   (void)Success;
14776   assert(Success &&
14777          "Failed to set up arguments for potential constant evaluation");
14778   CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
14779 
14780   APValue ResultScratch;
14781   Evaluate(ResultScratch, Info, E);
14782   return Diags.empty();
14783 }
14784 
14785 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
14786                                  unsigned Type) const {
14787   if (!getType()->isPointerType())
14788     return false;
14789 
14790   Expr::EvalStatus Status;
14791   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
14792   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
14793 }
14794