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 // Determine if T is a character type for which we guarantee that
8323 // sizeof(T) == 1.
8324 static bool isOneByteCharacterType(QualType T) {
8325   return T->isCharType() || T->isChar8Type();
8326 }
8327 
8328 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8329                                                 unsigned BuiltinOp) {
8330   switch (BuiltinOp) {
8331   case Builtin::BI__builtin_addressof:
8332     return evaluateLValue(E->getArg(0), Result);
8333   case Builtin::BI__builtin_assume_aligned: {
8334     // We need to be very careful here because: if the pointer does not have the
8335     // asserted alignment, then the behavior is undefined, and undefined
8336     // behavior is non-constant.
8337     if (!evaluatePointer(E->getArg(0), Result))
8338       return false;
8339 
8340     LValue OffsetResult(Result);
8341     APSInt Alignment;
8342     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
8343                               Alignment))
8344       return false;
8345     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
8346 
8347     if (E->getNumArgs() > 2) {
8348       APSInt Offset;
8349       if (!EvaluateInteger(E->getArg(2), Offset, Info))
8350         return false;
8351 
8352       int64_t AdditionalOffset = -Offset.getZExtValue();
8353       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
8354     }
8355 
8356     // If there is a base object, then it must have the correct alignment.
8357     if (OffsetResult.Base) {
8358       CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
8359 
8360       if (BaseAlignment < Align) {
8361         Result.Designator.setInvalid();
8362         // FIXME: Add support to Diagnostic for long / long long.
8363         CCEDiag(E->getArg(0),
8364                 diag::note_constexpr_baa_insufficient_alignment) << 0
8365           << (unsigned)BaseAlignment.getQuantity()
8366           << (unsigned)Align.getQuantity();
8367         return false;
8368       }
8369     }
8370 
8371     // The offset must also have the correct alignment.
8372     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
8373       Result.Designator.setInvalid();
8374 
8375       (OffsetResult.Base
8376            ? CCEDiag(E->getArg(0),
8377                      diag::note_constexpr_baa_insufficient_alignment) << 1
8378            : CCEDiag(E->getArg(0),
8379                      diag::note_constexpr_baa_value_insufficient_alignment))
8380         << (int)OffsetResult.Offset.getQuantity()
8381         << (unsigned)Align.getQuantity();
8382       return false;
8383     }
8384 
8385     return true;
8386   }
8387   case Builtin::BI__builtin_align_up:
8388   case Builtin::BI__builtin_align_down: {
8389     if (!evaluatePointer(E->getArg(0), Result))
8390       return false;
8391     APSInt Alignment;
8392     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
8393                               Alignment))
8394       return false;
8395     CharUnits BaseAlignment = getBaseAlignment(Info, Result);
8396     CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
8397     // For align_up/align_down, we can return the same value if the alignment
8398     // is known to be greater or equal to the requested value.
8399     if (PtrAlign.getQuantity() >= Alignment)
8400       return true;
8401 
8402     // The alignment could be greater than the minimum at run-time, so we cannot
8403     // infer much about the resulting pointer value. One case is possible:
8404     // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
8405     // can infer the correct index if the requested alignment is smaller than
8406     // the base alignment so we can perform the computation on the offset.
8407     if (BaseAlignment.getQuantity() >= Alignment) {
8408       assert(Alignment.getBitWidth() <= 64 &&
8409              "Cannot handle > 64-bit address-space");
8410       uint64_t Alignment64 = Alignment.getZExtValue();
8411       CharUnits NewOffset = CharUnits::fromQuantity(
8412           BuiltinOp == Builtin::BI__builtin_align_down
8413               ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
8414               : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
8415       Result.adjustOffset(NewOffset - Result.Offset);
8416       // TODO: diagnose out-of-bounds values/only allow for arrays?
8417       return true;
8418     }
8419     // Otherwise, we cannot constant-evaluate the result.
8420     Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
8421         << Alignment;
8422     return false;
8423   }
8424   case Builtin::BI__builtin_operator_new:
8425     return HandleOperatorNewCall(Info, E, Result);
8426   case Builtin::BI__builtin_launder:
8427     return evaluatePointer(E->getArg(0), Result);
8428   case Builtin::BIstrchr:
8429   case Builtin::BIwcschr:
8430   case Builtin::BImemchr:
8431   case Builtin::BIwmemchr:
8432     if (Info.getLangOpts().CPlusPlus11)
8433       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8434         << /*isConstexpr*/0 << /*isConstructor*/0
8435         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
8436     else
8437       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
8438     LLVM_FALLTHROUGH;
8439   case Builtin::BI__builtin_strchr:
8440   case Builtin::BI__builtin_wcschr:
8441   case Builtin::BI__builtin_memchr:
8442   case Builtin::BI__builtin_char_memchr:
8443   case Builtin::BI__builtin_wmemchr: {
8444     if (!Visit(E->getArg(0)))
8445       return false;
8446     APSInt Desired;
8447     if (!EvaluateInteger(E->getArg(1), Desired, Info))
8448       return false;
8449     uint64_t MaxLength = uint64_t(-1);
8450     if (BuiltinOp != Builtin::BIstrchr &&
8451         BuiltinOp != Builtin::BIwcschr &&
8452         BuiltinOp != Builtin::BI__builtin_strchr &&
8453         BuiltinOp != Builtin::BI__builtin_wcschr) {
8454       APSInt N;
8455       if (!EvaluateInteger(E->getArg(2), N, Info))
8456         return false;
8457       MaxLength = N.getExtValue();
8458     }
8459     // We cannot find the value if there are no candidates to match against.
8460     if (MaxLength == 0u)
8461       return ZeroInitialization(E);
8462     if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
8463         Result.Designator.Invalid)
8464       return false;
8465     QualType CharTy = Result.Designator.getType(Info.Ctx);
8466     bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
8467                      BuiltinOp == Builtin::BI__builtin_memchr;
8468     assert(IsRawByte ||
8469            Info.Ctx.hasSameUnqualifiedType(
8470                CharTy, E->getArg(0)->getType()->getPointeeType()));
8471     // Pointers to const void may point to objects of incomplete type.
8472     if (IsRawByte && CharTy->isIncompleteType()) {
8473       Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
8474       return false;
8475     }
8476     // Give up on byte-oriented matching against multibyte elements.
8477     // FIXME: We can compare the bytes in the correct order.
8478     if (IsRawByte && !isOneByteCharacterType(CharTy)) {
8479       Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
8480           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
8481           << CharTy;
8482       return false;
8483     }
8484     // Figure out what value we're actually looking for (after converting to
8485     // the corresponding unsigned type if necessary).
8486     uint64_t DesiredVal;
8487     bool StopAtNull = false;
8488     switch (BuiltinOp) {
8489     case Builtin::BIstrchr:
8490     case Builtin::BI__builtin_strchr:
8491       // strchr compares directly to the passed integer, and therefore
8492       // always fails if given an int that is not a char.
8493       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
8494                                                   E->getArg(1)->getType(),
8495                                                   Desired),
8496                                Desired))
8497         return ZeroInitialization(E);
8498       StopAtNull = true;
8499       LLVM_FALLTHROUGH;
8500     case Builtin::BImemchr:
8501     case Builtin::BI__builtin_memchr:
8502     case Builtin::BI__builtin_char_memchr:
8503       // memchr compares by converting both sides to unsigned char. That's also
8504       // correct for strchr if we get this far (to cope with plain char being
8505       // unsigned in the strchr case).
8506       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
8507       break;
8508 
8509     case Builtin::BIwcschr:
8510     case Builtin::BI__builtin_wcschr:
8511       StopAtNull = true;
8512       LLVM_FALLTHROUGH;
8513     case Builtin::BIwmemchr:
8514     case Builtin::BI__builtin_wmemchr:
8515       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
8516       DesiredVal = Desired.getZExtValue();
8517       break;
8518     }
8519 
8520     for (; MaxLength; --MaxLength) {
8521       APValue Char;
8522       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
8523           !Char.isInt())
8524         return false;
8525       if (Char.getInt().getZExtValue() == DesiredVal)
8526         return true;
8527       if (StopAtNull && !Char.getInt())
8528         break;
8529       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
8530         return false;
8531     }
8532     // Not found: return nullptr.
8533     return ZeroInitialization(E);
8534   }
8535 
8536   case Builtin::BImemcpy:
8537   case Builtin::BImemmove:
8538   case Builtin::BIwmemcpy:
8539   case Builtin::BIwmemmove:
8540     if (Info.getLangOpts().CPlusPlus11)
8541       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8542         << /*isConstexpr*/0 << /*isConstructor*/0
8543         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
8544     else
8545       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
8546     LLVM_FALLTHROUGH;
8547   case Builtin::BI__builtin_memcpy:
8548   case Builtin::BI__builtin_memmove:
8549   case Builtin::BI__builtin_wmemcpy:
8550   case Builtin::BI__builtin_wmemmove: {
8551     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
8552                  BuiltinOp == Builtin::BIwmemmove ||
8553                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
8554                  BuiltinOp == Builtin::BI__builtin_wmemmove;
8555     bool Move = BuiltinOp == Builtin::BImemmove ||
8556                 BuiltinOp == Builtin::BIwmemmove ||
8557                 BuiltinOp == Builtin::BI__builtin_memmove ||
8558                 BuiltinOp == Builtin::BI__builtin_wmemmove;
8559 
8560     // The result of mem* is the first argument.
8561     if (!Visit(E->getArg(0)))
8562       return false;
8563     LValue Dest = Result;
8564 
8565     LValue Src;
8566     if (!EvaluatePointer(E->getArg(1), Src, Info))
8567       return false;
8568 
8569     APSInt N;
8570     if (!EvaluateInteger(E->getArg(2), N, Info))
8571       return false;
8572     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
8573 
8574     // If the size is zero, we treat this as always being a valid no-op.
8575     // (Even if one of the src and dest pointers is null.)
8576     if (!N)
8577       return true;
8578 
8579     // Otherwise, if either of the operands is null, we can't proceed. Don't
8580     // try to determine the type of the copied objects, because there aren't
8581     // any.
8582     if (!Src.Base || !Dest.Base) {
8583       APValue Val;
8584       (!Src.Base ? Src : Dest).moveInto(Val);
8585       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
8586           << Move << WChar << !!Src.Base
8587           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
8588       return false;
8589     }
8590     if (Src.Designator.Invalid || Dest.Designator.Invalid)
8591       return false;
8592 
8593     // We require that Src and Dest are both pointers to arrays of
8594     // trivially-copyable type. (For the wide version, the designator will be
8595     // invalid if the designated object is not a wchar_t.)
8596     QualType T = Dest.Designator.getType(Info.Ctx);
8597     QualType SrcT = Src.Designator.getType(Info.Ctx);
8598     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
8599       // FIXME: Consider using our bit_cast implementation to support this.
8600       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
8601       return false;
8602     }
8603     if (T->isIncompleteType()) {
8604       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
8605       return false;
8606     }
8607     if (!T.isTriviallyCopyableType(Info.Ctx)) {
8608       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
8609       return false;
8610     }
8611 
8612     // Figure out how many T's we're copying.
8613     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
8614     if (!WChar) {
8615       uint64_t Remainder;
8616       llvm::APInt OrigN = N;
8617       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
8618       if (Remainder) {
8619         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
8620             << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
8621             << (unsigned)TSize;
8622         return false;
8623       }
8624     }
8625 
8626     // Check that the copying will remain within the arrays, just so that we
8627     // can give a more meaningful diagnostic. This implicitly also checks that
8628     // N fits into 64 bits.
8629     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
8630     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
8631     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
8632       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
8633           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
8634           << N.toString(10, /*Signed*/false);
8635       return false;
8636     }
8637     uint64_t NElems = N.getZExtValue();
8638     uint64_t NBytes = NElems * TSize;
8639 
8640     // Check for overlap.
8641     int Direction = 1;
8642     if (HasSameBase(Src, Dest)) {
8643       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
8644       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
8645       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
8646         // Dest is inside the source region.
8647         if (!Move) {
8648           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
8649           return false;
8650         }
8651         // For memmove and friends, copy backwards.
8652         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
8653             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
8654           return false;
8655         Direction = -1;
8656       } else if (!Move && SrcOffset >= DestOffset &&
8657                  SrcOffset - DestOffset < NBytes) {
8658         // Src is inside the destination region for memcpy: invalid.
8659         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
8660         return false;
8661       }
8662     }
8663 
8664     while (true) {
8665       APValue Val;
8666       // FIXME: Set WantObjectRepresentation to true if we're copying a
8667       // char-like type?
8668       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
8669           !handleAssignment(Info, E, Dest, T, Val))
8670         return false;
8671       // Do not iterate past the last element; if we're copying backwards, that
8672       // might take us off the start of the array.
8673       if (--NElems == 0)
8674         return true;
8675       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
8676           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
8677         return false;
8678     }
8679   }
8680 
8681   default:
8682     break;
8683   }
8684 
8685   return visitNonBuiltinCallExpr(E);
8686 }
8687 
8688 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
8689                                      APValue &Result, const InitListExpr *ILE,
8690                                      QualType AllocType);
8691 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
8692                                           APValue &Result,
8693                                           const CXXConstructExpr *CCE,
8694                                           QualType AllocType);
8695 
8696 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
8697   if (!Info.getLangOpts().CPlusPlus2a)
8698     Info.CCEDiag(E, diag::note_constexpr_new);
8699 
8700   // We cannot speculatively evaluate a delete expression.
8701   if (Info.SpeculativeEvaluationDepth)
8702     return false;
8703 
8704   FunctionDecl *OperatorNew = E->getOperatorNew();
8705 
8706   bool IsNothrow = false;
8707   bool IsPlacement = false;
8708   if (OperatorNew->isReservedGlobalPlacementOperator() &&
8709       Info.CurrentCall->isStdFunction() && !E->isArray()) {
8710     // FIXME Support array placement new.
8711     assert(E->getNumPlacementArgs() == 1);
8712     if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
8713       return false;
8714     if (Result.Designator.Invalid)
8715       return false;
8716     IsPlacement = true;
8717   } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
8718     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
8719         << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
8720     return false;
8721   } else if (E->getNumPlacementArgs()) {
8722     // The only new-placement list we support is of the form (std::nothrow).
8723     //
8724     // FIXME: There is no restriction on this, but it's not clear that any
8725     // other form makes any sense. We get here for cases such as:
8726     //
8727     //   new (std::align_val_t{N}) X(int)
8728     //
8729     // (which should presumably be valid only if N is a multiple of
8730     // alignof(int), and in any case can't be deallocated unless N is
8731     // alignof(X) and X has new-extended alignment).
8732     if (E->getNumPlacementArgs() != 1 ||
8733         !E->getPlacementArg(0)->getType()->isNothrowT())
8734       return Error(E, diag::note_constexpr_new_placement);
8735 
8736     LValue Nothrow;
8737     if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
8738       return false;
8739     IsNothrow = true;
8740   }
8741 
8742   const Expr *Init = E->getInitializer();
8743   const InitListExpr *ResizedArrayILE = nullptr;
8744   const CXXConstructExpr *ResizedArrayCCE = nullptr;
8745 
8746   QualType AllocType = E->getAllocatedType();
8747   if (Optional<const Expr*> ArraySize = E->getArraySize()) {
8748     const Expr *Stripped = *ArraySize;
8749     for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
8750          Stripped = ICE->getSubExpr())
8751       if (ICE->getCastKind() != CK_NoOp &&
8752           ICE->getCastKind() != CK_IntegralCast)
8753         break;
8754 
8755     llvm::APSInt ArrayBound;
8756     if (!EvaluateInteger(Stripped, ArrayBound, Info))
8757       return false;
8758 
8759     // C++ [expr.new]p9:
8760     //   The expression is erroneous if:
8761     //   -- [...] its value before converting to size_t [or] applying the
8762     //      second standard conversion sequence is less than zero
8763     if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
8764       if (IsNothrow)
8765         return ZeroInitialization(E);
8766 
8767       Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
8768           << ArrayBound << (*ArraySize)->getSourceRange();
8769       return false;
8770     }
8771 
8772     //   -- its value is such that the size of the allocated object would
8773     //      exceed the implementation-defined limit
8774     if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
8775                                                 ArrayBound) >
8776         ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
8777       if (IsNothrow)
8778         return ZeroInitialization(E);
8779 
8780       Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
8781         << ArrayBound << (*ArraySize)->getSourceRange();
8782       return false;
8783     }
8784 
8785     //   -- the new-initializer is a braced-init-list and the number of
8786     //      array elements for which initializers are provided [...]
8787     //      exceeds the number of elements to initialize
8788     if (Init && !isa<CXXConstructExpr>(Init)) {
8789       auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
8790       assert(CAT && "unexpected type for array initializer");
8791 
8792       unsigned Bits =
8793           std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
8794       llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits);
8795       llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits);
8796       if (InitBound.ugt(AllocBound)) {
8797         if (IsNothrow)
8798           return ZeroInitialization(E);
8799 
8800         Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
8801             << AllocBound.toString(10, /*Signed=*/false)
8802             << InitBound.toString(10, /*Signed=*/false)
8803             << (*ArraySize)->getSourceRange();
8804         return false;
8805       }
8806 
8807       // If the sizes differ, we must have an initializer list, and we need
8808       // special handling for this case when we initialize.
8809       if (InitBound != AllocBound)
8810         ResizedArrayILE = cast<InitListExpr>(Init);
8811     } else if (Init) {
8812       ResizedArrayCCE = cast<CXXConstructExpr>(Init);
8813     }
8814 
8815     AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
8816                                               ArrayType::Normal, 0);
8817   } else {
8818     assert(!AllocType->isArrayType() &&
8819            "array allocation with non-array new");
8820   }
8821 
8822   APValue *Val;
8823   if (IsPlacement) {
8824     AccessKinds AK = AK_Construct;
8825     struct FindObjectHandler {
8826       EvalInfo &Info;
8827       const Expr *E;
8828       QualType AllocType;
8829       const AccessKinds AccessKind;
8830       APValue *Value;
8831 
8832       typedef bool result_type;
8833       bool failed() { return false; }
8834       bool found(APValue &Subobj, QualType SubobjType) {
8835         // FIXME: Reject the cases where [basic.life]p8 would not permit the
8836         // old name of the object to be used to name the new object.
8837         if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
8838           Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
8839             SubobjType << AllocType;
8840           return false;
8841         }
8842         Value = &Subobj;
8843         return true;
8844       }
8845       bool found(APSInt &Value, QualType SubobjType) {
8846         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
8847         return false;
8848       }
8849       bool found(APFloat &Value, QualType SubobjType) {
8850         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
8851         return false;
8852       }
8853     } Handler = {Info, E, AllocType, AK, nullptr};
8854 
8855     CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
8856     if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
8857       return false;
8858 
8859     Val = Handler.Value;
8860 
8861     // [basic.life]p1:
8862     //   The lifetime of an object o of type T ends when [...] the storage
8863     //   which the object occupies is [...] reused by an object that is not
8864     //   nested within o (6.6.2).
8865     *Val = APValue();
8866   } else {
8867     // Perform the allocation and obtain a pointer to the resulting object.
8868     Val = Info.createHeapAlloc(E, AllocType, Result);
8869     if (!Val)
8870       return false;
8871   }
8872 
8873   if (ResizedArrayILE) {
8874     if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
8875                                   AllocType))
8876       return false;
8877   } else if (ResizedArrayCCE) {
8878     if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
8879                                        AllocType))
8880       return false;
8881   } else if (Init) {
8882     if (!EvaluateInPlace(*Val, Info, Result, Init))
8883       return false;
8884   } else {
8885     *Val = getDefaultInitValue(AllocType);
8886   }
8887 
8888   // Array new returns a pointer to the first element, not a pointer to the
8889   // array.
8890   if (auto *AT = AllocType->getAsArrayTypeUnsafe())
8891     Result.addArray(Info, E, cast<ConstantArrayType>(AT));
8892 
8893   return true;
8894 }
8895 //===----------------------------------------------------------------------===//
8896 // Member Pointer Evaluation
8897 //===----------------------------------------------------------------------===//
8898 
8899 namespace {
8900 class MemberPointerExprEvaluator
8901   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
8902   MemberPtr &Result;
8903 
8904   bool Success(const ValueDecl *D) {
8905     Result = MemberPtr(D);
8906     return true;
8907   }
8908 public:
8909 
8910   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
8911     : ExprEvaluatorBaseTy(Info), Result(Result) {}
8912 
8913   bool Success(const APValue &V, const Expr *E) {
8914     Result.setFrom(V);
8915     return true;
8916   }
8917   bool ZeroInitialization(const Expr *E) {
8918     return Success((const ValueDecl*)nullptr);
8919   }
8920 
8921   bool VisitCastExpr(const CastExpr *E);
8922   bool VisitUnaryAddrOf(const UnaryOperator *E);
8923 };
8924 } // end anonymous namespace
8925 
8926 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
8927                                   EvalInfo &Info) {
8928   assert(E->isRValue() && E->getType()->isMemberPointerType());
8929   return MemberPointerExprEvaluator(Info, Result).Visit(E);
8930 }
8931 
8932 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8933   switch (E->getCastKind()) {
8934   default:
8935     return ExprEvaluatorBaseTy::VisitCastExpr(E);
8936 
8937   case CK_NullToMemberPointer:
8938     VisitIgnoredValue(E->getSubExpr());
8939     return ZeroInitialization(E);
8940 
8941   case CK_BaseToDerivedMemberPointer: {
8942     if (!Visit(E->getSubExpr()))
8943       return false;
8944     if (E->path_empty())
8945       return true;
8946     // Base-to-derived member pointer casts store the path in derived-to-base
8947     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
8948     // the wrong end of the derived->base arc, so stagger the path by one class.
8949     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
8950     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
8951          PathI != PathE; ++PathI) {
8952       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
8953       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
8954       if (!Result.castToDerived(Derived))
8955         return Error(E);
8956     }
8957     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
8958     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
8959       return Error(E);
8960     return true;
8961   }
8962 
8963   case CK_DerivedToBaseMemberPointer:
8964     if (!Visit(E->getSubExpr()))
8965       return false;
8966     for (CastExpr::path_const_iterator PathI = E->path_begin(),
8967          PathE = E->path_end(); PathI != PathE; ++PathI) {
8968       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
8969       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
8970       if (!Result.castToBase(Base))
8971         return Error(E);
8972     }
8973     return true;
8974   }
8975 }
8976 
8977 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8978   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
8979   // member can be formed.
8980   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
8981 }
8982 
8983 //===----------------------------------------------------------------------===//
8984 // Record Evaluation
8985 //===----------------------------------------------------------------------===//
8986 
8987 namespace {
8988   class RecordExprEvaluator
8989   : public ExprEvaluatorBase<RecordExprEvaluator> {
8990     const LValue &This;
8991     APValue &Result;
8992   public:
8993 
8994     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
8995       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
8996 
8997     bool Success(const APValue &V, const Expr *E) {
8998       Result = V;
8999       return true;
9000     }
9001     bool ZeroInitialization(const Expr *E) {
9002       return ZeroInitialization(E, E->getType());
9003     }
9004     bool ZeroInitialization(const Expr *E, QualType T);
9005 
9006     bool VisitCallExpr(const CallExpr *E) {
9007       return handleCallExpr(E, Result, &This);
9008     }
9009     bool VisitCastExpr(const CastExpr *E);
9010     bool VisitInitListExpr(const InitListExpr *E);
9011     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9012       return VisitCXXConstructExpr(E, E->getType());
9013     }
9014     bool VisitLambdaExpr(const LambdaExpr *E);
9015     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
9016     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
9017     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
9018     bool VisitBinCmp(const BinaryOperator *E);
9019   };
9020 }
9021 
9022 /// Perform zero-initialization on an object of non-union class type.
9023 /// C++11 [dcl.init]p5:
9024 ///  To zero-initialize an object or reference of type T means:
9025 ///    [...]
9026 ///    -- if T is a (possibly cv-qualified) non-union class type,
9027 ///       each non-static data member and each base-class subobject is
9028 ///       zero-initialized
9029 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
9030                                           const RecordDecl *RD,
9031                                           const LValue &This, APValue &Result) {
9032   assert(!RD->isUnion() && "Expected non-union class type");
9033   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
9034   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
9035                    std::distance(RD->field_begin(), RD->field_end()));
9036 
9037   if (RD->isInvalidDecl()) return false;
9038   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9039 
9040   if (CD) {
9041     unsigned Index = 0;
9042     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
9043            End = CD->bases_end(); I != End; ++I, ++Index) {
9044       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
9045       LValue Subobject = This;
9046       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
9047         return false;
9048       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
9049                                          Result.getStructBase(Index)))
9050         return false;
9051     }
9052   }
9053 
9054   for (const auto *I : RD->fields()) {
9055     // -- if T is a reference type, no initialization is performed.
9056     if (I->getType()->isReferenceType())
9057       continue;
9058 
9059     LValue Subobject = This;
9060     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
9061       return false;
9062 
9063     ImplicitValueInitExpr VIE(I->getType());
9064     if (!EvaluateInPlace(
9065           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
9066       return false;
9067   }
9068 
9069   return true;
9070 }
9071 
9072 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
9073   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
9074   if (RD->isInvalidDecl()) return false;
9075   if (RD->isUnion()) {
9076     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
9077     // object's first non-static named data member is zero-initialized
9078     RecordDecl::field_iterator I = RD->field_begin();
9079     if (I == RD->field_end()) {
9080       Result = APValue((const FieldDecl*)nullptr);
9081       return true;
9082     }
9083 
9084     LValue Subobject = This;
9085     if (!HandleLValueMember(Info, E, Subobject, *I))
9086       return false;
9087     Result = APValue(*I);
9088     ImplicitValueInitExpr VIE(I->getType());
9089     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
9090   }
9091 
9092   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
9093     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
9094     return false;
9095   }
9096 
9097   return HandleClassZeroInitialization(Info, E, RD, This, Result);
9098 }
9099 
9100 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
9101   switch (E->getCastKind()) {
9102   default:
9103     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9104 
9105   case CK_ConstructorConversion:
9106     return Visit(E->getSubExpr());
9107 
9108   case CK_DerivedToBase:
9109   case CK_UncheckedDerivedToBase: {
9110     APValue DerivedObject;
9111     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
9112       return false;
9113     if (!DerivedObject.isStruct())
9114       return Error(E->getSubExpr());
9115 
9116     // Derived-to-base rvalue conversion: just slice off the derived part.
9117     APValue *Value = &DerivedObject;
9118     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
9119     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9120          PathE = E->path_end(); PathI != PathE; ++PathI) {
9121       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
9122       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9123       Value = &Value->getStructBase(getBaseIndex(RD, Base));
9124       RD = Base;
9125     }
9126     Result = *Value;
9127     return true;
9128   }
9129   }
9130 }
9131 
9132 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9133   if (E->isTransparent())
9134     return Visit(E->getInit(0));
9135 
9136   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
9137   if (RD->isInvalidDecl()) return false;
9138   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9139   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
9140 
9141   EvalInfo::EvaluatingConstructorRAII EvalObj(
9142       Info,
9143       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
9144       CXXRD && CXXRD->getNumBases());
9145 
9146   if (RD->isUnion()) {
9147     const FieldDecl *Field = E->getInitializedFieldInUnion();
9148     Result = APValue(Field);
9149     if (!Field)
9150       return true;
9151 
9152     // If the initializer list for a union does not contain any elements, the
9153     // first element of the union is value-initialized.
9154     // FIXME: The element should be initialized from an initializer list.
9155     //        Is this difference ever observable for initializer lists which
9156     //        we don't build?
9157     ImplicitValueInitExpr VIE(Field->getType());
9158     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
9159 
9160     LValue Subobject = This;
9161     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
9162       return false;
9163 
9164     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9165     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9166                                   isa<CXXDefaultInitExpr>(InitExpr));
9167 
9168     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
9169   }
9170 
9171   if (!Result.hasValue())
9172     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
9173                      std::distance(RD->field_begin(), RD->field_end()));
9174   unsigned ElementNo = 0;
9175   bool Success = true;
9176 
9177   // Initialize base classes.
9178   if (CXXRD && CXXRD->getNumBases()) {
9179     for (const auto &Base : CXXRD->bases()) {
9180       assert(ElementNo < E->getNumInits() && "missing init for base class");
9181       const Expr *Init = E->getInit(ElementNo);
9182 
9183       LValue Subobject = This;
9184       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
9185         return false;
9186 
9187       APValue &FieldVal = Result.getStructBase(ElementNo);
9188       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
9189         if (!Info.noteFailure())
9190           return false;
9191         Success = false;
9192       }
9193       ++ElementNo;
9194     }
9195 
9196     EvalObj.finishedConstructingBases();
9197   }
9198 
9199   // Initialize members.
9200   for (const auto *Field : RD->fields()) {
9201     // Anonymous bit-fields are not considered members of the class for
9202     // purposes of aggregate initialization.
9203     if (Field->isUnnamedBitfield())
9204       continue;
9205 
9206     LValue Subobject = This;
9207 
9208     bool HaveInit = ElementNo < E->getNumInits();
9209 
9210     // FIXME: Diagnostics here should point to the end of the initializer
9211     // list, not the start.
9212     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
9213                             Subobject, Field, &Layout))
9214       return false;
9215 
9216     // Perform an implicit value-initialization for members beyond the end of
9217     // the initializer list.
9218     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
9219     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
9220 
9221     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9222     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9223                                   isa<CXXDefaultInitExpr>(Init));
9224 
9225     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9226     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
9227         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
9228                                                        FieldVal, Field))) {
9229       if (!Info.noteFailure())
9230         return false;
9231       Success = false;
9232     }
9233   }
9234 
9235   EvalObj.finishedConstructingFields();
9236 
9237   return Success;
9238 }
9239 
9240 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
9241                                                 QualType T) {
9242   // Note that E's type is not necessarily the type of our class here; we might
9243   // be initializing an array element instead.
9244   const CXXConstructorDecl *FD = E->getConstructor();
9245   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
9246 
9247   bool ZeroInit = E->requiresZeroInitialization();
9248   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
9249     // If we've already performed zero-initialization, we're already done.
9250     if (Result.hasValue())
9251       return true;
9252 
9253     if (ZeroInit)
9254       return ZeroInitialization(E, T);
9255 
9256     Result = getDefaultInitValue(T);
9257     return true;
9258   }
9259 
9260   const FunctionDecl *Definition = nullptr;
9261   auto Body = FD->getBody(Definition);
9262 
9263   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9264     return false;
9265 
9266   // Avoid materializing a temporary for an elidable copy/move constructor.
9267   if (E->isElidable() && !ZeroInit)
9268     if (const MaterializeTemporaryExpr *ME
9269           = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
9270       return Visit(ME->getSubExpr());
9271 
9272   if (ZeroInit && !ZeroInitialization(E, T))
9273     return false;
9274 
9275   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
9276   return HandleConstructorCall(E, This, Args,
9277                                cast<CXXConstructorDecl>(Definition), Info,
9278                                Result);
9279 }
9280 
9281 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
9282     const CXXInheritedCtorInitExpr *E) {
9283   if (!Info.CurrentCall) {
9284     assert(Info.checkingPotentialConstantExpression());
9285     return false;
9286   }
9287 
9288   const CXXConstructorDecl *FD = E->getConstructor();
9289   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
9290     return false;
9291 
9292   const FunctionDecl *Definition = nullptr;
9293   auto Body = FD->getBody(Definition);
9294 
9295   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9296     return false;
9297 
9298   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
9299                                cast<CXXConstructorDecl>(Definition), Info,
9300                                Result);
9301 }
9302 
9303 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
9304     const CXXStdInitializerListExpr *E) {
9305   const ConstantArrayType *ArrayType =
9306       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
9307 
9308   LValue Array;
9309   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
9310     return false;
9311 
9312   // Get a pointer to the first element of the array.
9313   Array.addArray(Info, E, ArrayType);
9314 
9315   // FIXME: Perform the checks on the field types in SemaInit.
9316   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
9317   RecordDecl::field_iterator Field = Record->field_begin();
9318   if (Field == Record->field_end())
9319     return Error(E);
9320 
9321   // Start pointer.
9322   if (!Field->getType()->isPointerType() ||
9323       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
9324                             ArrayType->getElementType()))
9325     return Error(E);
9326 
9327   // FIXME: What if the initializer_list type has base classes, etc?
9328   Result = APValue(APValue::UninitStruct(), 0, 2);
9329   Array.moveInto(Result.getStructField(0));
9330 
9331   if (++Field == Record->field_end())
9332     return Error(E);
9333 
9334   if (Field->getType()->isPointerType() &&
9335       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
9336                            ArrayType->getElementType())) {
9337     // End pointer.
9338     if (!HandleLValueArrayAdjustment(Info, E, Array,
9339                                      ArrayType->getElementType(),
9340                                      ArrayType->getSize().getZExtValue()))
9341       return false;
9342     Array.moveInto(Result.getStructField(1));
9343   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
9344     // Length.
9345     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
9346   else
9347     return Error(E);
9348 
9349   if (++Field != Record->field_end())
9350     return Error(E);
9351 
9352   return true;
9353 }
9354 
9355 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
9356   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
9357   if (ClosureClass->isInvalidDecl())
9358     return false;
9359 
9360   const size_t NumFields =
9361       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
9362 
9363   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
9364                                             E->capture_init_end()) &&
9365          "The number of lambda capture initializers should equal the number of "
9366          "fields within the closure type");
9367 
9368   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
9369   // Iterate through all the lambda's closure object's fields and initialize
9370   // them.
9371   auto *CaptureInitIt = E->capture_init_begin();
9372   const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
9373   bool Success = true;
9374   for (const auto *Field : ClosureClass->fields()) {
9375     assert(CaptureInitIt != E->capture_init_end());
9376     // Get the initializer for this field
9377     Expr *const CurFieldInit = *CaptureInitIt++;
9378 
9379     // If there is no initializer, either this is a VLA or an error has
9380     // occurred.
9381     if (!CurFieldInit)
9382       return Error(E);
9383 
9384     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9385     if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
9386       if (!Info.keepEvaluatingAfterFailure())
9387         return false;
9388       Success = false;
9389     }
9390     ++CaptureIt;
9391   }
9392   return Success;
9393 }
9394 
9395 static bool EvaluateRecord(const Expr *E, const LValue &This,
9396                            APValue &Result, EvalInfo &Info) {
9397   assert(E->isRValue() && E->getType()->isRecordType() &&
9398          "can't evaluate expression as a record rvalue");
9399   return RecordExprEvaluator(Info, This, Result).Visit(E);
9400 }
9401 
9402 //===----------------------------------------------------------------------===//
9403 // Temporary Evaluation
9404 //
9405 // Temporaries are represented in the AST as rvalues, but generally behave like
9406 // lvalues. The full-object of which the temporary is a subobject is implicitly
9407 // materialized so that a reference can bind to it.
9408 //===----------------------------------------------------------------------===//
9409 namespace {
9410 class TemporaryExprEvaluator
9411   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
9412 public:
9413   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
9414     LValueExprEvaluatorBaseTy(Info, Result, false) {}
9415 
9416   /// Visit an expression which constructs the value of this temporary.
9417   bool VisitConstructExpr(const Expr *E) {
9418     APValue &Value =
9419         Info.CurrentCall->createTemporary(E, E->getType(), false, Result);
9420     return EvaluateInPlace(Value, Info, Result, E);
9421   }
9422 
9423   bool VisitCastExpr(const CastExpr *E) {
9424     switch (E->getCastKind()) {
9425     default:
9426       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
9427 
9428     case CK_ConstructorConversion:
9429       return VisitConstructExpr(E->getSubExpr());
9430     }
9431   }
9432   bool VisitInitListExpr(const InitListExpr *E) {
9433     return VisitConstructExpr(E);
9434   }
9435   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9436     return VisitConstructExpr(E);
9437   }
9438   bool VisitCallExpr(const CallExpr *E) {
9439     return VisitConstructExpr(E);
9440   }
9441   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
9442     return VisitConstructExpr(E);
9443   }
9444   bool VisitLambdaExpr(const LambdaExpr *E) {
9445     return VisitConstructExpr(E);
9446   }
9447 };
9448 } // end anonymous namespace
9449 
9450 /// Evaluate an expression of record type as a temporary.
9451 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
9452   assert(E->isRValue() && E->getType()->isRecordType());
9453   return TemporaryExprEvaluator(Info, Result).Visit(E);
9454 }
9455 
9456 //===----------------------------------------------------------------------===//
9457 // Vector Evaluation
9458 //===----------------------------------------------------------------------===//
9459 
9460 namespace {
9461   class VectorExprEvaluator
9462   : public ExprEvaluatorBase<VectorExprEvaluator> {
9463     APValue &Result;
9464   public:
9465 
9466     VectorExprEvaluator(EvalInfo &info, APValue &Result)
9467       : ExprEvaluatorBaseTy(info), Result(Result) {}
9468 
9469     bool Success(ArrayRef<APValue> V, const Expr *E) {
9470       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
9471       // FIXME: remove this APValue copy.
9472       Result = APValue(V.data(), V.size());
9473       return true;
9474     }
9475     bool Success(const APValue &V, const Expr *E) {
9476       assert(V.isVector());
9477       Result = V;
9478       return true;
9479     }
9480     bool ZeroInitialization(const Expr *E);
9481 
9482     bool VisitUnaryReal(const UnaryOperator *E)
9483       { return Visit(E->getSubExpr()); }
9484     bool VisitCastExpr(const CastExpr* E);
9485     bool VisitInitListExpr(const InitListExpr *E);
9486     bool VisitUnaryImag(const UnaryOperator *E);
9487     // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
9488     //                 binary comparisons, binary and/or/xor,
9489     //                 conditional operator (for GNU conditional select),
9490     //                 shufflevector, ExtVectorElementExpr
9491   };
9492 } // end anonymous namespace
9493 
9494 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
9495   assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
9496   return VectorExprEvaluator(Info, Result).Visit(E);
9497 }
9498 
9499 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
9500   const VectorType *VTy = E->getType()->castAs<VectorType>();
9501   unsigned NElts = VTy->getNumElements();
9502 
9503   const Expr *SE = E->getSubExpr();
9504   QualType SETy = SE->getType();
9505 
9506   switch (E->getCastKind()) {
9507   case CK_VectorSplat: {
9508     APValue Val = APValue();
9509     if (SETy->isIntegerType()) {
9510       APSInt IntResult;
9511       if (!EvaluateInteger(SE, IntResult, Info))
9512         return false;
9513       Val = APValue(std::move(IntResult));
9514     } else if (SETy->isRealFloatingType()) {
9515       APFloat FloatResult(0.0);
9516       if (!EvaluateFloat(SE, FloatResult, Info))
9517         return false;
9518       Val = APValue(std::move(FloatResult));
9519     } else {
9520       return Error(E);
9521     }
9522 
9523     // Splat and create vector APValue.
9524     SmallVector<APValue, 4> Elts(NElts, Val);
9525     return Success(Elts, E);
9526   }
9527   case CK_BitCast: {
9528     // Evaluate the operand into an APInt we can extract from.
9529     llvm::APInt SValInt;
9530     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
9531       return false;
9532     // Extract the elements
9533     QualType EltTy = VTy->getElementType();
9534     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
9535     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
9536     SmallVector<APValue, 4> Elts;
9537     if (EltTy->isRealFloatingType()) {
9538       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
9539       unsigned FloatEltSize = EltSize;
9540       if (&Sem == &APFloat::x87DoubleExtended())
9541         FloatEltSize = 80;
9542       for (unsigned i = 0; i < NElts; i++) {
9543         llvm::APInt Elt;
9544         if (BigEndian)
9545           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
9546         else
9547           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
9548         Elts.push_back(APValue(APFloat(Sem, Elt)));
9549       }
9550     } else if (EltTy->isIntegerType()) {
9551       for (unsigned i = 0; i < NElts; i++) {
9552         llvm::APInt Elt;
9553         if (BigEndian)
9554           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
9555         else
9556           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
9557         Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
9558       }
9559     } else {
9560       return Error(E);
9561     }
9562     return Success(Elts, E);
9563   }
9564   default:
9565     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9566   }
9567 }
9568 
9569 bool
9570 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9571   const VectorType *VT = E->getType()->castAs<VectorType>();
9572   unsigned NumInits = E->getNumInits();
9573   unsigned NumElements = VT->getNumElements();
9574 
9575   QualType EltTy = VT->getElementType();
9576   SmallVector<APValue, 4> Elements;
9577 
9578   // The number of initializers can be less than the number of
9579   // vector elements. For OpenCL, this can be due to nested vector
9580   // initialization. For GCC compatibility, missing trailing elements
9581   // should be initialized with zeroes.
9582   unsigned CountInits = 0, CountElts = 0;
9583   while (CountElts < NumElements) {
9584     // Handle nested vector initialization.
9585     if (CountInits < NumInits
9586         && E->getInit(CountInits)->getType()->isVectorType()) {
9587       APValue v;
9588       if (!EvaluateVector(E->getInit(CountInits), v, Info))
9589         return Error(E);
9590       unsigned vlen = v.getVectorLength();
9591       for (unsigned j = 0; j < vlen; j++)
9592         Elements.push_back(v.getVectorElt(j));
9593       CountElts += vlen;
9594     } else if (EltTy->isIntegerType()) {
9595       llvm::APSInt sInt(32);
9596       if (CountInits < NumInits) {
9597         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
9598           return false;
9599       } else // trailing integer zero.
9600         sInt = Info.Ctx.MakeIntValue(0, EltTy);
9601       Elements.push_back(APValue(sInt));
9602       CountElts++;
9603     } else {
9604       llvm::APFloat f(0.0);
9605       if (CountInits < NumInits) {
9606         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
9607           return false;
9608       } else // trailing float zero.
9609         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
9610       Elements.push_back(APValue(f));
9611       CountElts++;
9612     }
9613     CountInits++;
9614   }
9615   return Success(Elements, E);
9616 }
9617 
9618 bool
9619 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
9620   const auto *VT = E->getType()->castAs<VectorType>();
9621   QualType EltTy = VT->getElementType();
9622   APValue ZeroElement;
9623   if (EltTy->isIntegerType())
9624     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
9625   else
9626     ZeroElement =
9627         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
9628 
9629   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
9630   return Success(Elements, E);
9631 }
9632 
9633 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9634   VisitIgnoredValue(E->getSubExpr());
9635   return ZeroInitialization(E);
9636 }
9637 
9638 //===----------------------------------------------------------------------===//
9639 // Array Evaluation
9640 //===----------------------------------------------------------------------===//
9641 
9642 namespace {
9643   class ArrayExprEvaluator
9644   : public ExprEvaluatorBase<ArrayExprEvaluator> {
9645     const LValue &This;
9646     APValue &Result;
9647   public:
9648 
9649     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
9650       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
9651 
9652     bool Success(const APValue &V, const Expr *E) {
9653       assert(V.isArray() && "expected array");
9654       Result = V;
9655       return true;
9656     }
9657 
9658     bool ZeroInitialization(const Expr *E) {
9659       const ConstantArrayType *CAT =
9660           Info.Ctx.getAsConstantArrayType(E->getType());
9661       if (!CAT)
9662         return Error(E);
9663 
9664       Result = APValue(APValue::UninitArray(), 0,
9665                        CAT->getSize().getZExtValue());
9666       if (!Result.hasArrayFiller()) return true;
9667 
9668       // Zero-initialize all elements.
9669       LValue Subobject = This;
9670       Subobject.addArray(Info, E, CAT);
9671       ImplicitValueInitExpr VIE(CAT->getElementType());
9672       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
9673     }
9674 
9675     bool VisitCallExpr(const CallExpr *E) {
9676       return handleCallExpr(E, Result, &This);
9677     }
9678     bool VisitInitListExpr(const InitListExpr *E,
9679                            QualType AllocType = QualType());
9680     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
9681     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
9682     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
9683                                const LValue &Subobject,
9684                                APValue *Value, QualType Type);
9685     bool VisitStringLiteral(const StringLiteral *E,
9686                             QualType AllocType = QualType()) {
9687       expandStringLiteral(Info, E, Result, AllocType);
9688       return true;
9689     }
9690   };
9691 } // end anonymous namespace
9692 
9693 static bool EvaluateArray(const Expr *E, const LValue &This,
9694                           APValue &Result, EvalInfo &Info) {
9695   assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
9696   return ArrayExprEvaluator(Info, This, Result).Visit(E);
9697 }
9698 
9699 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9700                                      APValue &Result, const InitListExpr *ILE,
9701                                      QualType AllocType) {
9702   assert(ILE->isRValue() && ILE->getType()->isArrayType() &&
9703          "not an array rvalue");
9704   return ArrayExprEvaluator(Info, This, Result)
9705       .VisitInitListExpr(ILE, AllocType);
9706 }
9707 
9708 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
9709                                           APValue &Result,
9710                                           const CXXConstructExpr *CCE,
9711                                           QualType AllocType) {
9712   assert(CCE->isRValue() && CCE->getType()->isArrayType() &&
9713          "not an array rvalue");
9714   return ArrayExprEvaluator(Info, This, Result)
9715       .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
9716 }
9717 
9718 // Return true iff the given array filler may depend on the element index.
9719 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
9720   // For now, just whitelist non-class value-initialization and initialization
9721   // lists comprised of them.
9722   if (isa<ImplicitValueInitExpr>(FillerExpr))
9723     return false;
9724   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
9725     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
9726       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
9727         return true;
9728     }
9729     return false;
9730   }
9731   return true;
9732 }
9733 
9734 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
9735                                            QualType AllocType) {
9736   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
9737       AllocType.isNull() ? E->getType() : AllocType);
9738   if (!CAT)
9739     return Error(E);
9740 
9741   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
9742   // an appropriately-typed string literal enclosed in braces.
9743   if (E->isStringLiteralInit()) {
9744     auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens());
9745     // FIXME: Support ObjCEncodeExpr here once we support it in
9746     // ArrayExprEvaluator generally.
9747     if (!SL)
9748       return Error(E);
9749     return VisitStringLiteral(SL, AllocType);
9750   }
9751 
9752   bool Success = true;
9753 
9754   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
9755          "zero-initialized array shouldn't have any initialized elts");
9756   APValue Filler;
9757   if (Result.isArray() && Result.hasArrayFiller())
9758     Filler = Result.getArrayFiller();
9759 
9760   unsigned NumEltsToInit = E->getNumInits();
9761   unsigned NumElts = CAT->getSize().getZExtValue();
9762   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
9763 
9764   // If the initializer might depend on the array index, run it for each
9765   // array element.
9766   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
9767     NumEltsToInit = NumElts;
9768 
9769   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
9770                           << NumEltsToInit << ".\n");
9771 
9772   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
9773 
9774   // If the array was previously zero-initialized, preserve the
9775   // zero-initialized values.
9776   if (Filler.hasValue()) {
9777     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
9778       Result.getArrayInitializedElt(I) = Filler;
9779     if (Result.hasArrayFiller())
9780       Result.getArrayFiller() = Filler;
9781   }
9782 
9783   LValue Subobject = This;
9784   Subobject.addArray(Info, E, CAT);
9785   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
9786     const Expr *Init =
9787         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
9788     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
9789                          Info, Subobject, Init) ||
9790         !HandleLValueArrayAdjustment(Info, Init, Subobject,
9791                                      CAT->getElementType(), 1)) {
9792       if (!Info.noteFailure())
9793         return false;
9794       Success = false;
9795     }
9796   }
9797 
9798   if (!Result.hasArrayFiller())
9799     return Success;
9800 
9801   // If we get here, we have a trivial filler, which we can just evaluate
9802   // once and splat over the rest of the array elements.
9803   assert(FillerExpr && "no array filler for incomplete init list");
9804   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
9805                          FillerExpr) && Success;
9806 }
9807 
9808 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
9809   LValue CommonLV;
9810   if (E->getCommonExpr() &&
9811       !Evaluate(Info.CurrentCall->createTemporary(
9812                     E->getCommonExpr(),
9813                     getStorageType(Info.Ctx, E->getCommonExpr()), false,
9814                     CommonLV),
9815                 Info, E->getCommonExpr()->getSourceExpr()))
9816     return false;
9817 
9818   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
9819 
9820   uint64_t Elements = CAT->getSize().getZExtValue();
9821   Result = APValue(APValue::UninitArray(), Elements, Elements);
9822 
9823   LValue Subobject = This;
9824   Subobject.addArray(Info, E, CAT);
9825 
9826   bool Success = true;
9827   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
9828     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
9829                          Info, Subobject, E->getSubExpr()) ||
9830         !HandleLValueArrayAdjustment(Info, E, Subobject,
9831                                      CAT->getElementType(), 1)) {
9832       if (!Info.noteFailure())
9833         return false;
9834       Success = false;
9835     }
9836   }
9837 
9838   return Success;
9839 }
9840 
9841 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
9842   return VisitCXXConstructExpr(E, This, &Result, E->getType());
9843 }
9844 
9845 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
9846                                                const LValue &Subobject,
9847                                                APValue *Value,
9848                                                QualType Type) {
9849   bool HadZeroInit = Value->hasValue();
9850 
9851   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
9852     unsigned N = CAT->getSize().getZExtValue();
9853 
9854     // Preserve the array filler if we had prior zero-initialization.
9855     APValue Filler =
9856       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
9857                                              : APValue();
9858 
9859     *Value = APValue(APValue::UninitArray(), N, N);
9860 
9861     if (HadZeroInit)
9862       for (unsigned I = 0; I != N; ++I)
9863         Value->getArrayInitializedElt(I) = Filler;
9864 
9865     // Initialize the elements.
9866     LValue ArrayElt = Subobject;
9867     ArrayElt.addArray(Info, E, CAT);
9868     for (unsigned I = 0; I != N; ++I)
9869       if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
9870                                  CAT->getElementType()) ||
9871           !HandleLValueArrayAdjustment(Info, E, ArrayElt,
9872                                        CAT->getElementType(), 1))
9873         return false;
9874 
9875     return true;
9876   }
9877 
9878   if (!Type->isRecordType())
9879     return Error(E);
9880 
9881   return RecordExprEvaluator(Info, Subobject, *Value)
9882              .VisitCXXConstructExpr(E, Type);
9883 }
9884 
9885 //===----------------------------------------------------------------------===//
9886 // Integer Evaluation
9887 //
9888 // As a GNU extension, we support casting pointers to sufficiently-wide integer
9889 // types and back in constant folding. Integer values are thus represented
9890 // either as an integer-valued APValue, or as an lvalue-valued APValue.
9891 //===----------------------------------------------------------------------===//
9892 
9893 namespace {
9894 class IntExprEvaluator
9895         : public ExprEvaluatorBase<IntExprEvaluator> {
9896   APValue &Result;
9897 public:
9898   IntExprEvaluator(EvalInfo &info, APValue &result)
9899       : ExprEvaluatorBaseTy(info), Result(result) {}
9900 
9901   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
9902     assert(E->getType()->isIntegralOrEnumerationType() &&
9903            "Invalid evaluation result.");
9904     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
9905            "Invalid evaluation result.");
9906     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
9907            "Invalid evaluation result.");
9908     Result = APValue(SI);
9909     return true;
9910   }
9911   bool Success(const llvm::APSInt &SI, const Expr *E) {
9912     return Success(SI, E, Result);
9913   }
9914 
9915   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
9916     assert(E->getType()->isIntegralOrEnumerationType() &&
9917            "Invalid evaluation result.");
9918     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
9919            "Invalid evaluation result.");
9920     Result = APValue(APSInt(I));
9921     Result.getInt().setIsUnsigned(
9922                             E->getType()->isUnsignedIntegerOrEnumerationType());
9923     return true;
9924   }
9925   bool Success(const llvm::APInt &I, const Expr *E) {
9926     return Success(I, E, Result);
9927   }
9928 
9929   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
9930     assert(E->getType()->isIntegralOrEnumerationType() &&
9931            "Invalid evaluation result.");
9932     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
9933     return true;
9934   }
9935   bool Success(uint64_t Value, const Expr *E) {
9936     return Success(Value, E, Result);
9937   }
9938 
9939   bool Success(CharUnits Size, const Expr *E) {
9940     return Success(Size.getQuantity(), E);
9941   }
9942 
9943   bool Success(const APValue &V, const Expr *E) {
9944     if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
9945       Result = V;
9946       return true;
9947     }
9948     return Success(V.getInt(), E);
9949   }
9950 
9951   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
9952 
9953   //===--------------------------------------------------------------------===//
9954   //                            Visitor Methods
9955   //===--------------------------------------------------------------------===//
9956 
9957   bool VisitConstantExpr(const ConstantExpr *E);
9958 
9959   bool VisitIntegerLiteral(const IntegerLiteral *E) {
9960     return Success(E->getValue(), E);
9961   }
9962   bool VisitCharacterLiteral(const CharacterLiteral *E) {
9963     return Success(E->getValue(), E);
9964   }
9965 
9966   bool CheckReferencedDecl(const Expr *E, const Decl *D);
9967   bool VisitDeclRefExpr(const DeclRefExpr *E) {
9968     if (CheckReferencedDecl(E, E->getDecl()))
9969       return true;
9970 
9971     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
9972   }
9973   bool VisitMemberExpr(const MemberExpr *E) {
9974     if (CheckReferencedDecl(E, E->getMemberDecl())) {
9975       VisitIgnoredBaseExpression(E->getBase());
9976       return true;
9977     }
9978 
9979     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
9980   }
9981 
9982   bool VisitCallExpr(const CallExpr *E);
9983   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
9984   bool VisitBinaryOperator(const BinaryOperator *E);
9985   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
9986   bool VisitUnaryOperator(const UnaryOperator *E);
9987 
9988   bool VisitCastExpr(const CastExpr* E);
9989   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
9990 
9991   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
9992     return Success(E->getValue(), E);
9993   }
9994 
9995   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
9996     return Success(E->getValue(), E);
9997   }
9998 
9999   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
10000     if (Info.ArrayInitIndex == uint64_t(-1)) {
10001       // We were asked to evaluate this subexpression independent of the
10002       // enclosing ArrayInitLoopExpr. We can't do that.
10003       Info.FFDiag(E);
10004       return false;
10005     }
10006     return Success(Info.ArrayInitIndex, E);
10007   }
10008 
10009   // Note, GNU defines __null as an integer, not a pointer.
10010   bool VisitGNUNullExpr(const GNUNullExpr *E) {
10011     return ZeroInitialization(E);
10012   }
10013 
10014   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
10015     return Success(E->getValue(), E);
10016   }
10017 
10018   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
10019     return Success(E->getValue(), E);
10020   }
10021 
10022   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
10023     return Success(E->getValue(), E);
10024   }
10025 
10026   bool VisitUnaryReal(const UnaryOperator *E);
10027   bool VisitUnaryImag(const UnaryOperator *E);
10028 
10029   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
10030   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
10031   bool VisitSourceLocExpr(const SourceLocExpr *E);
10032   bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
10033   bool VisitRequiresExpr(const RequiresExpr *E);
10034   // FIXME: Missing: array subscript of vector, member of vector
10035 };
10036 
10037 class FixedPointExprEvaluator
10038     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
10039   APValue &Result;
10040 
10041  public:
10042   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
10043       : ExprEvaluatorBaseTy(info), Result(result) {}
10044 
10045   bool Success(const llvm::APInt &I, const Expr *E) {
10046     return Success(
10047         APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10048   }
10049 
10050   bool Success(uint64_t Value, const Expr *E) {
10051     return Success(
10052         APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10053   }
10054 
10055   bool Success(const APValue &V, const Expr *E) {
10056     return Success(V.getFixedPoint(), E);
10057   }
10058 
10059   bool Success(const APFixedPoint &V, const Expr *E) {
10060     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
10061     assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10062            "Invalid evaluation result.");
10063     Result = APValue(V);
10064     return true;
10065   }
10066 
10067   //===--------------------------------------------------------------------===//
10068   //                            Visitor Methods
10069   //===--------------------------------------------------------------------===//
10070 
10071   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
10072     return Success(E->getValue(), E);
10073   }
10074 
10075   bool VisitCastExpr(const CastExpr *E);
10076   bool VisitUnaryOperator(const UnaryOperator *E);
10077   bool VisitBinaryOperator(const BinaryOperator *E);
10078 };
10079 } // end anonymous namespace
10080 
10081 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
10082 /// produce either the integer value or a pointer.
10083 ///
10084 /// GCC has a heinous extension which folds casts between pointer types and
10085 /// pointer-sized integral types. We support this by allowing the evaluation of
10086 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
10087 /// Some simple arithmetic on such values is supported (they are treated much
10088 /// like char*).
10089 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
10090                                     EvalInfo &Info) {
10091   assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
10092   return IntExprEvaluator(Info, Result).Visit(E);
10093 }
10094 
10095 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
10096   APValue Val;
10097   if (!EvaluateIntegerOrLValue(E, Val, Info))
10098     return false;
10099   if (!Val.isInt()) {
10100     // FIXME: It would be better to produce the diagnostic for casting
10101     //        a pointer to an integer.
10102     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10103     return false;
10104   }
10105   Result = Val.getInt();
10106   return true;
10107 }
10108 
10109 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
10110   APValue Evaluated = E->EvaluateInContext(
10111       Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
10112   return Success(Evaluated, E);
10113 }
10114 
10115 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
10116                                EvalInfo &Info) {
10117   if (E->getType()->isFixedPointType()) {
10118     APValue Val;
10119     if (!FixedPointExprEvaluator(Info, Val).Visit(E))
10120       return false;
10121     if (!Val.isFixedPoint())
10122       return false;
10123 
10124     Result = Val.getFixedPoint();
10125     return true;
10126   }
10127   return false;
10128 }
10129 
10130 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
10131                                         EvalInfo &Info) {
10132   if (E->getType()->isIntegerType()) {
10133     auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
10134     APSInt Val;
10135     if (!EvaluateInteger(E, Val, Info))
10136       return false;
10137     Result = APFixedPoint(Val, FXSema);
10138     return true;
10139   } else if (E->getType()->isFixedPointType()) {
10140     return EvaluateFixedPoint(E, Result, Info);
10141   }
10142   return false;
10143 }
10144 
10145 /// Check whether the given declaration can be directly converted to an integral
10146 /// rvalue. If not, no diagnostic is produced; there are other things we can
10147 /// try.
10148 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
10149   // Enums are integer constant exprs.
10150   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
10151     // Check for signedness/width mismatches between E type and ECD value.
10152     bool SameSign = (ECD->getInitVal().isSigned()
10153                      == E->getType()->isSignedIntegerOrEnumerationType());
10154     bool SameWidth = (ECD->getInitVal().getBitWidth()
10155                       == Info.Ctx.getIntWidth(E->getType()));
10156     if (SameSign && SameWidth)
10157       return Success(ECD->getInitVal(), E);
10158     else {
10159       // Get rid of mismatch (otherwise Success assertions will fail)
10160       // by computing a new value matching the type of E.
10161       llvm::APSInt Val = ECD->getInitVal();
10162       if (!SameSign)
10163         Val.setIsSigned(!ECD->getInitVal().isSigned());
10164       if (!SameWidth)
10165         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
10166       return Success(Val, E);
10167     }
10168   }
10169   return false;
10170 }
10171 
10172 /// Values returned by __builtin_classify_type, chosen to match the values
10173 /// produced by GCC's builtin.
10174 enum class GCCTypeClass {
10175   None = -1,
10176   Void = 0,
10177   Integer = 1,
10178   // GCC reserves 2 for character types, but instead classifies them as
10179   // integers.
10180   Enum = 3,
10181   Bool = 4,
10182   Pointer = 5,
10183   // GCC reserves 6 for references, but appears to never use it (because
10184   // expressions never have reference type, presumably).
10185   PointerToDataMember = 7,
10186   RealFloat = 8,
10187   Complex = 9,
10188   // GCC reserves 10 for functions, but does not use it since GCC version 6 due
10189   // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
10190   // GCC claims to reserve 11 for pointers to member functions, but *actually*
10191   // uses 12 for that purpose, same as for a class or struct. Maybe it
10192   // internally implements a pointer to member as a struct?  Who knows.
10193   PointerToMemberFunction = 12, // Not a bug, see above.
10194   ClassOrStruct = 12,
10195   Union = 13,
10196   // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
10197   // decay to pointer. (Prior to version 6 it was only used in C++ mode).
10198   // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
10199   // literals.
10200 };
10201 
10202 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
10203 /// as GCC.
10204 static GCCTypeClass
10205 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
10206   assert(!T->isDependentType() && "unexpected dependent type");
10207 
10208   QualType CanTy = T.getCanonicalType();
10209   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
10210 
10211   switch (CanTy->getTypeClass()) {
10212 #define TYPE(ID, BASE)
10213 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
10214 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
10215 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
10216 #include "clang/AST/TypeNodes.inc"
10217   case Type::Auto:
10218   case Type::DeducedTemplateSpecialization:
10219       llvm_unreachable("unexpected non-canonical or dependent type");
10220 
10221   case Type::Builtin:
10222     switch (BT->getKind()) {
10223 #define BUILTIN_TYPE(ID, SINGLETON_ID)
10224 #define SIGNED_TYPE(ID, SINGLETON_ID) \
10225     case BuiltinType::ID: return GCCTypeClass::Integer;
10226 #define FLOATING_TYPE(ID, SINGLETON_ID) \
10227     case BuiltinType::ID: return GCCTypeClass::RealFloat;
10228 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
10229     case BuiltinType::ID: break;
10230 #include "clang/AST/BuiltinTypes.def"
10231     case BuiltinType::Void:
10232       return GCCTypeClass::Void;
10233 
10234     case BuiltinType::Bool:
10235       return GCCTypeClass::Bool;
10236 
10237     case BuiltinType::Char_U:
10238     case BuiltinType::UChar:
10239     case BuiltinType::WChar_U:
10240     case BuiltinType::Char8:
10241     case BuiltinType::Char16:
10242     case BuiltinType::Char32:
10243     case BuiltinType::UShort:
10244     case BuiltinType::UInt:
10245     case BuiltinType::ULong:
10246     case BuiltinType::ULongLong:
10247     case BuiltinType::UInt128:
10248       return GCCTypeClass::Integer;
10249 
10250     case BuiltinType::UShortAccum:
10251     case BuiltinType::UAccum:
10252     case BuiltinType::ULongAccum:
10253     case BuiltinType::UShortFract:
10254     case BuiltinType::UFract:
10255     case BuiltinType::ULongFract:
10256     case BuiltinType::SatUShortAccum:
10257     case BuiltinType::SatUAccum:
10258     case BuiltinType::SatULongAccum:
10259     case BuiltinType::SatUShortFract:
10260     case BuiltinType::SatUFract:
10261     case BuiltinType::SatULongFract:
10262       return GCCTypeClass::None;
10263 
10264     case BuiltinType::NullPtr:
10265 
10266     case BuiltinType::ObjCId:
10267     case BuiltinType::ObjCClass:
10268     case BuiltinType::ObjCSel:
10269 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
10270     case BuiltinType::Id:
10271 #include "clang/Basic/OpenCLImageTypes.def"
10272 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
10273     case BuiltinType::Id:
10274 #include "clang/Basic/OpenCLExtensionTypes.def"
10275     case BuiltinType::OCLSampler:
10276     case BuiltinType::OCLEvent:
10277     case BuiltinType::OCLClkEvent:
10278     case BuiltinType::OCLQueue:
10279     case BuiltinType::OCLReserveID:
10280 #define SVE_TYPE(Name, Id, SingletonId) \
10281     case BuiltinType::Id:
10282 #include "clang/Basic/AArch64SVEACLETypes.def"
10283       return GCCTypeClass::None;
10284 
10285     case BuiltinType::Dependent:
10286       llvm_unreachable("unexpected dependent type");
10287     };
10288     llvm_unreachable("unexpected placeholder type");
10289 
10290   case Type::Enum:
10291     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
10292 
10293   case Type::Pointer:
10294   case Type::ConstantArray:
10295   case Type::VariableArray:
10296   case Type::IncompleteArray:
10297   case Type::FunctionNoProto:
10298   case Type::FunctionProto:
10299     return GCCTypeClass::Pointer;
10300 
10301   case Type::MemberPointer:
10302     return CanTy->isMemberDataPointerType()
10303                ? GCCTypeClass::PointerToDataMember
10304                : GCCTypeClass::PointerToMemberFunction;
10305 
10306   case Type::Complex:
10307     return GCCTypeClass::Complex;
10308 
10309   case Type::Record:
10310     return CanTy->isUnionType() ? GCCTypeClass::Union
10311                                 : GCCTypeClass::ClassOrStruct;
10312 
10313   case Type::Atomic:
10314     // GCC classifies _Atomic T the same as T.
10315     return EvaluateBuiltinClassifyType(
10316         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
10317 
10318   case Type::BlockPointer:
10319   case Type::Vector:
10320   case Type::ExtVector:
10321   case Type::ObjCObject:
10322   case Type::ObjCInterface:
10323   case Type::ObjCObjectPointer:
10324   case Type::Pipe:
10325     // GCC classifies vectors as None. We follow its lead and classify all
10326     // other types that don't fit into the regular classification the same way.
10327     return GCCTypeClass::None;
10328 
10329   case Type::LValueReference:
10330   case Type::RValueReference:
10331     llvm_unreachable("invalid type for expression");
10332   }
10333 
10334   llvm_unreachable("unexpected type class");
10335 }
10336 
10337 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
10338 /// as GCC.
10339 static GCCTypeClass
10340 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
10341   // If no argument was supplied, default to None. This isn't
10342   // ideal, however it is what gcc does.
10343   if (E->getNumArgs() == 0)
10344     return GCCTypeClass::None;
10345 
10346   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
10347   // being an ICE, but still folds it to a constant using the type of the first
10348   // argument.
10349   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
10350 }
10351 
10352 /// EvaluateBuiltinConstantPForLValue - Determine the result of
10353 /// __builtin_constant_p when applied to the given pointer.
10354 ///
10355 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
10356 /// or it points to the first character of a string literal.
10357 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
10358   APValue::LValueBase Base = LV.getLValueBase();
10359   if (Base.isNull()) {
10360     // A null base is acceptable.
10361     return true;
10362   } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
10363     if (!isa<StringLiteral>(E))
10364       return false;
10365     return LV.getLValueOffset().isZero();
10366   } else if (Base.is<TypeInfoLValue>()) {
10367     // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
10368     // evaluate to true.
10369     return true;
10370   } else {
10371     // Any other base is not constant enough for GCC.
10372     return false;
10373   }
10374 }
10375 
10376 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
10377 /// GCC as we can manage.
10378 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
10379   // This evaluation is not permitted to have side-effects, so evaluate it in
10380   // a speculative evaluation context.
10381   SpeculativeEvaluationRAII SpeculativeEval(Info);
10382 
10383   // Constant-folding is always enabled for the operand of __builtin_constant_p
10384   // (even when the enclosing evaluation context otherwise requires a strict
10385   // language-specific constant expression).
10386   FoldConstant Fold(Info, true);
10387 
10388   QualType ArgType = Arg->getType();
10389 
10390   // __builtin_constant_p always has one operand. The rules which gcc follows
10391   // are not precisely documented, but are as follows:
10392   //
10393   //  - If the operand is of integral, floating, complex or enumeration type,
10394   //    and can be folded to a known value of that type, it returns 1.
10395   //  - If the operand can be folded to a pointer to the first character
10396   //    of a string literal (or such a pointer cast to an integral type)
10397   //    or to a null pointer or an integer cast to a pointer, it returns 1.
10398   //
10399   // Otherwise, it returns 0.
10400   //
10401   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
10402   // its support for this did not work prior to GCC 9 and is not yet well
10403   // understood.
10404   if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
10405       ArgType->isAnyComplexType() || ArgType->isPointerType() ||
10406       ArgType->isNullPtrType()) {
10407     APValue V;
10408     if (!::EvaluateAsRValue(Info, Arg, V)) {
10409       Fold.keepDiagnostics();
10410       return false;
10411     }
10412 
10413     // For a pointer (possibly cast to integer), there are special rules.
10414     if (V.getKind() == APValue::LValue)
10415       return EvaluateBuiltinConstantPForLValue(V);
10416 
10417     // Otherwise, any constant value is good enough.
10418     return V.hasValue();
10419   }
10420 
10421   // Anything else isn't considered to be sufficiently constant.
10422   return false;
10423 }
10424 
10425 /// Retrieves the "underlying object type" of the given expression,
10426 /// as used by __builtin_object_size.
10427 static QualType getObjectType(APValue::LValueBase B) {
10428   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
10429     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
10430       return VD->getType();
10431   } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
10432     if (isa<CompoundLiteralExpr>(E))
10433       return E->getType();
10434   } else if (B.is<TypeInfoLValue>()) {
10435     return B.getTypeInfoType();
10436   } else if (B.is<DynamicAllocLValue>()) {
10437     return B.getDynamicAllocType();
10438   }
10439 
10440   return QualType();
10441 }
10442 
10443 /// A more selective version of E->IgnoreParenCasts for
10444 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
10445 /// to change the type of E.
10446 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
10447 ///
10448 /// Always returns an RValue with a pointer representation.
10449 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
10450   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
10451 
10452   auto *NoParens = E->IgnoreParens();
10453   auto *Cast = dyn_cast<CastExpr>(NoParens);
10454   if (Cast == nullptr)
10455     return NoParens;
10456 
10457   // We only conservatively allow a few kinds of casts, because this code is
10458   // inherently a simple solution that seeks to support the common case.
10459   auto CastKind = Cast->getCastKind();
10460   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
10461       CastKind != CK_AddressSpaceConversion)
10462     return NoParens;
10463 
10464   auto *SubExpr = Cast->getSubExpr();
10465   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
10466     return NoParens;
10467   return ignorePointerCastsAndParens(SubExpr);
10468 }
10469 
10470 /// Checks to see if the given LValue's Designator is at the end of the LValue's
10471 /// record layout. e.g.
10472 ///   struct { struct { int a, b; } fst, snd; } obj;
10473 ///   obj.fst   // no
10474 ///   obj.snd   // yes
10475 ///   obj.fst.a // no
10476 ///   obj.fst.b // no
10477 ///   obj.snd.a // no
10478 ///   obj.snd.b // yes
10479 ///
10480 /// Please note: this function is specialized for how __builtin_object_size
10481 /// views "objects".
10482 ///
10483 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
10484 /// correct result, it will always return true.
10485 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
10486   assert(!LVal.Designator.Invalid);
10487 
10488   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
10489     const RecordDecl *Parent = FD->getParent();
10490     Invalid = Parent->isInvalidDecl();
10491     if (Invalid || Parent->isUnion())
10492       return true;
10493     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
10494     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
10495   };
10496 
10497   auto &Base = LVal.getLValueBase();
10498   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
10499     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
10500       bool Invalid;
10501       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
10502         return Invalid;
10503     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
10504       for (auto *FD : IFD->chain()) {
10505         bool Invalid;
10506         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
10507           return Invalid;
10508       }
10509     }
10510   }
10511 
10512   unsigned I = 0;
10513   QualType BaseType = getType(Base);
10514   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
10515     // If we don't know the array bound, conservatively assume we're looking at
10516     // the final array element.
10517     ++I;
10518     if (BaseType->isIncompleteArrayType())
10519       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
10520     else
10521       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
10522   }
10523 
10524   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
10525     const auto &Entry = LVal.Designator.Entries[I];
10526     if (BaseType->isArrayType()) {
10527       // Because __builtin_object_size treats arrays as objects, we can ignore
10528       // the index iff this is the last array in the Designator.
10529       if (I + 1 == E)
10530         return true;
10531       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
10532       uint64_t Index = Entry.getAsArrayIndex();
10533       if (Index + 1 != CAT->getSize())
10534         return false;
10535       BaseType = CAT->getElementType();
10536     } else if (BaseType->isAnyComplexType()) {
10537       const auto *CT = BaseType->castAs<ComplexType>();
10538       uint64_t Index = Entry.getAsArrayIndex();
10539       if (Index != 1)
10540         return false;
10541       BaseType = CT->getElementType();
10542     } else if (auto *FD = getAsField(Entry)) {
10543       bool Invalid;
10544       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
10545         return Invalid;
10546       BaseType = FD->getType();
10547     } else {
10548       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
10549       return false;
10550     }
10551   }
10552   return true;
10553 }
10554 
10555 /// Tests to see if the LValue has a user-specified designator (that isn't
10556 /// necessarily valid). Note that this always returns 'true' if the LValue has
10557 /// an unsized array as its first designator entry, because there's currently no
10558 /// way to tell if the user typed *foo or foo[0].
10559 static bool refersToCompleteObject(const LValue &LVal) {
10560   if (LVal.Designator.Invalid)
10561     return false;
10562 
10563   if (!LVal.Designator.Entries.empty())
10564     return LVal.Designator.isMostDerivedAnUnsizedArray();
10565 
10566   if (!LVal.InvalidBase)
10567     return true;
10568 
10569   // If `E` is a MemberExpr, then the first part of the designator is hiding in
10570   // the LValueBase.
10571   const auto *E = LVal.Base.dyn_cast<const Expr *>();
10572   return !E || !isa<MemberExpr>(E);
10573 }
10574 
10575 /// Attempts to detect a user writing into a piece of memory that's impossible
10576 /// to figure out the size of by just using types.
10577 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
10578   const SubobjectDesignator &Designator = LVal.Designator;
10579   // Notes:
10580   // - Users can only write off of the end when we have an invalid base. Invalid
10581   //   bases imply we don't know where the memory came from.
10582   // - We used to be a bit more aggressive here; we'd only be conservative if
10583   //   the array at the end was flexible, or if it had 0 or 1 elements. This
10584   //   broke some common standard library extensions (PR30346), but was
10585   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
10586   //   with some sort of whitelist. OTOH, it seems that GCC is always
10587   //   conservative with the last element in structs (if it's an array), so our
10588   //   current behavior is more compatible than a whitelisting approach would
10589   //   be.
10590   return LVal.InvalidBase &&
10591          Designator.Entries.size() == Designator.MostDerivedPathLength &&
10592          Designator.MostDerivedIsArrayElement &&
10593          isDesignatorAtObjectEnd(Ctx, LVal);
10594 }
10595 
10596 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
10597 /// Fails if the conversion would cause loss of precision.
10598 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
10599                                             CharUnits &Result) {
10600   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
10601   if (Int.ugt(CharUnitsMax))
10602     return false;
10603   Result = CharUnits::fromQuantity(Int.getZExtValue());
10604   return true;
10605 }
10606 
10607 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
10608 /// determine how many bytes exist from the beginning of the object to either
10609 /// the end of the current subobject, or the end of the object itself, depending
10610 /// on what the LValue looks like + the value of Type.
10611 ///
10612 /// If this returns false, the value of Result is undefined.
10613 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
10614                                unsigned Type, const LValue &LVal,
10615                                CharUnits &EndOffset) {
10616   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
10617 
10618   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
10619     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
10620       return false;
10621     return HandleSizeof(Info, ExprLoc, Ty, Result);
10622   };
10623 
10624   // We want to evaluate the size of the entire object. This is a valid fallback
10625   // for when Type=1 and the designator is invalid, because we're asked for an
10626   // upper-bound.
10627   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
10628     // Type=3 wants a lower bound, so we can't fall back to this.
10629     if (Type == 3 && !DetermineForCompleteObject)
10630       return false;
10631 
10632     llvm::APInt APEndOffset;
10633     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
10634         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
10635       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
10636 
10637     if (LVal.InvalidBase)
10638       return false;
10639 
10640     QualType BaseTy = getObjectType(LVal.getLValueBase());
10641     return CheckedHandleSizeof(BaseTy, EndOffset);
10642   }
10643 
10644   // We want to evaluate the size of a subobject.
10645   const SubobjectDesignator &Designator = LVal.Designator;
10646 
10647   // The following is a moderately common idiom in C:
10648   //
10649   // struct Foo { int a; char c[1]; };
10650   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
10651   // strcpy(&F->c[0], Bar);
10652   //
10653   // In order to not break too much legacy code, we need to support it.
10654   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
10655     // If we can resolve this to an alloc_size call, we can hand that back,
10656     // because we know for certain how many bytes there are to write to.
10657     llvm::APInt APEndOffset;
10658     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
10659         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
10660       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
10661 
10662     // If we cannot determine the size of the initial allocation, then we can't
10663     // given an accurate upper-bound. However, we are still able to give
10664     // conservative lower-bounds for Type=3.
10665     if (Type == 1)
10666       return false;
10667   }
10668 
10669   CharUnits BytesPerElem;
10670   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
10671     return false;
10672 
10673   // According to the GCC documentation, we want the size of the subobject
10674   // denoted by the pointer. But that's not quite right -- what we actually
10675   // want is the size of the immediately-enclosing array, if there is one.
10676   int64_t ElemsRemaining;
10677   if (Designator.MostDerivedIsArrayElement &&
10678       Designator.Entries.size() == Designator.MostDerivedPathLength) {
10679     uint64_t ArraySize = Designator.getMostDerivedArraySize();
10680     uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
10681     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
10682   } else {
10683     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
10684   }
10685 
10686   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
10687   return true;
10688 }
10689 
10690 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
10691 /// returns true and stores the result in @p Size.
10692 ///
10693 /// If @p WasError is non-null, this will report whether the failure to evaluate
10694 /// is to be treated as an Error in IntExprEvaluator.
10695 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
10696                                          EvalInfo &Info, uint64_t &Size) {
10697   // Determine the denoted object.
10698   LValue LVal;
10699   {
10700     // The operand of __builtin_object_size is never evaluated for side-effects.
10701     // If there are any, but we can determine the pointed-to object anyway, then
10702     // ignore the side-effects.
10703     SpeculativeEvaluationRAII SpeculativeEval(Info);
10704     IgnoreSideEffectsRAII Fold(Info);
10705 
10706     if (E->isGLValue()) {
10707       // It's possible for us to be given GLValues if we're called via
10708       // Expr::tryEvaluateObjectSize.
10709       APValue RVal;
10710       if (!EvaluateAsRValue(Info, E, RVal))
10711         return false;
10712       LVal.setFrom(Info.Ctx, RVal);
10713     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
10714                                 /*InvalidBaseOK=*/true))
10715       return false;
10716   }
10717 
10718   // If we point to before the start of the object, there are no accessible
10719   // bytes.
10720   if (LVal.getLValueOffset().isNegative()) {
10721     Size = 0;
10722     return true;
10723   }
10724 
10725   CharUnits EndOffset;
10726   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
10727     return false;
10728 
10729   // If we've fallen outside of the end offset, just pretend there's nothing to
10730   // write to/read from.
10731   if (EndOffset <= LVal.getLValueOffset())
10732     Size = 0;
10733   else
10734     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
10735   return true;
10736 }
10737 
10738 bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
10739   llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
10740   if (E->getResultAPValueKind() != APValue::None)
10741     return Success(E->getAPValueResult(), E);
10742   return ExprEvaluatorBaseTy::VisitConstantExpr(E);
10743 }
10744 
10745 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
10746   if (unsigned BuiltinOp = E->getBuiltinCallee())
10747     return VisitBuiltinCallExpr(E, BuiltinOp);
10748 
10749   return ExprEvaluatorBaseTy::VisitCallExpr(E);
10750 }
10751 
10752 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
10753                                      APValue &Val, APSInt &Alignment) {
10754   QualType SrcTy = E->getArg(0)->getType();
10755   if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
10756     return false;
10757   // Even though we are evaluating integer expressions we could get a pointer
10758   // argument for the __builtin_is_aligned() case.
10759   if (SrcTy->isPointerType()) {
10760     LValue Ptr;
10761     if (!EvaluatePointer(E->getArg(0), Ptr, Info))
10762       return false;
10763     Ptr.moveInto(Val);
10764   } else if (!SrcTy->isIntegralOrEnumerationType()) {
10765     Info.FFDiag(E->getArg(0));
10766     return false;
10767   } else {
10768     APSInt SrcInt;
10769     if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
10770       return false;
10771     assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
10772            "Bit widths must be the same");
10773     Val = APValue(SrcInt);
10774   }
10775   assert(Val.hasValue());
10776   return true;
10777 }
10778 
10779 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
10780                                             unsigned BuiltinOp) {
10781   switch (BuiltinOp) {
10782   default:
10783     return ExprEvaluatorBaseTy::VisitCallExpr(E);
10784 
10785   case Builtin::BI__builtin_dynamic_object_size:
10786   case Builtin::BI__builtin_object_size: {
10787     // The type was checked when we built the expression.
10788     unsigned Type =
10789         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
10790     assert(Type <= 3 && "unexpected type");
10791 
10792     uint64_t Size;
10793     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
10794       return Success(Size, E);
10795 
10796     if (E->getArg(0)->HasSideEffects(Info.Ctx))
10797       return Success((Type & 2) ? 0 : -1, E);
10798 
10799     // Expression had no side effects, but we couldn't statically determine the
10800     // size of the referenced object.
10801     switch (Info.EvalMode) {
10802     case EvalInfo::EM_ConstantExpression:
10803     case EvalInfo::EM_ConstantFold:
10804     case EvalInfo::EM_IgnoreSideEffects:
10805       // Leave it to IR generation.
10806       return Error(E);
10807     case EvalInfo::EM_ConstantExpressionUnevaluated:
10808       // Reduce it to a constant now.
10809       return Success((Type & 2) ? 0 : -1, E);
10810     }
10811 
10812     llvm_unreachable("unexpected EvalMode");
10813   }
10814 
10815   case Builtin::BI__builtin_os_log_format_buffer_size: {
10816     analyze_os_log::OSLogBufferLayout Layout;
10817     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
10818     return Success(Layout.size().getQuantity(), E);
10819   }
10820 
10821   case Builtin::BI__builtin_is_aligned: {
10822     APValue Src;
10823     APSInt Alignment;
10824     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
10825       return false;
10826     if (Src.isLValue()) {
10827       // If we evaluated a pointer, check the minimum known alignment.
10828       LValue Ptr;
10829       Ptr.setFrom(Info.Ctx, Src);
10830       CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
10831       CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
10832       // We can return true if the known alignment at the computed offset is
10833       // greater than the requested alignment.
10834       assert(PtrAlign.isPowerOfTwo());
10835       assert(Alignment.isPowerOf2());
10836       if (PtrAlign.getQuantity() >= Alignment)
10837         return Success(1, E);
10838       // If the alignment is not known to be sufficient, some cases could still
10839       // be aligned at run time. However, if the requested alignment is less or
10840       // equal to the base alignment and the offset is not aligned, we know that
10841       // the run-time value can never be aligned.
10842       if (BaseAlignment.getQuantity() >= Alignment &&
10843           PtrAlign.getQuantity() < Alignment)
10844         return Success(0, E);
10845       // Otherwise we can't infer whether the value is sufficiently aligned.
10846       // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
10847       //  in cases where we can't fully evaluate the pointer.
10848       Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
10849           << Alignment;
10850       return false;
10851     }
10852     assert(Src.isInt());
10853     return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
10854   }
10855   case Builtin::BI__builtin_align_up: {
10856     APValue Src;
10857     APSInt Alignment;
10858     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
10859       return false;
10860     if (!Src.isInt())
10861       return Error(E);
10862     APSInt AlignedVal =
10863         APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
10864                Src.getInt().isUnsigned());
10865     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
10866     return Success(AlignedVal, E);
10867   }
10868   case Builtin::BI__builtin_align_down: {
10869     APValue Src;
10870     APSInt Alignment;
10871     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
10872       return false;
10873     if (!Src.isInt())
10874       return Error(E);
10875     APSInt AlignedVal =
10876         APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
10877     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
10878     return Success(AlignedVal, E);
10879   }
10880 
10881   case Builtin::BI__builtin_bswap16:
10882   case Builtin::BI__builtin_bswap32:
10883   case Builtin::BI__builtin_bswap64: {
10884     APSInt Val;
10885     if (!EvaluateInteger(E->getArg(0), Val, Info))
10886       return false;
10887 
10888     return Success(Val.byteSwap(), E);
10889   }
10890 
10891   case Builtin::BI__builtin_classify_type:
10892     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
10893 
10894   case Builtin::BI__builtin_clrsb:
10895   case Builtin::BI__builtin_clrsbl:
10896   case Builtin::BI__builtin_clrsbll: {
10897     APSInt Val;
10898     if (!EvaluateInteger(E->getArg(0), Val, Info))
10899       return false;
10900 
10901     return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
10902   }
10903 
10904   case Builtin::BI__builtin_clz:
10905   case Builtin::BI__builtin_clzl:
10906   case Builtin::BI__builtin_clzll:
10907   case Builtin::BI__builtin_clzs: {
10908     APSInt Val;
10909     if (!EvaluateInteger(E->getArg(0), Val, Info))
10910       return false;
10911     if (!Val)
10912       return Error(E);
10913 
10914     return Success(Val.countLeadingZeros(), E);
10915   }
10916 
10917   case Builtin::BI__builtin_constant_p: {
10918     const Expr *Arg = E->getArg(0);
10919     if (EvaluateBuiltinConstantP(Info, Arg))
10920       return Success(true, E);
10921     if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
10922       // Outside a constant context, eagerly evaluate to false in the presence
10923       // of side-effects in order to avoid -Wunsequenced false-positives in
10924       // a branch on __builtin_constant_p(expr).
10925       return Success(false, E);
10926     }
10927     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10928     return false;
10929   }
10930 
10931   case Builtin::BI__builtin_is_constant_evaluated: {
10932     const auto *Callee = Info.CurrentCall->getCallee();
10933     if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
10934         (Info.CallStackDepth == 1 ||
10935          (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
10936           Callee->getIdentifier() &&
10937           Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
10938       // FIXME: Find a better way to avoid duplicated diagnostics.
10939       if (Info.EvalStatus.Diag)
10940         Info.report((Info.CallStackDepth == 1) ? E->getExprLoc()
10941                                                : Info.CurrentCall->CallLoc,
10942                     diag::warn_is_constant_evaluated_always_true_constexpr)
10943             << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
10944                                          : "std::is_constant_evaluated");
10945     }
10946 
10947     return Success(Info.InConstantContext, E);
10948   }
10949 
10950   case Builtin::BI__builtin_ctz:
10951   case Builtin::BI__builtin_ctzl:
10952   case Builtin::BI__builtin_ctzll:
10953   case Builtin::BI__builtin_ctzs: {
10954     APSInt Val;
10955     if (!EvaluateInteger(E->getArg(0), Val, Info))
10956       return false;
10957     if (!Val)
10958       return Error(E);
10959 
10960     return Success(Val.countTrailingZeros(), E);
10961   }
10962 
10963   case Builtin::BI__builtin_eh_return_data_regno: {
10964     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
10965     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
10966     return Success(Operand, E);
10967   }
10968 
10969   case Builtin::BI__builtin_expect:
10970     return Visit(E->getArg(0));
10971 
10972   case Builtin::BI__builtin_ffs:
10973   case Builtin::BI__builtin_ffsl:
10974   case Builtin::BI__builtin_ffsll: {
10975     APSInt Val;
10976     if (!EvaluateInteger(E->getArg(0), Val, Info))
10977       return false;
10978 
10979     unsigned N = Val.countTrailingZeros();
10980     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
10981   }
10982 
10983   case Builtin::BI__builtin_fpclassify: {
10984     APFloat Val(0.0);
10985     if (!EvaluateFloat(E->getArg(5), Val, Info))
10986       return false;
10987     unsigned Arg;
10988     switch (Val.getCategory()) {
10989     case APFloat::fcNaN: Arg = 0; break;
10990     case APFloat::fcInfinity: Arg = 1; break;
10991     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
10992     case APFloat::fcZero: Arg = 4; break;
10993     }
10994     return Visit(E->getArg(Arg));
10995   }
10996 
10997   case Builtin::BI__builtin_isinf_sign: {
10998     APFloat Val(0.0);
10999     return EvaluateFloat(E->getArg(0), Val, Info) &&
11000            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
11001   }
11002 
11003   case Builtin::BI__builtin_isinf: {
11004     APFloat Val(0.0);
11005     return EvaluateFloat(E->getArg(0), Val, Info) &&
11006            Success(Val.isInfinity() ? 1 : 0, E);
11007   }
11008 
11009   case Builtin::BI__builtin_isfinite: {
11010     APFloat Val(0.0);
11011     return EvaluateFloat(E->getArg(0), Val, Info) &&
11012            Success(Val.isFinite() ? 1 : 0, E);
11013   }
11014 
11015   case Builtin::BI__builtin_isnan: {
11016     APFloat Val(0.0);
11017     return EvaluateFloat(E->getArg(0), Val, Info) &&
11018            Success(Val.isNaN() ? 1 : 0, E);
11019   }
11020 
11021   case Builtin::BI__builtin_isnormal: {
11022     APFloat Val(0.0);
11023     return EvaluateFloat(E->getArg(0), Val, Info) &&
11024            Success(Val.isNormal() ? 1 : 0, E);
11025   }
11026 
11027   case Builtin::BI__builtin_parity:
11028   case Builtin::BI__builtin_parityl:
11029   case Builtin::BI__builtin_parityll: {
11030     APSInt Val;
11031     if (!EvaluateInteger(E->getArg(0), Val, Info))
11032       return false;
11033 
11034     return Success(Val.countPopulation() % 2, E);
11035   }
11036 
11037   case Builtin::BI__builtin_popcount:
11038   case Builtin::BI__builtin_popcountl:
11039   case Builtin::BI__builtin_popcountll: {
11040     APSInt Val;
11041     if (!EvaluateInteger(E->getArg(0), Val, Info))
11042       return false;
11043 
11044     return Success(Val.countPopulation(), E);
11045   }
11046 
11047   case Builtin::BIstrlen:
11048   case Builtin::BIwcslen:
11049     // A call to strlen is not a constant expression.
11050     if (Info.getLangOpts().CPlusPlus11)
11051       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11052         << /*isConstexpr*/0 << /*isConstructor*/0
11053         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11054     else
11055       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11056     LLVM_FALLTHROUGH;
11057   case Builtin::BI__builtin_strlen:
11058   case Builtin::BI__builtin_wcslen: {
11059     // As an extension, we support __builtin_strlen() as a constant expression,
11060     // and support folding strlen() to a constant.
11061     LValue String;
11062     if (!EvaluatePointer(E->getArg(0), String, Info))
11063       return false;
11064 
11065     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
11066 
11067     // Fast path: if it's a string literal, search the string value.
11068     if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
11069             String.getLValueBase().dyn_cast<const Expr *>())) {
11070       // The string literal may have embedded null characters. Find the first
11071       // one and truncate there.
11072       StringRef Str = S->getBytes();
11073       int64_t Off = String.Offset.getQuantity();
11074       if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
11075           S->getCharByteWidth() == 1 &&
11076           // FIXME: Add fast-path for wchar_t too.
11077           Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
11078         Str = Str.substr(Off);
11079 
11080         StringRef::size_type Pos = Str.find(0);
11081         if (Pos != StringRef::npos)
11082           Str = Str.substr(0, Pos);
11083 
11084         return Success(Str.size(), E);
11085       }
11086 
11087       // Fall through to slow path to issue appropriate diagnostic.
11088     }
11089 
11090     // Slow path: scan the bytes of the string looking for the terminating 0.
11091     for (uint64_t Strlen = 0; /**/; ++Strlen) {
11092       APValue Char;
11093       if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
11094           !Char.isInt())
11095         return false;
11096       if (!Char.getInt())
11097         return Success(Strlen, E);
11098       if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
11099         return false;
11100     }
11101   }
11102 
11103   case Builtin::BIstrcmp:
11104   case Builtin::BIwcscmp:
11105   case Builtin::BIstrncmp:
11106   case Builtin::BIwcsncmp:
11107   case Builtin::BImemcmp:
11108   case Builtin::BIbcmp:
11109   case Builtin::BIwmemcmp:
11110     // A call to strlen is not a constant expression.
11111     if (Info.getLangOpts().CPlusPlus11)
11112       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11113         << /*isConstexpr*/0 << /*isConstructor*/0
11114         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11115     else
11116       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11117     LLVM_FALLTHROUGH;
11118   case Builtin::BI__builtin_strcmp:
11119   case Builtin::BI__builtin_wcscmp:
11120   case Builtin::BI__builtin_strncmp:
11121   case Builtin::BI__builtin_wcsncmp:
11122   case Builtin::BI__builtin_memcmp:
11123   case Builtin::BI__builtin_bcmp:
11124   case Builtin::BI__builtin_wmemcmp: {
11125     LValue String1, String2;
11126     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
11127         !EvaluatePointer(E->getArg(1), String2, Info))
11128       return false;
11129 
11130     uint64_t MaxLength = uint64_t(-1);
11131     if (BuiltinOp != Builtin::BIstrcmp &&
11132         BuiltinOp != Builtin::BIwcscmp &&
11133         BuiltinOp != Builtin::BI__builtin_strcmp &&
11134         BuiltinOp != Builtin::BI__builtin_wcscmp) {
11135       APSInt N;
11136       if (!EvaluateInteger(E->getArg(2), N, Info))
11137         return false;
11138       MaxLength = N.getExtValue();
11139     }
11140 
11141     // Empty substrings compare equal by definition.
11142     if (MaxLength == 0u)
11143       return Success(0, E);
11144 
11145     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11146         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11147         String1.Designator.Invalid || String2.Designator.Invalid)
11148       return false;
11149 
11150     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
11151     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
11152 
11153     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
11154                      BuiltinOp == Builtin::BIbcmp ||
11155                      BuiltinOp == Builtin::BI__builtin_memcmp ||
11156                      BuiltinOp == Builtin::BI__builtin_bcmp;
11157 
11158     assert(IsRawByte ||
11159            (Info.Ctx.hasSameUnqualifiedType(
11160                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
11161             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
11162 
11163     // For memcmp, allow comparing any arrays of '[[un]signed] char' or
11164     // 'char8_t', but no other types.
11165     if (IsRawByte &&
11166         !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
11167       // FIXME: Consider using our bit_cast implementation to support this.
11168       Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
11169           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
11170           << CharTy1 << CharTy2;
11171       return false;
11172     }
11173 
11174     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
11175       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
11176              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
11177              Char1.isInt() && Char2.isInt();
11178     };
11179     const auto &AdvanceElems = [&] {
11180       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
11181              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
11182     };
11183 
11184     bool StopAtNull =
11185         (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
11186          BuiltinOp != Builtin::BIwmemcmp &&
11187          BuiltinOp != Builtin::BI__builtin_memcmp &&
11188          BuiltinOp != Builtin::BI__builtin_bcmp &&
11189          BuiltinOp != Builtin::BI__builtin_wmemcmp);
11190     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
11191                   BuiltinOp == Builtin::BIwcsncmp ||
11192                   BuiltinOp == Builtin::BIwmemcmp ||
11193                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
11194                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
11195                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
11196 
11197     for (; MaxLength; --MaxLength) {
11198       APValue Char1, Char2;
11199       if (!ReadCurElems(Char1, Char2))
11200         return false;
11201       if (Char1.getInt().ne(Char2.getInt())) {
11202         if (IsWide) // wmemcmp compares with wchar_t signedness.
11203           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
11204         // memcmp always compares unsigned chars.
11205         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
11206       }
11207       if (StopAtNull && !Char1.getInt())
11208         return Success(0, E);
11209       assert(!(StopAtNull && !Char2.getInt()));
11210       if (!AdvanceElems())
11211         return false;
11212     }
11213     // We hit the strncmp / memcmp limit.
11214     return Success(0, E);
11215   }
11216 
11217   case Builtin::BI__atomic_always_lock_free:
11218   case Builtin::BI__atomic_is_lock_free:
11219   case Builtin::BI__c11_atomic_is_lock_free: {
11220     APSInt SizeVal;
11221     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
11222       return false;
11223 
11224     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
11225     // of two less than the maximum inline atomic width, we know it is
11226     // lock-free.  If the size isn't a power of two, or greater than the
11227     // maximum alignment where we promote atomics, we know it is not lock-free
11228     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
11229     // the answer can only be determined at runtime; for example, 16-byte
11230     // atomics have lock-free implementations on some, but not all,
11231     // x86-64 processors.
11232 
11233     // Check power-of-two.
11234     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
11235     if (Size.isPowerOfTwo()) {
11236       // Check against inlining width.
11237       unsigned InlineWidthBits =
11238           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
11239       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
11240         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
11241             Size == CharUnits::One() ||
11242             E->getArg(1)->isNullPointerConstant(Info.Ctx,
11243                                                 Expr::NPC_NeverValueDependent))
11244           // OK, we will inline appropriately-aligned operations of this size,
11245           // and _Atomic(T) is appropriately-aligned.
11246           return Success(1, E);
11247 
11248         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
11249           castAs<PointerType>()->getPointeeType();
11250         if (!PointeeType->isIncompleteType() &&
11251             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
11252           // OK, we will inline operations on this object.
11253           return Success(1, E);
11254         }
11255       }
11256     }
11257 
11258     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
11259         Success(0, E) : Error(E);
11260   }
11261   case Builtin::BIomp_is_initial_device:
11262     // We can decide statically which value the runtime would return if called.
11263     return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
11264   case Builtin::BI__builtin_add_overflow:
11265   case Builtin::BI__builtin_sub_overflow:
11266   case Builtin::BI__builtin_mul_overflow:
11267   case Builtin::BI__builtin_sadd_overflow:
11268   case Builtin::BI__builtin_uadd_overflow:
11269   case Builtin::BI__builtin_uaddl_overflow:
11270   case Builtin::BI__builtin_uaddll_overflow:
11271   case Builtin::BI__builtin_usub_overflow:
11272   case Builtin::BI__builtin_usubl_overflow:
11273   case Builtin::BI__builtin_usubll_overflow:
11274   case Builtin::BI__builtin_umul_overflow:
11275   case Builtin::BI__builtin_umull_overflow:
11276   case Builtin::BI__builtin_umulll_overflow:
11277   case Builtin::BI__builtin_saddl_overflow:
11278   case Builtin::BI__builtin_saddll_overflow:
11279   case Builtin::BI__builtin_ssub_overflow:
11280   case Builtin::BI__builtin_ssubl_overflow:
11281   case Builtin::BI__builtin_ssubll_overflow:
11282   case Builtin::BI__builtin_smul_overflow:
11283   case Builtin::BI__builtin_smull_overflow:
11284   case Builtin::BI__builtin_smulll_overflow: {
11285     LValue ResultLValue;
11286     APSInt LHS, RHS;
11287 
11288     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
11289     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
11290         !EvaluateInteger(E->getArg(1), RHS, Info) ||
11291         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
11292       return false;
11293 
11294     APSInt Result;
11295     bool DidOverflow = false;
11296 
11297     // If the types don't have to match, enlarge all 3 to the largest of them.
11298     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
11299         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
11300         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
11301       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
11302                       ResultType->isSignedIntegerOrEnumerationType();
11303       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
11304                       ResultType->isSignedIntegerOrEnumerationType();
11305       uint64_t LHSSize = LHS.getBitWidth();
11306       uint64_t RHSSize = RHS.getBitWidth();
11307       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
11308       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
11309 
11310       // Add an additional bit if the signedness isn't uniformly agreed to. We
11311       // could do this ONLY if there is a signed and an unsigned that both have
11312       // MaxBits, but the code to check that is pretty nasty.  The issue will be
11313       // caught in the shrink-to-result later anyway.
11314       if (IsSigned && !AllSigned)
11315         ++MaxBits;
11316 
11317       LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
11318       RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
11319       Result = APSInt(MaxBits, !IsSigned);
11320     }
11321 
11322     // Find largest int.
11323     switch (BuiltinOp) {
11324     default:
11325       llvm_unreachable("Invalid value for BuiltinOp");
11326     case Builtin::BI__builtin_add_overflow:
11327     case Builtin::BI__builtin_sadd_overflow:
11328     case Builtin::BI__builtin_saddl_overflow:
11329     case Builtin::BI__builtin_saddll_overflow:
11330     case Builtin::BI__builtin_uadd_overflow:
11331     case Builtin::BI__builtin_uaddl_overflow:
11332     case Builtin::BI__builtin_uaddll_overflow:
11333       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
11334                               : LHS.uadd_ov(RHS, DidOverflow);
11335       break;
11336     case Builtin::BI__builtin_sub_overflow:
11337     case Builtin::BI__builtin_ssub_overflow:
11338     case Builtin::BI__builtin_ssubl_overflow:
11339     case Builtin::BI__builtin_ssubll_overflow:
11340     case Builtin::BI__builtin_usub_overflow:
11341     case Builtin::BI__builtin_usubl_overflow:
11342     case Builtin::BI__builtin_usubll_overflow:
11343       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
11344                               : LHS.usub_ov(RHS, DidOverflow);
11345       break;
11346     case Builtin::BI__builtin_mul_overflow:
11347     case Builtin::BI__builtin_smul_overflow:
11348     case Builtin::BI__builtin_smull_overflow:
11349     case Builtin::BI__builtin_smulll_overflow:
11350     case Builtin::BI__builtin_umul_overflow:
11351     case Builtin::BI__builtin_umull_overflow:
11352     case Builtin::BI__builtin_umulll_overflow:
11353       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
11354                               : LHS.umul_ov(RHS, DidOverflow);
11355       break;
11356     }
11357 
11358     // In the case where multiple sizes are allowed, truncate and see if
11359     // the values are the same.
11360     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
11361         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
11362         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
11363       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
11364       // since it will give us the behavior of a TruncOrSelf in the case where
11365       // its parameter <= its size.  We previously set Result to be at least the
11366       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
11367       // will work exactly like TruncOrSelf.
11368       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
11369       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
11370 
11371       if (!APSInt::isSameValue(Temp, Result))
11372         DidOverflow = true;
11373       Result = Temp;
11374     }
11375 
11376     APValue APV{Result};
11377     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
11378       return false;
11379     return Success(DidOverflow, E);
11380   }
11381   }
11382 }
11383 
11384 /// Determine whether this is a pointer past the end of the complete
11385 /// object referred to by the lvalue.
11386 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
11387                                             const LValue &LV) {
11388   // A null pointer can be viewed as being "past the end" but we don't
11389   // choose to look at it that way here.
11390   if (!LV.getLValueBase())
11391     return false;
11392 
11393   // If the designator is valid and refers to a subobject, we're not pointing
11394   // past the end.
11395   if (!LV.getLValueDesignator().Invalid &&
11396       !LV.getLValueDesignator().isOnePastTheEnd())
11397     return false;
11398 
11399   // A pointer to an incomplete type might be past-the-end if the type's size is
11400   // zero.  We cannot tell because the type is incomplete.
11401   QualType Ty = getType(LV.getLValueBase());
11402   if (Ty->isIncompleteType())
11403     return true;
11404 
11405   // We're a past-the-end pointer if we point to the byte after the object,
11406   // no matter what our type or path is.
11407   auto Size = Ctx.getTypeSizeInChars(Ty);
11408   return LV.getLValueOffset() == Size;
11409 }
11410 
11411 namespace {
11412 
11413 /// Data recursive integer evaluator of certain binary operators.
11414 ///
11415 /// We use a data recursive algorithm for binary operators so that we are able
11416 /// to handle extreme cases of chained binary operators without causing stack
11417 /// overflow.
11418 class DataRecursiveIntBinOpEvaluator {
11419   struct EvalResult {
11420     APValue Val;
11421     bool Failed;
11422 
11423     EvalResult() : Failed(false) { }
11424 
11425     void swap(EvalResult &RHS) {
11426       Val.swap(RHS.Val);
11427       Failed = RHS.Failed;
11428       RHS.Failed = false;
11429     }
11430   };
11431 
11432   struct Job {
11433     const Expr *E;
11434     EvalResult LHSResult; // meaningful only for binary operator expression.
11435     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
11436 
11437     Job() = default;
11438     Job(Job &&) = default;
11439 
11440     void startSpeculativeEval(EvalInfo &Info) {
11441       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
11442     }
11443 
11444   private:
11445     SpeculativeEvaluationRAII SpecEvalRAII;
11446   };
11447 
11448   SmallVector<Job, 16> Queue;
11449 
11450   IntExprEvaluator &IntEval;
11451   EvalInfo &Info;
11452   APValue &FinalResult;
11453 
11454 public:
11455   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
11456     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
11457 
11458   /// True if \param E is a binary operator that we are going to handle
11459   /// data recursively.
11460   /// We handle binary operators that are comma, logical, or that have operands
11461   /// with integral or enumeration type.
11462   static bool shouldEnqueue(const BinaryOperator *E) {
11463     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
11464            (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
11465             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
11466             E->getRHS()->getType()->isIntegralOrEnumerationType());
11467   }
11468 
11469   bool Traverse(const BinaryOperator *E) {
11470     enqueue(E);
11471     EvalResult PrevResult;
11472     while (!Queue.empty())
11473       process(PrevResult);
11474 
11475     if (PrevResult.Failed) return false;
11476 
11477     FinalResult.swap(PrevResult.Val);
11478     return true;
11479   }
11480 
11481 private:
11482   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
11483     return IntEval.Success(Value, E, Result);
11484   }
11485   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
11486     return IntEval.Success(Value, E, Result);
11487   }
11488   bool Error(const Expr *E) {
11489     return IntEval.Error(E);
11490   }
11491   bool Error(const Expr *E, diag::kind D) {
11492     return IntEval.Error(E, D);
11493   }
11494 
11495   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
11496     return Info.CCEDiag(E, D);
11497   }
11498 
11499   // Returns true if visiting the RHS is necessary, false otherwise.
11500   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
11501                          bool &SuppressRHSDiags);
11502 
11503   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
11504                   const BinaryOperator *E, APValue &Result);
11505 
11506   void EvaluateExpr(const Expr *E, EvalResult &Result) {
11507     Result.Failed = !Evaluate(Result.Val, Info, E);
11508     if (Result.Failed)
11509       Result.Val = APValue();
11510   }
11511 
11512   void process(EvalResult &Result);
11513 
11514   void enqueue(const Expr *E) {
11515     E = E->IgnoreParens();
11516     Queue.resize(Queue.size()+1);
11517     Queue.back().E = E;
11518     Queue.back().Kind = Job::AnyExprKind;
11519   }
11520 };
11521 
11522 }
11523 
11524 bool DataRecursiveIntBinOpEvaluator::
11525        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
11526                          bool &SuppressRHSDiags) {
11527   if (E->getOpcode() == BO_Comma) {
11528     // Ignore LHS but note if we could not evaluate it.
11529     if (LHSResult.Failed)
11530       return Info.noteSideEffect();
11531     return true;
11532   }
11533 
11534   if (E->isLogicalOp()) {
11535     bool LHSAsBool;
11536     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
11537       // We were able to evaluate the LHS, see if we can get away with not
11538       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
11539       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
11540         Success(LHSAsBool, E, LHSResult.Val);
11541         return false; // Ignore RHS
11542       }
11543     } else {
11544       LHSResult.Failed = true;
11545 
11546       // Since we weren't able to evaluate the left hand side, it
11547       // might have had side effects.
11548       if (!Info.noteSideEffect())
11549         return false;
11550 
11551       // We can't evaluate the LHS; however, sometimes the result
11552       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
11553       // Don't ignore RHS and suppress diagnostics from this arm.
11554       SuppressRHSDiags = true;
11555     }
11556 
11557     return true;
11558   }
11559 
11560   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
11561          E->getRHS()->getType()->isIntegralOrEnumerationType());
11562 
11563   if (LHSResult.Failed && !Info.noteFailure())
11564     return false; // Ignore RHS;
11565 
11566   return true;
11567 }
11568 
11569 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
11570                                     bool IsSub) {
11571   // Compute the new offset in the appropriate width, wrapping at 64 bits.
11572   // FIXME: When compiling for a 32-bit target, we should use 32-bit
11573   // offsets.
11574   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
11575   CharUnits &Offset = LVal.getLValueOffset();
11576   uint64_t Offset64 = Offset.getQuantity();
11577   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
11578   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
11579                                          : Offset64 + Index64);
11580 }
11581 
11582 bool DataRecursiveIntBinOpEvaluator::
11583        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
11584                   const BinaryOperator *E, APValue &Result) {
11585   if (E->getOpcode() == BO_Comma) {
11586     if (RHSResult.Failed)
11587       return false;
11588     Result = RHSResult.Val;
11589     return true;
11590   }
11591 
11592   if (E->isLogicalOp()) {
11593     bool lhsResult, rhsResult;
11594     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
11595     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
11596 
11597     if (LHSIsOK) {
11598       if (RHSIsOK) {
11599         if (E->getOpcode() == BO_LOr)
11600           return Success(lhsResult || rhsResult, E, Result);
11601         else
11602           return Success(lhsResult && rhsResult, E, Result);
11603       }
11604     } else {
11605       if (RHSIsOK) {
11606         // We can't evaluate the LHS; however, sometimes the result
11607         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
11608         if (rhsResult == (E->getOpcode() == BO_LOr))
11609           return Success(rhsResult, E, Result);
11610       }
11611     }
11612 
11613     return false;
11614   }
11615 
11616   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
11617          E->getRHS()->getType()->isIntegralOrEnumerationType());
11618 
11619   if (LHSResult.Failed || RHSResult.Failed)
11620     return false;
11621 
11622   const APValue &LHSVal = LHSResult.Val;
11623   const APValue &RHSVal = RHSResult.Val;
11624 
11625   // Handle cases like (unsigned long)&a + 4.
11626   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
11627     Result = LHSVal;
11628     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
11629     return true;
11630   }
11631 
11632   // Handle cases like 4 + (unsigned long)&a
11633   if (E->getOpcode() == BO_Add &&
11634       RHSVal.isLValue() && LHSVal.isInt()) {
11635     Result = RHSVal;
11636     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
11637     return true;
11638   }
11639 
11640   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
11641     // Handle (intptr_t)&&A - (intptr_t)&&B.
11642     if (!LHSVal.getLValueOffset().isZero() ||
11643         !RHSVal.getLValueOffset().isZero())
11644       return false;
11645     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
11646     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
11647     if (!LHSExpr || !RHSExpr)
11648       return false;
11649     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
11650     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
11651     if (!LHSAddrExpr || !RHSAddrExpr)
11652       return false;
11653     // Make sure both labels come from the same function.
11654     if (LHSAddrExpr->getLabel()->getDeclContext() !=
11655         RHSAddrExpr->getLabel()->getDeclContext())
11656       return false;
11657     Result = APValue(LHSAddrExpr, RHSAddrExpr);
11658     return true;
11659   }
11660 
11661   // All the remaining cases expect both operands to be an integer
11662   if (!LHSVal.isInt() || !RHSVal.isInt())
11663     return Error(E);
11664 
11665   // Set up the width and signedness manually, in case it can't be deduced
11666   // from the operation we're performing.
11667   // FIXME: Don't do this in the cases where we can deduce it.
11668   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
11669                E->getType()->isUnsignedIntegerOrEnumerationType());
11670   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
11671                          RHSVal.getInt(), Value))
11672     return false;
11673   return Success(Value, E, Result);
11674 }
11675 
11676 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
11677   Job &job = Queue.back();
11678 
11679   switch (job.Kind) {
11680     case Job::AnyExprKind: {
11681       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
11682         if (shouldEnqueue(Bop)) {
11683           job.Kind = Job::BinOpKind;
11684           enqueue(Bop->getLHS());
11685           return;
11686         }
11687       }
11688 
11689       EvaluateExpr(job.E, Result);
11690       Queue.pop_back();
11691       return;
11692     }
11693 
11694     case Job::BinOpKind: {
11695       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
11696       bool SuppressRHSDiags = false;
11697       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
11698         Queue.pop_back();
11699         return;
11700       }
11701       if (SuppressRHSDiags)
11702         job.startSpeculativeEval(Info);
11703       job.LHSResult.swap(Result);
11704       job.Kind = Job::BinOpVisitedLHSKind;
11705       enqueue(Bop->getRHS());
11706       return;
11707     }
11708 
11709     case Job::BinOpVisitedLHSKind: {
11710       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
11711       EvalResult RHS;
11712       RHS.swap(Result);
11713       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
11714       Queue.pop_back();
11715       return;
11716     }
11717   }
11718 
11719   llvm_unreachable("Invalid Job::Kind!");
11720 }
11721 
11722 namespace {
11723 /// Used when we determine that we should fail, but can keep evaluating prior to
11724 /// noting that we had a failure.
11725 class DelayedNoteFailureRAII {
11726   EvalInfo &Info;
11727   bool NoteFailure;
11728 
11729 public:
11730   DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
11731       : Info(Info), NoteFailure(NoteFailure) {}
11732   ~DelayedNoteFailureRAII() {
11733     if (NoteFailure) {
11734       bool ContinueAfterFailure = Info.noteFailure();
11735       (void)ContinueAfterFailure;
11736       assert(ContinueAfterFailure &&
11737              "Shouldn't have kept evaluating on failure.");
11738     }
11739   }
11740 };
11741 
11742 enum class CmpResult {
11743   Unequal,
11744   Less,
11745   Equal,
11746   Greater,
11747   Unordered,
11748 };
11749 }
11750 
11751 template <class SuccessCB, class AfterCB>
11752 static bool
11753 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
11754                                  SuccessCB &&Success, AfterCB &&DoAfter) {
11755   assert(E->isComparisonOp() && "expected comparison operator");
11756   assert((E->getOpcode() == BO_Cmp ||
11757           E->getType()->isIntegralOrEnumerationType()) &&
11758          "unsupported binary expression evaluation");
11759   auto Error = [&](const Expr *E) {
11760     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11761     return false;
11762   };
11763 
11764   bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
11765   bool IsEquality = E->isEqualityOp();
11766 
11767   QualType LHSTy = E->getLHS()->getType();
11768   QualType RHSTy = E->getRHS()->getType();
11769 
11770   if (LHSTy->isIntegralOrEnumerationType() &&
11771       RHSTy->isIntegralOrEnumerationType()) {
11772     APSInt LHS, RHS;
11773     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
11774     if (!LHSOK && !Info.noteFailure())
11775       return false;
11776     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
11777       return false;
11778     if (LHS < RHS)
11779       return Success(CmpResult::Less, E);
11780     if (LHS > RHS)
11781       return Success(CmpResult::Greater, E);
11782     return Success(CmpResult::Equal, E);
11783   }
11784 
11785   if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
11786     APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
11787     APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
11788 
11789     bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
11790     if (!LHSOK && !Info.noteFailure())
11791       return false;
11792     if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
11793       return false;
11794     if (LHSFX < RHSFX)
11795       return Success(CmpResult::Less, E);
11796     if (LHSFX > RHSFX)
11797       return Success(CmpResult::Greater, E);
11798     return Success(CmpResult::Equal, E);
11799   }
11800 
11801   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
11802     ComplexValue LHS, RHS;
11803     bool LHSOK;
11804     if (E->isAssignmentOp()) {
11805       LValue LV;
11806       EvaluateLValue(E->getLHS(), LV, Info);
11807       LHSOK = false;
11808     } else if (LHSTy->isRealFloatingType()) {
11809       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
11810       if (LHSOK) {
11811         LHS.makeComplexFloat();
11812         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
11813       }
11814     } else {
11815       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
11816     }
11817     if (!LHSOK && !Info.noteFailure())
11818       return false;
11819 
11820     if (E->getRHS()->getType()->isRealFloatingType()) {
11821       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
11822         return false;
11823       RHS.makeComplexFloat();
11824       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
11825     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
11826       return false;
11827 
11828     if (LHS.isComplexFloat()) {
11829       APFloat::cmpResult CR_r =
11830         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
11831       APFloat::cmpResult CR_i =
11832         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
11833       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
11834       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
11835     } else {
11836       assert(IsEquality && "invalid complex comparison");
11837       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
11838                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
11839       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
11840     }
11841   }
11842 
11843   if (LHSTy->isRealFloatingType() &&
11844       RHSTy->isRealFloatingType()) {
11845     APFloat RHS(0.0), LHS(0.0);
11846 
11847     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
11848     if (!LHSOK && !Info.noteFailure())
11849       return false;
11850 
11851     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
11852       return false;
11853 
11854     assert(E->isComparisonOp() && "Invalid binary operator!");
11855     auto GetCmpRes = [&]() {
11856       switch (LHS.compare(RHS)) {
11857       case APFloat::cmpEqual:
11858         return CmpResult::Equal;
11859       case APFloat::cmpLessThan:
11860         return CmpResult::Less;
11861       case APFloat::cmpGreaterThan:
11862         return CmpResult::Greater;
11863       case APFloat::cmpUnordered:
11864         return CmpResult::Unordered;
11865       }
11866       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
11867     };
11868     return Success(GetCmpRes(), E);
11869   }
11870 
11871   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
11872     LValue LHSValue, RHSValue;
11873 
11874     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
11875     if (!LHSOK && !Info.noteFailure())
11876       return false;
11877 
11878     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
11879       return false;
11880 
11881     // Reject differing bases from the normal codepath; we special-case
11882     // comparisons to null.
11883     if (!HasSameBase(LHSValue, RHSValue)) {
11884       // Inequalities and subtractions between unrelated pointers have
11885       // unspecified or undefined behavior.
11886       if (!IsEquality) {
11887         Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified);
11888         return false;
11889       }
11890       // A constant address may compare equal to the address of a symbol.
11891       // The one exception is that address of an object cannot compare equal
11892       // to a null pointer constant.
11893       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
11894           (!RHSValue.Base && !RHSValue.Offset.isZero()))
11895         return Error(E);
11896       // It's implementation-defined whether distinct literals will have
11897       // distinct addresses. In clang, the result of such a comparison is
11898       // unspecified, so it is not a constant expression. However, we do know
11899       // that the address of a literal will be non-null.
11900       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
11901           LHSValue.Base && RHSValue.Base)
11902         return Error(E);
11903       // We can't tell whether weak symbols will end up pointing to the same
11904       // object.
11905       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
11906         return Error(E);
11907       // We can't compare the address of the start of one object with the
11908       // past-the-end address of another object, per C++ DR1652.
11909       if ((LHSValue.Base && LHSValue.Offset.isZero() &&
11910            isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
11911           (RHSValue.Base && RHSValue.Offset.isZero() &&
11912            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
11913         return Error(E);
11914       // We can't tell whether an object is at the same address as another
11915       // zero sized object.
11916       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
11917           (LHSValue.Base && isZeroSized(RHSValue)))
11918         return Error(E);
11919       return Success(CmpResult::Unequal, E);
11920     }
11921 
11922     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
11923     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
11924 
11925     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
11926     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
11927 
11928     // C++11 [expr.rel]p3:
11929     //   Pointers to void (after pointer conversions) can be compared, with a
11930     //   result defined as follows: If both pointers represent the same
11931     //   address or are both the null pointer value, the result is true if the
11932     //   operator is <= or >= and false otherwise; otherwise the result is
11933     //   unspecified.
11934     // We interpret this as applying to pointers to *cv* void.
11935     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
11936       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
11937 
11938     // C++11 [expr.rel]p2:
11939     // - If two pointers point to non-static data members of the same object,
11940     //   or to subobjects or array elements fo such members, recursively, the
11941     //   pointer to the later declared member compares greater provided the
11942     //   two members have the same access control and provided their class is
11943     //   not a union.
11944     //   [...]
11945     // - Otherwise pointer comparisons are unspecified.
11946     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
11947       bool WasArrayIndex;
11948       unsigned Mismatch = FindDesignatorMismatch(
11949           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
11950       // At the point where the designators diverge, the comparison has a
11951       // specified value if:
11952       //  - we are comparing array indices
11953       //  - we are comparing fields of a union, or fields with the same access
11954       // Otherwise, the result is unspecified and thus the comparison is not a
11955       // constant expression.
11956       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
11957           Mismatch < RHSDesignator.Entries.size()) {
11958         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
11959         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
11960         if (!LF && !RF)
11961           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
11962         else if (!LF)
11963           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
11964               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
11965               << RF->getParent() << RF;
11966         else if (!RF)
11967           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
11968               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
11969               << LF->getParent() << LF;
11970         else if (!LF->getParent()->isUnion() &&
11971                  LF->getAccess() != RF->getAccess())
11972           Info.CCEDiag(E,
11973                        diag::note_constexpr_pointer_comparison_differing_access)
11974               << LF << LF->getAccess() << RF << RF->getAccess()
11975               << LF->getParent();
11976       }
11977     }
11978 
11979     // The comparison here must be unsigned, and performed with the same
11980     // width as the pointer.
11981     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
11982     uint64_t CompareLHS = LHSOffset.getQuantity();
11983     uint64_t CompareRHS = RHSOffset.getQuantity();
11984     assert(PtrSize <= 64 && "Unexpected pointer width");
11985     uint64_t Mask = ~0ULL >> (64 - PtrSize);
11986     CompareLHS &= Mask;
11987     CompareRHS &= Mask;
11988 
11989     // If there is a base and this is a relational operator, we can only
11990     // compare pointers within the object in question; otherwise, the result
11991     // depends on where the object is located in memory.
11992     if (!LHSValue.Base.isNull() && IsRelational) {
11993       QualType BaseTy = getType(LHSValue.Base);
11994       if (BaseTy->isIncompleteType())
11995         return Error(E);
11996       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
11997       uint64_t OffsetLimit = Size.getQuantity();
11998       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
11999         return Error(E);
12000     }
12001 
12002     if (CompareLHS < CompareRHS)
12003       return Success(CmpResult::Less, E);
12004     if (CompareLHS > CompareRHS)
12005       return Success(CmpResult::Greater, E);
12006     return Success(CmpResult::Equal, E);
12007   }
12008 
12009   if (LHSTy->isMemberPointerType()) {
12010     assert(IsEquality && "unexpected member pointer operation");
12011     assert(RHSTy->isMemberPointerType() && "invalid comparison");
12012 
12013     MemberPtr LHSValue, RHSValue;
12014 
12015     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
12016     if (!LHSOK && !Info.noteFailure())
12017       return false;
12018 
12019     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12020       return false;
12021 
12022     // C++11 [expr.eq]p2:
12023     //   If both operands are null, they compare equal. Otherwise if only one is
12024     //   null, they compare unequal.
12025     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
12026       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
12027       return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12028     }
12029 
12030     //   Otherwise if either is a pointer to a virtual member function, the
12031     //   result is unspecified.
12032     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
12033       if (MD->isVirtual())
12034         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12035     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
12036       if (MD->isVirtual())
12037         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12038 
12039     //   Otherwise they compare equal if and only if they would refer to the
12040     //   same member of the same most derived object or the same subobject if
12041     //   they were dereferenced with a hypothetical object of the associated
12042     //   class type.
12043     bool Equal = LHSValue == RHSValue;
12044     return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12045   }
12046 
12047   if (LHSTy->isNullPtrType()) {
12048     assert(E->isComparisonOp() && "unexpected nullptr operation");
12049     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
12050     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
12051     // are compared, the result is true of the operator is <=, >= or ==, and
12052     // false otherwise.
12053     return Success(CmpResult::Equal, E);
12054   }
12055 
12056   return DoAfter();
12057 }
12058 
12059 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
12060   if (!CheckLiteralType(Info, E))
12061     return false;
12062 
12063   auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12064     ComparisonCategoryResult CCR;
12065     switch (CR) {
12066     case CmpResult::Unequal:
12067       llvm_unreachable("should never produce Unequal for three-way comparison");
12068     case CmpResult::Less:
12069       CCR = ComparisonCategoryResult::Less;
12070       break;
12071     case CmpResult::Equal:
12072       CCR = ComparisonCategoryResult::Equal;
12073       break;
12074     case CmpResult::Greater:
12075       CCR = ComparisonCategoryResult::Greater;
12076       break;
12077     case CmpResult::Unordered:
12078       CCR = ComparisonCategoryResult::Unordered;
12079       break;
12080     }
12081     // Evaluation succeeded. Lookup the information for the comparison category
12082     // type and fetch the VarDecl for the result.
12083     const ComparisonCategoryInfo &CmpInfo =
12084         Info.Ctx.CompCategories.getInfoForType(E->getType());
12085     const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
12086     // Check and evaluate the result as a constant expression.
12087     LValue LV;
12088     LV.set(VD);
12089     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
12090       return false;
12091     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
12092   };
12093   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12094     return ExprEvaluatorBaseTy::VisitBinCmp(E);
12095   });
12096 }
12097 
12098 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12099   // We don't call noteFailure immediately because the assignment happens after
12100   // we evaluate LHS and RHS.
12101   if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
12102     return Error(E);
12103 
12104   DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
12105   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
12106     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
12107 
12108   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
12109           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
12110          "DataRecursiveIntBinOpEvaluator should have handled integral types");
12111 
12112   if (E->isComparisonOp()) {
12113     // Evaluate builtin binary comparisons by evaluating them as three-way
12114     // comparisons and then translating the result.
12115     auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12116       assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
12117              "should only produce Unequal for equality comparisons");
12118       bool IsEqual   = CR == CmpResult::Equal,
12119            IsLess    = CR == CmpResult::Less,
12120            IsGreater = CR == CmpResult::Greater;
12121       auto Op = E->getOpcode();
12122       switch (Op) {
12123       default:
12124         llvm_unreachable("unsupported binary operator");
12125       case BO_EQ:
12126       case BO_NE:
12127         return Success(IsEqual == (Op == BO_EQ), E);
12128       case BO_LT:
12129         return Success(IsLess, E);
12130       case BO_GT:
12131         return Success(IsGreater, E);
12132       case BO_LE:
12133         return Success(IsEqual || IsLess, E);
12134       case BO_GE:
12135         return Success(IsEqual || IsGreater, E);
12136       }
12137     };
12138     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12139       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12140     });
12141   }
12142 
12143   QualType LHSTy = E->getLHS()->getType();
12144   QualType RHSTy = E->getRHS()->getType();
12145 
12146   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
12147       E->getOpcode() == BO_Sub) {
12148     LValue LHSValue, RHSValue;
12149 
12150     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12151     if (!LHSOK && !Info.noteFailure())
12152       return false;
12153 
12154     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12155       return false;
12156 
12157     // Reject differing bases from the normal codepath; we special-case
12158     // comparisons to null.
12159     if (!HasSameBase(LHSValue, RHSValue)) {
12160       // Handle &&A - &&B.
12161       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
12162         return Error(E);
12163       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
12164       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
12165       if (!LHSExpr || !RHSExpr)
12166         return Error(E);
12167       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12168       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12169       if (!LHSAddrExpr || !RHSAddrExpr)
12170         return Error(E);
12171       // Make sure both labels come from the same function.
12172       if (LHSAddrExpr->getLabel()->getDeclContext() !=
12173           RHSAddrExpr->getLabel()->getDeclContext())
12174         return Error(E);
12175       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
12176     }
12177     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12178     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12179 
12180     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12181     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12182 
12183     // C++11 [expr.add]p6:
12184     //   Unless both pointers point to elements of the same array object, or
12185     //   one past the last element of the array object, the behavior is
12186     //   undefined.
12187     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
12188         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
12189                                 RHSDesignator))
12190       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
12191 
12192     QualType Type = E->getLHS()->getType();
12193     QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
12194 
12195     CharUnits ElementSize;
12196     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
12197       return false;
12198 
12199     // As an extension, a type may have zero size (empty struct or union in
12200     // C, array of zero length). Pointer subtraction in such cases has
12201     // undefined behavior, so is not constant.
12202     if (ElementSize.isZero()) {
12203       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
12204           << ElementType;
12205       return false;
12206     }
12207 
12208     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
12209     // and produce incorrect results when it overflows. Such behavior
12210     // appears to be non-conforming, but is common, so perhaps we should
12211     // assume the standard intended for such cases to be undefined behavior
12212     // and check for them.
12213 
12214     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
12215     // overflow in the final conversion to ptrdiff_t.
12216     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
12217     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
12218     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
12219                     false);
12220     APSInt TrueResult = (LHS - RHS) / ElemSize;
12221     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
12222 
12223     if (Result.extend(65) != TrueResult &&
12224         !HandleOverflow(Info, E, TrueResult, E->getType()))
12225       return false;
12226     return Success(Result, E);
12227   }
12228 
12229   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12230 }
12231 
12232 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
12233 /// a result as the expression's type.
12234 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
12235                                     const UnaryExprOrTypeTraitExpr *E) {
12236   switch(E->getKind()) {
12237   case UETT_PreferredAlignOf:
12238   case UETT_AlignOf: {
12239     if (E->isArgumentType())
12240       return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
12241                      E);
12242     else
12243       return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
12244                      E);
12245   }
12246 
12247   case UETT_VecStep: {
12248     QualType Ty = E->getTypeOfArgument();
12249 
12250     if (Ty->isVectorType()) {
12251       unsigned n = Ty->castAs<VectorType>()->getNumElements();
12252 
12253       // The vec_step built-in functions that take a 3-component
12254       // vector return 4. (OpenCL 1.1 spec 6.11.12)
12255       if (n == 3)
12256         n = 4;
12257 
12258       return Success(n, E);
12259     } else
12260       return Success(1, E);
12261   }
12262 
12263   case UETT_SizeOf: {
12264     QualType SrcTy = E->getTypeOfArgument();
12265     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
12266     //   the result is the size of the referenced type."
12267     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
12268       SrcTy = Ref->getPointeeType();
12269 
12270     CharUnits Sizeof;
12271     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
12272       return false;
12273     return Success(Sizeof, E);
12274   }
12275   case UETT_OpenMPRequiredSimdAlign:
12276     assert(E->isArgumentType());
12277     return Success(
12278         Info.Ctx.toCharUnitsFromBits(
12279                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
12280             .getQuantity(),
12281         E);
12282   }
12283 
12284   llvm_unreachable("unknown expr/type trait");
12285 }
12286 
12287 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
12288   CharUnits Result;
12289   unsigned n = OOE->getNumComponents();
12290   if (n == 0)
12291     return Error(OOE);
12292   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
12293   for (unsigned i = 0; i != n; ++i) {
12294     OffsetOfNode ON = OOE->getComponent(i);
12295     switch (ON.getKind()) {
12296     case OffsetOfNode::Array: {
12297       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
12298       APSInt IdxResult;
12299       if (!EvaluateInteger(Idx, IdxResult, Info))
12300         return false;
12301       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
12302       if (!AT)
12303         return Error(OOE);
12304       CurrentType = AT->getElementType();
12305       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
12306       Result += IdxResult.getSExtValue() * ElementSize;
12307       break;
12308     }
12309 
12310     case OffsetOfNode::Field: {
12311       FieldDecl *MemberDecl = ON.getField();
12312       const RecordType *RT = CurrentType->getAs<RecordType>();
12313       if (!RT)
12314         return Error(OOE);
12315       RecordDecl *RD = RT->getDecl();
12316       if (RD->isInvalidDecl()) return false;
12317       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
12318       unsigned i = MemberDecl->getFieldIndex();
12319       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
12320       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
12321       CurrentType = MemberDecl->getType().getNonReferenceType();
12322       break;
12323     }
12324 
12325     case OffsetOfNode::Identifier:
12326       llvm_unreachable("dependent __builtin_offsetof");
12327 
12328     case OffsetOfNode::Base: {
12329       CXXBaseSpecifier *BaseSpec = ON.getBase();
12330       if (BaseSpec->isVirtual())
12331         return Error(OOE);
12332 
12333       // Find the layout of the class whose base we are looking into.
12334       const RecordType *RT = CurrentType->getAs<RecordType>();
12335       if (!RT)
12336         return Error(OOE);
12337       RecordDecl *RD = RT->getDecl();
12338       if (RD->isInvalidDecl()) return false;
12339       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
12340 
12341       // Find the base class itself.
12342       CurrentType = BaseSpec->getType();
12343       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
12344       if (!BaseRT)
12345         return Error(OOE);
12346 
12347       // Add the offset to the base.
12348       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
12349       break;
12350     }
12351     }
12352   }
12353   return Success(Result, OOE);
12354 }
12355 
12356 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12357   switch (E->getOpcode()) {
12358   default:
12359     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
12360     // See C99 6.6p3.
12361     return Error(E);
12362   case UO_Extension:
12363     // FIXME: Should extension allow i-c-e extension expressions in its scope?
12364     // If so, we could clear the diagnostic ID.
12365     return Visit(E->getSubExpr());
12366   case UO_Plus:
12367     // The result is just the value.
12368     return Visit(E->getSubExpr());
12369   case UO_Minus: {
12370     if (!Visit(E->getSubExpr()))
12371       return false;
12372     if (!Result.isInt()) return Error(E);
12373     const APSInt &Value = Result.getInt();
12374     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
12375         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
12376                         E->getType()))
12377       return false;
12378     return Success(-Value, E);
12379   }
12380   case UO_Not: {
12381     if (!Visit(E->getSubExpr()))
12382       return false;
12383     if (!Result.isInt()) return Error(E);
12384     return Success(~Result.getInt(), E);
12385   }
12386   case UO_LNot: {
12387     bool bres;
12388     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
12389       return false;
12390     return Success(!bres, E);
12391   }
12392   }
12393 }
12394 
12395 /// HandleCast - This is used to evaluate implicit or explicit casts where the
12396 /// result type is integer.
12397 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
12398   const Expr *SubExpr = E->getSubExpr();
12399   QualType DestType = E->getType();
12400   QualType SrcType = SubExpr->getType();
12401 
12402   switch (E->getCastKind()) {
12403   case CK_BaseToDerived:
12404   case CK_DerivedToBase:
12405   case CK_UncheckedDerivedToBase:
12406   case CK_Dynamic:
12407   case CK_ToUnion:
12408   case CK_ArrayToPointerDecay:
12409   case CK_FunctionToPointerDecay:
12410   case CK_NullToPointer:
12411   case CK_NullToMemberPointer:
12412   case CK_BaseToDerivedMemberPointer:
12413   case CK_DerivedToBaseMemberPointer:
12414   case CK_ReinterpretMemberPointer:
12415   case CK_ConstructorConversion:
12416   case CK_IntegralToPointer:
12417   case CK_ToVoid:
12418   case CK_VectorSplat:
12419   case CK_IntegralToFloating:
12420   case CK_FloatingCast:
12421   case CK_CPointerToObjCPointerCast:
12422   case CK_BlockPointerToObjCPointerCast:
12423   case CK_AnyPointerToBlockPointerCast:
12424   case CK_ObjCObjectLValueCast:
12425   case CK_FloatingRealToComplex:
12426   case CK_FloatingComplexToReal:
12427   case CK_FloatingComplexCast:
12428   case CK_FloatingComplexToIntegralComplex:
12429   case CK_IntegralRealToComplex:
12430   case CK_IntegralComplexCast:
12431   case CK_IntegralComplexToFloatingComplex:
12432   case CK_BuiltinFnToFnPtr:
12433   case CK_ZeroToOCLOpaqueType:
12434   case CK_NonAtomicToAtomic:
12435   case CK_AddressSpaceConversion:
12436   case CK_IntToOCLSampler:
12437   case CK_FixedPointCast:
12438   case CK_IntegralToFixedPoint:
12439     llvm_unreachable("invalid cast kind for integral value");
12440 
12441   case CK_BitCast:
12442   case CK_Dependent:
12443   case CK_LValueBitCast:
12444   case CK_ARCProduceObject:
12445   case CK_ARCConsumeObject:
12446   case CK_ARCReclaimReturnedObject:
12447   case CK_ARCExtendBlockObject:
12448   case CK_CopyAndAutoreleaseBlockObject:
12449     return Error(E);
12450 
12451   case CK_UserDefinedConversion:
12452   case CK_LValueToRValue:
12453   case CK_AtomicToNonAtomic:
12454   case CK_NoOp:
12455   case CK_LValueToRValueBitCast:
12456     return ExprEvaluatorBaseTy::VisitCastExpr(E);
12457 
12458   case CK_MemberPointerToBoolean:
12459   case CK_PointerToBoolean:
12460   case CK_IntegralToBoolean:
12461   case CK_FloatingToBoolean:
12462   case CK_BooleanToSignedIntegral:
12463   case CK_FloatingComplexToBoolean:
12464   case CK_IntegralComplexToBoolean: {
12465     bool BoolResult;
12466     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
12467       return false;
12468     uint64_t IntResult = BoolResult;
12469     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
12470       IntResult = (uint64_t)-1;
12471     return Success(IntResult, E);
12472   }
12473 
12474   case CK_FixedPointToIntegral: {
12475     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
12476     if (!EvaluateFixedPoint(SubExpr, Src, Info))
12477       return false;
12478     bool Overflowed;
12479     llvm::APSInt Result = Src.convertToInt(
12480         Info.Ctx.getIntWidth(DestType),
12481         DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
12482     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
12483       return false;
12484     return Success(Result, E);
12485   }
12486 
12487   case CK_FixedPointToBoolean: {
12488     // Unsigned padding does not affect this.
12489     APValue Val;
12490     if (!Evaluate(Val, Info, SubExpr))
12491       return false;
12492     return Success(Val.getFixedPoint().getBoolValue(), E);
12493   }
12494 
12495   case CK_IntegralCast: {
12496     if (!Visit(SubExpr))
12497       return false;
12498 
12499     if (!Result.isInt()) {
12500       // Allow casts of address-of-label differences if they are no-ops
12501       // or narrowing.  (The narrowing case isn't actually guaranteed to
12502       // be constant-evaluatable except in some narrow cases which are hard
12503       // to detect here.  We let it through on the assumption the user knows
12504       // what they are doing.)
12505       if (Result.isAddrLabelDiff())
12506         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
12507       // Only allow casts of lvalues if they are lossless.
12508       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
12509     }
12510 
12511     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
12512                                       Result.getInt()), E);
12513   }
12514 
12515   case CK_PointerToIntegral: {
12516     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
12517 
12518     LValue LV;
12519     if (!EvaluatePointer(SubExpr, LV, Info))
12520       return false;
12521 
12522     if (LV.getLValueBase()) {
12523       // Only allow based lvalue casts if they are lossless.
12524       // FIXME: Allow a larger integer size than the pointer size, and allow
12525       // narrowing back down to pointer width in subsequent integral casts.
12526       // FIXME: Check integer type's active bits, not its type size.
12527       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
12528         return Error(E);
12529 
12530       LV.Designator.setInvalid();
12531       LV.moveInto(Result);
12532       return true;
12533     }
12534 
12535     APSInt AsInt;
12536     APValue V;
12537     LV.moveInto(V);
12538     if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
12539       llvm_unreachable("Can't cast this!");
12540 
12541     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
12542   }
12543 
12544   case CK_IntegralComplexToReal: {
12545     ComplexValue C;
12546     if (!EvaluateComplex(SubExpr, C, Info))
12547       return false;
12548     return Success(C.getComplexIntReal(), E);
12549   }
12550 
12551   case CK_FloatingToIntegral: {
12552     APFloat F(0.0);
12553     if (!EvaluateFloat(SubExpr, F, Info))
12554       return false;
12555 
12556     APSInt Value;
12557     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
12558       return false;
12559     return Success(Value, E);
12560   }
12561   }
12562 
12563   llvm_unreachable("unknown cast resulting in integral value");
12564 }
12565 
12566 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
12567   if (E->getSubExpr()->getType()->isAnyComplexType()) {
12568     ComplexValue LV;
12569     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
12570       return false;
12571     if (!LV.isComplexInt())
12572       return Error(E);
12573     return Success(LV.getComplexIntReal(), E);
12574   }
12575 
12576   return Visit(E->getSubExpr());
12577 }
12578 
12579 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
12580   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
12581     ComplexValue LV;
12582     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
12583       return false;
12584     if (!LV.isComplexInt())
12585       return Error(E);
12586     return Success(LV.getComplexIntImag(), E);
12587   }
12588 
12589   VisitIgnoredValue(E->getSubExpr());
12590   return Success(0, E);
12591 }
12592 
12593 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
12594   return Success(E->getPackLength(), E);
12595 }
12596 
12597 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
12598   return Success(E->getValue(), E);
12599 }
12600 
12601 bool IntExprEvaluator::VisitConceptSpecializationExpr(
12602        const ConceptSpecializationExpr *E) {
12603   return Success(E->isSatisfied(), E);
12604 }
12605 
12606 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
12607   return Success(E->isSatisfied(), E);
12608 }
12609 
12610 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12611   switch (E->getOpcode()) {
12612     default:
12613       // Invalid unary operators
12614       return Error(E);
12615     case UO_Plus:
12616       // The result is just the value.
12617       return Visit(E->getSubExpr());
12618     case UO_Minus: {
12619       if (!Visit(E->getSubExpr())) return false;
12620       if (!Result.isFixedPoint())
12621         return Error(E);
12622       bool Overflowed;
12623       APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
12624       if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
12625         return false;
12626       return Success(Negated, E);
12627     }
12628     case UO_LNot: {
12629       bool bres;
12630       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
12631         return false;
12632       return Success(!bres, E);
12633     }
12634   }
12635 }
12636 
12637 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
12638   const Expr *SubExpr = E->getSubExpr();
12639   QualType DestType = E->getType();
12640   assert(DestType->isFixedPointType() &&
12641          "Expected destination type to be a fixed point type");
12642   auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
12643 
12644   switch (E->getCastKind()) {
12645   case CK_FixedPointCast: {
12646     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
12647     if (!EvaluateFixedPoint(SubExpr, Src, Info))
12648       return false;
12649     bool Overflowed;
12650     APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
12651     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
12652       return false;
12653     return Success(Result, E);
12654   }
12655   case CK_IntegralToFixedPoint: {
12656     APSInt Src;
12657     if (!EvaluateInteger(SubExpr, Src, Info))
12658       return false;
12659 
12660     bool Overflowed;
12661     APFixedPoint IntResult = APFixedPoint::getFromIntValue(
12662         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
12663 
12664     if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType))
12665       return false;
12666 
12667     return Success(IntResult, E);
12668   }
12669   case CK_NoOp:
12670   case CK_LValueToRValue:
12671     return ExprEvaluatorBaseTy::VisitCastExpr(E);
12672   default:
12673     return Error(E);
12674   }
12675 }
12676 
12677 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12678   const Expr *LHS = E->getLHS();
12679   const Expr *RHS = E->getRHS();
12680   FixedPointSemantics ResultFXSema =
12681       Info.Ctx.getFixedPointSemantics(E->getType());
12682 
12683   APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
12684   if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
12685     return false;
12686   APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
12687   if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
12688     return false;
12689 
12690   switch (E->getOpcode()) {
12691   case BO_Add: {
12692     bool AddOverflow, ConversionOverflow;
12693     APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow)
12694                               .convert(ResultFXSema, &ConversionOverflow);
12695     if ((AddOverflow || ConversionOverflow) &&
12696         !HandleOverflow(Info, E, Result, E->getType()))
12697       return false;
12698     return Success(Result, E);
12699   }
12700   default:
12701     return false;
12702   }
12703   llvm_unreachable("Should've exited before this");
12704 }
12705 
12706 //===----------------------------------------------------------------------===//
12707 // Float Evaluation
12708 //===----------------------------------------------------------------------===//
12709 
12710 namespace {
12711 class FloatExprEvaluator
12712   : public ExprEvaluatorBase<FloatExprEvaluator> {
12713   APFloat &Result;
12714 public:
12715   FloatExprEvaluator(EvalInfo &info, APFloat &result)
12716     : ExprEvaluatorBaseTy(info), Result(result) {}
12717 
12718   bool Success(const APValue &V, const Expr *e) {
12719     Result = V.getFloat();
12720     return true;
12721   }
12722 
12723   bool ZeroInitialization(const Expr *E) {
12724     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
12725     return true;
12726   }
12727 
12728   bool VisitCallExpr(const CallExpr *E);
12729 
12730   bool VisitUnaryOperator(const UnaryOperator *E);
12731   bool VisitBinaryOperator(const BinaryOperator *E);
12732   bool VisitFloatingLiteral(const FloatingLiteral *E);
12733   bool VisitCastExpr(const CastExpr *E);
12734 
12735   bool VisitUnaryReal(const UnaryOperator *E);
12736   bool VisitUnaryImag(const UnaryOperator *E);
12737 
12738   // FIXME: Missing: array subscript of vector, member of vector
12739 };
12740 } // end anonymous namespace
12741 
12742 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
12743   assert(E->isRValue() && E->getType()->isRealFloatingType());
12744   return FloatExprEvaluator(Info, Result).Visit(E);
12745 }
12746 
12747 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
12748                                   QualType ResultTy,
12749                                   const Expr *Arg,
12750                                   bool SNaN,
12751                                   llvm::APFloat &Result) {
12752   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
12753   if (!S) return false;
12754 
12755   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
12756 
12757   llvm::APInt fill;
12758 
12759   // Treat empty strings as if they were zero.
12760   if (S->getString().empty())
12761     fill = llvm::APInt(32, 0);
12762   else if (S->getString().getAsInteger(0, fill))
12763     return false;
12764 
12765   if (Context.getTargetInfo().isNan2008()) {
12766     if (SNaN)
12767       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
12768     else
12769       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
12770   } else {
12771     // Prior to IEEE 754-2008, architectures were allowed to choose whether
12772     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
12773     // a different encoding to what became a standard in 2008, and for pre-
12774     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
12775     // sNaN. This is now known as "legacy NaN" encoding.
12776     if (SNaN)
12777       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
12778     else
12779       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
12780   }
12781 
12782   return true;
12783 }
12784 
12785 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
12786   switch (E->getBuiltinCallee()) {
12787   default:
12788     return ExprEvaluatorBaseTy::VisitCallExpr(E);
12789 
12790   case Builtin::BI__builtin_huge_val:
12791   case Builtin::BI__builtin_huge_valf:
12792   case Builtin::BI__builtin_huge_vall:
12793   case Builtin::BI__builtin_huge_valf128:
12794   case Builtin::BI__builtin_inf:
12795   case Builtin::BI__builtin_inff:
12796   case Builtin::BI__builtin_infl:
12797   case Builtin::BI__builtin_inff128: {
12798     const llvm::fltSemantics &Sem =
12799       Info.Ctx.getFloatTypeSemantics(E->getType());
12800     Result = llvm::APFloat::getInf(Sem);
12801     return true;
12802   }
12803 
12804   case Builtin::BI__builtin_nans:
12805   case Builtin::BI__builtin_nansf:
12806   case Builtin::BI__builtin_nansl:
12807   case Builtin::BI__builtin_nansf128:
12808     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
12809                                true, Result))
12810       return Error(E);
12811     return true;
12812 
12813   case Builtin::BI__builtin_nan:
12814   case Builtin::BI__builtin_nanf:
12815   case Builtin::BI__builtin_nanl:
12816   case Builtin::BI__builtin_nanf128:
12817     // If this is __builtin_nan() turn this into a nan, otherwise we
12818     // can't constant fold it.
12819     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
12820                                false, Result))
12821       return Error(E);
12822     return true;
12823 
12824   case Builtin::BI__builtin_fabs:
12825   case Builtin::BI__builtin_fabsf:
12826   case Builtin::BI__builtin_fabsl:
12827   case Builtin::BI__builtin_fabsf128:
12828     if (!EvaluateFloat(E->getArg(0), Result, Info))
12829       return false;
12830 
12831     if (Result.isNegative())
12832       Result.changeSign();
12833     return true;
12834 
12835   // FIXME: Builtin::BI__builtin_powi
12836   // FIXME: Builtin::BI__builtin_powif
12837   // FIXME: Builtin::BI__builtin_powil
12838 
12839   case Builtin::BI__builtin_copysign:
12840   case Builtin::BI__builtin_copysignf:
12841   case Builtin::BI__builtin_copysignl:
12842   case Builtin::BI__builtin_copysignf128: {
12843     APFloat RHS(0.);
12844     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
12845         !EvaluateFloat(E->getArg(1), RHS, Info))
12846       return false;
12847     Result.copySign(RHS);
12848     return true;
12849   }
12850   }
12851 }
12852 
12853 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
12854   if (E->getSubExpr()->getType()->isAnyComplexType()) {
12855     ComplexValue CV;
12856     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
12857       return false;
12858     Result = CV.FloatReal;
12859     return true;
12860   }
12861 
12862   return Visit(E->getSubExpr());
12863 }
12864 
12865 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
12866   if (E->getSubExpr()->getType()->isAnyComplexType()) {
12867     ComplexValue CV;
12868     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
12869       return false;
12870     Result = CV.FloatImag;
12871     return true;
12872   }
12873 
12874   VisitIgnoredValue(E->getSubExpr());
12875   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
12876   Result = llvm::APFloat::getZero(Sem);
12877   return true;
12878 }
12879 
12880 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12881   switch (E->getOpcode()) {
12882   default: return Error(E);
12883   case UO_Plus:
12884     return EvaluateFloat(E->getSubExpr(), Result, Info);
12885   case UO_Minus:
12886     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
12887       return false;
12888     Result.changeSign();
12889     return true;
12890   }
12891 }
12892 
12893 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12894   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
12895     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12896 
12897   APFloat RHS(0.0);
12898   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
12899   if (!LHSOK && !Info.noteFailure())
12900     return false;
12901   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
12902          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
12903 }
12904 
12905 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
12906   Result = E->getValue();
12907   return true;
12908 }
12909 
12910 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
12911   const Expr* SubExpr = E->getSubExpr();
12912 
12913   switch (E->getCastKind()) {
12914   default:
12915     return ExprEvaluatorBaseTy::VisitCastExpr(E);
12916 
12917   case CK_IntegralToFloating: {
12918     APSInt IntResult;
12919     return EvaluateInteger(SubExpr, IntResult, Info) &&
12920            HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
12921                                 E->getType(), Result);
12922   }
12923 
12924   case CK_FloatingCast: {
12925     if (!Visit(SubExpr))
12926       return false;
12927     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
12928                                   Result);
12929   }
12930 
12931   case CK_FloatingComplexToReal: {
12932     ComplexValue V;
12933     if (!EvaluateComplex(SubExpr, V, Info))
12934       return false;
12935     Result = V.getComplexFloatReal();
12936     return true;
12937   }
12938   }
12939 }
12940 
12941 //===----------------------------------------------------------------------===//
12942 // Complex Evaluation (for float and integer)
12943 //===----------------------------------------------------------------------===//
12944 
12945 namespace {
12946 class ComplexExprEvaluator
12947   : public ExprEvaluatorBase<ComplexExprEvaluator> {
12948   ComplexValue &Result;
12949 
12950 public:
12951   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
12952     : ExprEvaluatorBaseTy(info), Result(Result) {}
12953 
12954   bool Success(const APValue &V, const Expr *e) {
12955     Result.setFrom(V);
12956     return true;
12957   }
12958 
12959   bool ZeroInitialization(const Expr *E);
12960 
12961   //===--------------------------------------------------------------------===//
12962   //                            Visitor Methods
12963   //===--------------------------------------------------------------------===//
12964 
12965   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
12966   bool VisitCastExpr(const CastExpr *E);
12967   bool VisitBinaryOperator(const BinaryOperator *E);
12968   bool VisitUnaryOperator(const UnaryOperator *E);
12969   bool VisitInitListExpr(const InitListExpr *E);
12970 };
12971 } // end anonymous namespace
12972 
12973 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
12974                             EvalInfo &Info) {
12975   assert(E->isRValue() && E->getType()->isAnyComplexType());
12976   return ComplexExprEvaluator(Info, Result).Visit(E);
12977 }
12978 
12979 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
12980   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
12981   if (ElemTy->isRealFloatingType()) {
12982     Result.makeComplexFloat();
12983     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
12984     Result.FloatReal = Zero;
12985     Result.FloatImag = Zero;
12986   } else {
12987     Result.makeComplexInt();
12988     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
12989     Result.IntReal = Zero;
12990     Result.IntImag = Zero;
12991   }
12992   return true;
12993 }
12994 
12995 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
12996   const Expr* SubExpr = E->getSubExpr();
12997 
12998   if (SubExpr->getType()->isRealFloatingType()) {
12999     Result.makeComplexFloat();
13000     APFloat &Imag = Result.FloatImag;
13001     if (!EvaluateFloat(SubExpr, Imag, Info))
13002       return false;
13003 
13004     Result.FloatReal = APFloat(Imag.getSemantics());
13005     return true;
13006   } else {
13007     assert(SubExpr->getType()->isIntegerType() &&
13008            "Unexpected imaginary literal.");
13009 
13010     Result.makeComplexInt();
13011     APSInt &Imag = Result.IntImag;
13012     if (!EvaluateInteger(SubExpr, Imag, Info))
13013       return false;
13014 
13015     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
13016     return true;
13017   }
13018 }
13019 
13020 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
13021 
13022   switch (E->getCastKind()) {
13023   case CK_BitCast:
13024   case CK_BaseToDerived:
13025   case CK_DerivedToBase:
13026   case CK_UncheckedDerivedToBase:
13027   case CK_Dynamic:
13028   case CK_ToUnion:
13029   case CK_ArrayToPointerDecay:
13030   case CK_FunctionToPointerDecay:
13031   case CK_NullToPointer:
13032   case CK_NullToMemberPointer:
13033   case CK_BaseToDerivedMemberPointer:
13034   case CK_DerivedToBaseMemberPointer:
13035   case CK_MemberPointerToBoolean:
13036   case CK_ReinterpretMemberPointer:
13037   case CK_ConstructorConversion:
13038   case CK_IntegralToPointer:
13039   case CK_PointerToIntegral:
13040   case CK_PointerToBoolean:
13041   case CK_ToVoid:
13042   case CK_VectorSplat:
13043   case CK_IntegralCast:
13044   case CK_BooleanToSignedIntegral:
13045   case CK_IntegralToBoolean:
13046   case CK_IntegralToFloating:
13047   case CK_FloatingToIntegral:
13048   case CK_FloatingToBoolean:
13049   case CK_FloatingCast:
13050   case CK_CPointerToObjCPointerCast:
13051   case CK_BlockPointerToObjCPointerCast:
13052   case CK_AnyPointerToBlockPointerCast:
13053   case CK_ObjCObjectLValueCast:
13054   case CK_FloatingComplexToReal:
13055   case CK_FloatingComplexToBoolean:
13056   case CK_IntegralComplexToReal:
13057   case CK_IntegralComplexToBoolean:
13058   case CK_ARCProduceObject:
13059   case CK_ARCConsumeObject:
13060   case CK_ARCReclaimReturnedObject:
13061   case CK_ARCExtendBlockObject:
13062   case CK_CopyAndAutoreleaseBlockObject:
13063   case CK_BuiltinFnToFnPtr:
13064   case CK_ZeroToOCLOpaqueType:
13065   case CK_NonAtomicToAtomic:
13066   case CK_AddressSpaceConversion:
13067   case CK_IntToOCLSampler:
13068   case CK_FixedPointCast:
13069   case CK_FixedPointToBoolean:
13070   case CK_FixedPointToIntegral:
13071   case CK_IntegralToFixedPoint:
13072     llvm_unreachable("invalid cast kind for complex value");
13073 
13074   case CK_LValueToRValue:
13075   case CK_AtomicToNonAtomic:
13076   case CK_NoOp:
13077   case CK_LValueToRValueBitCast:
13078     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13079 
13080   case CK_Dependent:
13081   case CK_LValueBitCast:
13082   case CK_UserDefinedConversion:
13083     return Error(E);
13084 
13085   case CK_FloatingRealToComplex: {
13086     APFloat &Real = Result.FloatReal;
13087     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
13088       return false;
13089 
13090     Result.makeComplexFloat();
13091     Result.FloatImag = APFloat(Real.getSemantics());
13092     return true;
13093   }
13094 
13095   case CK_FloatingComplexCast: {
13096     if (!Visit(E->getSubExpr()))
13097       return false;
13098 
13099     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13100     QualType From
13101       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13102 
13103     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
13104            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
13105   }
13106 
13107   case CK_FloatingComplexToIntegralComplex: {
13108     if (!Visit(E->getSubExpr()))
13109       return false;
13110 
13111     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13112     QualType From
13113       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13114     Result.makeComplexInt();
13115     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
13116                                 To, Result.IntReal) &&
13117            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
13118                                 To, Result.IntImag);
13119   }
13120 
13121   case CK_IntegralRealToComplex: {
13122     APSInt &Real = Result.IntReal;
13123     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
13124       return false;
13125 
13126     Result.makeComplexInt();
13127     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
13128     return true;
13129   }
13130 
13131   case CK_IntegralComplexCast: {
13132     if (!Visit(E->getSubExpr()))
13133       return false;
13134 
13135     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13136     QualType From
13137       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13138 
13139     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
13140     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
13141     return true;
13142   }
13143 
13144   case CK_IntegralComplexToFloatingComplex: {
13145     if (!Visit(E->getSubExpr()))
13146       return false;
13147 
13148     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13149     QualType From
13150       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13151     Result.makeComplexFloat();
13152     return HandleIntToFloatCast(Info, E, From, Result.IntReal,
13153                                 To, Result.FloatReal) &&
13154            HandleIntToFloatCast(Info, E, From, Result.IntImag,
13155                                 To, Result.FloatImag);
13156   }
13157   }
13158 
13159   llvm_unreachable("unknown cast resulting in complex value");
13160 }
13161 
13162 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13163   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13164     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13165 
13166   // Track whether the LHS or RHS is real at the type system level. When this is
13167   // the case we can simplify our evaluation strategy.
13168   bool LHSReal = false, RHSReal = false;
13169 
13170   bool LHSOK;
13171   if (E->getLHS()->getType()->isRealFloatingType()) {
13172     LHSReal = true;
13173     APFloat &Real = Result.FloatReal;
13174     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
13175     if (LHSOK) {
13176       Result.makeComplexFloat();
13177       Result.FloatImag = APFloat(Real.getSemantics());
13178     }
13179   } else {
13180     LHSOK = Visit(E->getLHS());
13181   }
13182   if (!LHSOK && !Info.noteFailure())
13183     return false;
13184 
13185   ComplexValue RHS;
13186   if (E->getRHS()->getType()->isRealFloatingType()) {
13187     RHSReal = true;
13188     APFloat &Real = RHS.FloatReal;
13189     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
13190       return false;
13191     RHS.makeComplexFloat();
13192     RHS.FloatImag = APFloat(Real.getSemantics());
13193   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
13194     return false;
13195 
13196   assert(!(LHSReal && RHSReal) &&
13197          "Cannot have both operands of a complex operation be real.");
13198   switch (E->getOpcode()) {
13199   default: return Error(E);
13200   case BO_Add:
13201     if (Result.isComplexFloat()) {
13202       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
13203                                        APFloat::rmNearestTiesToEven);
13204       if (LHSReal)
13205         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
13206       else if (!RHSReal)
13207         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
13208                                          APFloat::rmNearestTiesToEven);
13209     } else {
13210       Result.getComplexIntReal() += RHS.getComplexIntReal();
13211       Result.getComplexIntImag() += RHS.getComplexIntImag();
13212     }
13213     break;
13214   case BO_Sub:
13215     if (Result.isComplexFloat()) {
13216       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
13217                                             APFloat::rmNearestTiesToEven);
13218       if (LHSReal) {
13219         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
13220         Result.getComplexFloatImag().changeSign();
13221       } else if (!RHSReal) {
13222         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
13223                                               APFloat::rmNearestTiesToEven);
13224       }
13225     } else {
13226       Result.getComplexIntReal() -= RHS.getComplexIntReal();
13227       Result.getComplexIntImag() -= RHS.getComplexIntImag();
13228     }
13229     break;
13230   case BO_Mul:
13231     if (Result.isComplexFloat()) {
13232       // This is an implementation of complex multiplication according to the
13233       // constraints laid out in C11 Annex G. The implementation uses the
13234       // following naming scheme:
13235       //   (a + ib) * (c + id)
13236       ComplexValue LHS = Result;
13237       APFloat &A = LHS.getComplexFloatReal();
13238       APFloat &B = LHS.getComplexFloatImag();
13239       APFloat &C = RHS.getComplexFloatReal();
13240       APFloat &D = RHS.getComplexFloatImag();
13241       APFloat &ResR = Result.getComplexFloatReal();
13242       APFloat &ResI = Result.getComplexFloatImag();
13243       if (LHSReal) {
13244         assert(!RHSReal && "Cannot have two real operands for a complex op!");
13245         ResR = A * C;
13246         ResI = A * D;
13247       } else if (RHSReal) {
13248         ResR = C * A;
13249         ResI = C * B;
13250       } else {
13251         // In the fully general case, we need to handle NaNs and infinities
13252         // robustly.
13253         APFloat AC = A * C;
13254         APFloat BD = B * D;
13255         APFloat AD = A * D;
13256         APFloat BC = B * C;
13257         ResR = AC - BD;
13258         ResI = AD + BC;
13259         if (ResR.isNaN() && ResI.isNaN()) {
13260           bool Recalc = false;
13261           if (A.isInfinity() || B.isInfinity()) {
13262             A = APFloat::copySign(
13263                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
13264             B = APFloat::copySign(
13265                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
13266             if (C.isNaN())
13267               C = APFloat::copySign(APFloat(C.getSemantics()), C);
13268             if (D.isNaN())
13269               D = APFloat::copySign(APFloat(D.getSemantics()), D);
13270             Recalc = true;
13271           }
13272           if (C.isInfinity() || D.isInfinity()) {
13273             C = APFloat::copySign(
13274                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
13275             D = APFloat::copySign(
13276                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
13277             if (A.isNaN())
13278               A = APFloat::copySign(APFloat(A.getSemantics()), A);
13279             if (B.isNaN())
13280               B = APFloat::copySign(APFloat(B.getSemantics()), B);
13281             Recalc = true;
13282           }
13283           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
13284                           AD.isInfinity() || BC.isInfinity())) {
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             if (C.isNaN())
13290               C = APFloat::copySign(APFloat(C.getSemantics()), C);
13291             if (D.isNaN())
13292               D = APFloat::copySign(APFloat(D.getSemantics()), D);
13293             Recalc = true;
13294           }
13295           if (Recalc) {
13296             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
13297             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
13298           }
13299         }
13300       }
13301     } else {
13302       ComplexValue LHS = Result;
13303       Result.getComplexIntReal() =
13304         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
13305          LHS.getComplexIntImag() * RHS.getComplexIntImag());
13306       Result.getComplexIntImag() =
13307         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
13308          LHS.getComplexIntImag() * RHS.getComplexIntReal());
13309     }
13310     break;
13311   case BO_Div:
13312     if (Result.isComplexFloat()) {
13313       // This is an implementation of complex division according to the
13314       // constraints laid out in C11 Annex G. The implementation uses the
13315       // following naming scheme:
13316       //   (a + ib) / (c + id)
13317       ComplexValue LHS = Result;
13318       APFloat &A = LHS.getComplexFloatReal();
13319       APFloat &B = LHS.getComplexFloatImag();
13320       APFloat &C = RHS.getComplexFloatReal();
13321       APFloat &D = RHS.getComplexFloatImag();
13322       APFloat &ResR = Result.getComplexFloatReal();
13323       APFloat &ResI = Result.getComplexFloatImag();
13324       if (RHSReal) {
13325         ResR = A / C;
13326         ResI = B / C;
13327       } else {
13328         if (LHSReal) {
13329           // No real optimizations we can do here, stub out with zero.
13330           B = APFloat::getZero(A.getSemantics());
13331         }
13332         int DenomLogB = 0;
13333         APFloat MaxCD = maxnum(abs(C), abs(D));
13334         if (MaxCD.isFinite()) {
13335           DenomLogB = ilogb(MaxCD);
13336           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
13337           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
13338         }
13339         APFloat Denom = C * C + D * D;
13340         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
13341                       APFloat::rmNearestTiesToEven);
13342         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
13343                       APFloat::rmNearestTiesToEven);
13344         if (ResR.isNaN() && ResI.isNaN()) {
13345           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
13346             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
13347             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
13348           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
13349                      D.isFinite()) {
13350             A = APFloat::copySign(
13351                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
13352             B = APFloat::copySign(
13353                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
13354             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
13355             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
13356           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
13357             C = APFloat::copySign(
13358                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
13359             D = APFloat::copySign(
13360                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
13361             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
13362             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
13363           }
13364         }
13365       }
13366     } else {
13367       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
13368         return Error(E, diag::note_expr_divide_by_zero);
13369 
13370       ComplexValue LHS = Result;
13371       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
13372         RHS.getComplexIntImag() * RHS.getComplexIntImag();
13373       Result.getComplexIntReal() =
13374         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
13375          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
13376       Result.getComplexIntImag() =
13377         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
13378          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
13379     }
13380     break;
13381   }
13382 
13383   return true;
13384 }
13385 
13386 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13387   // Get the operand value into 'Result'.
13388   if (!Visit(E->getSubExpr()))
13389     return false;
13390 
13391   switch (E->getOpcode()) {
13392   default:
13393     return Error(E);
13394   case UO_Extension:
13395     return true;
13396   case UO_Plus:
13397     // The result is always just the subexpr.
13398     return true;
13399   case UO_Minus:
13400     if (Result.isComplexFloat()) {
13401       Result.getComplexFloatReal().changeSign();
13402       Result.getComplexFloatImag().changeSign();
13403     }
13404     else {
13405       Result.getComplexIntReal() = -Result.getComplexIntReal();
13406       Result.getComplexIntImag() = -Result.getComplexIntImag();
13407     }
13408     return true;
13409   case UO_Not:
13410     if (Result.isComplexFloat())
13411       Result.getComplexFloatImag().changeSign();
13412     else
13413       Result.getComplexIntImag() = -Result.getComplexIntImag();
13414     return true;
13415   }
13416 }
13417 
13418 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
13419   if (E->getNumInits() == 2) {
13420     if (E->getType()->isComplexType()) {
13421       Result.makeComplexFloat();
13422       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
13423         return false;
13424       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
13425         return false;
13426     } else {
13427       Result.makeComplexInt();
13428       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
13429         return false;
13430       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
13431         return false;
13432     }
13433     return true;
13434   }
13435   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
13436 }
13437 
13438 //===----------------------------------------------------------------------===//
13439 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
13440 // implicit conversion.
13441 //===----------------------------------------------------------------------===//
13442 
13443 namespace {
13444 class AtomicExprEvaluator :
13445     public ExprEvaluatorBase<AtomicExprEvaluator> {
13446   const LValue *This;
13447   APValue &Result;
13448 public:
13449   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
13450       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
13451 
13452   bool Success(const APValue &V, const Expr *E) {
13453     Result = V;
13454     return true;
13455   }
13456 
13457   bool ZeroInitialization(const Expr *E) {
13458     ImplicitValueInitExpr VIE(
13459         E->getType()->castAs<AtomicType>()->getValueType());
13460     // For atomic-qualified class (and array) types in C++, initialize the
13461     // _Atomic-wrapped subobject directly, in-place.
13462     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
13463                 : Evaluate(Result, Info, &VIE);
13464   }
13465 
13466   bool VisitCastExpr(const CastExpr *E) {
13467     switch (E->getCastKind()) {
13468     default:
13469       return ExprEvaluatorBaseTy::VisitCastExpr(E);
13470     case CK_NonAtomicToAtomic:
13471       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
13472                   : Evaluate(Result, Info, E->getSubExpr());
13473     }
13474   }
13475 };
13476 } // end anonymous namespace
13477 
13478 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
13479                            EvalInfo &Info) {
13480   assert(E->isRValue() && E->getType()->isAtomicType());
13481   return AtomicExprEvaluator(Info, This, Result).Visit(E);
13482 }
13483 
13484 //===----------------------------------------------------------------------===//
13485 // Void expression evaluation, primarily for a cast to void on the LHS of a
13486 // comma operator
13487 //===----------------------------------------------------------------------===//
13488 
13489 namespace {
13490 class VoidExprEvaluator
13491   : public ExprEvaluatorBase<VoidExprEvaluator> {
13492 public:
13493   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
13494 
13495   bool Success(const APValue &V, const Expr *e) { return true; }
13496 
13497   bool ZeroInitialization(const Expr *E) { return true; }
13498 
13499   bool VisitCastExpr(const CastExpr *E) {
13500     switch (E->getCastKind()) {
13501     default:
13502       return ExprEvaluatorBaseTy::VisitCastExpr(E);
13503     case CK_ToVoid:
13504       VisitIgnoredValue(E->getSubExpr());
13505       return true;
13506     }
13507   }
13508 
13509   bool VisitCallExpr(const CallExpr *E) {
13510     switch (E->getBuiltinCallee()) {
13511     case Builtin::BI__assume:
13512     case Builtin::BI__builtin_assume:
13513       // The argument is not evaluated!
13514       return true;
13515 
13516     case Builtin::BI__builtin_operator_delete:
13517       return HandleOperatorDeleteCall(Info, E);
13518 
13519     default:
13520       break;
13521     }
13522 
13523     return ExprEvaluatorBaseTy::VisitCallExpr(E);
13524   }
13525 
13526   bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
13527 };
13528 } // end anonymous namespace
13529 
13530 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
13531   // We cannot speculatively evaluate a delete expression.
13532   if (Info.SpeculativeEvaluationDepth)
13533     return false;
13534 
13535   FunctionDecl *OperatorDelete = E->getOperatorDelete();
13536   if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
13537     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
13538         << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
13539     return false;
13540   }
13541 
13542   const Expr *Arg = E->getArgument();
13543 
13544   LValue Pointer;
13545   if (!EvaluatePointer(Arg, Pointer, Info))
13546     return false;
13547   if (Pointer.Designator.Invalid)
13548     return false;
13549 
13550   // Deleting a null pointer has no effect.
13551   if (Pointer.isNullPointer()) {
13552     // This is the only case where we need to produce an extension warning:
13553     // the only other way we can succeed is if we find a dynamic allocation,
13554     // and we will have warned when we allocated it in that case.
13555     if (!Info.getLangOpts().CPlusPlus2a)
13556       Info.CCEDiag(E, diag::note_constexpr_new);
13557     return true;
13558   }
13559 
13560   Optional<DynAlloc *> Alloc = CheckDeleteKind(
13561       Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
13562   if (!Alloc)
13563     return false;
13564   QualType AllocType = Pointer.Base.getDynamicAllocType();
13565 
13566   // For the non-array case, the designator must be empty if the static type
13567   // does not have a virtual destructor.
13568   if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
13569       !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
13570     Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
13571         << Arg->getType()->getPointeeType() << AllocType;
13572     return false;
13573   }
13574 
13575   // For a class type with a virtual destructor, the selected operator delete
13576   // is the one looked up when building the destructor.
13577   if (!E->isArrayForm() && !E->isGlobalDelete()) {
13578     const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
13579     if (VirtualDelete &&
13580         !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
13581       Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
13582           << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
13583       return false;
13584     }
13585   }
13586 
13587   if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
13588                          (*Alloc)->Value, AllocType))
13589     return false;
13590 
13591   if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
13592     // The element was already erased. This means the destructor call also
13593     // deleted the object.
13594     // FIXME: This probably results in undefined behavior before we get this
13595     // far, and should be diagnosed elsewhere first.
13596     Info.FFDiag(E, diag::note_constexpr_double_delete);
13597     return false;
13598   }
13599 
13600   return true;
13601 }
13602 
13603 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
13604   assert(E->isRValue() && E->getType()->isVoidType());
13605   return VoidExprEvaluator(Info).Visit(E);
13606 }
13607 
13608 //===----------------------------------------------------------------------===//
13609 // Top level Expr::EvaluateAsRValue method.
13610 //===----------------------------------------------------------------------===//
13611 
13612 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
13613   // In C, function designators are not lvalues, but we evaluate them as if they
13614   // are.
13615   QualType T = E->getType();
13616   if (E->isGLValue() || T->isFunctionType()) {
13617     LValue LV;
13618     if (!EvaluateLValue(E, LV, Info))
13619       return false;
13620     LV.moveInto(Result);
13621   } else if (T->isVectorType()) {
13622     if (!EvaluateVector(E, Result, Info))
13623       return false;
13624   } else if (T->isIntegralOrEnumerationType()) {
13625     if (!IntExprEvaluator(Info, Result).Visit(E))
13626       return false;
13627   } else if (T->hasPointerRepresentation()) {
13628     LValue LV;
13629     if (!EvaluatePointer(E, LV, Info))
13630       return false;
13631     LV.moveInto(Result);
13632   } else if (T->isRealFloatingType()) {
13633     llvm::APFloat F(0.0);
13634     if (!EvaluateFloat(E, F, Info))
13635       return false;
13636     Result = APValue(F);
13637   } else if (T->isAnyComplexType()) {
13638     ComplexValue C;
13639     if (!EvaluateComplex(E, C, Info))
13640       return false;
13641     C.moveInto(Result);
13642   } else if (T->isFixedPointType()) {
13643     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
13644   } else if (T->isMemberPointerType()) {
13645     MemberPtr P;
13646     if (!EvaluateMemberPointer(E, P, Info))
13647       return false;
13648     P.moveInto(Result);
13649     return true;
13650   } else if (T->isArrayType()) {
13651     LValue LV;
13652     APValue &Value =
13653         Info.CurrentCall->createTemporary(E, T, false, LV);
13654     if (!EvaluateArray(E, LV, Value, Info))
13655       return false;
13656     Result = Value;
13657   } else if (T->isRecordType()) {
13658     LValue LV;
13659     APValue &Value = Info.CurrentCall->createTemporary(E, T, false, LV);
13660     if (!EvaluateRecord(E, LV, Value, Info))
13661       return false;
13662     Result = Value;
13663   } else if (T->isVoidType()) {
13664     if (!Info.getLangOpts().CPlusPlus11)
13665       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
13666         << E->getType();
13667     if (!EvaluateVoid(E, Info))
13668       return false;
13669   } else if (T->isAtomicType()) {
13670     QualType Unqual = T.getAtomicUnqualifiedType();
13671     if (Unqual->isArrayType() || Unqual->isRecordType()) {
13672       LValue LV;
13673       APValue &Value = Info.CurrentCall->createTemporary(E, Unqual, false, LV);
13674       if (!EvaluateAtomic(E, &LV, Value, Info))
13675         return false;
13676     } else {
13677       if (!EvaluateAtomic(E, nullptr, Result, Info))
13678         return false;
13679     }
13680   } else if (Info.getLangOpts().CPlusPlus11) {
13681     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
13682     return false;
13683   } else {
13684     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
13685     return false;
13686   }
13687 
13688   return true;
13689 }
13690 
13691 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
13692 /// cases, the in-place evaluation is essential, since later initializers for
13693 /// an object can indirectly refer to subobjects which were initialized earlier.
13694 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
13695                             const Expr *E, bool AllowNonLiteralTypes) {
13696   assert(!E->isValueDependent());
13697 
13698   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
13699     return false;
13700 
13701   if (E->isRValue()) {
13702     // Evaluate arrays and record types in-place, so that later initializers can
13703     // refer to earlier-initialized members of the object.
13704     QualType T = E->getType();
13705     if (T->isArrayType())
13706       return EvaluateArray(E, This, Result, Info);
13707     else if (T->isRecordType())
13708       return EvaluateRecord(E, This, Result, Info);
13709     else if (T->isAtomicType()) {
13710       QualType Unqual = T.getAtomicUnqualifiedType();
13711       if (Unqual->isArrayType() || Unqual->isRecordType())
13712         return EvaluateAtomic(E, &This, Result, Info);
13713     }
13714   }
13715 
13716   // For any other type, in-place evaluation is unimportant.
13717   return Evaluate(Result, Info, E);
13718 }
13719 
13720 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
13721 /// lvalue-to-rvalue cast if it is an lvalue.
13722 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
13723   if (Info.EnableNewConstInterp) {
13724     if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
13725       return false;
13726   } else {
13727     if (E->getType().isNull())
13728       return false;
13729 
13730     if (!CheckLiteralType(Info, E))
13731       return false;
13732 
13733     if (!::Evaluate(Result, Info, E))
13734       return false;
13735 
13736     if (E->isGLValue()) {
13737       LValue LV;
13738       LV.setFrom(Info.Ctx, Result);
13739       if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
13740         return false;
13741     }
13742   }
13743 
13744   // Check this core constant expression is a constant expression.
13745   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result) &&
13746          CheckMemoryLeaks(Info);
13747 }
13748 
13749 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
13750                                  const ASTContext &Ctx, bool &IsConst) {
13751   // Fast-path evaluations of integer literals, since we sometimes see files
13752   // containing vast quantities of these.
13753   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
13754     Result.Val = APValue(APSInt(L->getValue(),
13755                                 L->getType()->isUnsignedIntegerType()));
13756     IsConst = true;
13757     return true;
13758   }
13759 
13760   // This case should be rare, but we need to check it before we check on
13761   // the type below.
13762   if (Exp->getType().isNull()) {
13763     IsConst = false;
13764     return true;
13765   }
13766 
13767   // FIXME: Evaluating values of large array and record types can cause
13768   // performance problems. Only do so in C++11 for now.
13769   if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
13770                           Exp->getType()->isRecordType()) &&
13771       !Ctx.getLangOpts().CPlusPlus11) {
13772     IsConst = false;
13773     return true;
13774   }
13775   return false;
13776 }
13777 
13778 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
13779                                       Expr::SideEffectsKind SEK) {
13780   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
13781          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
13782 }
13783 
13784 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
13785                              const ASTContext &Ctx, EvalInfo &Info) {
13786   bool IsConst;
13787   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
13788     return IsConst;
13789 
13790   return EvaluateAsRValue(Info, E, Result.Val);
13791 }
13792 
13793 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
13794                           const ASTContext &Ctx,
13795                           Expr::SideEffectsKind AllowSideEffects,
13796                           EvalInfo &Info) {
13797   if (!E->getType()->isIntegralOrEnumerationType())
13798     return false;
13799 
13800   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
13801       !ExprResult.Val.isInt() ||
13802       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
13803     return false;
13804 
13805   return true;
13806 }
13807 
13808 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
13809                                  const ASTContext &Ctx,
13810                                  Expr::SideEffectsKind AllowSideEffects,
13811                                  EvalInfo &Info) {
13812   if (!E->getType()->isFixedPointType())
13813     return false;
13814 
13815   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
13816     return false;
13817 
13818   if (!ExprResult.Val.isFixedPoint() ||
13819       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
13820     return false;
13821 
13822   return true;
13823 }
13824 
13825 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
13826 /// any crazy technique (that has nothing to do with language standards) that
13827 /// we want to.  If this function returns true, it returns the folded constant
13828 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
13829 /// will be applied to the result.
13830 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
13831                             bool InConstantContext) const {
13832   assert(!isValueDependent() &&
13833          "Expression evaluator can't be called on a dependent expression.");
13834   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
13835   Info.InConstantContext = InConstantContext;
13836   return ::EvaluateAsRValue(this, Result, Ctx, Info);
13837 }
13838 
13839 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
13840                                       bool InConstantContext) const {
13841   assert(!isValueDependent() &&
13842          "Expression evaluator can't be called on a dependent expression.");
13843   EvalResult Scratch;
13844   return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
13845          HandleConversionToBool(Scratch.Val, Result);
13846 }
13847 
13848 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
13849                          SideEffectsKind AllowSideEffects,
13850                          bool InConstantContext) const {
13851   assert(!isValueDependent() &&
13852          "Expression evaluator can't be called on a dependent expression.");
13853   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
13854   Info.InConstantContext = InConstantContext;
13855   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
13856 }
13857 
13858 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
13859                                 SideEffectsKind AllowSideEffects,
13860                                 bool InConstantContext) const {
13861   assert(!isValueDependent() &&
13862          "Expression evaluator can't be called on a dependent expression.");
13863   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
13864   Info.InConstantContext = InConstantContext;
13865   return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
13866 }
13867 
13868 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
13869                            SideEffectsKind AllowSideEffects,
13870                            bool InConstantContext) const {
13871   assert(!isValueDependent() &&
13872          "Expression evaluator can't be called on a dependent expression.");
13873 
13874   if (!getType()->isRealFloatingType())
13875     return false;
13876 
13877   EvalResult ExprResult;
13878   if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
13879       !ExprResult.Val.isFloat() ||
13880       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
13881     return false;
13882 
13883   Result = ExprResult.Val.getFloat();
13884   return true;
13885 }
13886 
13887 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
13888                             bool InConstantContext) const {
13889   assert(!isValueDependent() &&
13890          "Expression evaluator can't be called on a dependent expression.");
13891 
13892   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
13893   Info.InConstantContext = InConstantContext;
13894   LValue LV;
13895   CheckedTemporaries CheckedTemps;
13896   if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
13897       Result.HasSideEffects ||
13898       !CheckLValueConstantExpression(Info, getExprLoc(),
13899                                      Ctx.getLValueReferenceType(getType()), LV,
13900                                      Expr::EvaluateForCodeGen, CheckedTemps))
13901     return false;
13902 
13903   LV.moveInto(Result.Val);
13904   return true;
13905 }
13906 
13907 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
13908                                   const ASTContext &Ctx, bool InPlace) const {
13909   assert(!isValueDependent() &&
13910          "Expression evaluator can't be called on a dependent expression.");
13911 
13912   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
13913   EvalInfo Info(Ctx, Result, EM);
13914   Info.InConstantContext = true;
13915 
13916   if (InPlace) {
13917     Info.setEvaluatingDecl(this, Result.Val);
13918     LValue LVal;
13919     LVal.set(this);
13920     if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
13921         Result.HasSideEffects)
13922       return false;
13923   } else if (!::Evaluate(Result.Val, Info, this) || Result.HasSideEffects)
13924     return false;
13925 
13926   if (!Info.discardCleanups())
13927     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
13928 
13929   return CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
13930                                  Result.Val, Usage) &&
13931          CheckMemoryLeaks(Info);
13932 }
13933 
13934 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
13935                                  const VarDecl *VD,
13936                             SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
13937   assert(!isValueDependent() &&
13938          "Expression evaluator can't be called on a dependent expression.");
13939 
13940   // FIXME: Evaluating initializers for large array and record types can cause
13941   // performance problems. Only do so in C++11 for now.
13942   if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
13943       !Ctx.getLangOpts().CPlusPlus11)
13944     return false;
13945 
13946   Expr::EvalStatus EStatus;
13947   EStatus.Diag = &Notes;
13948 
13949   EvalInfo Info(Ctx, EStatus, VD->isConstexpr()
13950                                       ? EvalInfo::EM_ConstantExpression
13951                                       : EvalInfo::EM_ConstantFold);
13952   Info.setEvaluatingDecl(VD, Value);
13953   Info.InConstantContext = true;
13954 
13955   SourceLocation DeclLoc = VD->getLocation();
13956   QualType DeclTy = VD->getType();
13957 
13958   if (Info.EnableNewConstInterp) {
13959     auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
13960     if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
13961       return false;
13962   } else {
13963     LValue LVal;
13964     LVal.set(VD);
13965 
13966     if (!EvaluateInPlace(Value, Info, LVal, this,
13967                          /*AllowNonLiteralTypes=*/true) ||
13968         EStatus.HasSideEffects)
13969       return false;
13970 
13971     // At this point, any lifetime-extended temporaries are completely
13972     // initialized.
13973     Info.performLifetimeExtension();
13974 
13975     if (!Info.discardCleanups())
13976       llvm_unreachable("Unhandled cleanup; missing full expression marker?");
13977   }
13978   return CheckConstantExpression(Info, DeclLoc, DeclTy, Value) &&
13979          CheckMemoryLeaks(Info);
13980 }
13981 
13982 bool VarDecl::evaluateDestruction(
13983     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
13984   Expr::EvalStatus EStatus;
13985   EStatus.Diag = &Notes;
13986 
13987   // Make a copy of the value for the destructor to mutate, if we know it.
13988   // Otherwise, treat the value as default-initialized; if the destructor works
13989   // anyway, then the destruction is constant (and must be essentially empty).
13990   APValue DestroyedValue =
13991       (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
13992           ? *getEvaluatedValue()
13993           : getDefaultInitValue(getType());
13994 
13995   EvalInfo Info(getASTContext(), EStatus, EvalInfo::EM_ConstantExpression);
13996   Info.setEvaluatingDecl(this, DestroyedValue,
13997                          EvalInfo::EvaluatingDeclKind::Dtor);
13998   Info.InConstantContext = true;
13999 
14000   SourceLocation DeclLoc = getLocation();
14001   QualType DeclTy = getType();
14002 
14003   LValue LVal;
14004   LVal.set(this);
14005 
14006   if (!HandleDestruction(Info, DeclLoc, LVal.Base, DestroyedValue, DeclTy) ||
14007       EStatus.HasSideEffects)
14008     return false;
14009 
14010   if (!Info.discardCleanups())
14011     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14012 
14013   ensureEvaluatedStmt()->HasConstantDestruction = true;
14014   return true;
14015 }
14016 
14017 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
14018 /// constant folded, but discard the result.
14019 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
14020   assert(!isValueDependent() &&
14021          "Expression evaluator can't be called on a dependent expression.");
14022 
14023   EvalResult Result;
14024   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
14025          !hasUnacceptableSideEffect(Result, SEK);
14026 }
14027 
14028 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
14029                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
14030   assert(!isValueDependent() &&
14031          "Expression evaluator can't be called on a dependent expression.");
14032 
14033   EvalResult EVResult;
14034   EVResult.Diag = Diag;
14035   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14036   Info.InConstantContext = true;
14037 
14038   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
14039   (void)Result;
14040   assert(Result && "Could not evaluate expression");
14041   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
14042 
14043   return EVResult.Val.getInt();
14044 }
14045 
14046 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
14047     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
14048   assert(!isValueDependent() &&
14049          "Expression evaluator can't be called on a dependent expression.");
14050 
14051   EvalResult EVResult;
14052   EVResult.Diag = Diag;
14053   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14054   Info.InConstantContext = true;
14055   Info.CheckingForUndefinedBehavior = true;
14056 
14057   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
14058   (void)Result;
14059   assert(Result && "Could not evaluate expression");
14060   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
14061 
14062   return EVResult.Val.getInt();
14063 }
14064 
14065 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
14066   assert(!isValueDependent() &&
14067          "Expression evaluator can't be called on a dependent expression.");
14068 
14069   bool IsConst;
14070   EvalResult EVResult;
14071   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
14072     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14073     Info.CheckingForUndefinedBehavior = true;
14074     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
14075   }
14076 }
14077 
14078 bool Expr::EvalResult::isGlobalLValue() const {
14079   assert(Val.isLValue());
14080   return IsGlobalLValue(Val.getLValueBase());
14081 }
14082 
14083 
14084 /// isIntegerConstantExpr - this recursive routine will test if an expression is
14085 /// an integer constant expression.
14086 
14087 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
14088 /// comma, etc
14089 
14090 // CheckICE - This function does the fundamental ICE checking: the returned
14091 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
14092 // and a (possibly null) SourceLocation indicating the location of the problem.
14093 //
14094 // Note that to reduce code duplication, this helper does no evaluation
14095 // itself; the caller checks whether the expression is evaluatable, and
14096 // in the rare cases where CheckICE actually cares about the evaluated
14097 // value, it calls into Evaluate.
14098 
14099 namespace {
14100 
14101 enum ICEKind {
14102   /// This expression is an ICE.
14103   IK_ICE,
14104   /// This expression is not an ICE, but if it isn't evaluated, it's
14105   /// a legal subexpression for an ICE. This return value is used to handle
14106   /// the comma operator in C99 mode, and non-constant subexpressions.
14107   IK_ICEIfUnevaluated,
14108   /// This expression is not an ICE, and is not a legal subexpression for one.
14109   IK_NotICE
14110 };
14111 
14112 struct ICEDiag {
14113   ICEKind Kind;
14114   SourceLocation Loc;
14115 
14116   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
14117 };
14118 
14119 }
14120 
14121 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
14122 
14123 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
14124 
14125 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
14126   Expr::EvalResult EVResult;
14127   Expr::EvalStatus Status;
14128   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
14129 
14130   Info.InConstantContext = true;
14131   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
14132       !EVResult.Val.isInt())
14133     return ICEDiag(IK_NotICE, E->getBeginLoc());
14134 
14135   return NoDiag();
14136 }
14137 
14138 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
14139   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
14140   if (!E->getType()->isIntegralOrEnumerationType())
14141     return ICEDiag(IK_NotICE, E->getBeginLoc());
14142 
14143   switch (E->getStmtClass()) {
14144 #define ABSTRACT_STMT(Node)
14145 #define STMT(Node, Base) case Expr::Node##Class:
14146 #define EXPR(Node, Base)
14147 #include "clang/AST/StmtNodes.inc"
14148   case Expr::PredefinedExprClass:
14149   case Expr::FloatingLiteralClass:
14150   case Expr::ImaginaryLiteralClass:
14151   case Expr::StringLiteralClass:
14152   case Expr::ArraySubscriptExprClass:
14153   case Expr::OMPArraySectionExprClass:
14154   case Expr::OMPArrayShapingExprClass:
14155   case Expr::OMPIteratorExprClass:
14156   case Expr::MemberExprClass:
14157   case Expr::CompoundAssignOperatorClass:
14158   case Expr::CompoundLiteralExprClass:
14159   case Expr::ExtVectorElementExprClass:
14160   case Expr::DesignatedInitExprClass:
14161   case Expr::ArrayInitLoopExprClass:
14162   case Expr::ArrayInitIndexExprClass:
14163   case Expr::NoInitExprClass:
14164   case Expr::DesignatedInitUpdateExprClass:
14165   case Expr::ImplicitValueInitExprClass:
14166   case Expr::ParenListExprClass:
14167   case Expr::VAArgExprClass:
14168   case Expr::AddrLabelExprClass:
14169   case Expr::StmtExprClass:
14170   case Expr::CXXMemberCallExprClass:
14171   case Expr::CUDAKernelCallExprClass:
14172   case Expr::CXXDynamicCastExprClass:
14173   case Expr::CXXTypeidExprClass:
14174   case Expr::CXXUuidofExprClass:
14175   case Expr::MSPropertyRefExprClass:
14176   case Expr::MSPropertySubscriptExprClass:
14177   case Expr::CXXNullPtrLiteralExprClass:
14178   case Expr::UserDefinedLiteralClass:
14179   case Expr::CXXThisExprClass:
14180   case Expr::CXXThrowExprClass:
14181   case Expr::CXXNewExprClass:
14182   case Expr::CXXDeleteExprClass:
14183   case Expr::CXXPseudoDestructorExprClass:
14184   case Expr::UnresolvedLookupExprClass:
14185   case Expr::TypoExprClass:
14186   case Expr::RecoveryExprClass:
14187   case Expr::DependentScopeDeclRefExprClass:
14188   case Expr::CXXConstructExprClass:
14189   case Expr::CXXInheritedCtorInitExprClass:
14190   case Expr::CXXStdInitializerListExprClass:
14191   case Expr::CXXBindTemporaryExprClass:
14192   case Expr::ExprWithCleanupsClass:
14193   case Expr::CXXTemporaryObjectExprClass:
14194   case Expr::CXXUnresolvedConstructExprClass:
14195   case Expr::CXXDependentScopeMemberExprClass:
14196   case Expr::UnresolvedMemberExprClass:
14197   case Expr::ObjCStringLiteralClass:
14198   case Expr::ObjCBoxedExprClass:
14199   case Expr::ObjCArrayLiteralClass:
14200   case Expr::ObjCDictionaryLiteralClass:
14201   case Expr::ObjCEncodeExprClass:
14202   case Expr::ObjCMessageExprClass:
14203   case Expr::ObjCSelectorExprClass:
14204   case Expr::ObjCProtocolExprClass:
14205   case Expr::ObjCIvarRefExprClass:
14206   case Expr::ObjCPropertyRefExprClass:
14207   case Expr::ObjCSubscriptRefExprClass:
14208   case Expr::ObjCIsaExprClass:
14209   case Expr::ObjCAvailabilityCheckExprClass:
14210   case Expr::ShuffleVectorExprClass:
14211   case Expr::ConvertVectorExprClass:
14212   case Expr::BlockExprClass:
14213   case Expr::NoStmtClass:
14214   case Expr::OpaqueValueExprClass:
14215   case Expr::PackExpansionExprClass:
14216   case Expr::SubstNonTypeTemplateParmPackExprClass:
14217   case Expr::FunctionParmPackExprClass:
14218   case Expr::AsTypeExprClass:
14219   case Expr::ObjCIndirectCopyRestoreExprClass:
14220   case Expr::MaterializeTemporaryExprClass:
14221   case Expr::PseudoObjectExprClass:
14222   case Expr::AtomicExprClass:
14223   case Expr::LambdaExprClass:
14224   case Expr::CXXFoldExprClass:
14225   case Expr::CoawaitExprClass:
14226   case Expr::DependentCoawaitExprClass:
14227   case Expr::CoyieldExprClass:
14228     return ICEDiag(IK_NotICE, E->getBeginLoc());
14229 
14230   case Expr::InitListExprClass: {
14231     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
14232     // form "T x = { a };" is equivalent to "T x = a;".
14233     // Unless we're initializing a reference, T is a scalar as it is known to be
14234     // of integral or enumeration type.
14235     if (E->isRValue())
14236       if (cast<InitListExpr>(E)->getNumInits() == 1)
14237         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
14238     return ICEDiag(IK_NotICE, E->getBeginLoc());
14239   }
14240 
14241   case Expr::SizeOfPackExprClass:
14242   case Expr::GNUNullExprClass:
14243   case Expr::SourceLocExprClass:
14244     return NoDiag();
14245 
14246   case Expr::SubstNonTypeTemplateParmExprClass:
14247     return
14248       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
14249 
14250   case Expr::ConstantExprClass:
14251     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
14252 
14253   case Expr::ParenExprClass:
14254     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
14255   case Expr::GenericSelectionExprClass:
14256     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
14257   case Expr::IntegerLiteralClass:
14258   case Expr::FixedPointLiteralClass:
14259   case Expr::CharacterLiteralClass:
14260   case Expr::ObjCBoolLiteralExprClass:
14261   case Expr::CXXBoolLiteralExprClass:
14262   case Expr::CXXScalarValueInitExprClass:
14263   case Expr::TypeTraitExprClass:
14264   case Expr::ConceptSpecializationExprClass:
14265   case Expr::RequiresExprClass:
14266   case Expr::ArrayTypeTraitExprClass:
14267   case Expr::ExpressionTraitExprClass:
14268   case Expr::CXXNoexceptExprClass:
14269     return NoDiag();
14270   case Expr::CallExprClass:
14271   case Expr::CXXOperatorCallExprClass: {
14272     // C99 6.6/3 allows function calls within unevaluated subexpressions of
14273     // constant expressions, but they can never be ICEs because an ICE cannot
14274     // contain an operand of (pointer to) function type.
14275     const CallExpr *CE = cast<CallExpr>(E);
14276     if (CE->getBuiltinCallee())
14277       return CheckEvalInICE(E, Ctx);
14278     return ICEDiag(IK_NotICE, E->getBeginLoc());
14279   }
14280   case Expr::CXXRewrittenBinaryOperatorClass:
14281     return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
14282                     Ctx);
14283   case Expr::DeclRefExprClass: {
14284     if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
14285       return NoDiag();
14286     const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
14287     if (Ctx.getLangOpts().CPlusPlus &&
14288         D && IsConstNonVolatile(D->getType())) {
14289       // Parameter variables are never constants.  Without this check,
14290       // getAnyInitializer() can find a default argument, which leads
14291       // to chaos.
14292       if (isa<ParmVarDecl>(D))
14293         return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
14294 
14295       // C++ 7.1.5.1p2
14296       //   A variable of non-volatile const-qualified integral or enumeration
14297       //   type initialized by an ICE can be used in ICEs.
14298       if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
14299         if (!Dcl->getType()->isIntegralOrEnumerationType())
14300           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
14301 
14302         const VarDecl *VD;
14303         // Look for a declaration of this variable that has an initializer, and
14304         // check whether it is an ICE.
14305         if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
14306           return NoDiag();
14307         else
14308           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
14309       }
14310     }
14311     return ICEDiag(IK_NotICE, E->getBeginLoc());
14312   }
14313   case Expr::UnaryOperatorClass: {
14314     const UnaryOperator *Exp = cast<UnaryOperator>(E);
14315     switch (Exp->getOpcode()) {
14316     case UO_PostInc:
14317     case UO_PostDec:
14318     case UO_PreInc:
14319     case UO_PreDec:
14320     case UO_AddrOf:
14321     case UO_Deref:
14322     case UO_Coawait:
14323       // C99 6.6/3 allows increment and decrement within unevaluated
14324       // subexpressions of constant expressions, but they can never be ICEs
14325       // because an ICE cannot contain an lvalue operand.
14326       return ICEDiag(IK_NotICE, E->getBeginLoc());
14327     case UO_Extension:
14328     case UO_LNot:
14329     case UO_Plus:
14330     case UO_Minus:
14331     case UO_Not:
14332     case UO_Real:
14333     case UO_Imag:
14334       return CheckICE(Exp->getSubExpr(), Ctx);
14335     }
14336     llvm_unreachable("invalid unary operator class");
14337   }
14338   case Expr::OffsetOfExprClass: {
14339     // Note that per C99, offsetof must be an ICE. And AFAIK, using
14340     // EvaluateAsRValue matches the proposed gcc behavior for cases like
14341     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
14342     // compliance: we should warn earlier for offsetof expressions with
14343     // array subscripts that aren't ICEs, and if the array subscripts
14344     // are ICEs, the value of the offsetof must be an integer constant.
14345     return CheckEvalInICE(E, Ctx);
14346   }
14347   case Expr::UnaryExprOrTypeTraitExprClass: {
14348     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
14349     if ((Exp->getKind() ==  UETT_SizeOf) &&
14350         Exp->getTypeOfArgument()->isVariableArrayType())
14351       return ICEDiag(IK_NotICE, E->getBeginLoc());
14352     return NoDiag();
14353   }
14354   case Expr::BinaryOperatorClass: {
14355     const BinaryOperator *Exp = cast<BinaryOperator>(E);
14356     switch (Exp->getOpcode()) {
14357     case BO_PtrMemD:
14358     case BO_PtrMemI:
14359     case BO_Assign:
14360     case BO_MulAssign:
14361     case BO_DivAssign:
14362     case BO_RemAssign:
14363     case BO_AddAssign:
14364     case BO_SubAssign:
14365     case BO_ShlAssign:
14366     case BO_ShrAssign:
14367     case BO_AndAssign:
14368     case BO_XorAssign:
14369     case BO_OrAssign:
14370       // C99 6.6/3 allows assignments within unevaluated subexpressions of
14371       // constant expressions, but they can never be ICEs because an ICE cannot
14372       // contain an lvalue operand.
14373       return ICEDiag(IK_NotICE, E->getBeginLoc());
14374 
14375     case BO_Mul:
14376     case BO_Div:
14377     case BO_Rem:
14378     case BO_Add:
14379     case BO_Sub:
14380     case BO_Shl:
14381     case BO_Shr:
14382     case BO_LT:
14383     case BO_GT:
14384     case BO_LE:
14385     case BO_GE:
14386     case BO_EQ:
14387     case BO_NE:
14388     case BO_And:
14389     case BO_Xor:
14390     case BO_Or:
14391     case BO_Comma:
14392     case BO_Cmp: {
14393       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
14394       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
14395       if (Exp->getOpcode() == BO_Div ||
14396           Exp->getOpcode() == BO_Rem) {
14397         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
14398         // we don't evaluate one.
14399         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
14400           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
14401           if (REval == 0)
14402             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
14403           if (REval.isSigned() && REval.isAllOnesValue()) {
14404             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
14405             if (LEval.isMinSignedValue())
14406               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
14407           }
14408         }
14409       }
14410       if (Exp->getOpcode() == BO_Comma) {
14411         if (Ctx.getLangOpts().C99) {
14412           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
14413           // if it isn't evaluated.
14414           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
14415             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
14416         } else {
14417           // In both C89 and C++, commas in ICEs are illegal.
14418           return ICEDiag(IK_NotICE, E->getBeginLoc());
14419         }
14420       }
14421       return Worst(LHSResult, RHSResult);
14422     }
14423     case BO_LAnd:
14424     case BO_LOr: {
14425       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
14426       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
14427       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
14428         // Rare case where the RHS has a comma "side-effect"; we need
14429         // to actually check the condition to see whether the side
14430         // with the comma is evaluated.
14431         if ((Exp->getOpcode() == BO_LAnd) !=
14432             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
14433           return RHSResult;
14434         return NoDiag();
14435       }
14436 
14437       return Worst(LHSResult, RHSResult);
14438     }
14439     }
14440     llvm_unreachable("invalid binary operator kind");
14441   }
14442   case Expr::ImplicitCastExprClass:
14443   case Expr::CStyleCastExprClass:
14444   case Expr::CXXFunctionalCastExprClass:
14445   case Expr::CXXStaticCastExprClass:
14446   case Expr::CXXReinterpretCastExprClass:
14447   case Expr::CXXConstCastExprClass:
14448   case Expr::ObjCBridgedCastExprClass: {
14449     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
14450     if (isa<ExplicitCastExpr>(E)) {
14451       if (const FloatingLiteral *FL
14452             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
14453         unsigned DestWidth = Ctx.getIntWidth(E->getType());
14454         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
14455         APSInt IgnoredVal(DestWidth, !DestSigned);
14456         bool Ignored;
14457         // If the value does not fit in the destination type, the behavior is
14458         // undefined, so we are not required to treat it as a constant
14459         // expression.
14460         if (FL->getValue().convertToInteger(IgnoredVal,
14461                                             llvm::APFloat::rmTowardZero,
14462                                             &Ignored) & APFloat::opInvalidOp)
14463           return ICEDiag(IK_NotICE, E->getBeginLoc());
14464         return NoDiag();
14465       }
14466     }
14467     switch (cast<CastExpr>(E)->getCastKind()) {
14468     case CK_LValueToRValue:
14469     case CK_AtomicToNonAtomic:
14470     case CK_NonAtomicToAtomic:
14471     case CK_NoOp:
14472     case CK_IntegralToBoolean:
14473     case CK_IntegralCast:
14474       return CheckICE(SubExpr, Ctx);
14475     default:
14476       return ICEDiag(IK_NotICE, E->getBeginLoc());
14477     }
14478   }
14479   case Expr::BinaryConditionalOperatorClass: {
14480     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
14481     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
14482     if (CommonResult.Kind == IK_NotICE) return CommonResult;
14483     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
14484     if (FalseResult.Kind == IK_NotICE) return FalseResult;
14485     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
14486     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
14487         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
14488     return FalseResult;
14489   }
14490   case Expr::ConditionalOperatorClass: {
14491     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
14492     // If the condition (ignoring parens) is a __builtin_constant_p call,
14493     // then only the true side is actually considered in an integer constant
14494     // expression, and it is fully evaluated.  This is an important GNU
14495     // extension.  See GCC PR38377 for discussion.
14496     if (const CallExpr *CallCE
14497         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
14498       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
14499         return CheckEvalInICE(E, Ctx);
14500     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
14501     if (CondResult.Kind == IK_NotICE)
14502       return CondResult;
14503 
14504     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
14505     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
14506 
14507     if (TrueResult.Kind == IK_NotICE)
14508       return TrueResult;
14509     if (FalseResult.Kind == IK_NotICE)
14510       return FalseResult;
14511     if (CondResult.Kind == IK_ICEIfUnevaluated)
14512       return CondResult;
14513     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
14514       return NoDiag();
14515     // Rare case where the diagnostics depend on which side is evaluated
14516     // Note that if we get here, CondResult is 0, and at least one of
14517     // TrueResult and FalseResult is non-zero.
14518     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
14519       return FalseResult;
14520     return TrueResult;
14521   }
14522   case Expr::CXXDefaultArgExprClass:
14523     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
14524   case Expr::CXXDefaultInitExprClass:
14525     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
14526   case Expr::ChooseExprClass: {
14527     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
14528   }
14529   case Expr::BuiltinBitCastExprClass: {
14530     if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
14531       return ICEDiag(IK_NotICE, E->getBeginLoc());
14532     return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
14533   }
14534   }
14535 
14536   llvm_unreachable("Invalid StmtClass!");
14537 }
14538 
14539 /// Evaluate an expression as a C++11 integral constant expression.
14540 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
14541                                                     const Expr *E,
14542                                                     llvm::APSInt *Value,
14543                                                     SourceLocation *Loc) {
14544   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
14545     if (Loc) *Loc = E->getExprLoc();
14546     return false;
14547   }
14548 
14549   APValue Result;
14550   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
14551     return false;
14552 
14553   if (!Result.isInt()) {
14554     if (Loc) *Loc = E->getExprLoc();
14555     return false;
14556   }
14557 
14558   if (Value) *Value = Result.getInt();
14559   return true;
14560 }
14561 
14562 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
14563                                  SourceLocation *Loc) const {
14564   assert(!isValueDependent() &&
14565          "Expression evaluator can't be called on a dependent expression.");
14566 
14567   if (Ctx.getLangOpts().CPlusPlus11)
14568     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
14569 
14570   ICEDiag D = CheckICE(this, Ctx);
14571   if (D.Kind != IK_ICE) {
14572     if (Loc) *Loc = D.Loc;
14573     return false;
14574   }
14575   return true;
14576 }
14577 
14578 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
14579                                  SourceLocation *Loc, bool isEvaluated) const {
14580   assert(!isValueDependent() &&
14581          "Expression evaluator can't be called on a dependent expression.");
14582 
14583   if (Ctx.getLangOpts().CPlusPlus11)
14584     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
14585 
14586   if (!isIntegerConstantExpr(Ctx, Loc))
14587     return false;
14588 
14589   // The only possible side-effects here are due to UB discovered in the
14590   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
14591   // required to treat the expression as an ICE, so we produce the folded
14592   // value.
14593   EvalResult ExprResult;
14594   Expr::EvalStatus Status;
14595   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
14596   Info.InConstantContext = true;
14597 
14598   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
14599     llvm_unreachable("ICE cannot be evaluated!");
14600 
14601   Value = ExprResult.Val.getInt();
14602   return true;
14603 }
14604 
14605 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
14606   assert(!isValueDependent() &&
14607          "Expression evaluator can't be called on a dependent expression.");
14608 
14609   return CheckICE(this, Ctx).Kind == IK_ICE;
14610 }
14611 
14612 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
14613                                SourceLocation *Loc) const {
14614   assert(!isValueDependent() &&
14615          "Expression evaluator can't be called on a dependent expression.");
14616 
14617   // We support this checking in C++98 mode in order to diagnose compatibility
14618   // issues.
14619   assert(Ctx.getLangOpts().CPlusPlus);
14620 
14621   // Build evaluation settings.
14622   Expr::EvalStatus Status;
14623   SmallVector<PartialDiagnosticAt, 8> Diags;
14624   Status.Diag = &Diags;
14625   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
14626 
14627   APValue Scratch;
14628   bool IsConstExpr =
14629       ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
14630       // FIXME: We don't produce a diagnostic for this, but the callers that
14631       // call us on arbitrary full-expressions should generally not care.
14632       Info.discardCleanups() && !Status.HasSideEffects;
14633 
14634   if (!Diags.empty()) {
14635     IsConstExpr = false;
14636     if (Loc) *Loc = Diags[0].first;
14637   } else if (!IsConstExpr) {
14638     // FIXME: This shouldn't happen.
14639     if (Loc) *Loc = getExprLoc();
14640   }
14641 
14642   return IsConstExpr;
14643 }
14644 
14645 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
14646                                     const FunctionDecl *Callee,
14647                                     ArrayRef<const Expr*> Args,
14648                                     const Expr *This) const {
14649   assert(!isValueDependent() &&
14650          "Expression evaluator can't be called on a dependent expression.");
14651 
14652   Expr::EvalStatus Status;
14653   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
14654   Info.InConstantContext = true;
14655 
14656   LValue ThisVal;
14657   const LValue *ThisPtr = nullptr;
14658   if (This) {
14659 #ifndef NDEBUG
14660     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
14661     assert(MD && "Don't provide `this` for non-methods.");
14662     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
14663 #endif
14664     if (!This->isValueDependent() &&
14665         EvaluateObjectArgument(Info, This, ThisVal) &&
14666         !Info.EvalStatus.HasSideEffects)
14667       ThisPtr = &ThisVal;
14668 
14669     // Ignore any side-effects from a failed evaluation. This is safe because
14670     // they can't interfere with any other argument evaluation.
14671     Info.EvalStatus.HasSideEffects = false;
14672   }
14673 
14674   ArgVector ArgValues(Args.size());
14675   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
14676        I != E; ++I) {
14677     if ((*I)->isValueDependent() ||
14678         !Evaluate(ArgValues[I - Args.begin()], Info, *I) ||
14679         Info.EvalStatus.HasSideEffects)
14680       // If evaluation fails, throw away the argument entirely.
14681       ArgValues[I - Args.begin()] = APValue();
14682 
14683     // Ignore any side-effects from a failed evaluation. This is safe because
14684     // they can't interfere with any other argument evaluation.
14685     Info.EvalStatus.HasSideEffects = false;
14686   }
14687 
14688   // Parameter cleanups happen in the caller and are not part of this
14689   // evaluation.
14690   Info.discardCleanups();
14691   Info.EvalStatus.HasSideEffects = false;
14692 
14693   // Build fake call to Callee.
14694   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
14695                        ArgValues.data());
14696   // FIXME: Missing ExprWithCleanups in enable_if conditions?
14697   FullExpressionRAII Scope(Info);
14698   return Evaluate(Value, Info, this) && Scope.destroy() &&
14699          !Info.EvalStatus.HasSideEffects;
14700 }
14701 
14702 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
14703                                    SmallVectorImpl<
14704                                      PartialDiagnosticAt> &Diags) {
14705   // FIXME: It would be useful to check constexpr function templates, but at the
14706   // moment the constant expression evaluator cannot cope with the non-rigorous
14707   // ASTs which we build for dependent expressions.
14708   if (FD->isDependentContext())
14709     return true;
14710 
14711   Expr::EvalStatus Status;
14712   Status.Diag = &Diags;
14713 
14714   EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
14715   Info.InConstantContext = true;
14716   Info.CheckingPotentialConstantExpression = true;
14717 
14718   // The constexpr VM attempts to compile all methods to bytecode here.
14719   if (Info.EnableNewConstInterp) {
14720     Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
14721     return Diags.empty();
14722   }
14723 
14724   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
14725   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
14726 
14727   // Fabricate an arbitrary expression on the stack and pretend that it
14728   // is a temporary being used as the 'this' pointer.
14729   LValue This;
14730   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
14731   This.set({&VIE, Info.CurrentCall->Index});
14732 
14733   ArrayRef<const Expr*> Args;
14734 
14735   APValue Scratch;
14736   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
14737     // Evaluate the call as a constant initializer, to allow the construction
14738     // of objects of non-literal types.
14739     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
14740     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
14741   } else {
14742     SourceLocation Loc = FD->getLocation();
14743     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
14744                        Args, FD->getBody(), Info, Scratch, nullptr);
14745   }
14746 
14747   return Diags.empty();
14748 }
14749 
14750 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
14751                                               const FunctionDecl *FD,
14752                                               SmallVectorImpl<
14753                                                 PartialDiagnosticAt> &Diags) {
14754   assert(!E->isValueDependent() &&
14755          "Expression evaluator can't be called on a dependent expression.");
14756 
14757   Expr::EvalStatus Status;
14758   Status.Diag = &Diags;
14759 
14760   EvalInfo Info(FD->getASTContext(), Status,
14761                 EvalInfo::EM_ConstantExpressionUnevaluated);
14762   Info.InConstantContext = true;
14763   Info.CheckingPotentialConstantExpression = true;
14764 
14765   // Fabricate a call stack frame to give the arguments a plausible cover story.
14766   ArrayRef<const Expr*> Args;
14767   ArgVector ArgValues(0);
14768   bool Success = EvaluateArgs(Args, ArgValues, Info, FD);
14769   (void)Success;
14770   assert(Success &&
14771          "Failed to set up arguments for potential constant evaluation");
14772   CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
14773 
14774   APValue ResultScratch;
14775   Evaluate(ResultScratch, Info, E);
14776   return Diags.empty();
14777 }
14778 
14779 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
14780                                  unsigned Type) const {
14781   if (!getType()->isPointerType())
14782     return false;
14783 
14784   Expr::EvalStatus Status;
14785   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
14786   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
14787 }
14788