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/Debug.h"
58 #include "llvm/Support/SaveAndRestore.h"
59 #include "llvm/Support/raw_ostream.h"
60 #include <cstring>
61 #include <functional>
62 
63 #define DEBUG_TYPE "exprconstant"
64 
65 using namespace clang;
66 using llvm::APInt;
67 using llvm::APSInt;
68 using llvm::APFloat;
69 using llvm::Optional;
70 
71 namespace {
72   struct LValue;
73   class CallStackFrame;
74   class EvalInfo;
75 
76   using SourceLocExprScopeGuard =
77       CurrentSourceLocExprScope::SourceLocExprScopeGuard;
78 
79   static QualType getType(APValue::LValueBase B) {
80     if (!B) return QualType();
81     if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
82       // FIXME: It's unclear where we're supposed to take the type from, and
83       // this actually matters for arrays of unknown bound. Eg:
84       //
85       // extern int arr[]; void f() { extern int arr[3]; };
86       // constexpr int *p = &arr[1]; // valid?
87       //
88       // For now, we take the array bound from the most recent declaration.
89       for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
90            Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
91         QualType T = Redecl->getType();
92         if (!T->isIncompleteArrayType())
93           return T;
94       }
95       return D->getType();
96     }
97 
98     if (B.is<TypeInfoLValue>())
99       return B.getTypeInfoType();
100 
101     if (B.is<DynamicAllocLValue>())
102       return B.getDynamicAllocType();
103 
104     const Expr *Base = B.get<const Expr*>();
105 
106     // For a materialized temporary, the type of the temporary we materialized
107     // may not be the type of the expression.
108     if (const MaterializeTemporaryExpr *MTE =
109             dyn_cast<MaterializeTemporaryExpr>(Base)) {
110       SmallVector<const Expr *, 2> CommaLHSs;
111       SmallVector<SubobjectAdjustment, 2> Adjustments;
112       const Expr *Temp = MTE->getSubExpr();
113       const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
114                                                                Adjustments);
115       // Keep any cv-qualifiers from the reference if we generated a temporary
116       // for it directly. Otherwise use the type after adjustment.
117       if (!Adjustments.empty())
118         return Inner->getType();
119     }
120 
121     return Base->getType();
122   }
123 
124   /// Get an LValue path entry, which is known to not be an array index, as a
125   /// field declaration.
126   static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
127     return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
128   }
129   /// Get an LValue path entry, which is known to not be an array index, as a
130   /// base class declaration.
131   static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
132     return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
133   }
134   /// Determine whether this LValue path entry for a base class names a virtual
135   /// base class.
136   static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
137     return E.getAsBaseOrMember().getInt();
138   }
139 
140   /// Given an expression, determine the type used to store the result of
141   /// evaluating that expression.
142   static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
143     if (E->isRValue())
144       return E->getType();
145     return Ctx.getLValueReferenceType(E->getType());
146   }
147 
148   /// Given a CallExpr, try to get the alloc_size attribute. May return null.
149   static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
150     const FunctionDecl *Callee = CE->getDirectCallee();
151     return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
152   }
153 
154   /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
155   /// This will look through a single cast.
156   ///
157   /// Returns null if we couldn't unwrap a function with alloc_size.
158   static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
159     if (!E->getType()->isPointerType())
160       return nullptr;
161 
162     E = E->IgnoreParens();
163     // If we're doing a variable assignment from e.g. malloc(N), there will
164     // probably be a cast of some kind. In exotic cases, we might also see a
165     // top-level ExprWithCleanups. Ignore them either way.
166     if (const auto *FE = dyn_cast<FullExpr>(E))
167       E = FE->getSubExpr()->IgnoreParens();
168 
169     if (const auto *Cast = dyn_cast<CastExpr>(E))
170       E = Cast->getSubExpr()->IgnoreParens();
171 
172     if (const auto *CE = dyn_cast<CallExpr>(E))
173       return getAllocSizeAttr(CE) ? CE : nullptr;
174     return nullptr;
175   }
176 
177   /// Determines whether or not the given Base contains a call to a function
178   /// with the alloc_size attribute.
179   static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
180     const auto *E = Base.dyn_cast<const Expr *>();
181     return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
182   }
183 
184   /// The bound to claim that an array of unknown bound has.
185   /// The value in MostDerivedArraySize is undefined in this case. So, set it
186   /// to an arbitrary value that's likely to loudly break things if it's used.
187   static const uint64_t AssumedSizeForUnsizedArray =
188       std::numeric_limits<uint64_t>::max() / 2;
189 
190   /// Determines if an LValue with the given LValueBase will have an unsized
191   /// array in its designator.
192   /// Find the path length and type of the most-derived subobject in the given
193   /// path, and find the size of the containing array, if any.
194   static unsigned
195   findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
196                            ArrayRef<APValue::LValuePathEntry> Path,
197                            uint64_t &ArraySize, QualType &Type, bool &IsArray,
198                            bool &FirstEntryIsUnsizedArray) {
199     // This only accepts LValueBases from APValues, and APValues don't support
200     // arrays that lack size info.
201     assert(!isBaseAnAllocSizeCall(Base) &&
202            "Unsized arrays shouldn't appear here");
203     unsigned MostDerivedLength = 0;
204     Type = getType(Base);
205 
206     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
207       if (Type->isArrayType()) {
208         const ArrayType *AT = Ctx.getAsArrayType(Type);
209         Type = AT->getElementType();
210         MostDerivedLength = I + 1;
211         IsArray = true;
212 
213         if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
214           ArraySize = CAT->getSize().getZExtValue();
215         } else {
216           assert(I == 0 && "unexpected unsized array designator");
217           FirstEntryIsUnsizedArray = true;
218           ArraySize = AssumedSizeForUnsizedArray;
219         }
220       } else if (Type->isAnyComplexType()) {
221         const ComplexType *CT = Type->castAs<ComplexType>();
222         Type = CT->getElementType();
223         ArraySize = 2;
224         MostDerivedLength = I + 1;
225         IsArray = true;
226       } else if (const FieldDecl *FD = getAsField(Path[I])) {
227         Type = FD->getType();
228         ArraySize = 0;
229         MostDerivedLength = I + 1;
230         IsArray = false;
231       } else {
232         // Path[I] describes a base class.
233         ArraySize = 0;
234         IsArray = false;
235       }
236     }
237     return MostDerivedLength;
238   }
239 
240   /// A path from a glvalue to a subobject of that glvalue.
241   struct SubobjectDesignator {
242     /// True if the subobject was named in a manner not supported by C++11. Such
243     /// lvalues can still be folded, but they are not core constant expressions
244     /// and we cannot perform lvalue-to-rvalue conversions on them.
245     unsigned Invalid : 1;
246 
247     /// Is this a pointer one past the end of an object?
248     unsigned IsOnePastTheEnd : 1;
249 
250     /// Indicator of whether the first entry is an unsized array.
251     unsigned FirstEntryIsAnUnsizedArray : 1;
252 
253     /// Indicator of whether the most-derived object is an array element.
254     unsigned MostDerivedIsArrayElement : 1;
255 
256     /// The length of the path to the most-derived object of which this is a
257     /// subobject.
258     unsigned MostDerivedPathLength : 28;
259 
260     /// The size of the array of which the most-derived object is an element.
261     /// This will always be 0 if the most-derived object is not an array
262     /// element. 0 is not an indicator of whether or not the most-derived object
263     /// is an array, however, because 0-length arrays are allowed.
264     ///
265     /// If the current array is an unsized array, the value of this is
266     /// undefined.
267     uint64_t MostDerivedArraySize;
268 
269     /// The type of the most derived object referred to by this address.
270     QualType MostDerivedType;
271 
272     typedef APValue::LValuePathEntry PathEntry;
273 
274     /// The entries on the path from the glvalue to the designated subobject.
275     SmallVector<PathEntry, 8> Entries;
276 
277     SubobjectDesignator() : Invalid(true) {}
278 
279     explicit SubobjectDesignator(QualType T)
280         : Invalid(false), IsOnePastTheEnd(false),
281           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
282           MostDerivedPathLength(0), MostDerivedArraySize(0),
283           MostDerivedType(T) {}
284 
285     SubobjectDesignator(ASTContext &Ctx, const APValue &V)
286         : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
287           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
288           MostDerivedPathLength(0), MostDerivedArraySize(0) {
289       assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
290       if (!Invalid) {
291         IsOnePastTheEnd = V.isLValueOnePastTheEnd();
292         ArrayRef<PathEntry> VEntries = V.getLValuePath();
293         Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
294         if (V.getLValueBase()) {
295           bool IsArray = false;
296           bool FirstIsUnsizedArray = false;
297           MostDerivedPathLength = findMostDerivedSubobject(
298               Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
299               MostDerivedType, IsArray, FirstIsUnsizedArray);
300           MostDerivedIsArrayElement = IsArray;
301           FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
302         }
303       }
304     }
305 
306     void truncate(ASTContext &Ctx, APValue::LValueBase Base,
307                   unsigned NewLength) {
308       if (Invalid)
309         return;
310 
311       assert(Base && "cannot truncate path for null pointer");
312       assert(NewLength <= Entries.size() && "not a truncation");
313 
314       if (NewLength == Entries.size())
315         return;
316       Entries.resize(NewLength);
317 
318       bool IsArray = false;
319       bool FirstIsUnsizedArray = false;
320       MostDerivedPathLength = findMostDerivedSubobject(
321           Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
322           FirstIsUnsizedArray);
323       MostDerivedIsArrayElement = IsArray;
324       FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
325     }
326 
327     void setInvalid() {
328       Invalid = true;
329       Entries.clear();
330     }
331 
332     /// Determine whether the most derived subobject is an array without a
333     /// known bound.
334     bool isMostDerivedAnUnsizedArray() const {
335       assert(!Invalid && "Calling this makes no sense on invalid designators");
336       return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
337     }
338 
339     /// Determine what the most derived array's size is. Results in an assertion
340     /// failure if the most derived array lacks a size.
341     uint64_t getMostDerivedArraySize() const {
342       assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
343       return MostDerivedArraySize;
344     }
345 
346     /// Determine whether this is a one-past-the-end pointer.
347     bool isOnePastTheEnd() const {
348       assert(!Invalid);
349       if (IsOnePastTheEnd)
350         return true;
351       if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
352           Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
353               MostDerivedArraySize)
354         return true;
355       return false;
356     }
357 
358     /// Get the range of valid index adjustments in the form
359     ///   {maximum value that can be subtracted from this pointer,
360     ///    maximum value that can be added to this pointer}
361     std::pair<uint64_t, uint64_t> validIndexAdjustments() {
362       if (Invalid || isMostDerivedAnUnsizedArray())
363         return {0, 0};
364 
365       // [expr.add]p4: For the purposes of these operators, a pointer to a
366       // nonarray object behaves the same as a pointer to the first element of
367       // an array of length one with the type of the object as its element type.
368       bool IsArray = MostDerivedPathLength == Entries.size() &&
369                      MostDerivedIsArrayElement;
370       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
371                                     : (uint64_t)IsOnePastTheEnd;
372       uint64_t ArraySize =
373           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
374       return {ArrayIndex, ArraySize - ArrayIndex};
375     }
376 
377     /// Check that this refers to a valid subobject.
378     bool isValidSubobject() const {
379       if (Invalid)
380         return false;
381       return !isOnePastTheEnd();
382     }
383     /// Check that this refers to a valid subobject, and if not, produce a
384     /// relevant diagnostic and set the designator as invalid.
385     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
386 
387     /// Get the type of the designated object.
388     QualType getType(ASTContext &Ctx) const {
389       assert(!Invalid && "invalid designator has no subobject type");
390       return MostDerivedPathLength == Entries.size()
391                  ? MostDerivedType
392                  : Ctx.getRecordType(getAsBaseClass(Entries.back()));
393     }
394 
395     /// Update this designator to refer to the first element within this array.
396     void addArrayUnchecked(const ConstantArrayType *CAT) {
397       Entries.push_back(PathEntry::ArrayIndex(0));
398 
399       // This is a most-derived object.
400       MostDerivedType = CAT->getElementType();
401       MostDerivedIsArrayElement = true;
402       MostDerivedArraySize = CAT->getSize().getZExtValue();
403       MostDerivedPathLength = Entries.size();
404     }
405     /// Update this designator to refer to the first element within the array of
406     /// elements of type T. This is an array of unknown size.
407     void addUnsizedArrayUnchecked(QualType ElemTy) {
408       Entries.push_back(PathEntry::ArrayIndex(0));
409 
410       MostDerivedType = ElemTy;
411       MostDerivedIsArrayElement = true;
412       // The value in MostDerivedArraySize is undefined in this case. So, set it
413       // to an arbitrary value that's likely to loudly break things if it's
414       // used.
415       MostDerivedArraySize = AssumedSizeForUnsizedArray;
416       MostDerivedPathLength = Entries.size();
417     }
418     /// Update this designator to refer to the given base or member of this
419     /// object.
420     void addDeclUnchecked(const Decl *D, bool Virtual = false) {
421       Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
422 
423       // If this isn't a base class, it's a new most-derived object.
424       if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
425         MostDerivedType = FD->getType();
426         MostDerivedIsArrayElement = false;
427         MostDerivedArraySize = 0;
428         MostDerivedPathLength = Entries.size();
429       }
430     }
431     /// Update this designator to refer to the given complex component.
432     void addComplexUnchecked(QualType EltTy, bool Imag) {
433       Entries.push_back(PathEntry::ArrayIndex(Imag));
434 
435       // This is technically a most-derived object, though in practice this
436       // is unlikely to matter.
437       MostDerivedType = EltTy;
438       MostDerivedIsArrayElement = true;
439       MostDerivedArraySize = 2;
440       MostDerivedPathLength = Entries.size();
441     }
442     void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
443     void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
444                                    const APSInt &N);
445     /// Add N to the address of this subobject.
446     void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
447       if (Invalid || !N) return;
448       uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
449       if (isMostDerivedAnUnsizedArray()) {
450         diagnoseUnsizedArrayPointerArithmetic(Info, E);
451         // Can't verify -- trust that the user is doing the right thing (or if
452         // not, trust that the caller will catch the bad behavior).
453         // FIXME: Should we reject if this overflows, at least?
454         Entries.back() = PathEntry::ArrayIndex(
455             Entries.back().getAsArrayIndex() + TruncatedN);
456         return;
457       }
458 
459       // [expr.add]p4: For the purposes of these operators, a pointer to a
460       // nonarray object behaves the same as a pointer to the first element of
461       // an array of length one with the type of the object as its element type.
462       bool IsArray = MostDerivedPathLength == Entries.size() &&
463                      MostDerivedIsArrayElement;
464       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
465                                     : (uint64_t)IsOnePastTheEnd;
466       uint64_t ArraySize =
467           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
468 
469       if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
470         // Calculate the actual index in a wide enough type, so we can include
471         // it in the note.
472         N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
473         (llvm::APInt&)N += ArrayIndex;
474         assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
475         diagnosePointerArithmetic(Info, E, N);
476         setInvalid();
477         return;
478       }
479 
480       ArrayIndex += TruncatedN;
481       assert(ArrayIndex <= ArraySize &&
482              "bounds check succeeded for out-of-bounds index");
483 
484       if (IsArray)
485         Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
486       else
487         IsOnePastTheEnd = (ArrayIndex != 0);
488     }
489   };
490 
491   /// A stack frame in the constexpr call stack.
492   class CallStackFrame : public interp::Frame {
493   public:
494     EvalInfo &Info;
495 
496     /// Parent - The caller of this stack frame.
497     CallStackFrame *Caller;
498 
499     /// Callee - The function which was called.
500     const FunctionDecl *Callee;
501 
502     /// This - The binding for the this pointer in this call, if any.
503     const LValue *This;
504 
505     /// Arguments - Parameter bindings for this function call, indexed by
506     /// parameters' function scope indices.
507     APValue *Arguments;
508 
509     /// Source location information about the default argument or default
510     /// initializer expression we're evaluating, if any.
511     CurrentSourceLocExprScope CurSourceLocExprScope;
512 
513     // Note that we intentionally use std::map here so that references to
514     // values are stable.
515     typedef std::pair<const void *, unsigned> MapKeyTy;
516     typedef std::map<MapKeyTy, APValue> MapTy;
517     /// Temporaries - Temporary lvalues materialized within this stack frame.
518     MapTy Temporaries;
519 
520     /// CallLoc - The location of the call expression for this call.
521     SourceLocation CallLoc;
522 
523     /// Index - The call index of this call.
524     unsigned Index;
525 
526     /// The stack of integers for tracking version numbers for temporaries.
527     SmallVector<unsigned, 2> TempVersionStack = {1};
528     unsigned CurTempVersion = TempVersionStack.back();
529 
530     unsigned getTempVersion() const { return TempVersionStack.back(); }
531 
532     void pushTempVersion() {
533       TempVersionStack.push_back(++CurTempVersion);
534     }
535 
536     void popTempVersion() {
537       TempVersionStack.pop_back();
538     }
539 
540     // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
541     // on the overall stack usage of deeply-recursing constexpr evaluations.
542     // (We should cache this map rather than recomputing it repeatedly.)
543     // But let's try this and see how it goes; we can look into caching the map
544     // as a later change.
545 
546     /// LambdaCaptureFields - Mapping from captured variables/this to
547     /// corresponding data members in the closure class.
548     llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
549     FieldDecl *LambdaThisCaptureField;
550 
551     CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
552                    const FunctionDecl *Callee, const LValue *This,
553                    APValue *Arguments);
554     ~CallStackFrame();
555 
556     // Return the temporary for Key whose version number is Version.
557     APValue *getTemporary(const void *Key, unsigned Version) {
558       MapKeyTy KV(Key, Version);
559       auto LB = Temporaries.lower_bound(KV);
560       if (LB != Temporaries.end() && LB->first == KV)
561         return &LB->second;
562       // Pair (Key,Version) wasn't found in the map. Check that no elements
563       // in the map have 'Key' as their key.
564       assert((LB == Temporaries.end() || LB->first.first != Key) &&
565              (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
566              "Element with key 'Key' found in map");
567       return nullptr;
568     }
569 
570     // Return the current temporary for Key in the map.
571     APValue *getCurrentTemporary(const void *Key) {
572       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
573       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
574         return &std::prev(UB)->second;
575       return nullptr;
576     }
577 
578     // Return the version number of the current temporary for Key.
579     unsigned getCurrentTemporaryVersion(const void *Key) const {
580       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
581       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
582         return std::prev(UB)->first.second;
583       return 0;
584     }
585 
586     /// Allocate storage for an object of type T in this stack frame.
587     /// Populates LV with a handle to the created object. Key identifies
588     /// the temporary within the stack frame, and must not be reused without
589     /// bumping the temporary version number.
590     template<typename KeyT>
591     APValue &createTemporary(const KeyT *Key, QualType T,
592                              bool IsLifetimeExtended, LValue &LV);
593 
594     void describe(llvm::raw_ostream &OS) override;
595 
596     Frame *getCaller() const override { return Caller; }
597     SourceLocation getCallLocation() const override { return CallLoc; }
598     const FunctionDecl *getCallee() const override { return Callee; }
599 
600     bool isStdFunction() const {
601       for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
602         if (DC->isStdNamespace())
603           return true;
604       return false;
605     }
606   };
607 
608   /// Temporarily override 'this'.
609   class ThisOverrideRAII {
610   public:
611     ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
612         : Frame(Frame), OldThis(Frame.This) {
613       if (Enable)
614         Frame.This = NewThis;
615     }
616     ~ThisOverrideRAII() {
617       Frame.This = OldThis;
618     }
619   private:
620     CallStackFrame &Frame;
621     const LValue *OldThis;
622   };
623 }
624 
625 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
626                               const LValue &This, QualType ThisType);
627 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
628                               APValue::LValueBase LVBase, APValue &Value,
629                               QualType T);
630 
631 namespace {
632   /// A cleanup, and a flag indicating whether it is lifetime-extended.
633   class Cleanup {
634     llvm::PointerIntPair<APValue*, 1, bool> Value;
635     APValue::LValueBase Base;
636     QualType T;
637 
638   public:
639     Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
640             bool IsLifetimeExtended)
641         : Value(Val, IsLifetimeExtended), Base(Base), T(T) {}
642 
643     bool isLifetimeExtended() const { return Value.getInt(); }
644     bool endLifetime(EvalInfo &Info, bool RunDestructors) {
645       if (RunDestructors) {
646         SourceLocation Loc;
647         if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
648           Loc = VD->getLocation();
649         else if (const Expr *E = Base.dyn_cast<const Expr*>())
650           Loc = E->getExprLoc();
651         return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
652       }
653       *Value.getPointer() = APValue();
654       return true;
655     }
656 
657     bool hasSideEffect() {
658       return T.isDestructedType();
659     }
660   };
661 
662   /// A reference to an object whose construction we are currently evaluating.
663   struct ObjectUnderConstruction {
664     APValue::LValueBase Base;
665     ArrayRef<APValue::LValuePathEntry> Path;
666     friend bool operator==(const ObjectUnderConstruction &LHS,
667                            const ObjectUnderConstruction &RHS) {
668       return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
669     }
670     friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
671       return llvm::hash_combine(Obj.Base, Obj.Path);
672     }
673   };
674   enum class ConstructionPhase {
675     None,
676     Bases,
677     AfterBases,
678     AfterFields,
679     Destroying,
680     DestroyingBases
681   };
682 }
683 
684 namespace llvm {
685 template<> struct DenseMapInfo<ObjectUnderConstruction> {
686   using Base = DenseMapInfo<APValue::LValueBase>;
687   static ObjectUnderConstruction getEmptyKey() {
688     return {Base::getEmptyKey(), {}}; }
689   static ObjectUnderConstruction getTombstoneKey() {
690     return {Base::getTombstoneKey(), {}};
691   }
692   static unsigned getHashValue(const ObjectUnderConstruction &Object) {
693     return hash_value(Object);
694   }
695   static bool isEqual(const ObjectUnderConstruction &LHS,
696                       const ObjectUnderConstruction &RHS) {
697     return LHS == RHS;
698   }
699 };
700 }
701 
702 namespace {
703   /// A dynamically-allocated heap object.
704   struct DynAlloc {
705     /// The value of this heap-allocated object.
706     APValue Value;
707     /// The allocating expression; used for diagnostics. Either a CXXNewExpr
708     /// or a CallExpr (the latter is for direct calls to operator new inside
709     /// std::allocator<T>::allocate).
710     const Expr *AllocExpr = nullptr;
711 
712     enum Kind {
713       New,
714       ArrayNew,
715       StdAllocator
716     };
717 
718     /// Get the kind of the allocation. This must match between allocation
719     /// and deallocation.
720     Kind getKind() const {
721       if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
722         return NE->isArray() ? ArrayNew : New;
723       assert(isa<CallExpr>(AllocExpr));
724       return StdAllocator;
725     }
726   };
727 
728   struct DynAllocOrder {
729     bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
730       return L.getIndex() < R.getIndex();
731     }
732   };
733 
734   /// EvalInfo - This is a private struct used by the evaluator to capture
735   /// information about a subexpression as it is folded.  It retains information
736   /// about the AST context, but also maintains information about the folded
737   /// expression.
738   ///
739   /// If an expression could be evaluated, it is still possible it is not a C
740   /// "integer constant expression" or constant expression.  If not, this struct
741   /// captures information about how and why not.
742   ///
743   /// One bit of information passed *into* the request for constant folding
744   /// indicates whether the subexpression is "evaluated" or not according to C
745   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
746   /// evaluate the expression regardless of what the RHS is, but C only allows
747   /// certain things in certain situations.
748   class EvalInfo : public interp::State {
749   public:
750     ASTContext &Ctx;
751 
752     /// EvalStatus - Contains information about the evaluation.
753     Expr::EvalStatus &EvalStatus;
754 
755     /// CurrentCall - The top of the constexpr call stack.
756     CallStackFrame *CurrentCall;
757 
758     /// CallStackDepth - The number of calls in the call stack right now.
759     unsigned CallStackDepth;
760 
761     /// NextCallIndex - The next call index to assign.
762     unsigned NextCallIndex;
763 
764     /// StepsLeft - The remaining number of evaluation steps we're permitted
765     /// to perform. This is essentially a limit for the number of statements
766     /// we will evaluate.
767     unsigned StepsLeft;
768 
769     /// Enable the experimental new constant interpreter. If an expression is
770     /// not supported by the interpreter, an error is triggered.
771     bool EnableNewConstInterp;
772 
773     /// BottomFrame - The frame in which evaluation started. This must be
774     /// initialized after CurrentCall and CallStackDepth.
775     CallStackFrame BottomFrame;
776 
777     /// A stack of values whose lifetimes end at the end of some surrounding
778     /// evaluation frame.
779     llvm::SmallVector<Cleanup, 16> CleanupStack;
780 
781     /// EvaluatingDecl - This is the declaration whose initializer is being
782     /// evaluated, if any.
783     APValue::LValueBase EvaluatingDecl;
784 
785     enum class EvaluatingDeclKind {
786       None,
787       /// We're evaluating the construction of EvaluatingDecl.
788       Ctor,
789       /// We're evaluating the destruction of EvaluatingDecl.
790       Dtor,
791     };
792     EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
793 
794     /// EvaluatingDeclValue - This is the value being constructed for the
795     /// declaration whose initializer is being evaluated, if any.
796     APValue *EvaluatingDeclValue;
797 
798     /// Set of objects that are currently being constructed.
799     llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
800         ObjectsUnderConstruction;
801 
802     /// Current heap allocations, along with the location where each was
803     /// allocated. We use std::map here because we need stable addresses
804     /// for the stored APValues.
805     std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
806 
807     /// The number of heap allocations performed so far in this evaluation.
808     unsigned NumHeapAllocs = 0;
809 
810     struct EvaluatingConstructorRAII {
811       EvalInfo &EI;
812       ObjectUnderConstruction Object;
813       bool DidInsert;
814       EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
815                                 bool HasBases)
816           : EI(EI), Object(Object) {
817         DidInsert =
818             EI.ObjectsUnderConstruction
819                 .insert({Object, HasBases ? ConstructionPhase::Bases
820                                           : ConstructionPhase::AfterBases})
821                 .second;
822       }
823       void finishedConstructingBases() {
824         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
825       }
826       void finishedConstructingFields() {
827         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
828       }
829       ~EvaluatingConstructorRAII() {
830         if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
831       }
832     };
833 
834     struct EvaluatingDestructorRAII {
835       EvalInfo &EI;
836       ObjectUnderConstruction Object;
837       bool DidInsert;
838       EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
839           : EI(EI), Object(Object) {
840         DidInsert = EI.ObjectsUnderConstruction
841                         .insert({Object, ConstructionPhase::Destroying})
842                         .second;
843       }
844       void startedDestroyingBases() {
845         EI.ObjectsUnderConstruction[Object] =
846             ConstructionPhase::DestroyingBases;
847       }
848       ~EvaluatingDestructorRAII() {
849         if (DidInsert)
850           EI.ObjectsUnderConstruction.erase(Object);
851       }
852     };
853 
854     ConstructionPhase
855     isEvaluatingCtorDtor(APValue::LValueBase Base,
856                          ArrayRef<APValue::LValuePathEntry> Path) {
857       return ObjectsUnderConstruction.lookup({Base, Path});
858     }
859 
860     /// If we're currently speculatively evaluating, the outermost call stack
861     /// depth at which we can mutate state, otherwise 0.
862     unsigned SpeculativeEvaluationDepth = 0;
863 
864     /// The current array initialization index, if we're performing array
865     /// initialization.
866     uint64_t ArrayInitIndex = -1;
867 
868     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
869     /// notes attached to it will also be stored, otherwise they will not be.
870     bool HasActiveDiagnostic;
871 
872     /// Have we emitted a diagnostic explaining why we couldn't constant
873     /// fold (not just why it's not strictly a constant expression)?
874     bool HasFoldFailureDiagnostic;
875 
876     /// Whether or not we're in a context where the front end requires a
877     /// constant value.
878     bool InConstantContext;
879 
880     /// Whether we're checking that an expression is a potential constant
881     /// expression. If so, do not fail on constructs that could become constant
882     /// later on (such as a use of an undefined global).
883     bool CheckingPotentialConstantExpression = false;
884 
885     /// Whether we're checking for an expression that has undefined behavior.
886     /// If so, we will produce warnings if we encounter an operation that is
887     /// always undefined.
888     bool CheckingForUndefinedBehavior = false;
889 
890     enum EvaluationMode {
891       /// Evaluate as a constant expression. Stop if we find that the expression
892       /// is not a constant expression.
893       EM_ConstantExpression,
894 
895       /// Evaluate as a constant expression. Stop if we find that the expression
896       /// is not a constant expression. Some expressions can be retried in the
897       /// optimizer if we don't constant fold them here, but in an unevaluated
898       /// context we try to fold them immediately since the optimizer never
899       /// gets a chance to look at it.
900       EM_ConstantExpressionUnevaluated,
901 
902       /// Fold the expression to a constant. Stop if we hit a side-effect that
903       /// we can't model.
904       EM_ConstantFold,
905 
906       /// Evaluate in any way we know how. Don't worry about side-effects that
907       /// can't be modeled.
908       EM_IgnoreSideEffects,
909     } EvalMode;
910 
911     /// Are we checking whether the expression is a potential constant
912     /// expression?
913     bool checkingPotentialConstantExpression() const override  {
914       return CheckingPotentialConstantExpression;
915     }
916 
917     /// Are we checking an expression for overflow?
918     // FIXME: We should check for any kind of undefined or suspicious behavior
919     // in such constructs, not just overflow.
920     bool checkingForUndefinedBehavior() const override {
921       return CheckingForUndefinedBehavior;
922     }
923 
924     EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
925         : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
926           CallStackDepth(0), NextCallIndex(1),
927           StepsLeft(C.getLangOpts().ConstexprStepLimit),
928           EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
929           BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
930           EvaluatingDecl((const ValueDecl *)nullptr),
931           EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
932           HasFoldFailureDiagnostic(false), InConstantContext(false),
933           EvalMode(Mode) {}
934 
935     ~EvalInfo() {
936       discardCleanups();
937     }
938 
939     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
940                            EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
941       EvaluatingDecl = Base;
942       IsEvaluatingDecl = EDK;
943       EvaluatingDeclValue = &Value;
944     }
945 
946     bool CheckCallLimit(SourceLocation Loc) {
947       // Don't perform any constexpr calls (other than the call we're checking)
948       // when checking a potential constant expression.
949       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
950         return false;
951       if (NextCallIndex == 0) {
952         // NextCallIndex has wrapped around.
953         FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
954         return false;
955       }
956       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
957         return true;
958       FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
959         << getLangOpts().ConstexprCallDepth;
960       return false;
961     }
962 
963     std::pair<CallStackFrame *, unsigned>
964     getCallFrameAndDepth(unsigned CallIndex) {
965       assert(CallIndex && "no call index in getCallFrameAndDepth");
966       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
967       // be null in this loop.
968       unsigned Depth = CallStackDepth;
969       CallStackFrame *Frame = CurrentCall;
970       while (Frame->Index > CallIndex) {
971         Frame = Frame->Caller;
972         --Depth;
973       }
974       if (Frame->Index == CallIndex)
975         return {Frame, Depth};
976       return {nullptr, 0};
977     }
978 
979     bool nextStep(const Stmt *S) {
980       if (!StepsLeft) {
981         FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
982         return false;
983       }
984       --StepsLeft;
985       return true;
986     }
987 
988     APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
989 
990     Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) {
991       Optional<DynAlloc*> Result;
992       auto It = HeapAllocs.find(DA);
993       if (It != HeapAllocs.end())
994         Result = &It->second;
995       return Result;
996     }
997 
998     /// Information about a stack frame for std::allocator<T>::[de]allocate.
999     struct StdAllocatorCaller {
1000       unsigned FrameIndex;
1001       QualType ElemType;
1002       explicit operator bool() const { return FrameIndex != 0; };
1003     };
1004 
1005     StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1006       for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1007            Call = Call->Caller) {
1008         const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1009         if (!MD)
1010           continue;
1011         const IdentifierInfo *FnII = MD->getIdentifier();
1012         if (!FnII || !FnII->isStr(FnName))
1013           continue;
1014 
1015         const auto *CTSD =
1016             dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1017         if (!CTSD)
1018           continue;
1019 
1020         const IdentifierInfo *ClassII = CTSD->getIdentifier();
1021         const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1022         if (CTSD->isInStdNamespace() && ClassII &&
1023             ClassII->isStr("allocator") && TAL.size() >= 1 &&
1024             TAL[0].getKind() == TemplateArgument::Type)
1025           return {Call->Index, TAL[0].getAsType()};
1026       }
1027 
1028       return {};
1029     }
1030 
1031     void performLifetimeExtension() {
1032       // Disable the cleanups for lifetime-extended temporaries.
1033       CleanupStack.erase(
1034           std::remove_if(CleanupStack.begin(), CleanupStack.end(),
1035                          [](Cleanup &C) { return C.isLifetimeExtended(); }),
1036           CleanupStack.end());
1037      }
1038 
1039     /// Throw away any remaining cleanups at the end of evaluation. If any
1040     /// cleanups would have had a side-effect, note that as an unmodeled
1041     /// side-effect and return false. Otherwise, return true.
1042     bool discardCleanups() {
1043       for (Cleanup &C : CleanupStack) {
1044         if (C.hasSideEffect() && !noteSideEffect()) {
1045           CleanupStack.clear();
1046           return false;
1047         }
1048       }
1049       CleanupStack.clear();
1050       return true;
1051     }
1052 
1053   private:
1054     interp::Frame *getCurrentFrame() override { return CurrentCall; }
1055     const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1056 
1057     bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1058     void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1059 
1060     void setFoldFailureDiagnostic(bool Flag) override {
1061       HasFoldFailureDiagnostic = Flag;
1062     }
1063 
1064     Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1065 
1066     ASTContext &getCtx() const override { return Ctx; }
1067 
1068     // If we have a prior diagnostic, it will be noting that the expression
1069     // isn't a constant expression. This diagnostic is more important,
1070     // unless we require this evaluation to produce a constant expression.
1071     //
1072     // FIXME: We might want to show both diagnostics to the user in
1073     // EM_ConstantFold mode.
1074     bool hasPriorDiagnostic() override {
1075       if (!EvalStatus.Diag->empty()) {
1076         switch (EvalMode) {
1077         case EM_ConstantFold:
1078         case EM_IgnoreSideEffects:
1079           if (!HasFoldFailureDiagnostic)
1080             break;
1081           // We've already failed to fold something. Keep that diagnostic.
1082           LLVM_FALLTHROUGH;
1083         case EM_ConstantExpression:
1084         case EM_ConstantExpressionUnevaluated:
1085           setActiveDiagnostic(false);
1086           return true;
1087         }
1088       }
1089       return false;
1090     }
1091 
1092     unsigned getCallStackDepth() override { return CallStackDepth; }
1093 
1094   public:
1095     /// Should we continue evaluation after encountering a side-effect that we
1096     /// couldn't model?
1097     bool keepEvaluatingAfterSideEffect() {
1098       switch (EvalMode) {
1099       case EM_IgnoreSideEffects:
1100         return true;
1101 
1102       case EM_ConstantExpression:
1103       case EM_ConstantExpressionUnevaluated:
1104       case EM_ConstantFold:
1105         // By default, assume any side effect might be valid in some other
1106         // evaluation of this expression from a different context.
1107         return checkingPotentialConstantExpression() ||
1108                checkingForUndefinedBehavior();
1109       }
1110       llvm_unreachable("Missed EvalMode case");
1111     }
1112 
1113     /// Note that we have had a side-effect, and determine whether we should
1114     /// keep evaluating.
1115     bool noteSideEffect() {
1116       EvalStatus.HasSideEffects = true;
1117       return keepEvaluatingAfterSideEffect();
1118     }
1119 
1120     /// Should we continue evaluation after encountering undefined behavior?
1121     bool keepEvaluatingAfterUndefinedBehavior() {
1122       switch (EvalMode) {
1123       case EM_IgnoreSideEffects:
1124       case EM_ConstantFold:
1125         return true;
1126 
1127       case EM_ConstantExpression:
1128       case EM_ConstantExpressionUnevaluated:
1129         return checkingForUndefinedBehavior();
1130       }
1131       llvm_unreachable("Missed EvalMode case");
1132     }
1133 
1134     /// Note that we hit something that was technically undefined behavior, but
1135     /// that we can evaluate past it (such as signed overflow or floating-point
1136     /// division by zero.)
1137     bool noteUndefinedBehavior() override {
1138       EvalStatus.HasUndefinedBehavior = true;
1139       return keepEvaluatingAfterUndefinedBehavior();
1140     }
1141 
1142     /// Should we continue evaluation as much as possible after encountering a
1143     /// construct which can't be reduced to a value?
1144     bool keepEvaluatingAfterFailure() const override {
1145       if (!StepsLeft)
1146         return false;
1147 
1148       switch (EvalMode) {
1149       case EM_ConstantExpression:
1150       case EM_ConstantExpressionUnevaluated:
1151       case EM_ConstantFold:
1152       case EM_IgnoreSideEffects:
1153         return checkingPotentialConstantExpression() ||
1154                checkingForUndefinedBehavior();
1155       }
1156       llvm_unreachable("Missed EvalMode case");
1157     }
1158 
1159     /// Notes that we failed to evaluate an expression that other expressions
1160     /// directly depend on, and determine if we should keep evaluating. This
1161     /// should only be called if we actually intend to keep evaluating.
1162     ///
1163     /// Call noteSideEffect() instead if we may be able to ignore the value that
1164     /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1165     ///
1166     /// (Foo(), 1)      // use noteSideEffect
1167     /// (Foo() || true) // use noteSideEffect
1168     /// Foo() + 1       // use noteFailure
1169     LLVM_NODISCARD bool noteFailure() {
1170       // Failure when evaluating some expression often means there is some
1171       // subexpression whose evaluation was skipped. Therefore, (because we
1172       // don't track whether we skipped an expression when unwinding after an
1173       // evaluation failure) every evaluation failure that bubbles up from a
1174       // subexpression implies that a side-effect has potentially happened. We
1175       // skip setting the HasSideEffects flag to true until we decide to
1176       // continue evaluating after that point, which happens here.
1177       bool KeepGoing = keepEvaluatingAfterFailure();
1178       EvalStatus.HasSideEffects |= KeepGoing;
1179       return KeepGoing;
1180     }
1181 
1182     class ArrayInitLoopIndex {
1183       EvalInfo &Info;
1184       uint64_t OuterIndex;
1185 
1186     public:
1187       ArrayInitLoopIndex(EvalInfo &Info)
1188           : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1189         Info.ArrayInitIndex = 0;
1190       }
1191       ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1192 
1193       operator uint64_t&() { return Info.ArrayInitIndex; }
1194     };
1195   };
1196 
1197   /// Object used to treat all foldable expressions as constant expressions.
1198   struct FoldConstant {
1199     EvalInfo &Info;
1200     bool Enabled;
1201     bool HadNoPriorDiags;
1202     EvalInfo::EvaluationMode OldMode;
1203 
1204     explicit FoldConstant(EvalInfo &Info, bool Enabled)
1205       : Info(Info),
1206         Enabled(Enabled),
1207         HadNoPriorDiags(Info.EvalStatus.Diag &&
1208                         Info.EvalStatus.Diag->empty() &&
1209                         !Info.EvalStatus.HasSideEffects),
1210         OldMode(Info.EvalMode) {
1211       if (Enabled)
1212         Info.EvalMode = EvalInfo::EM_ConstantFold;
1213     }
1214     void keepDiagnostics() { Enabled = false; }
1215     ~FoldConstant() {
1216       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1217           !Info.EvalStatus.HasSideEffects)
1218         Info.EvalStatus.Diag->clear();
1219       Info.EvalMode = OldMode;
1220     }
1221   };
1222 
1223   /// RAII object used to set the current evaluation mode to ignore
1224   /// side-effects.
1225   struct IgnoreSideEffectsRAII {
1226     EvalInfo &Info;
1227     EvalInfo::EvaluationMode OldMode;
1228     explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1229         : Info(Info), OldMode(Info.EvalMode) {
1230       Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1231     }
1232 
1233     ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1234   };
1235 
1236   /// RAII object used to optionally suppress diagnostics and side-effects from
1237   /// a speculative evaluation.
1238   class SpeculativeEvaluationRAII {
1239     EvalInfo *Info = nullptr;
1240     Expr::EvalStatus OldStatus;
1241     unsigned OldSpeculativeEvaluationDepth;
1242 
1243     void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1244       Info = Other.Info;
1245       OldStatus = Other.OldStatus;
1246       OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1247       Other.Info = nullptr;
1248     }
1249 
1250     void maybeRestoreState() {
1251       if (!Info)
1252         return;
1253 
1254       Info->EvalStatus = OldStatus;
1255       Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1256     }
1257 
1258   public:
1259     SpeculativeEvaluationRAII() = default;
1260 
1261     SpeculativeEvaluationRAII(
1262         EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1263         : Info(&Info), OldStatus(Info.EvalStatus),
1264           OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1265       Info.EvalStatus.Diag = NewDiag;
1266       Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1267     }
1268 
1269     SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1270     SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1271       moveFromAndCancel(std::move(Other));
1272     }
1273 
1274     SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1275       maybeRestoreState();
1276       moveFromAndCancel(std::move(Other));
1277       return *this;
1278     }
1279 
1280     ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1281   };
1282 
1283   /// RAII object wrapping a full-expression or block scope, and handling
1284   /// the ending of the lifetime of temporaries created within it.
1285   template<bool IsFullExpression>
1286   class ScopeRAII {
1287     EvalInfo &Info;
1288     unsigned OldStackSize;
1289   public:
1290     ScopeRAII(EvalInfo &Info)
1291         : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1292       // Push a new temporary version. This is needed to distinguish between
1293       // temporaries created in different iterations of a loop.
1294       Info.CurrentCall->pushTempVersion();
1295     }
1296     bool destroy(bool RunDestructors = true) {
1297       bool OK = cleanup(Info, RunDestructors, OldStackSize);
1298       OldStackSize = -1U;
1299       return OK;
1300     }
1301     ~ScopeRAII() {
1302       if (OldStackSize != -1U)
1303         destroy(false);
1304       // Body moved to a static method to encourage the compiler to inline away
1305       // instances of this class.
1306       Info.CurrentCall->popTempVersion();
1307     }
1308   private:
1309     static bool cleanup(EvalInfo &Info, bool RunDestructors,
1310                         unsigned OldStackSize) {
1311       assert(OldStackSize <= Info.CleanupStack.size() &&
1312              "running cleanups out of order?");
1313 
1314       // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1315       // for a full-expression scope.
1316       bool Success = true;
1317       for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1318         if (!(IsFullExpression &&
1319               Info.CleanupStack[I - 1].isLifetimeExtended())) {
1320           if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1321             Success = false;
1322             break;
1323           }
1324         }
1325       }
1326 
1327       // Compact lifetime-extended cleanups.
1328       auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1329       if (IsFullExpression)
1330         NewEnd =
1331             std::remove_if(NewEnd, Info.CleanupStack.end(),
1332                            [](Cleanup &C) { return !C.isLifetimeExtended(); });
1333       Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1334       return Success;
1335     }
1336   };
1337   typedef ScopeRAII<false> BlockScopeRAII;
1338   typedef ScopeRAII<true> FullExpressionRAII;
1339 }
1340 
1341 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1342                                          CheckSubobjectKind CSK) {
1343   if (Invalid)
1344     return false;
1345   if (isOnePastTheEnd()) {
1346     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1347       << CSK;
1348     setInvalid();
1349     return false;
1350   }
1351   // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1352   // must actually be at least one array element; even a VLA cannot have a
1353   // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1354   return true;
1355 }
1356 
1357 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1358                                                                 const Expr *E) {
1359   Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1360   // Do not set the designator as invalid: we can represent this situation,
1361   // and correct handling of __builtin_object_size requires us to do so.
1362 }
1363 
1364 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1365                                                     const Expr *E,
1366                                                     const APSInt &N) {
1367   // If we're complaining, we must be able to statically determine the size of
1368   // the most derived array.
1369   if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1370     Info.CCEDiag(E, diag::note_constexpr_array_index)
1371       << N << /*array*/ 0
1372       << static_cast<unsigned>(getMostDerivedArraySize());
1373   else
1374     Info.CCEDiag(E, diag::note_constexpr_array_index)
1375       << N << /*non-array*/ 1;
1376   setInvalid();
1377 }
1378 
1379 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1380                                const FunctionDecl *Callee, const LValue *This,
1381                                APValue *Arguments)
1382     : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1383       Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1384   Info.CurrentCall = this;
1385   ++Info.CallStackDepth;
1386 }
1387 
1388 CallStackFrame::~CallStackFrame() {
1389   assert(Info.CurrentCall == this && "calls retired out of order");
1390   --Info.CallStackDepth;
1391   Info.CurrentCall = Caller;
1392 }
1393 
1394 static bool isRead(AccessKinds AK) {
1395   return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1396 }
1397 
1398 static bool isModification(AccessKinds AK) {
1399   switch (AK) {
1400   case AK_Read:
1401   case AK_ReadObjectRepresentation:
1402   case AK_MemberCall:
1403   case AK_DynamicCast:
1404   case AK_TypeId:
1405     return false;
1406   case AK_Assign:
1407   case AK_Increment:
1408   case AK_Decrement:
1409   case AK_Construct:
1410   case AK_Destroy:
1411     return true;
1412   }
1413   llvm_unreachable("unknown access kind");
1414 }
1415 
1416 static bool isAnyAccess(AccessKinds AK) {
1417   return isRead(AK) || isModification(AK);
1418 }
1419 
1420 /// Is this an access per the C++ definition?
1421 static bool isFormalAccess(AccessKinds AK) {
1422   return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
1423 }
1424 
1425 /// Is this kind of axcess valid on an indeterminate object value?
1426 static bool isValidIndeterminateAccess(AccessKinds AK) {
1427   switch (AK) {
1428   case AK_Read:
1429   case AK_Increment:
1430   case AK_Decrement:
1431     // These need the object's value.
1432     return false;
1433 
1434   case AK_ReadObjectRepresentation:
1435   case AK_Assign:
1436   case AK_Construct:
1437   case AK_Destroy:
1438     // Construction and destruction don't need the value.
1439     return true;
1440 
1441   case AK_MemberCall:
1442   case AK_DynamicCast:
1443   case AK_TypeId:
1444     // These aren't really meaningful on scalars.
1445     return true;
1446   }
1447   llvm_unreachable("unknown access kind");
1448 }
1449 
1450 namespace {
1451   struct ComplexValue {
1452   private:
1453     bool IsInt;
1454 
1455   public:
1456     APSInt IntReal, IntImag;
1457     APFloat FloatReal, FloatImag;
1458 
1459     ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1460 
1461     void makeComplexFloat() { IsInt = false; }
1462     bool isComplexFloat() const { return !IsInt; }
1463     APFloat &getComplexFloatReal() { return FloatReal; }
1464     APFloat &getComplexFloatImag() { return FloatImag; }
1465 
1466     void makeComplexInt() { IsInt = true; }
1467     bool isComplexInt() const { return IsInt; }
1468     APSInt &getComplexIntReal() { return IntReal; }
1469     APSInt &getComplexIntImag() { return IntImag; }
1470 
1471     void moveInto(APValue &v) const {
1472       if (isComplexFloat())
1473         v = APValue(FloatReal, FloatImag);
1474       else
1475         v = APValue(IntReal, IntImag);
1476     }
1477     void setFrom(const APValue &v) {
1478       assert(v.isComplexFloat() || v.isComplexInt());
1479       if (v.isComplexFloat()) {
1480         makeComplexFloat();
1481         FloatReal = v.getComplexFloatReal();
1482         FloatImag = v.getComplexFloatImag();
1483       } else {
1484         makeComplexInt();
1485         IntReal = v.getComplexIntReal();
1486         IntImag = v.getComplexIntImag();
1487       }
1488     }
1489   };
1490 
1491   struct LValue {
1492     APValue::LValueBase Base;
1493     CharUnits Offset;
1494     SubobjectDesignator Designator;
1495     bool IsNullPtr : 1;
1496     bool InvalidBase : 1;
1497 
1498     const APValue::LValueBase getLValueBase() const { return Base; }
1499     CharUnits &getLValueOffset() { return Offset; }
1500     const CharUnits &getLValueOffset() const { return Offset; }
1501     SubobjectDesignator &getLValueDesignator() { return Designator; }
1502     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1503     bool isNullPointer() const { return IsNullPtr;}
1504 
1505     unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1506     unsigned getLValueVersion() const { return Base.getVersion(); }
1507 
1508     void moveInto(APValue &V) const {
1509       if (Designator.Invalid)
1510         V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1511       else {
1512         assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1513         V = APValue(Base, Offset, Designator.Entries,
1514                     Designator.IsOnePastTheEnd, IsNullPtr);
1515       }
1516     }
1517     void setFrom(ASTContext &Ctx, const APValue &V) {
1518       assert(V.isLValue() && "Setting LValue from a non-LValue?");
1519       Base = V.getLValueBase();
1520       Offset = V.getLValueOffset();
1521       InvalidBase = false;
1522       Designator = SubobjectDesignator(Ctx, V);
1523       IsNullPtr = V.isNullPointer();
1524     }
1525 
1526     void set(APValue::LValueBase B, bool BInvalid = false) {
1527 #ifndef NDEBUG
1528       // We only allow a few types of invalid bases. Enforce that here.
1529       if (BInvalid) {
1530         const auto *E = B.get<const Expr *>();
1531         assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1532                "Unexpected type of invalid base");
1533       }
1534 #endif
1535 
1536       Base = B;
1537       Offset = CharUnits::fromQuantity(0);
1538       InvalidBase = BInvalid;
1539       Designator = SubobjectDesignator(getType(B));
1540       IsNullPtr = false;
1541     }
1542 
1543     void setNull(ASTContext &Ctx, QualType PointerTy) {
1544       Base = (Expr *)nullptr;
1545       Offset =
1546           CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
1547       InvalidBase = false;
1548       Designator = SubobjectDesignator(PointerTy->getPointeeType());
1549       IsNullPtr = true;
1550     }
1551 
1552     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1553       set(B, true);
1554     }
1555 
1556     std::string toString(ASTContext &Ctx, QualType T) const {
1557       APValue Printable;
1558       moveInto(Printable);
1559       return Printable.getAsString(Ctx, T);
1560     }
1561 
1562   private:
1563     // Check that this LValue is not based on a null pointer. If it is, produce
1564     // a diagnostic and mark the designator as invalid.
1565     template <typename GenDiagType>
1566     bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1567       if (Designator.Invalid)
1568         return false;
1569       if (IsNullPtr) {
1570         GenDiag();
1571         Designator.setInvalid();
1572         return false;
1573       }
1574       return true;
1575     }
1576 
1577   public:
1578     bool checkNullPointer(EvalInfo &Info, const Expr *E,
1579                           CheckSubobjectKind CSK) {
1580       return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1581         Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1582       });
1583     }
1584 
1585     bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1586                                        AccessKinds AK) {
1587       return checkNullPointerDiagnosingWith([&Info, E, AK] {
1588         Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1589       });
1590     }
1591 
1592     // Check this LValue refers to an object. If not, set the designator to be
1593     // invalid and emit a diagnostic.
1594     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1595       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1596              Designator.checkSubobject(Info, E, CSK);
1597     }
1598 
1599     void addDecl(EvalInfo &Info, const Expr *E,
1600                  const Decl *D, bool Virtual = false) {
1601       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1602         Designator.addDeclUnchecked(D, Virtual);
1603     }
1604     void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1605       if (!Designator.Entries.empty()) {
1606         Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1607         Designator.setInvalid();
1608         return;
1609       }
1610       if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1611         assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1612         Designator.FirstEntryIsAnUnsizedArray = true;
1613         Designator.addUnsizedArrayUnchecked(ElemTy);
1614       }
1615     }
1616     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1617       if (checkSubobject(Info, E, CSK_ArrayToPointer))
1618         Designator.addArrayUnchecked(CAT);
1619     }
1620     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1621       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1622         Designator.addComplexUnchecked(EltTy, Imag);
1623     }
1624     void clearIsNullPointer() {
1625       IsNullPtr = false;
1626     }
1627     void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1628                               const APSInt &Index, CharUnits ElementSize) {
1629       // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1630       // but we're not required to diagnose it and it's valid in C++.)
1631       if (!Index)
1632         return;
1633 
1634       // Compute the new offset in the appropriate width, wrapping at 64 bits.
1635       // FIXME: When compiling for a 32-bit target, we should use 32-bit
1636       // offsets.
1637       uint64_t Offset64 = Offset.getQuantity();
1638       uint64_t ElemSize64 = ElementSize.getQuantity();
1639       uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1640       Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1641 
1642       if (checkNullPointer(Info, E, CSK_ArrayIndex))
1643         Designator.adjustIndex(Info, E, Index);
1644       clearIsNullPointer();
1645     }
1646     void adjustOffset(CharUnits N) {
1647       Offset += N;
1648       if (N.getQuantity())
1649         clearIsNullPointer();
1650     }
1651   };
1652 
1653   struct MemberPtr {
1654     MemberPtr() {}
1655     explicit MemberPtr(const ValueDecl *Decl) :
1656       DeclAndIsDerivedMember(Decl, false), Path() {}
1657 
1658     /// The member or (direct or indirect) field referred to by this member
1659     /// pointer, or 0 if this is a null member pointer.
1660     const ValueDecl *getDecl() const {
1661       return DeclAndIsDerivedMember.getPointer();
1662     }
1663     /// Is this actually a member of some type derived from the relevant class?
1664     bool isDerivedMember() const {
1665       return DeclAndIsDerivedMember.getInt();
1666     }
1667     /// Get the class which the declaration actually lives in.
1668     const CXXRecordDecl *getContainingRecord() const {
1669       return cast<CXXRecordDecl>(
1670           DeclAndIsDerivedMember.getPointer()->getDeclContext());
1671     }
1672 
1673     void moveInto(APValue &V) const {
1674       V = APValue(getDecl(), isDerivedMember(), Path);
1675     }
1676     void setFrom(const APValue &V) {
1677       assert(V.isMemberPointer());
1678       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1679       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1680       Path.clear();
1681       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1682       Path.insert(Path.end(), P.begin(), P.end());
1683     }
1684 
1685     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1686     /// whether the member is a member of some class derived from the class type
1687     /// of the member pointer.
1688     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1689     /// Path - The path of base/derived classes from the member declaration's
1690     /// class (exclusive) to the class type of the member pointer (inclusive).
1691     SmallVector<const CXXRecordDecl*, 4> Path;
1692 
1693     /// Perform a cast towards the class of the Decl (either up or down the
1694     /// hierarchy).
1695     bool castBack(const CXXRecordDecl *Class) {
1696       assert(!Path.empty());
1697       const CXXRecordDecl *Expected;
1698       if (Path.size() >= 2)
1699         Expected = Path[Path.size() - 2];
1700       else
1701         Expected = getContainingRecord();
1702       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1703         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1704         // if B does not contain the original member and is not a base or
1705         // derived class of the class containing the original member, the result
1706         // of the cast is undefined.
1707         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1708         // (D::*). We consider that to be a language defect.
1709         return false;
1710       }
1711       Path.pop_back();
1712       return true;
1713     }
1714     /// Perform a base-to-derived member pointer cast.
1715     bool castToDerived(const CXXRecordDecl *Derived) {
1716       if (!getDecl())
1717         return true;
1718       if (!isDerivedMember()) {
1719         Path.push_back(Derived);
1720         return true;
1721       }
1722       if (!castBack(Derived))
1723         return false;
1724       if (Path.empty())
1725         DeclAndIsDerivedMember.setInt(false);
1726       return true;
1727     }
1728     /// Perform a derived-to-base member pointer cast.
1729     bool castToBase(const CXXRecordDecl *Base) {
1730       if (!getDecl())
1731         return true;
1732       if (Path.empty())
1733         DeclAndIsDerivedMember.setInt(true);
1734       if (isDerivedMember()) {
1735         Path.push_back(Base);
1736         return true;
1737       }
1738       return castBack(Base);
1739     }
1740   };
1741 
1742   /// Compare two member pointers, which are assumed to be of the same type.
1743   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1744     if (!LHS.getDecl() || !RHS.getDecl())
1745       return !LHS.getDecl() && !RHS.getDecl();
1746     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1747       return false;
1748     return LHS.Path == RHS.Path;
1749   }
1750 }
1751 
1752 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1753 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1754                             const LValue &This, const Expr *E,
1755                             bool AllowNonLiteralTypes = false);
1756 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1757                            bool InvalidBaseOK = false);
1758 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1759                             bool InvalidBaseOK = false);
1760 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1761                                   EvalInfo &Info);
1762 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1763 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1764 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1765                                     EvalInfo &Info);
1766 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1767 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1768 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1769                            EvalInfo &Info);
1770 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1771 
1772 /// Evaluate an integer or fixed point expression into an APResult.
1773 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1774                                         EvalInfo &Info);
1775 
1776 /// Evaluate only a fixed point expression into an APResult.
1777 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1778                                EvalInfo &Info);
1779 
1780 //===----------------------------------------------------------------------===//
1781 // Misc utilities
1782 //===----------------------------------------------------------------------===//
1783 
1784 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1785 /// preserving its value (by extending by up to one bit as needed).
1786 static void negateAsSigned(APSInt &Int) {
1787   if (Int.isUnsigned() || Int.isMinSignedValue()) {
1788     Int = Int.extend(Int.getBitWidth() + 1);
1789     Int.setIsSigned(true);
1790   }
1791   Int = -Int;
1792 }
1793 
1794 template<typename KeyT>
1795 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1796                                          bool IsLifetimeExtended, LValue &LV) {
1797   unsigned Version = getTempVersion();
1798   APValue::LValueBase Base(Key, Index, Version);
1799   LV.set(Base);
1800   APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1801   assert(Result.isAbsent() && "temporary created multiple times");
1802 
1803   // If we're creating a temporary immediately in the operand of a speculative
1804   // evaluation, don't register a cleanup to be run outside the speculative
1805   // evaluation context, since we won't actually be able to initialize this
1806   // object.
1807   if (Index <= Info.SpeculativeEvaluationDepth) {
1808     if (T.isDestructedType())
1809       Info.noteSideEffect();
1810   } else {
1811     Info.CleanupStack.push_back(Cleanup(&Result, Base, T, IsLifetimeExtended));
1812   }
1813   return Result;
1814 }
1815 
1816 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1817   if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1818     FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1819     return nullptr;
1820   }
1821 
1822   DynamicAllocLValue DA(NumHeapAllocs++);
1823   LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1824   auto Result = HeapAllocs.emplace(std::piecewise_construct,
1825                                    std::forward_as_tuple(DA), std::tuple<>());
1826   assert(Result.second && "reused a heap alloc index?");
1827   Result.first->second.AllocExpr = E;
1828   return &Result.first->second.Value;
1829 }
1830 
1831 /// Produce a string describing the given constexpr call.
1832 void CallStackFrame::describe(raw_ostream &Out) {
1833   unsigned ArgIndex = 0;
1834   bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1835                       !isa<CXXConstructorDecl>(Callee) &&
1836                       cast<CXXMethodDecl>(Callee)->isInstance();
1837 
1838   if (!IsMemberCall)
1839     Out << *Callee << '(';
1840 
1841   if (This && IsMemberCall) {
1842     APValue Val;
1843     This->moveInto(Val);
1844     Val.printPretty(Out, Info.Ctx,
1845                     This->Designator.MostDerivedType);
1846     // FIXME: Add parens around Val if needed.
1847     Out << "->" << *Callee << '(';
1848     IsMemberCall = false;
1849   }
1850 
1851   for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1852        E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
1853     if (ArgIndex > (unsigned)IsMemberCall)
1854       Out << ", ";
1855 
1856     const ParmVarDecl *Param = *I;
1857     const APValue &Arg = Arguments[ArgIndex];
1858     Arg.printPretty(Out, Info.Ctx, Param->getType());
1859 
1860     if (ArgIndex == 0 && IsMemberCall)
1861       Out << "->" << *Callee << '(';
1862   }
1863 
1864   Out << ')';
1865 }
1866 
1867 /// Evaluate an expression to see if it had side-effects, and discard its
1868 /// result.
1869 /// \return \c true if the caller should keep evaluating.
1870 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1871   APValue Scratch;
1872   if (!Evaluate(Scratch, Info, E))
1873     // We don't need the value, but we might have skipped a side effect here.
1874     return Info.noteSideEffect();
1875   return true;
1876 }
1877 
1878 /// Should this call expression be treated as a string literal?
1879 static bool IsStringLiteralCall(const CallExpr *E) {
1880   unsigned Builtin = E->getBuiltinCallee();
1881   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1882           Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1883 }
1884 
1885 static bool IsGlobalLValue(APValue::LValueBase B) {
1886   // C++11 [expr.const]p3 An address constant expression is a prvalue core
1887   // constant expression of pointer type that evaluates to...
1888 
1889   // ... a null pointer value, or a prvalue core constant expression of type
1890   // std::nullptr_t.
1891   if (!B) return true;
1892 
1893   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1894     // ... the address of an object with static storage duration,
1895     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1896       return VD->hasGlobalStorage();
1897     // ... the address of a function,
1898     // ... the address of a GUID [MS extension],
1899     return isa<FunctionDecl>(D) || isa<MSGuidDecl>(D);
1900   }
1901 
1902   if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
1903     return true;
1904 
1905   const Expr *E = B.get<const Expr*>();
1906   switch (E->getStmtClass()) {
1907   default:
1908     return false;
1909   case Expr::CompoundLiteralExprClass: {
1910     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1911     return CLE->isFileScope() && CLE->isLValue();
1912   }
1913   case Expr::MaterializeTemporaryExprClass:
1914     // A materialized temporary might have been lifetime-extended to static
1915     // storage duration.
1916     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1917   // A string literal has static storage duration.
1918   case Expr::StringLiteralClass:
1919   case Expr::PredefinedExprClass:
1920   case Expr::ObjCStringLiteralClass:
1921   case Expr::ObjCEncodeExprClass:
1922     return true;
1923   case Expr::ObjCBoxedExprClass:
1924     return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
1925   case Expr::CallExprClass:
1926     return IsStringLiteralCall(cast<CallExpr>(E));
1927   // For GCC compatibility, &&label has static storage duration.
1928   case Expr::AddrLabelExprClass:
1929     return true;
1930   // A Block literal expression may be used as the initialization value for
1931   // Block variables at global or local static scope.
1932   case Expr::BlockExprClass:
1933     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1934   case Expr::ImplicitValueInitExprClass:
1935     // FIXME:
1936     // We can never form an lvalue with an implicit value initialization as its
1937     // base through expression evaluation, so these only appear in one case: the
1938     // implicit variable declaration we invent when checking whether a constexpr
1939     // constructor can produce a constant expression. We must assume that such
1940     // an expression might be a global lvalue.
1941     return true;
1942   }
1943 }
1944 
1945 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1946   return LVal.Base.dyn_cast<const ValueDecl*>();
1947 }
1948 
1949 static bool IsLiteralLValue(const LValue &Value) {
1950   if (Value.getLValueCallIndex())
1951     return false;
1952   const Expr *E = Value.Base.dyn_cast<const Expr*>();
1953   return E && !isa<MaterializeTemporaryExpr>(E);
1954 }
1955 
1956 static bool IsWeakLValue(const LValue &Value) {
1957   const ValueDecl *Decl = GetLValueBaseDecl(Value);
1958   return Decl && Decl->isWeak();
1959 }
1960 
1961 static bool isZeroSized(const LValue &Value) {
1962   const ValueDecl *Decl = GetLValueBaseDecl(Value);
1963   if (Decl && isa<VarDecl>(Decl)) {
1964     QualType Ty = Decl->getType();
1965     if (Ty->isArrayType())
1966       return Ty->isIncompleteType() ||
1967              Decl->getASTContext().getTypeSize(Ty) == 0;
1968   }
1969   return false;
1970 }
1971 
1972 static bool HasSameBase(const LValue &A, const LValue &B) {
1973   if (!A.getLValueBase())
1974     return !B.getLValueBase();
1975   if (!B.getLValueBase())
1976     return false;
1977 
1978   if (A.getLValueBase().getOpaqueValue() !=
1979       B.getLValueBase().getOpaqueValue()) {
1980     const Decl *ADecl = GetLValueBaseDecl(A);
1981     if (!ADecl)
1982       return false;
1983     const Decl *BDecl = GetLValueBaseDecl(B);
1984     if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
1985       return false;
1986   }
1987 
1988   return IsGlobalLValue(A.getLValueBase()) ||
1989          (A.getLValueCallIndex() == B.getLValueCallIndex() &&
1990           A.getLValueVersion() == B.getLValueVersion());
1991 }
1992 
1993 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1994   assert(Base && "no location for a null lvalue");
1995   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1996   if (VD)
1997     Info.Note(VD->getLocation(), diag::note_declared_at);
1998   else if (const Expr *E = Base.dyn_cast<const Expr*>())
1999     Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2000   else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2001     // FIXME: Produce a note for dangling pointers too.
2002     if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA))
2003       Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2004                 diag::note_constexpr_dynamic_alloc_here);
2005   }
2006   // We have no information to show for a typeid(T) object.
2007 }
2008 
2009 enum class CheckEvaluationResultKind {
2010   ConstantExpression,
2011   FullyInitialized,
2012 };
2013 
2014 /// Materialized temporaries that we've already checked to determine if they're
2015 /// initializsed by a constant expression.
2016 using CheckedTemporaries =
2017     llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
2018 
2019 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2020                                   EvalInfo &Info, SourceLocation DiagLoc,
2021                                   QualType Type, const APValue &Value,
2022                                   Expr::ConstExprUsage Usage,
2023                                   SourceLocation SubobjectLoc,
2024                                   CheckedTemporaries &CheckedTemps);
2025 
2026 /// Check that this reference or pointer core constant expression is a valid
2027 /// value for an address or reference constant expression. Return true if we
2028 /// can fold this expression, whether or not it's a constant expression.
2029 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2030                                           QualType Type, const LValue &LVal,
2031                                           Expr::ConstExprUsage Usage,
2032                                           CheckedTemporaries &CheckedTemps) {
2033   bool IsReferenceType = Type->isReferenceType();
2034 
2035   APValue::LValueBase Base = LVal.getLValueBase();
2036   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2037 
2038   if (auto *VD = LVal.getLValueBase().dyn_cast<const ValueDecl *>()) {
2039     if (auto *FD = dyn_cast<FunctionDecl>(VD)) {
2040       if (FD->isConsteval()) {
2041         Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2042             << !Type->isAnyPointerType();
2043         Info.Note(FD->getLocation(), diag::note_declared_at);
2044         return false;
2045       }
2046     }
2047   }
2048 
2049   // Check that the object is a global. Note that the fake 'this' object we
2050   // manufacture when checking potential constant expressions is conservatively
2051   // assumed to be global here.
2052   if (!IsGlobalLValue(Base)) {
2053     if (Info.getLangOpts().CPlusPlus11) {
2054       const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2055       Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2056         << IsReferenceType << !Designator.Entries.empty()
2057         << !!VD << VD;
2058 
2059       auto *VarD = dyn_cast_or_null<VarDecl>(VD);
2060       if (VarD && VarD->isConstexpr()) {
2061         // Non-static local constexpr variables have unintuitive semantics:
2062         //   constexpr int a = 1;
2063         //   constexpr const int *p = &a;
2064         // ... is invalid because the address of 'a' is not constant. Suggest
2065         // adding a 'static' in this case.
2066         Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2067             << VarD
2068             << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2069       } else {
2070         NoteLValueLocation(Info, Base);
2071       }
2072     } else {
2073       Info.FFDiag(Loc);
2074     }
2075     // Don't allow references to temporaries to escape.
2076     return false;
2077   }
2078   assert((Info.checkingPotentialConstantExpression() ||
2079           LVal.getLValueCallIndex() == 0) &&
2080          "have call index for global lvalue");
2081 
2082   if (Base.is<DynamicAllocLValue>()) {
2083     Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2084         << IsReferenceType << !Designator.Entries.empty();
2085     NoteLValueLocation(Info, Base);
2086     return false;
2087   }
2088 
2089   if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
2090     if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
2091       // Check if this is a thread-local variable.
2092       if (Var->getTLSKind())
2093         // FIXME: Diagnostic!
2094         return false;
2095 
2096       // A dllimport variable never acts like a constant.
2097       if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
2098         // FIXME: Diagnostic!
2099         return false;
2100     }
2101     if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
2102       // __declspec(dllimport) must be handled very carefully:
2103       // We must never initialize an expression with the thunk in C++.
2104       // Doing otherwise would allow the same id-expression to yield
2105       // different addresses for the same function in different translation
2106       // units.  However, this means that we must dynamically initialize the
2107       // expression with the contents of the import address table at runtime.
2108       //
2109       // The C language has no notion of ODR; furthermore, it has no notion of
2110       // dynamic initialization.  This means that we are permitted to
2111       // perform initialization with the address of the thunk.
2112       if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
2113           FD->hasAttr<DLLImportAttr>())
2114         // FIXME: Diagnostic!
2115         return false;
2116     }
2117   } else if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(
2118                  Base.dyn_cast<const Expr *>())) {
2119     if (CheckedTemps.insert(MTE).second) {
2120       QualType TempType = getType(Base);
2121       if (TempType.isDestructedType()) {
2122         Info.FFDiag(MTE->getExprLoc(),
2123                     diag::note_constexpr_unsupported_tempoarary_nontrivial_dtor)
2124             << TempType;
2125         return false;
2126       }
2127 
2128       APValue *V = MTE->getOrCreateValue(false);
2129       assert(V && "evasluation result refers to uninitialised temporary");
2130       if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2131                                  Info, MTE->getExprLoc(), TempType, *V,
2132                                  Usage, SourceLocation(), CheckedTemps))
2133         return false;
2134     }
2135   }
2136 
2137   // Allow address constant expressions to be past-the-end pointers. This is
2138   // an extension: the standard requires them to point to an object.
2139   if (!IsReferenceType)
2140     return true;
2141 
2142   // A reference constant expression must refer to an object.
2143   if (!Base) {
2144     // FIXME: diagnostic
2145     Info.CCEDiag(Loc);
2146     return true;
2147   }
2148 
2149   // Does this refer one past the end of some object?
2150   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2151     const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2152     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2153       << !Designator.Entries.empty() << !!VD << VD;
2154     NoteLValueLocation(Info, Base);
2155   }
2156 
2157   return true;
2158 }
2159 
2160 /// Member pointers are constant expressions unless they point to a
2161 /// non-virtual dllimport member function.
2162 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2163                                                  SourceLocation Loc,
2164                                                  QualType Type,
2165                                                  const APValue &Value,
2166                                                  Expr::ConstExprUsage Usage) {
2167   const ValueDecl *Member = Value.getMemberPointerDecl();
2168   const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2169   if (!FD)
2170     return true;
2171   if (FD->isConsteval()) {
2172     Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2173     Info.Note(FD->getLocation(), diag::note_declared_at);
2174     return false;
2175   }
2176   return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
2177          !FD->hasAttr<DLLImportAttr>();
2178 }
2179 
2180 /// Check that this core constant expression is of literal type, and if not,
2181 /// produce an appropriate diagnostic.
2182 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2183                              const LValue *This = nullptr) {
2184   if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
2185     return true;
2186 
2187   // C++1y: A constant initializer for an object o [...] may also invoke
2188   // constexpr constructors for o and its subobjects even if those objects
2189   // are of non-literal class types.
2190   //
2191   // C++11 missed this detail for aggregates, so classes like this:
2192   //   struct foo_t { union { int i; volatile int j; } u; };
2193   // are not (obviously) initializable like so:
2194   //   __attribute__((__require_constant_initialization__))
2195   //   static const foo_t x = {{0}};
2196   // because "i" is a subobject with non-literal initialization (due to the
2197   // volatile member of the union). See:
2198   //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2199   // Therefore, we use the C++1y behavior.
2200   if (This && Info.EvaluatingDecl == This->getLValueBase())
2201     return true;
2202 
2203   // Prvalue constant expressions must be of literal types.
2204   if (Info.getLangOpts().CPlusPlus11)
2205     Info.FFDiag(E, diag::note_constexpr_nonliteral)
2206       << E->getType();
2207   else
2208     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2209   return false;
2210 }
2211 
2212 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2213                                   EvalInfo &Info, SourceLocation DiagLoc,
2214                                   QualType Type, const APValue &Value,
2215                                   Expr::ConstExprUsage Usage,
2216                                   SourceLocation SubobjectLoc,
2217                                   CheckedTemporaries &CheckedTemps) {
2218   if (!Value.hasValue()) {
2219     Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2220       << true << Type;
2221     if (SubobjectLoc.isValid())
2222       Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2223     return false;
2224   }
2225 
2226   // We allow _Atomic(T) to be initialized from anything that T can be
2227   // initialized from.
2228   if (const AtomicType *AT = Type->getAs<AtomicType>())
2229     Type = AT->getValueType();
2230 
2231   // Core issue 1454: For a literal constant expression of array or class type,
2232   // each subobject of its value shall have been initialized by a constant
2233   // expression.
2234   if (Value.isArray()) {
2235     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2236     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2237       if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2238                                  Value.getArrayInitializedElt(I), Usage,
2239                                  SubobjectLoc, CheckedTemps))
2240         return false;
2241     }
2242     if (!Value.hasArrayFiller())
2243       return true;
2244     return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2245                                  Value.getArrayFiller(), Usage, SubobjectLoc,
2246                                  CheckedTemps);
2247   }
2248   if (Value.isUnion() && Value.getUnionField()) {
2249     return CheckEvaluationResult(
2250         CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2251         Value.getUnionValue(), Usage, Value.getUnionField()->getLocation(),
2252         CheckedTemps);
2253   }
2254   if (Value.isStruct()) {
2255     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2256     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2257       unsigned BaseIndex = 0;
2258       for (const CXXBaseSpecifier &BS : CD->bases()) {
2259         if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2260                                    Value.getStructBase(BaseIndex), Usage,
2261                                    BS.getBeginLoc(), CheckedTemps))
2262           return false;
2263         ++BaseIndex;
2264       }
2265     }
2266     for (const auto *I : RD->fields()) {
2267       if (I->isUnnamedBitfield())
2268         continue;
2269 
2270       if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2271                                  Value.getStructField(I->getFieldIndex()),
2272                                  Usage, I->getLocation(), CheckedTemps))
2273         return false;
2274     }
2275   }
2276 
2277   if (Value.isLValue() &&
2278       CERK == CheckEvaluationResultKind::ConstantExpression) {
2279     LValue LVal;
2280     LVal.setFrom(Info.Ctx, Value);
2281     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage,
2282                                          CheckedTemps);
2283   }
2284 
2285   if (Value.isMemberPointer() &&
2286       CERK == CheckEvaluationResultKind::ConstantExpression)
2287     return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
2288 
2289   // Everything else is fine.
2290   return true;
2291 }
2292 
2293 /// Check that this core constant expression value is a valid value for a
2294 /// constant expression. If not, report an appropriate diagnostic. Does not
2295 /// check that the expression is of literal type.
2296 static bool
2297 CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
2298                         const APValue &Value,
2299                         Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
2300   CheckedTemporaries CheckedTemps;
2301   return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2302                                Info, DiagLoc, Type, Value, Usage,
2303                                SourceLocation(), CheckedTemps);
2304 }
2305 
2306 /// Check that this evaluated value is fully-initialized and can be loaded by
2307 /// an lvalue-to-rvalue conversion.
2308 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2309                                   QualType Type, const APValue &Value) {
2310   CheckedTemporaries CheckedTemps;
2311   return CheckEvaluationResult(
2312       CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2313       Expr::EvaluateForCodeGen, SourceLocation(), CheckedTemps);
2314 }
2315 
2316 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2317 /// "the allocated storage is deallocated within the evaluation".
2318 static bool CheckMemoryLeaks(EvalInfo &Info) {
2319   if (!Info.HeapAllocs.empty()) {
2320     // We can still fold to a constant despite a compile-time memory leak,
2321     // so long as the heap allocation isn't referenced in the result (we check
2322     // that in CheckConstantExpression).
2323     Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2324                  diag::note_constexpr_memory_leak)
2325         << unsigned(Info.HeapAllocs.size() - 1);
2326   }
2327   return true;
2328 }
2329 
2330 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2331   // A null base expression indicates a null pointer.  These are always
2332   // evaluatable, and they are false unless the offset is zero.
2333   if (!Value.getLValueBase()) {
2334     Result = !Value.getLValueOffset().isZero();
2335     return true;
2336   }
2337 
2338   // We have a non-null base.  These are generally known to be true, but if it's
2339   // a weak declaration it can be null at runtime.
2340   Result = true;
2341   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2342   return !Decl || !Decl->isWeak();
2343 }
2344 
2345 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2346   switch (Val.getKind()) {
2347   case APValue::None:
2348   case APValue::Indeterminate:
2349     return false;
2350   case APValue::Int:
2351     Result = Val.getInt().getBoolValue();
2352     return true;
2353   case APValue::FixedPoint:
2354     Result = Val.getFixedPoint().getBoolValue();
2355     return true;
2356   case APValue::Float:
2357     Result = !Val.getFloat().isZero();
2358     return true;
2359   case APValue::ComplexInt:
2360     Result = Val.getComplexIntReal().getBoolValue() ||
2361              Val.getComplexIntImag().getBoolValue();
2362     return true;
2363   case APValue::ComplexFloat:
2364     Result = !Val.getComplexFloatReal().isZero() ||
2365              !Val.getComplexFloatImag().isZero();
2366     return true;
2367   case APValue::LValue:
2368     return EvalPointerValueAsBool(Val, Result);
2369   case APValue::MemberPointer:
2370     Result = Val.getMemberPointerDecl();
2371     return true;
2372   case APValue::Vector:
2373   case APValue::Array:
2374   case APValue::Struct:
2375   case APValue::Union:
2376   case APValue::AddrLabelDiff:
2377     return false;
2378   }
2379 
2380   llvm_unreachable("unknown APValue kind");
2381 }
2382 
2383 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2384                                        EvalInfo &Info) {
2385   assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
2386   APValue Val;
2387   if (!Evaluate(Val, Info, E))
2388     return false;
2389   return HandleConversionToBool(Val, Result);
2390 }
2391 
2392 template<typename T>
2393 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2394                            const T &SrcValue, QualType DestType) {
2395   Info.CCEDiag(E, diag::note_constexpr_overflow)
2396     << SrcValue << DestType;
2397   return Info.noteUndefinedBehavior();
2398 }
2399 
2400 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2401                                  QualType SrcType, const APFloat &Value,
2402                                  QualType DestType, APSInt &Result) {
2403   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2404   // Determine whether we are converting to unsigned or signed.
2405   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2406 
2407   Result = APSInt(DestWidth, !DestSigned);
2408   bool ignored;
2409   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2410       & APFloat::opInvalidOp)
2411     return HandleOverflow(Info, E, Value, DestType);
2412   return true;
2413 }
2414 
2415 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2416                                    QualType SrcType, QualType DestType,
2417                                    APFloat &Result) {
2418   APFloat Value = Result;
2419   bool ignored;
2420   Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2421                  APFloat::rmNearestTiesToEven, &ignored);
2422   return true;
2423 }
2424 
2425 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2426                                  QualType DestType, QualType SrcType,
2427                                  const APSInt &Value) {
2428   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2429   // Figure out if this is a truncate, extend or noop cast.
2430   // If the input is signed, do a sign extend, noop, or truncate.
2431   APSInt Result = Value.extOrTrunc(DestWidth);
2432   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2433   if (DestType->isBooleanType())
2434     Result = Value.getBoolValue();
2435   return Result;
2436 }
2437 
2438 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2439                                  QualType SrcType, const APSInt &Value,
2440                                  QualType DestType, APFloat &Result) {
2441   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2442   Result.convertFromAPInt(Value, Value.isSigned(),
2443                           APFloat::rmNearestTiesToEven);
2444   return true;
2445 }
2446 
2447 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2448                                   APValue &Value, const FieldDecl *FD) {
2449   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2450 
2451   if (!Value.isInt()) {
2452     // Trying to store a pointer-cast-to-integer into a bitfield.
2453     // FIXME: In this case, we should provide the diagnostic for casting
2454     // a pointer to an integer.
2455     assert(Value.isLValue() && "integral value neither int nor lvalue?");
2456     Info.FFDiag(E);
2457     return false;
2458   }
2459 
2460   APSInt &Int = Value.getInt();
2461   unsigned OldBitWidth = Int.getBitWidth();
2462   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2463   if (NewBitWidth < OldBitWidth)
2464     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2465   return true;
2466 }
2467 
2468 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2469                                   llvm::APInt &Res) {
2470   APValue SVal;
2471   if (!Evaluate(SVal, Info, E))
2472     return false;
2473   if (SVal.isInt()) {
2474     Res = SVal.getInt();
2475     return true;
2476   }
2477   if (SVal.isFloat()) {
2478     Res = SVal.getFloat().bitcastToAPInt();
2479     return true;
2480   }
2481   if (SVal.isVector()) {
2482     QualType VecTy = E->getType();
2483     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2484     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2485     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2486     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2487     Res = llvm::APInt::getNullValue(VecSize);
2488     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2489       APValue &Elt = SVal.getVectorElt(i);
2490       llvm::APInt EltAsInt;
2491       if (Elt.isInt()) {
2492         EltAsInt = Elt.getInt();
2493       } else if (Elt.isFloat()) {
2494         EltAsInt = Elt.getFloat().bitcastToAPInt();
2495       } else {
2496         // Don't try to handle vectors of anything other than int or float
2497         // (not sure if it's possible to hit this case).
2498         Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2499         return false;
2500       }
2501       unsigned BaseEltSize = EltAsInt.getBitWidth();
2502       if (BigEndian)
2503         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2504       else
2505         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2506     }
2507     return true;
2508   }
2509   // Give up if the input isn't an int, float, or vector.  For example, we
2510   // reject "(v4i16)(intptr_t)&a".
2511   Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2512   return false;
2513 }
2514 
2515 /// Perform the given integer operation, which is known to need at most BitWidth
2516 /// bits, and check for overflow in the original type (if that type was not an
2517 /// unsigned type).
2518 template<typename Operation>
2519 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2520                                  const APSInt &LHS, const APSInt &RHS,
2521                                  unsigned BitWidth, Operation Op,
2522                                  APSInt &Result) {
2523   if (LHS.isUnsigned()) {
2524     Result = Op(LHS, RHS);
2525     return true;
2526   }
2527 
2528   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2529   Result = Value.trunc(LHS.getBitWidth());
2530   if (Result.extend(BitWidth) != Value) {
2531     if (Info.checkingForUndefinedBehavior())
2532       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2533                                        diag::warn_integer_constant_overflow)
2534           << Result.toString(10) << E->getType();
2535     else
2536       return HandleOverflow(Info, E, Value, E->getType());
2537   }
2538   return true;
2539 }
2540 
2541 /// Perform the given binary integer operation.
2542 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2543                               BinaryOperatorKind Opcode, APSInt RHS,
2544                               APSInt &Result) {
2545   switch (Opcode) {
2546   default:
2547     Info.FFDiag(E);
2548     return false;
2549   case BO_Mul:
2550     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2551                                 std::multiplies<APSInt>(), Result);
2552   case BO_Add:
2553     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2554                                 std::plus<APSInt>(), Result);
2555   case BO_Sub:
2556     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2557                                 std::minus<APSInt>(), Result);
2558   case BO_And: Result = LHS & RHS; return true;
2559   case BO_Xor: Result = LHS ^ RHS; return true;
2560   case BO_Or:  Result = LHS | RHS; return true;
2561   case BO_Div:
2562   case BO_Rem:
2563     if (RHS == 0) {
2564       Info.FFDiag(E, diag::note_expr_divide_by_zero);
2565       return false;
2566     }
2567     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2568     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2569     // this operation and gives the two's complement result.
2570     if (RHS.isNegative() && RHS.isAllOnesValue() &&
2571         LHS.isSigned() && LHS.isMinSignedValue())
2572       return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2573                             E->getType());
2574     return true;
2575   case BO_Shl: {
2576     if (Info.getLangOpts().OpenCL)
2577       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2578       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2579                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2580                     RHS.isUnsigned());
2581     else if (RHS.isSigned() && RHS.isNegative()) {
2582       // During constant-folding, a negative shift is an opposite shift. Such
2583       // a shift is not a constant expression.
2584       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2585       RHS = -RHS;
2586       goto shift_right;
2587     }
2588   shift_left:
2589     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2590     // the shifted type.
2591     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2592     if (SA != RHS) {
2593       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2594         << RHS << E->getType() << LHS.getBitWidth();
2595     } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2596       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2597       // operand, and must not overflow the corresponding unsigned type.
2598       // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2599       // E1 x 2^E2 module 2^N.
2600       if (LHS.isNegative())
2601         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2602       else if (LHS.countLeadingZeros() < SA)
2603         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2604     }
2605     Result = LHS << SA;
2606     return true;
2607   }
2608   case BO_Shr: {
2609     if (Info.getLangOpts().OpenCL)
2610       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2611       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2612                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2613                     RHS.isUnsigned());
2614     else if (RHS.isSigned() && RHS.isNegative()) {
2615       // During constant-folding, a negative shift is an opposite shift. Such a
2616       // shift is not a constant expression.
2617       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2618       RHS = -RHS;
2619       goto shift_left;
2620     }
2621   shift_right:
2622     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2623     // shifted type.
2624     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2625     if (SA != RHS)
2626       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2627         << RHS << E->getType() << LHS.getBitWidth();
2628     Result = LHS >> SA;
2629     return true;
2630   }
2631 
2632   case BO_LT: Result = LHS < RHS; return true;
2633   case BO_GT: Result = LHS > RHS; return true;
2634   case BO_LE: Result = LHS <= RHS; return true;
2635   case BO_GE: Result = LHS >= RHS; return true;
2636   case BO_EQ: Result = LHS == RHS; return true;
2637   case BO_NE: Result = LHS != RHS; return true;
2638   case BO_Cmp:
2639     llvm_unreachable("BO_Cmp should be handled elsewhere");
2640   }
2641 }
2642 
2643 /// Perform the given binary floating-point operation, in-place, on LHS.
2644 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2645                                   APFloat &LHS, BinaryOperatorKind Opcode,
2646                                   const APFloat &RHS) {
2647   switch (Opcode) {
2648   default:
2649     Info.FFDiag(E);
2650     return false;
2651   case BO_Mul:
2652     LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2653     break;
2654   case BO_Add:
2655     LHS.add(RHS, APFloat::rmNearestTiesToEven);
2656     break;
2657   case BO_Sub:
2658     LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2659     break;
2660   case BO_Div:
2661     // [expr.mul]p4:
2662     //   If the second operand of / or % is zero the behavior is undefined.
2663     if (RHS.isZero())
2664       Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2665     LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2666     break;
2667   }
2668 
2669   // [expr.pre]p4:
2670   //   If during the evaluation of an expression, the result is not
2671   //   mathematically defined [...], the behavior is undefined.
2672   // FIXME: C++ rules require us to not conform to IEEE 754 here.
2673   if (LHS.isNaN()) {
2674     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2675     return Info.noteUndefinedBehavior();
2676   }
2677   return true;
2678 }
2679 
2680 static bool handleLogicalOpForVector(const APInt &LHSValue,
2681                                      BinaryOperatorKind Opcode,
2682                                      const APInt &RHSValue, APInt &Result) {
2683   bool LHS = (LHSValue != 0);
2684   bool RHS = (RHSValue != 0);
2685 
2686   if (Opcode == BO_LAnd)
2687     Result = LHS && RHS;
2688   else
2689     Result = LHS || RHS;
2690   return true;
2691 }
2692 static bool handleLogicalOpForVector(const APFloat &LHSValue,
2693                                      BinaryOperatorKind Opcode,
2694                                      const APFloat &RHSValue, APInt &Result) {
2695   bool LHS = !LHSValue.isZero();
2696   bool RHS = !RHSValue.isZero();
2697 
2698   if (Opcode == BO_LAnd)
2699     Result = LHS && RHS;
2700   else
2701     Result = LHS || RHS;
2702   return true;
2703 }
2704 
2705 static bool handleLogicalOpForVector(const APValue &LHSValue,
2706                                      BinaryOperatorKind Opcode,
2707                                      const APValue &RHSValue, APInt &Result) {
2708   // The result is always an int type, however operands match the first.
2709   if (LHSValue.getKind() == APValue::Int)
2710     return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2711                                     RHSValue.getInt(), Result);
2712   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2713   return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2714                                   RHSValue.getFloat(), Result);
2715 }
2716 
2717 template <typename APTy>
2718 static bool
2719 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
2720                                const APTy &RHSValue, APInt &Result) {
2721   switch (Opcode) {
2722   default:
2723     llvm_unreachable("unsupported binary operator");
2724   case BO_EQ:
2725     Result = (LHSValue == RHSValue);
2726     break;
2727   case BO_NE:
2728     Result = (LHSValue != RHSValue);
2729     break;
2730   case BO_LT:
2731     Result = (LHSValue < RHSValue);
2732     break;
2733   case BO_GT:
2734     Result = (LHSValue > RHSValue);
2735     break;
2736   case BO_LE:
2737     Result = (LHSValue <= RHSValue);
2738     break;
2739   case BO_GE:
2740     Result = (LHSValue >= RHSValue);
2741     break;
2742   }
2743 
2744   return true;
2745 }
2746 
2747 static bool handleCompareOpForVector(const APValue &LHSValue,
2748                                      BinaryOperatorKind Opcode,
2749                                      const APValue &RHSValue, APInt &Result) {
2750   // The result is always an int type, however operands match the first.
2751   if (LHSValue.getKind() == APValue::Int)
2752     return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
2753                                           RHSValue.getInt(), Result);
2754   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2755   return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
2756                                         RHSValue.getFloat(), Result);
2757 }
2758 
2759 // Perform binary operations for vector types, in place on the LHS.
2760 static bool handleVectorVectorBinOp(EvalInfo &Info, const Expr *E,
2761                                     BinaryOperatorKind Opcode,
2762                                     APValue &LHSValue,
2763                                     const APValue &RHSValue) {
2764   assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
2765          "Operation not supported on vector types");
2766 
2767   const auto *VT = E->getType()->castAs<VectorType>();
2768   unsigned NumElements = VT->getNumElements();
2769   QualType EltTy = VT->getElementType();
2770 
2771   // In the cases (typically C as I've observed) where we aren't evaluating
2772   // constexpr but are checking for cases where the LHS isn't yet evaluatable,
2773   // just give up.
2774   if (!LHSValue.isVector()) {
2775     assert(LHSValue.isLValue() &&
2776            "A vector result that isn't a vector OR uncalculated LValue");
2777     Info.FFDiag(E);
2778     return false;
2779   }
2780 
2781   assert(LHSValue.getVectorLength() == NumElements &&
2782          RHSValue.getVectorLength() == NumElements && "Different vector sizes");
2783 
2784   SmallVector<APValue, 4> ResultElements;
2785 
2786   for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
2787     APValue LHSElt = LHSValue.getVectorElt(EltNum);
2788     APValue RHSElt = RHSValue.getVectorElt(EltNum);
2789 
2790     if (EltTy->isIntegerType()) {
2791       APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
2792                        EltTy->isUnsignedIntegerType()};
2793       bool Success = true;
2794 
2795       if (BinaryOperator::isLogicalOp(Opcode))
2796         Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
2797       else if (BinaryOperator::isComparisonOp(Opcode))
2798         Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
2799       else
2800         Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
2801                                     RHSElt.getInt(), EltResult);
2802 
2803       if (!Success) {
2804         Info.FFDiag(E);
2805         return false;
2806       }
2807       ResultElements.emplace_back(EltResult);
2808 
2809     } else if (EltTy->isFloatingType()) {
2810       assert(LHSElt.getKind() == APValue::Float &&
2811              RHSElt.getKind() == APValue::Float &&
2812              "Mismatched LHS/RHS/Result Type");
2813       APFloat LHSFloat = LHSElt.getFloat();
2814 
2815       if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
2816                                  RHSElt.getFloat())) {
2817         Info.FFDiag(E);
2818         return false;
2819       }
2820 
2821       ResultElements.emplace_back(LHSFloat);
2822     }
2823   }
2824 
2825   LHSValue = APValue(ResultElements.data(), ResultElements.size());
2826   return true;
2827 }
2828 
2829 /// Cast an lvalue referring to a base subobject to a derived class, by
2830 /// truncating the lvalue's path to the given length.
2831 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2832                                const RecordDecl *TruncatedType,
2833                                unsigned TruncatedElements) {
2834   SubobjectDesignator &D = Result.Designator;
2835 
2836   // Check we actually point to a derived class object.
2837   if (TruncatedElements == D.Entries.size())
2838     return true;
2839   assert(TruncatedElements >= D.MostDerivedPathLength &&
2840          "not casting to a derived class");
2841   if (!Result.checkSubobject(Info, E, CSK_Derived))
2842     return false;
2843 
2844   // Truncate the path to the subobject, and remove any derived-to-base offsets.
2845   const RecordDecl *RD = TruncatedType;
2846   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
2847     if (RD->isInvalidDecl()) return false;
2848     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2849     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
2850     if (isVirtualBaseClass(D.Entries[I]))
2851       Result.Offset -= Layout.getVBaseClassOffset(Base);
2852     else
2853       Result.Offset -= Layout.getBaseClassOffset(Base);
2854     RD = Base;
2855   }
2856   D.Entries.resize(TruncatedElements);
2857   return true;
2858 }
2859 
2860 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2861                                    const CXXRecordDecl *Derived,
2862                                    const CXXRecordDecl *Base,
2863                                    const ASTRecordLayout *RL = nullptr) {
2864   if (!RL) {
2865     if (Derived->isInvalidDecl()) return false;
2866     RL = &Info.Ctx.getASTRecordLayout(Derived);
2867   }
2868 
2869   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
2870   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
2871   return true;
2872 }
2873 
2874 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2875                              const CXXRecordDecl *DerivedDecl,
2876                              const CXXBaseSpecifier *Base) {
2877   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2878 
2879   if (!Base->isVirtual())
2880     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
2881 
2882   SubobjectDesignator &D = Obj.Designator;
2883   if (D.Invalid)
2884     return false;
2885 
2886   // Extract most-derived object and corresponding type.
2887   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2888   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2889     return false;
2890 
2891   // Find the virtual base class.
2892   if (DerivedDecl->isInvalidDecl()) return false;
2893   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2894   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
2895   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
2896   return true;
2897 }
2898 
2899 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2900                                  QualType Type, LValue &Result) {
2901   for (CastExpr::path_const_iterator PathI = E->path_begin(),
2902                                      PathE = E->path_end();
2903        PathI != PathE; ++PathI) {
2904     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2905                           *PathI))
2906       return false;
2907     Type = (*PathI)->getType();
2908   }
2909   return true;
2910 }
2911 
2912 /// Cast an lvalue referring to a derived class to a known base subobject.
2913 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
2914                             const CXXRecordDecl *DerivedRD,
2915                             const CXXRecordDecl *BaseRD) {
2916   CXXBasePaths Paths(/*FindAmbiguities=*/false,
2917                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
2918   if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
2919     llvm_unreachable("Class must be derived from the passed in base class!");
2920 
2921   for (CXXBasePathElement &Elem : Paths.front())
2922     if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
2923       return false;
2924   return true;
2925 }
2926 
2927 /// Update LVal to refer to the given field, which must be a member of the type
2928 /// currently described by LVal.
2929 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
2930                                const FieldDecl *FD,
2931                                const ASTRecordLayout *RL = nullptr) {
2932   if (!RL) {
2933     if (FD->getParent()->isInvalidDecl()) return false;
2934     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
2935   }
2936 
2937   unsigned I = FD->getFieldIndex();
2938   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
2939   LVal.addDecl(Info, E, FD);
2940   return true;
2941 }
2942 
2943 /// Update LVal to refer to the given indirect field.
2944 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
2945                                        LValue &LVal,
2946                                        const IndirectFieldDecl *IFD) {
2947   for (const auto *C : IFD->chain())
2948     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
2949       return false;
2950   return true;
2951 }
2952 
2953 /// Get the size of the given type in char units.
2954 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2955                          QualType Type, CharUnits &Size) {
2956   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2957   // extension.
2958   if (Type->isVoidType() || Type->isFunctionType()) {
2959     Size = CharUnits::One();
2960     return true;
2961   }
2962 
2963   if (Type->isDependentType()) {
2964     Info.FFDiag(Loc);
2965     return false;
2966   }
2967 
2968   if (!Type->isConstantSizeType()) {
2969     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2970     // FIXME: Better diagnostic.
2971     Info.FFDiag(Loc);
2972     return false;
2973   }
2974 
2975   Size = Info.Ctx.getTypeSizeInChars(Type);
2976   return true;
2977 }
2978 
2979 /// Update a pointer value to model pointer arithmetic.
2980 /// \param Info - Information about the ongoing evaluation.
2981 /// \param E - The expression being evaluated, for diagnostic purposes.
2982 /// \param LVal - The pointer value to be updated.
2983 /// \param EltTy - The pointee type represented by LVal.
2984 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
2985 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2986                                         LValue &LVal, QualType EltTy,
2987                                         APSInt Adjustment) {
2988   CharUnits SizeOfPointee;
2989   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
2990     return false;
2991 
2992   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
2993   return true;
2994 }
2995 
2996 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2997                                         LValue &LVal, QualType EltTy,
2998                                         int64_t Adjustment) {
2999   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3000                                      APSInt::get(Adjustment));
3001 }
3002 
3003 /// Update an lvalue to refer to a component of a complex number.
3004 /// \param Info - Information about the ongoing evaluation.
3005 /// \param LVal - The lvalue to be updated.
3006 /// \param EltTy - The complex number's component type.
3007 /// \param Imag - False for the real component, true for the imaginary.
3008 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3009                                        LValue &LVal, QualType EltTy,
3010                                        bool Imag) {
3011   if (Imag) {
3012     CharUnits SizeOfComponent;
3013     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3014       return false;
3015     LVal.Offset += SizeOfComponent;
3016   }
3017   LVal.addComplex(Info, E, EltTy, Imag);
3018   return true;
3019 }
3020 
3021 /// Try to evaluate the initializer for a variable declaration.
3022 ///
3023 /// \param Info   Information about the ongoing evaluation.
3024 /// \param E      An expression to be used when printing diagnostics.
3025 /// \param VD     The variable whose initializer should be obtained.
3026 /// \param Frame  The frame in which the variable was created. Must be null
3027 ///               if this variable is not local to the evaluation.
3028 /// \param Result Filled in with a pointer to the value of the variable.
3029 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3030                                 const VarDecl *VD, CallStackFrame *Frame,
3031                                 APValue *&Result, const LValue *LVal) {
3032 
3033   // If this is a parameter to an active constexpr function call, perform
3034   // argument substitution.
3035   if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
3036     // Assume arguments of a potential constant expression are unknown
3037     // constant expressions.
3038     if (Info.checkingPotentialConstantExpression())
3039       return false;
3040     if (!Frame || !Frame->Arguments) {
3041       Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown) << VD;
3042       return false;
3043     }
3044     Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
3045     return true;
3046   }
3047 
3048   // If this is a local variable, dig out its value.
3049   if (Frame) {
3050     Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
3051                   : Frame->getCurrentTemporary(VD);
3052     if (!Result) {
3053       // Assume variables referenced within a lambda's call operator that were
3054       // not declared within the call operator are captures and during checking
3055       // of a potential constant expression, assume they are unknown constant
3056       // expressions.
3057       assert(isLambdaCallOperator(Frame->Callee) &&
3058              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3059              "missing value for local variable");
3060       if (Info.checkingPotentialConstantExpression())
3061         return false;
3062       // FIXME: implement capture evaluation during constant expr evaluation.
3063       Info.FFDiag(E->getBeginLoc(),
3064                   diag::note_unimplemented_constexpr_lambda_feature_ast)
3065           << "captures not currently allowed";
3066       return false;
3067     }
3068     return true;
3069   }
3070 
3071   // Dig out the initializer, and use the declaration which it's attached to.
3072   // FIXME: We should eventually check whether the variable has a reachable
3073   // initializing declaration.
3074   const Expr *Init = VD->getAnyInitializer(VD);
3075   if (!Init) {
3076     // Don't diagnose during potential constant expression checking; an
3077     // initializer might be added later.
3078     if (!Info.checkingPotentialConstantExpression()) {
3079       Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3080         << VD;
3081       Info.Note(VD->getLocation(), diag::note_declared_at);
3082     }
3083     return false;
3084   }
3085 
3086   if (Init->isValueDependent()) {
3087     // The DeclRefExpr is not value-dependent, but the variable it refers to
3088     // has a value-dependent initializer. This should only happen in
3089     // constant-folding cases, where the variable is not actually of a suitable
3090     // type for use in a constant expression (otherwise the DeclRefExpr would
3091     // have been value-dependent too), so diagnose that.
3092     assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3093     if (!Info.checkingPotentialConstantExpression()) {
3094       Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3095                          ? diag::note_constexpr_ltor_non_constexpr
3096                          : diag::note_constexpr_ltor_non_integral, 1)
3097           << VD << VD->getType();
3098       Info.Note(VD->getLocation(), diag::note_declared_at);
3099     }
3100     return false;
3101   }
3102 
3103   // If we're currently evaluating the initializer of this declaration, use that
3104   // in-flight value.
3105   if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
3106     Result = Info.EvaluatingDeclValue;
3107     return true;
3108   }
3109 
3110   // Check that we can fold the initializer. In C++, we will have already done
3111   // this in the cases where it matters for conformance.
3112   SmallVector<PartialDiagnosticAt, 8> Notes;
3113   if (!VD->evaluateValue(Notes)) {
3114     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
3115               Notes.size() + 1) << VD;
3116     Info.Note(VD->getLocation(), diag::note_declared_at);
3117     Info.addNotes(Notes);
3118     return false;
3119   }
3120 
3121   // Check that the variable is actually usable in constant expressions.
3122   if (!VD->checkInitIsICE()) {
3123     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
3124                  Notes.size() + 1) << VD;
3125     Info.Note(VD->getLocation(), diag::note_declared_at);
3126     Info.addNotes(Notes);
3127   }
3128 
3129   // Never use the initializer of a weak variable, not even for constant
3130   // folding. We can't be sure that this is the definition that will be used.
3131   if (VD->isWeak()) {
3132     Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3133     Info.Note(VD->getLocation(), diag::note_declared_at);
3134     return false;
3135   }
3136 
3137   Result = VD->getEvaluatedValue();
3138   return true;
3139 }
3140 
3141 static bool IsConstNonVolatile(QualType T) {
3142   Qualifiers Quals = T.getQualifiers();
3143   return Quals.hasConst() && !Quals.hasVolatile();
3144 }
3145 
3146 /// Get the base index of the given base class within an APValue representing
3147 /// the given derived class.
3148 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3149                              const CXXRecordDecl *Base) {
3150   Base = Base->getCanonicalDecl();
3151   unsigned Index = 0;
3152   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3153          E = Derived->bases_end(); I != E; ++I, ++Index) {
3154     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3155       return Index;
3156   }
3157 
3158   llvm_unreachable("base class missing from derived class's bases list");
3159 }
3160 
3161 /// Extract the value of a character from a string literal.
3162 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3163                                             uint64_t Index) {
3164   assert(!isa<SourceLocExpr>(Lit) &&
3165          "SourceLocExpr should have already been converted to a StringLiteral");
3166 
3167   // FIXME: Support MakeStringConstant
3168   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3169     std::string Str;
3170     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3171     assert(Index <= Str.size() && "Index too large");
3172     return APSInt::getUnsigned(Str.c_str()[Index]);
3173   }
3174 
3175   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3176     Lit = PE->getFunctionName();
3177   const StringLiteral *S = cast<StringLiteral>(Lit);
3178   const ConstantArrayType *CAT =
3179       Info.Ctx.getAsConstantArrayType(S->getType());
3180   assert(CAT && "string literal isn't an array");
3181   QualType CharType = CAT->getElementType();
3182   assert(CharType->isIntegerType() && "unexpected character type");
3183 
3184   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3185                CharType->isUnsignedIntegerType());
3186   if (Index < S->getLength())
3187     Value = S->getCodeUnit(Index);
3188   return Value;
3189 }
3190 
3191 // Expand a string literal into an array of characters.
3192 //
3193 // FIXME: This is inefficient; we should probably introduce something similar
3194 // to the LLVM ConstantDataArray to make this cheaper.
3195 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3196                                 APValue &Result,
3197                                 QualType AllocType = QualType()) {
3198   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3199       AllocType.isNull() ? S->getType() : AllocType);
3200   assert(CAT && "string literal isn't an array");
3201   QualType CharType = CAT->getElementType();
3202   assert(CharType->isIntegerType() && "unexpected character type");
3203 
3204   unsigned Elts = CAT->getSize().getZExtValue();
3205   Result = APValue(APValue::UninitArray(),
3206                    std::min(S->getLength(), Elts), Elts);
3207   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3208                CharType->isUnsignedIntegerType());
3209   if (Result.hasArrayFiller())
3210     Result.getArrayFiller() = APValue(Value);
3211   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3212     Value = S->getCodeUnit(I);
3213     Result.getArrayInitializedElt(I) = APValue(Value);
3214   }
3215 }
3216 
3217 // Expand an array so that it has more than Index filled elements.
3218 static void expandArray(APValue &Array, unsigned Index) {
3219   unsigned Size = Array.getArraySize();
3220   assert(Index < Size);
3221 
3222   // Always at least double the number of elements for which we store a value.
3223   unsigned OldElts = Array.getArrayInitializedElts();
3224   unsigned NewElts = std::max(Index+1, OldElts * 2);
3225   NewElts = std::min(Size, std::max(NewElts, 8u));
3226 
3227   // Copy the data across.
3228   APValue NewValue(APValue::UninitArray(), NewElts, Size);
3229   for (unsigned I = 0; I != OldElts; ++I)
3230     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3231   for (unsigned I = OldElts; I != NewElts; ++I)
3232     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3233   if (NewValue.hasArrayFiller())
3234     NewValue.getArrayFiller() = Array.getArrayFiller();
3235   Array.swap(NewValue);
3236 }
3237 
3238 /// Determine whether a type would actually be read by an lvalue-to-rvalue
3239 /// conversion. If it's of class type, we may assume that the copy operation
3240 /// is trivial. Note that this is never true for a union type with fields
3241 /// (because the copy always "reads" the active member) and always true for
3242 /// a non-class type.
3243 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3244 static bool isReadByLvalueToRvalueConversion(QualType T) {
3245   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3246   return !RD || isReadByLvalueToRvalueConversion(RD);
3247 }
3248 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3249   // FIXME: A trivial copy of a union copies the object representation, even if
3250   // the union is empty.
3251   if (RD->isUnion())
3252     return !RD->field_empty();
3253   if (RD->isEmpty())
3254     return false;
3255 
3256   for (auto *Field : RD->fields())
3257     if (!Field->isUnnamedBitfield() &&
3258         isReadByLvalueToRvalueConversion(Field->getType()))
3259       return true;
3260 
3261   for (auto &BaseSpec : RD->bases())
3262     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3263       return true;
3264 
3265   return false;
3266 }
3267 
3268 /// Diagnose an attempt to read from any unreadable field within the specified
3269 /// type, which might be a class type.
3270 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3271                                   QualType T) {
3272   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3273   if (!RD)
3274     return false;
3275 
3276   if (!RD->hasMutableFields())
3277     return false;
3278 
3279   for (auto *Field : RD->fields()) {
3280     // If we're actually going to read this field in some way, then it can't
3281     // be mutable. If we're in a union, then assigning to a mutable field
3282     // (even an empty one) can change the active member, so that's not OK.
3283     // FIXME: Add core issue number for the union case.
3284     if (Field->isMutable() &&
3285         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3286       Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3287       Info.Note(Field->getLocation(), diag::note_declared_at);
3288       return true;
3289     }
3290 
3291     if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3292       return true;
3293   }
3294 
3295   for (auto &BaseSpec : RD->bases())
3296     if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3297       return true;
3298 
3299   // All mutable fields were empty, and thus not actually read.
3300   return false;
3301 }
3302 
3303 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3304                                         APValue::LValueBase Base,
3305                                         bool MutableSubobject = false) {
3306   // A temporary we created.
3307   if (Base.getCallIndex())
3308     return true;
3309 
3310   auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3311   if (!Evaluating)
3312     return false;
3313 
3314   auto *BaseD = Base.dyn_cast<const ValueDecl*>();
3315 
3316   switch (Info.IsEvaluatingDecl) {
3317   case EvalInfo::EvaluatingDeclKind::None:
3318     return false;
3319 
3320   case EvalInfo::EvaluatingDeclKind::Ctor:
3321     // The variable whose initializer we're evaluating.
3322     if (BaseD)
3323       return declaresSameEntity(Evaluating, BaseD);
3324 
3325     // A temporary lifetime-extended by the variable whose initializer we're
3326     // evaluating.
3327     if (auto *BaseE = Base.dyn_cast<const Expr *>())
3328       if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3329         return declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating);
3330     return false;
3331 
3332   case EvalInfo::EvaluatingDeclKind::Dtor:
3333     // C++2a [expr.const]p6:
3334     //   [during constant destruction] the lifetime of a and its non-mutable
3335     //   subobjects (but not its mutable subobjects) [are] considered to start
3336     //   within e.
3337     //
3338     // FIXME: We can meaningfully extend this to cover non-const objects, but
3339     // we will need special handling: we should be able to access only
3340     // subobjects of such objects that are themselves declared const.
3341     if (!BaseD ||
3342         !(BaseD->getType().isConstQualified() ||
3343           BaseD->getType()->isReferenceType()) ||
3344         MutableSubobject)
3345       return false;
3346     return declaresSameEntity(Evaluating, BaseD);
3347   }
3348 
3349   llvm_unreachable("unknown evaluating decl kind");
3350 }
3351 
3352 namespace {
3353 /// A handle to a complete object (an object that is not a subobject of
3354 /// another object).
3355 struct CompleteObject {
3356   /// The identity of the object.
3357   APValue::LValueBase Base;
3358   /// The value of the complete object.
3359   APValue *Value;
3360   /// The type of the complete object.
3361   QualType Type;
3362 
3363   CompleteObject() : Value(nullptr) {}
3364   CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3365       : Base(Base), Value(Value), Type(Type) {}
3366 
3367   bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3368     // If this isn't a "real" access (eg, if it's just accessing the type
3369     // info), allow it. We assume the type doesn't change dynamically for
3370     // subobjects of constexpr objects (even though we'd hit UB here if it
3371     // did). FIXME: Is this right?
3372     if (!isAnyAccess(AK))
3373       return true;
3374 
3375     // In C++14 onwards, it is permitted to read a mutable member whose
3376     // lifetime began within the evaluation.
3377     // FIXME: Should we also allow this in C++11?
3378     if (!Info.getLangOpts().CPlusPlus14)
3379       return false;
3380     return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3381   }
3382 
3383   explicit operator bool() const { return !Type.isNull(); }
3384 };
3385 } // end anonymous namespace
3386 
3387 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3388                                  bool IsMutable = false) {
3389   // C++ [basic.type.qualifier]p1:
3390   // - A const object is an object of type const T or a non-mutable subobject
3391   //   of a const object.
3392   if (ObjType.isConstQualified() && !IsMutable)
3393     SubobjType.addConst();
3394   // - A volatile object is an object of type const T or a subobject of a
3395   //   volatile object.
3396   if (ObjType.isVolatileQualified())
3397     SubobjType.addVolatile();
3398   return SubobjType;
3399 }
3400 
3401 /// Find the designated sub-object of an rvalue.
3402 template<typename SubobjectHandler>
3403 typename SubobjectHandler::result_type
3404 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3405               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3406   if (Sub.Invalid)
3407     // A diagnostic will have already been produced.
3408     return handler.failed();
3409   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3410     if (Info.getLangOpts().CPlusPlus11)
3411       Info.FFDiag(E, Sub.isOnePastTheEnd()
3412                          ? diag::note_constexpr_access_past_end
3413                          : diag::note_constexpr_access_unsized_array)
3414           << handler.AccessKind;
3415     else
3416       Info.FFDiag(E);
3417     return handler.failed();
3418   }
3419 
3420   APValue *O = Obj.Value;
3421   QualType ObjType = Obj.Type;
3422   const FieldDecl *LastField = nullptr;
3423   const FieldDecl *VolatileField = nullptr;
3424 
3425   // Walk the designator's path to find the subobject.
3426   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3427     // Reading an indeterminate value is undefined, but assigning over one is OK.
3428     if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3429         (O->isIndeterminate() &&
3430          !isValidIndeterminateAccess(handler.AccessKind))) {
3431       if (!Info.checkingPotentialConstantExpression())
3432         Info.FFDiag(E, diag::note_constexpr_access_uninit)
3433             << handler.AccessKind << O->isIndeterminate();
3434       return handler.failed();
3435     }
3436 
3437     // C++ [class.ctor]p5, C++ [class.dtor]p5:
3438     //    const and volatile semantics are not applied on an object under
3439     //    {con,de}struction.
3440     if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3441         ObjType->isRecordType() &&
3442         Info.isEvaluatingCtorDtor(
3443             Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3444                                          Sub.Entries.begin() + I)) !=
3445                           ConstructionPhase::None) {
3446       ObjType = Info.Ctx.getCanonicalType(ObjType);
3447       ObjType.removeLocalConst();
3448       ObjType.removeLocalVolatile();
3449     }
3450 
3451     // If this is our last pass, check that the final object type is OK.
3452     if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3453       // Accesses to volatile objects are prohibited.
3454       if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3455         if (Info.getLangOpts().CPlusPlus) {
3456           int DiagKind;
3457           SourceLocation Loc;
3458           const NamedDecl *Decl = nullptr;
3459           if (VolatileField) {
3460             DiagKind = 2;
3461             Loc = VolatileField->getLocation();
3462             Decl = VolatileField;
3463           } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3464             DiagKind = 1;
3465             Loc = VD->getLocation();
3466             Decl = VD;
3467           } else {
3468             DiagKind = 0;
3469             if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3470               Loc = E->getExprLoc();
3471           }
3472           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3473               << handler.AccessKind << DiagKind << Decl;
3474           Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3475         } else {
3476           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3477         }
3478         return handler.failed();
3479       }
3480 
3481       // If we are reading an object of class type, there may still be more
3482       // things we need to check: if there are any mutable subobjects, we
3483       // cannot perform this read. (This only happens when performing a trivial
3484       // copy or assignment.)
3485       if (ObjType->isRecordType() &&
3486           !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3487           diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3488         return handler.failed();
3489     }
3490 
3491     if (I == N) {
3492       if (!handler.found(*O, ObjType))
3493         return false;
3494 
3495       // If we modified a bit-field, truncate it to the right width.
3496       if (isModification(handler.AccessKind) &&
3497           LastField && LastField->isBitField() &&
3498           !truncateBitfieldValue(Info, E, *O, LastField))
3499         return false;
3500 
3501       return true;
3502     }
3503 
3504     LastField = nullptr;
3505     if (ObjType->isArrayType()) {
3506       // Next subobject is an array element.
3507       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3508       assert(CAT && "vla in literal type?");
3509       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3510       if (CAT->getSize().ule(Index)) {
3511         // Note, it should not be possible to form a pointer with a valid
3512         // designator which points more than one past the end of the array.
3513         if (Info.getLangOpts().CPlusPlus11)
3514           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3515             << handler.AccessKind;
3516         else
3517           Info.FFDiag(E);
3518         return handler.failed();
3519       }
3520 
3521       ObjType = CAT->getElementType();
3522 
3523       if (O->getArrayInitializedElts() > Index)
3524         O = &O->getArrayInitializedElt(Index);
3525       else if (!isRead(handler.AccessKind)) {
3526         expandArray(*O, Index);
3527         O = &O->getArrayInitializedElt(Index);
3528       } else
3529         O = &O->getArrayFiller();
3530     } else if (ObjType->isAnyComplexType()) {
3531       // Next subobject is a complex number.
3532       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3533       if (Index > 1) {
3534         if (Info.getLangOpts().CPlusPlus11)
3535           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3536             << handler.AccessKind;
3537         else
3538           Info.FFDiag(E);
3539         return handler.failed();
3540       }
3541 
3542       ObjType = getSubobjectType(
3543           ObjType, ObjType->castAs<ComplexType>()->getElementType());
3544 
3545       assert(I == N - 1 && "extracting subobject of scalar?");
3546       if (O->isComplexInt()) {
3547         return handler.found(Index ? O->getComplexIntImag()
3548                                    : O->getComplexIntReal(), ObjType);
3549       } else {
3550         assert(O->isComplexFloat());
3551         return handler.found(Index ? O->getComplexFloatImag()
3552                                    : O->getComplexFloatReal(), ObjType);
3553       }
3554     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3555       if (Field->isMutable() &&
3556           !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3557         Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3558           << handler.AccessKind << Field;
3559         Info.Note(Field->getLocation(), diag::note_declared_at);
3560         return handler.failed();
3561       }
3562 
3563       // Next subobject is a class, struct or union field.
3564       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3565       if (RD->isUnion()) {
3566         const FieldDecl *UnionField = O->getUnionField();
3567         if (!UnionField ||
3568             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3569           if (I == N - 1 && handler.AccessKind == AK_Construct) {
3570             // Placement new onto an inactive union member makes it active.
3571             O->setUnion(Field, APValue());
3572           } else {
3573             // FIXME: If O->getUnionValue() is absent, report that there's no
3574             // active union member rather than reporting the prior active union
3575             // member. We'll need to fix nullptr_t to not use APValue() as its
3576             // representation first.
3577             Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3578                 << handler.AccessKind << Field << !UnionField << UnionField;
3579             return handler.failed();
3580           }
3581         }
3582         O = &O->getUnionValue();
3583       } else
3584         O = &O->getStructField(Field->getFieldIndex());
3585 
3586       ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3587       LastField = Field;
3588       if (Field->getType().isVolatileQualified())
3589         VolatileField = Field;
3590     } else {
3591       // Next subobject is a base class.
3592       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3593       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3594       O = &O->getStructBase(getBaseIndex(Derived, Base));
3595 
3596       ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3597     }
3598   }
3599 }
3600 
3601 namespace {
3602 struct ExtractSubobjectHandler {
3603   EvalInfo &Info;
3604   const Expr *E;
3605   APValue &Result;
3606   const AccessKinds AccessKind;
3607 
3608   typedef bool result_type;
3609   bool failed() { return false; }
3610   bool found(APValue &Subobj, QualType SubobjType) {
3611     Result = Subobj;
3612     if (AccessKind == AK_ReadObjectRepresentation)
3613       return true;
3614     return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3615   }
3616   bool found(APSInt &Value, QualType SubobjType) {
3617     Result = APValue(Value);
3618     return true;
3619   }
3620   bool found(APFloat &Value, QualType SubobjType) {
3621     Result = APValue(Value);
3622     return true;
3623   }
3624 };
3625 } // end anonymous namespace
3626 
3627 /// Extract the designated sub-object of an rvalue.
3628 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3629                              const CompleteObject &Obj,
3630                              const SubobjectDesignator &Sub, APValue &Result,
3631                              AccessKinds AK = AK_Read) {
3632   assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3633   ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3634   return findSubobject(Info, E, Obj, Sub, Handler);
3635 }
3636 
3637 namespace {
3638 struct ModifySubobjectHandler {
3639   EvalInfo &Info;
3640   APValue &NewVal;
3641   const Expr *E;
3642 
3643   typedef bool result_type;
3644   static const AccessKinds AccessKind = AK_Assign;
3645 
3646   bool checkConst(QualType QT) {
3647     // Assigning to a const object has undefined behavior.
3648     if (QT.isConstQualified()) {
3649       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3650       return false;
3651     }
3652     return true;
3653   }
3654 
3655   bool failed() { return false; }
3656   bool found(APValue &Subobj, QualType SubobjType) {
3657     if (!checkConst(SubobjType))
3658       return false;
3659     // We've been given ownership of NewVal, so just swap it in.
3660     Subobj.swap(NewVal);
3661     return true;
3662   }
3663   bool found(APSInt &Value, QualType SubobjType) {
3664     if (!checkConst(SubobjType))
3665       return false;
3666     if (!NewVal.isInt()) {
3667       // Maybe trying to write a cast pointer value into a complex?
3668       Info.FFDiag(E);
3669       return false;
3670     }
3671     Value = NewVal.getInt();
3672     return true;
3673   }
3674   bool found(APFloat &Value, QualType SubobjType) {
3675     if (!checkConst(SubobjType))
3676       return false;
3677     Value = NewVal.getFloat();
3678     return true;
3679   }
3680 };
3681 } // end anonymous namespace
3682 
3683 const AccessKinds ModifySubobjectHandler::AccessKind;
3684 
3685 /// Update the designated sub-object of an rvalue to the given value.
3686 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3687                             const CompleteObject &Obj,
3688                             const SubobjectDesignator &Sub,
3689                             APValue &NewVal) {
3690   ModifySubobjectHandler Handler = { Info, NewVal, E };
3691   return findSubobject(Info, E, Obj, Sub, Handler);
3692 }
3693 
3694 /// Find the position where two subobject designators diverge, or equivalently
3695 /// the length of the common initial subsequence.
3696 static unsigned FindDesignatorMismatch(QualType ObjType,
3697                                        const SubobjectDesignator &A,
3698                                        const SubobjectDesignator &B,
3699                                        bool &WasArrayIndex) {
3700   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3701   for (/**/; I != N; ++I) {
3702     if (!ObjType.isNull() &&
3703         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3704       // Next subobject is an array element.
3705       if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3706         WasArrayIndex = true;
3707         return I;
3708       }
3709       if (ObjType->isAnyComplexType())
3710         ObjType = ObjType->castAs<ComplexType>()->getElementType();
3711       else
3712         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3713     } else {
3714       if (A.Entries[I].getAsBaseOrMember() !=
3715           B.Entries[I].getAsBaseOrMember()) {
3716         WasArrayIndex = false;
3717         return I;
3718       }
3719       if (const FieldDecl *FD = getAsField(A.Entries[I]))
3720         // Next subobject is a field.
3721         ObjType = FD->getType();
3722       else
3723         // Next subobject is a base class.
3724         ObjType = QualType();
3725     }
3726   }
3727   WasArrayIndex = false;
3728   return I;
3729 }
3730 
3731 /// Determine whether the given subobject designators refer to elements of the
3732 /// same array object.
3733 static bool AreElementsOfSameArray(QualType ObjType,
3734                                    const SubobjectDesignator &A,
3735                                    const SubobjectDesignator &B) {
3736   if (A.Entries.size() != B.Entries.size())
3737     return false;
3738 
3739   bool IsArray = A.MostDerivedIsArrayElement;
3740   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3741     // A is a subobject of the array element.
3742     return false;
3743 
3744   // If A (and B) designates an array element, the last entry will be the array
3745   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3746   // of length 1' case, and the entire path must match.
3747   bool WasArrayIndex;
3748   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3749   return CommonLength >= A.Entries.size() - IsArray;
3750 }
3751 
3752 /// Find the complete object to which an LValue refers.
3753 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3754                                          AccessKinds AK, const LValue &LVal,
3755                                          QualType LValType) {
3756   if (LVal.InvalidBase) {
3757     Info.FFDiag(E);
3758     return CompleteObject();
3759   }
3760 
3761   if (!LVal.Base) {
3762     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3763     return CompleteObject();
3764   }
3765 
3766   CallStackFrame *Frame = nullptr;
3767   unsigned Depth = 0;
3768   if (LVal.getLValueCallIndex()) {
3769     std::tie(Frame, Depth) =
3770         Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3771     if (!Frame) {
3772       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3773         << AK << LVal.Base.is<const ValueDecl*>();
3774       NoteLValueLocation(Info, LVal.Base);
3775       return CompleteObject();
3776     }
3777   }
3778 
3779   bool IsAccess = isAnyAccess(AK);
3780 
3781   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3782   // is not a constant expression (even if the object is non-volatile). We also
3783   // apply this rule to C++98, in order to conform to the expected 'volatile'
3784   // semantics.
3785   if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
3786     if (Info.getLangOpts().CPlusPlus)
3787       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3788         << AK << LValType;
3789     else
3790       Info.FFDiag(E);
3791     return CompleteObject();
3792   }
3793 
3794   // Compute value storage location and type of base object.
3795   APValue *BaseVal = nullptr;
3796   QualType BaseType = getType(LVal.Base);
3797 
3798   if (const ConstantExpr *CE =
3799           dyn_cast_or_null<ConstantExpr>(LVal.Base.dyn_cast<const Expr *>())) {
3800     /// Nested immediate invocation have been previously removed so if we found
3801     /// a ConstantExpr it can only be the EvaluatingDecl.
3802     assert(CE->isImmediateInvocation() && CE == Info.EvaluatingDecl);
3803     (void)CE;
3804     BaseVal = Info.EvaluatingDeclValue;
3805   } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
3806     // Allow reading from a GUID declaration.
3807     if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
3808       if (isModification(AK)) {
3809         // All the remaining cases do not permit modification of the object.
3810         Info.FFDiag(E, diag::note_constexpr_modify_global);
3811         return CompleteObject();
3812       }
3813       APValue &V = GD->getAsAPValue();
3814       if (V.isAbsent()) {
3815         Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
3816             << GD->getType();
3817         return CompleteObject();
3818       }
3819       return CompleteObject(LVal.Base, &V, GD->getType());
3820     }
3821 
3822     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3823     // In C++11, constexpr, non-volatile variables initialized with constant
3824     // expressions are constant expressions too. Inside constexpr functions,
3825     // parameters are constant expressions even if they're non-const.
3826     // In C++1y, objects local to a constant expression (those with a Frame) are
3827     // both readable and writable inside constant expressions.
3828     // In C, such things can also be folded, although they are not ICEs.
3829     const VarDecl *VD = dyn_cast<VarDecl>(D);
3830     if (VD) {
3831       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3832         VD = VDef;
3833     }
3834     if (!VD || VD->isInvalidDecl()) {
3835       Info.FFDiag(E);
3836       return CompleteObject();
3837     }
3838 
3839     // In OpenCL if a variable is in constant address space it is a const value.
3840     bool IsConstant = BaseType.isConstQualified() ||
3841                       (Info.getLangOpts().OpenCL &&
3842                        BaseType.getAddressSpace() == LangAS::opencl_constant);
3843 
3844     // Unless we're looking at a local variable or argument in a constexpr call,
3845     // the variable we're reading must be const.
3846     if (!Frame) {
3847       if (Info.getLangOpts().CPlusPlus14 &&
3848           lifetimeStartedInEvaluation(Info, LVal.Base)) {
3849         // OK, we can read and modify an object if we're in the process of
3850         // evaluating its initializer, because its lifetime began in this
3851         // evaluation.
3852       } else if (isModification(AK)) {
3853         // All the remaining cases do not permit modification of the object.
3854         Info.FFDiag(E, diag::note_constexpr_modify_global);
3855         return CompleteObject();
3856       } else if (VD->isConstexpr()) {
3857         // OK, we can read this variable.
3858       } else if (BaseType->isIntegralOrEnumerationType()) {
3859         // In OpenCL if a variable is in constant address space it is a const
3860         // value.
3861         if (!IsConstant) {
3862           if (!IsAccess)
3863             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3864           if (Info.getLangOpts().CPlusPlus) {
3865             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
3866             Info.Note(VD->getLocation(), diag::note_declared_at);
3867           } else {
3868             Info.FFDiag(E);
3869           }
3870           return CompleteObject();
3871         }
3872       } else if (!IsAccess) {
3873         return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3874       } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
3875                  BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
3876         // This variable might end up being constexpr. Don't diagnose it yet.
3877       } else if (IsConstant) {
3878         // Keep evaluating to see what we can do. In particular, we support
3879         // folding of const floating-point types, in order to make static const
3880         // data members of such types (supported as an extension) more useful.
3881         if (Info.getLangOpts().CPlusPlus) {
3882           Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
3883                               ? diag::note_constexpr_ltor_non_constexpr
3884                               : diag::note_constexpr_ltor_non_integral, 1)
3885               << VD << BaseType;
3886           Info.Note(VD->getLocation(), diag::note_declared_at);
3887         } else {
3888           Info.CCEDiag(E);
3889         }
3890       } else {
3891         // Never allow reading a non-const value.
3892         if (Info.getLangOpts().CPlusPlus) {
3893           Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3894                              ? diag::note_constexpr_ltor_non_constexpr
3895                              : diag::note_constexpr_ltor_non_integral, 1)
3896               << VD << BaseType;
3897           Info.Note(VD->getLocation(), diag::note_declared_at);
3898         } else {
3899           Info.FFDiag(E);
3900         }
3901         return CompleteObject();
3902       }
3903     }
3904 
3905     if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
3906       return CompleteObject();
3907   } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
3908     Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
3909     if (!Alloc) {
3910       Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
3911       return CompleteObject();
3912     }
3913     return CompleteObject(LVal.Base, &(*Alloc)->Value,
3914                           LVal.Base.getDynamicAllocType());
3915   } else {
3916     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3917 
3918     if (!Frame) {
3919       if (const MaterializeTemporaryExpr *MTE =
3920               dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
3921         assert(MTE->getStorageDuration() == SD_Static &&
3922                "should have a frame for a non-global materialized temporary");
3923 
3924         // Per C++1y [expr.const]p2:
3925         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3926         //   - a [...] glvalue of integral or enumeration type that refers to
3927         //     a non-volatile const object [...]
3928         //   [...]
3929         //   - a [...] glvalue of literal type that refers to a non-volatile
3930         //     object whose lifetime began within the evaluation of e.
3931         //
3932         // C++11 misses the 'began within the evaluation of e' check and
3933         // instead allows all temporaries, including things like:
3934         //   int &&r = 1;
3935         //   int x = ++r;
3936         //   constexpr int k = r;
3937         // Therefore we use the C++14 rules in C++11 too.
3938         //
3939         // Note that temporaries whose lifetimes began while evaluating a
3940         // variable's constructor are not usable while evaluating the
3941         // corresponding destructor, not even if they're of const-qualified
3942         // types.
3943         if (!(BaseType.isConstQualified() &&
3944               BaseType->isIntegralOrEnumerationType()) &&
3945             !lifetimeStartedInEvaluation(Info, LVal.Base)) {
3946           if (!IsAccess)
3947             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3948           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
3949           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3950           return CompleteObject();
3951         }
3952 
3953         BaseVal = MTE->getOrCreateValue(false);
3954         assert(BaseVal && "got reference to unevaluated temporary");
3955       } else {
3956         if (!IsAccess)
3957           return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3958         APValue Val;
3959         LVal.moveInto(Val);
3960         Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
3961             << AK
3962             << Val.getAsString(Info.Ctx,
3963                                Info.Ctx.getLValueReferenceType(LValType));
3964         NoteLValueLocation(Info, LVal.Base);
3965         return CompleteObject();
3966       }
3967     } else {
3968       BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
3969       assert(BaseVal && "missing value for temporary");
3970     }
3971   }
3972 
3973   // In C++14, we can't safely access any mutable state when we might be
3974   // evaluating after an unmodeled side effect.
3975   //
3976   // FIXME: Not all local state is mutable. Allow local constant subobjects
3977   // to be read here (but take care with 'mutable' fields).
3978   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3979        Info.EvalStatus.HasSideEffects) ||
3980       (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth))
3981     return CompleteObject();
3982 
3983   return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
3984 }
3985 
3986 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
3987 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3988 /// glvalue referred to by an entity of reference type.
3989 ///
3990 /// \param Info - Information about the ongoing evaluation.
3991 /// \param Conv - The expression for which we are performing the conversion.
3992 ///               Used for diagnostics.
3993 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3994 ///               case of a non-class type).
3995 /// \param LVal - The glvalue on which we are attempting to perform this action.
3996 /// \param RVal - The produced value will be placed here.
3997 /// \param WantObjectRepresentation - If true, we're looking for the object
3998 ///               representation rather than the value, and in particular,
3999 ///               there is no requirement that the result be fully initialized.
4000 static bool
4001 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
4002                                const LValue &LVal, APValue &RVal,
4003                                bool WantObjectRepresentation = false) {
4004   if (LVal.Designator.Invalid)
4005     return false;
4006 
4007   // Check for special cases where there is no existing APValue to look at.
4008   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4009 
4010   AccessKinds AK =
4011       WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4012 
4013   if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4014     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4015       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4016       // initializer until now for such expressions. Such an expression can't be
4017       // an ICE in C, so this only matters for fold.
4018       if (Type.isVolatileQualified()) {
4019         Info.FFDiag(Conv);
4020         return false;
4021       }
4022       APValue Lit;
4023       if (!Evaluate(Lit, Info, CLE->getInitializer()))
4024         return false;
4025       CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4026       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4027     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4028       // Special-case character extraction so we don't have to construct an
4029       // APValue for the whole string.
4030       assert(LVal.Designator.Entries.size() <= 1 &&
4031              "Can only read characters from string literals");
4032       if (LVal.Designator.Entries.empty()) {
4033         // Fail for now for LValue to RValue conversion of an array.
4034         // (This shouldn't show up in C/C++, but it could be triggered by a
4035         // weird EvaluateAsRValue call from a tool.)
4036         Info.FFDiag(Conv);
4037         return false;
4038       }
4039       if (LVal.Designator.isOnePastTheEnd()) {
4040         if (Info.getLangOpts().CPlusPlus11)
4041           Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4042         else
4043           Info.FFDiag(Conv);
4044         return false;
4045       }
4046       uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4047       RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4048       return true;
4049     }
4050   }
4051 
4052   CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4053   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4054 }
4055 
4056 /// Perform an assignment of Val to LVal. Takes ownership of Val.
4057 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4058                              QualType LValType, APValue &Val) {
4059   if (LVal.Designator.Invalid)
4060     return false;
4061 
4062   if (!Info.getLangOpts().CPlusPlus14) {
4063     Info.FFDiag(E);
4064     return false;
4065   }
4066 
4067   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4068   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4069 }
4070 
4071 namespace {
4072 struct CompoundAssignSubobjectHandler {
4073   EvalInfo &Info;
4074   const Expr *E;
4075   QualType PromotedLHSType;
4076   BinaryOperatorKind Opcode;
4077   const APValue &RHS;
4078 
4079   static const AccessKinds AccessKind = AK_Assign;
4080 
4081   typedef bool result_type;
4082 
4083   bool checkConst(QualType QT) {
4084     // Assigning to a const object has undefined behavior.
4085     if (QT.isConstQualified()) {
4086       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4087       return false;
4088     }
4089     return true;
4090   }
4091 
4092   bool failed() { return false; }
4093   bool found(APValue &Subobj, QualType SubobjType) {
4094     switch (Subobj.getKind()) {
4095     case APValue::Int:
4096       return found(Subobj.getInt(), SubobjType);
4097     case APValue::Float:
4098       return found(Subobj.getFloat(), SubobjType);
4099     case APValue::ComplexInt:
4100     case APValue::ComplexFloat:
4101       // FIXME: Implement complex compound assignment.
4102       Info.FFDiag(E);
4103       return false;
4104     case APValue::LValue:
4105       return foundPointer(Subobj, SubobjType);
4106     case APValue::Vector:
4107       return foundVector(Subobj, SubobjType);
4108     default:
4109       // FIXME: can this happen?
4110       Info.FFDiag(E);
4111       return false;
4112     }
4113   }
4114 
4115   bool foundVector(APValue &Value, QualType SubobjType) {
4116     if (!checkConst(SubobjType))
4117       return false;
4118 
4119     if (!SubobjType->isVectorType()) {
4120       Info.FFDiag(E);
4121       return false;
4122     }
4123     return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4124   }
4125 
4126   bool found(APSInt &Value, QualType SubobjType) {
4127     if (!checkConst(SubobjType))
4128       return false;
4129 
4130     if (!SubobjType->isIntegerType()) {
4131       // We don't support compound assignment on integer-cast-to-pointer
4132       // values.
4133       Info.FFDiag(E);
4134       return false;
4135     }
4136 
4137     if (RHS.isInt()) {
4138       APSInt LHS =
4139           HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4140       if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4141         return false;
4142       Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4143       return true;
4144     } else if (RHS.isFloat()) {
4145       APFloat FValue(0.0);
4146       return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
4147                                   FValue) &&
4148              handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4149              HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4150                                   Value);
4151     }
4152 
4153     Info.FFDiag(E);
4154     return false;
4155   }
4156   bool found(APFloat &Value, QualType SubobjType) {
4157     return checkConst(SubobjType) &&
4158            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4159                                   Value) &&
4160            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4161            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4162   }
4163   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4164     if (!checkConst(SubobjType))
4165       return false;
4166 
4167     QualType PointeeType;
4168     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4169       PointeeType = PT->getPointeeType();
4170 
4171     if (PointeeType.isNull() || !RHS.isInt() ||
4172         (Opcode != BO_Add && Opcode != BO_Sub)) {
4173       Info.FFDiag(E);
4174       return false;
4175     }
4176 
4177     APSInt Offset = RHS.getInt();
4178     if (Opcode == BO_Sub)
4179       negateAsSigned(Offset);
4180 
4181     LValue LVal;
4182     LVal.setFrom(Info.Ctx, Subobj);
4183     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4184       return false;
4185     LVal.moveInto(Subobj);
4186     return true;
4187   }
4188 };
4189 } // end anonymous namespace
4190 
4191 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4192 
4193 /// Perform a compound assignment of LVal <op>= RVal.
4194 static bool handleCompoundAssignment(
4195     EvalInfo &Info, const Expr *E,
4196     const LValue &LVal, QualType LValType, QualType PromotedLValType,
4197     BinaryOperatorKind Opcode, const APValue &RVal) {
4198   if (LVal.Designator.Invalid)
4199     return false;
4200 
4201   if (!Info.getLangOpts().CPlusPlus14) {
4202     Info.FFDiag(E);
4203     return false;
4204   }
4205 
4206   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4207   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4208                                              RVal };
4209   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4210 }
4211 
4212 namespace {
4213 struct IncDecSubobjectHandler {
4214   EvalInfo &Info;
4215   const UnaryOperator *E;
4216   AccessKinds AccessKind;
4217   APValue *Old;
4218 
4219   typedef bool result_type;
4220 
4221   bool checkConst(QualType QT) {
4222     // Assigning to a const object has undefined behavior.
4223     if (QT.isConstQualified()) {
4224       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4225       return false;
4226     }
4227     return true;
4228   }
4229 
4230   bool failed() { return false; }
4231   bool found(APValue &Subobj, QualType SubobjType) {
4232     // Stash the old value. Also clear Old, so we don't clobber it later
4233     // if we're post-incrementing a complex.
4234     if (Old) {
4235       *Old = Subobj;
4236       Old = nullptr;
4237     }
4238 
4239     switch (Subobj.getKind()) {
4240     case APValue::Int:
4241       return found(Subobj.getInt(), SubobjType);
4242     case APValue::Float:
4243       return found(Subobj.getFloat(), SubobjType);
4244     case APValue::ComplexInt:
4245       return found(Subobj.getComplexIntReal(),
4246                    SubobjType->castAs<ComplexType>()->getElementType()
4247                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4248     case APValue::ComplexFloat:
4249       return found(Subobj.getComplexFloatReal(),
4250                    SubobjType->castAs<ComplexType>()->getElementType()
4251                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4252     case APValue::LValue:
4253       return foundPointer(Subobj, SubobjType);
4254     default:
4255       // FIXME: can this happen?
4256       Info.FFDiag(E);
4257       return false;
4258     }
4259   }
4260   bool found(APSInt &Value, QualType SubobjType) {
4261     if (!checkConst(SubobjType))
4262       return false;
4263 
4264     if (!SubobjType->isIntegerType()) {
4265       // We don't support increment / decrement on integer-cast-to-pointer
4266       // values.
4267       Info.FFDiag(E);
4268       return false;
4269     }
4270 
4271     if (Old) *Old = APValue(Value);
4272 
4273     // bool arithmetic promotes to int, and the conversion back to bool
4274     // doesn't reduce mod 2^n, so special-case it.
4275     if (SubobjType->isBooleanType()) {
4276       if (AccessKind == AK_Increment)
4277         Value = 1;
4278       else
4279         Value = !Value;
4280       return true;
4281     }
4282 
4283     bool WasNegative = Value.isNegative();
4284     if (AccessKind == AK_Increment) {
4285       ++Value;
4286 
4287       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4288         APSInt ActualValue(Value, /*IsUnsigned*/true);
4289         return HandleOverflow(Info, E, ActualValue, SubobjType);
4290       }
4291     } else {
4292       --Value;
4293 
4294       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4295         unsigned BitWidth = Value.getBitWidth();
4296         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4297         ActualValue.setBit(BitWidth);
4298         return HandleOverflow(Info, E, ActualValue, SubobjType);
4299       }
4300     }
4301     return true;
4302   }
4303   bool found(APFloat &Value, QualType SubobjType) {
4304     if (!checkConst(SubobjType))
4305       return false;
4306 
4307     if (Old) *Old = APValue(Value);
4308 
4309     APFloat One(Value.getSemantics(), 1);
4310     if (AccessKind == AK_Increment)
4311       Value.add(One, APFloat::rmNearestTiesToEven);
4312     else
4313       Value.subtract(One, APFloat::rmNearestTiesToEven);
4314     return true;
4315   }
4316   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4317     if (!checkConst(SubobjType))
4318       return false;
4319 
4320     QualType PointeeType;
4321     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4322       PointeeType = PT->getPointeeType();
4323     else {
4324       Info.FFDiag(E);
4325       return false;
4326     }
4327 
4328     LValue LVal;
4329     LVal.setFrom(Info.Ctx, Subobj);
4330     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4331                                      AccessKind == AK_Increment ? 1 : -1))
4332       return false;
4333     LVal.moveInto(Subobj);
4334     return true;
4335   }
4336 };
4337 } // end anonymous namespace
4338 
4339 /// Perform an increment or decrement on LVal.
4340 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4341                          QualType LValType, bool IsIncrement, APValue *Old) {
4342   if (LVal.Designator.Invalid)
4343     return false;
4344 
4345   if (!Info.getLangOpts().CPlusPlus14) {
4346     Info.FFDiag(E);
4347     return false;
4348   }
4349 
4350   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4351   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4352   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4353   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4354 }
4355 
4356 /// Build an lvalue for the object argument of a member function call.
4357 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4358                                    LValue &This) {
4359   if (Object->getType()->isPointerType() && Object->isRValue())
4360     return EvaluatePointer(Object, This, Info);
4361 
4362   if (Object->isGLValue())
4363     return EvaluateLValue(Object, This, Info);
4364 
4365   if (Object->getType()->isLiteralType(Info.Ctx))
4366     return EvaluateTemporary(Object, This, Info);
4367 
4368   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4369   return false;
4370 }
4371 
4372 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
4373 /// lvalue referring to the result.
4374 ///
4375 /// \param Info - Information about the ongoing evaluation.
4376 /// \param LV - An lvalue referring to the base of the member pointer.
4377 /// \param RHS - The member pointer expression.
4378 /// \param IncludeMember - Specifies whether the member itself is included in
4379 ///        the resulting LValue subobject designator. This is not possible when
4380 ///        creating a bound member function.
4381 /// \return The field or method declaration to which the member pointer refers,
4382 ///         or 0 if evaluation fails.
4383 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4384                                                   QualType LVType,
4385                                                   LValue &LV,
4386                                                   const Expr *RHS,
4387                                                   bool IncludeMember = true) {
4388   MemberPtr MemPtr;
4389   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4390     return nullptr;
4391 
4392   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4393   // member value, the behavior is undefined.
4394   if (!MemPtr.getDecl()) {
4395     // FIXME: Specific diagnostic.
4396     Info.FFDiag(RHS);
4397     return nullptr;
4398   }
4399 
4400   if (MemPtr.isDerivedMember()) {
4401     // This is a member of some derived class. Truncate LV appropriately.
4402     // The end of the derived-to-base path for the base object must match the
4403     // derived-to-base path for the member pointer.
4404     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4405         LV.Designator.Entries.size()) {
4406       Info.FFDiag(RHS);
4407       return nullptr;
4408     }
4409     unsigned PathLengthToMember =
4410         LV.Designator.Entries.size() - MemPtr.Path.size();
4411     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4412       const CXXRecordDecl *LVDecl = getAsBaseClass(
4413           LV.Designator.Entries[PathLengthToMember + I]);
4414       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4415       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4416         Info.FFDiag(RHS);
4417         return nullptr;
4418       }
4419     }
4420 
4421     // Truncate the lvalue to the appropriate derived class.
4422     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4423                             PathLengthToMember))
4424       return nullptr;
4425   } else if (!MemPtr.Path.empty()) {
4426     // Extend the LValue path with the member pointer's path.
4427     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4428                                   MemPtr.Path.size() + IncludeMember);
4429 
4430     // Walk down to the appropriate base class.
4431     if (const PointerType *PT = LVType->getAs<PointerType>())
4432       LVType = PT->getPointeeType();
4433     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4434     assert(RD && "member pointer access on non-class-type expression");
4435     // The first class in the path is that of the lvalue.
4436     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4437       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4438       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4439         return nullptr;
4440       RD = Base;
4441     }
4442     // Finally cast to the class containing the member.
4443     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4444                                 MemPtr.getContainingRecord()))
4445       return nullptr;
4446   }
4447 
4448   // Add the member. Note that we cannot build bound member functions here.
4449   if (IncludeMember) {
4450     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4451       if (!HandleLValueMember(Info, RHS, LV, FD))
4452         return nullptr;
4453     } else if (const IndirectFieldDecl *IFD =
4454                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4455       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4456         return nullptr;
4457     } else {
4458       llvm_unreachable("can't construct reference to bound member function");
4459     }
4460   }
4461 
4462   return MemPtr.getDecl();
4463 }
4464 
4465 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4466                                                   const BinaryOperator *BO,
4467                                                   LValue &LV,
4468                                                   bool IncludeMember = true) {
4469   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4470 
4471   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4472     if (Info.noteFailure()) {
4473       MemberPtr MemPtr;
4474       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4475     }
4476     return nullptr;
4477   }
4478 
4479   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4480                                    BO->getRHS(), IncludeMember);
4481 }
4482 
4483 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4484 /// the provided lvalue, which currently refers to the base object.
4485 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4486                                     LValue &Result) {
4487   SubobjectDesignator &D = Result.Designator;
4488   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4489     return false;
4490 
4491   QualType TargetQT = E->getType();
4492   if (const PointerType *PT = TargetQT->getAs<PointerType>())
4493     TargetQT = PT->getPointeeType();
4494 
4495   // Check this cast lands within the final derived-to-base subobject path.
4496   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4497     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4498       << D.MostDerivedType << TargetQT;
4499     return false;
4500   }
4501 
4502   // Check the type of the final cast. We don't need to check the path,
4503   // since a cast can only be formed if the path is unique.
4504   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4505   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4506   const CXXRecordDecl *FinalType;
4507   if (NewEntriesSize == D.MostDerivedPathLength)
4508     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4509   else
4510     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4511   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4512     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4513       << D.MostDerivedType << TargetQT;
4514     return false;
4515   }
4516 
4517   // Truncate the lvalue to the appropriate derived class.
4518   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4519 }
4520 
4521 /// Get the value to use for a default-initialized object of type T.
4522 /// Return false if it encounters something invalid.
4523 static bool getDefaultInitValue(QualType T, APValue &Result) {
4524   bool Success = true;
4525   if (auto *RD = T->getAsCXXRecordDecl()) {
4526     if (RD->isInvalidDecl()) {
4527       Result = APValue();
4528       return false;
4529     }
4530     if (RD->isUnion()) {
4531       Result = APValue((const FieldDecl *)nullptr);
4532       return true;
4533     }
4534     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4535                      std::distance(RD->field_begin(), RD->field_end()));
4536 
4537     unsigned Index = 0;
4538     for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4539                                                   End = RD->bases_end();
4540          I != End; ++I, ++Index)
4541       Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index));
4542 
4543     for (const auto *I : RD->fields()) {
4544       if (I->isUnnamedBitfield())
4545         continue;
4546       Success &= getDefaultInitValue(I->getType(),
4547                                      Result.getStructField(I->getFieldIndex()));
4548     }
4549     return Success;
4550   }
4551 
4552   if (auto *AT =
4553           dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4554     Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4555     if (Result.hasArrayFiller())
4556       Success &=
4557           getDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
4558 
4559     return Success;
4560   }
4561 
4562   Result = APValue::IndeterminateValue();
4563   return true;
4564 }
4565 
4566 namespace {
4567 enum EvalStmtResult {
4568   /// Evaluation failed.
4569   ESR_Failed,
4570   /// Hit a 'return' statement.
4571   ESR_Returned,
4572   /// Evaluation succeeded.
4573   ESR_Succeeded,
4574   /// Hit a 'continue' statement.
4575   ESR_Continue,
4576   /// Hit a 'break' statement.
4577   ESR_Break,
4578   /// Still scanning for 'case' or 'default' statement.
4579   ESR_CaseNotFound
4580 };
4581 }
4582 
4583 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4584   // We don't need to evaluate the initializer for a static local.
4585   if (!VD->hasLocalStorage())
4586     return true;
4587 
4588   LValue Result;
4589   APValue &Val =
4590       Info.CurrentCall->createTemporary(VD, VD->getType(), true, Result);
4591 
4592   const Expr *InitE = VD->getInit();
4593   if (!InitE)
4594     return getDefaultInitValue(VD->getType(), Val);
4595 
4596   if (InitE->isValueDependent())
4597     return false;
4598 
4599   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4600     // Wipe out any partially-computed value, to allow tracking that this
4601     // evaluation failed.
4602     Val = APValue();
4603     return false;
4604   }
4605 
4606   return true;
4607 }
4608 
4609 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4610   bool OK = true;
4611 
4612   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4613     OK &= EvaluateVarDecl(Info, VD);
4614 
4615   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4616     for (auto *BD : DD->bindings())
4617       if (auto *VD = BD->getHoldingVar())
4618         OK &= EvaluateDecl(Info, VD);
4619 
4620   return OK;
4621 }
4622 
4623 
4624 /// Evaluate a condition (either a variable declaration or an expression).
4625 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4626                          const Expr *Cond, bool &Result) {
4627   FullExpressionRAII Scope(Info);
4628   if (CondDecl && !EvaluateDecl(Info, CondDecl))
4629     return false;
4630   if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4631     return false;
4632   return Scope.destroy();
4633 }
4634 
4635 namespace {
4636 /// A location where the result (returned value) of evaluating a
4637 /// statement should be stored.
4638 struct StmtResult {
4639   /// The APValue that should be filled in with the returned value.
4640   APValue &Value;
4641   /// The location containing the result, if any (used to support RVO).
4642   const LValue *Slot;
4643 };
4644 
4645 struct TempVersionRAII {
4646   CallStackFrame &Frame;
4647 
4648   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4649     Frame.pushTempVersion();
4650   }
4651 
4652   ~TempVersionRAII() {
4653     Frame.popTempVersion();
4654   }
4655 };
4656 
4657 }
4658 
4659 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4660                                    const Stmt *S,
4661                                    const SwitchCase *SC = nullptr);
4662 
4663 /// Evaluate the body of a loop, and translate the result as appropriate.
4664 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4665                                        const Stmt *Body,
4666                                        const SwitchCase *Case = nullptr) {
4667   BlockScopeRAII Scope(Info);
4668 
4669   EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4670   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4671     ESR = ESR_Failed;
4672 
4673   switch (ESR) {
4674   case ESR_Break:
4675     return ESR_Succeeded;
4676   case ESR_Succeeded:
4677   case ESR_Continue:
4678     return ESR_Continue;
4679   case ESR_Failed:
4680   case ESR_Returned:
4681   case ESR_CaseNotFound:
4682     return ESR;
4683   }
4684   llvm_unreachable("Invalid EvalStmtResult!");
4685 }
4686 
4687 /// Evaluate a switch statement.
4688 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4689                                      const SwitchStmt *SS) {
4690   BlockScopeRAII Scope(Info);
4691 
4692   // Evaluate the switch condition.
4693   APSInt Value;
4694   {
4695     if (const Stmt *Init = SS->getInit()) {
4696       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4697       if (ESR != ESR_Succeeded) {
4698         if (ESR != ESR_Failed && !Scope.destroy())
4699           ESR = ESR_Failed;
4700         return ESR;
4701       }
4702     }
4703 
4704     FullExpressionRAII CondScope(Info);
4705     if (SS->getConditionVariable() &&
4706         !EvaluateDecl(Info, SS->getConditionVariable()))
4707       return ESR_Failed;
4708     if (!EvaluateInteger(SS->getCond(), Value, Info))
4709       return ESR_Failed;
4710     if (!CondScope.destroy())
4711       return ESR_Failed;
4712   }
4713 
4714   // Find the switch case corresponding to the value of the condition.
4715   // FIXME: Cache this lookup.
4716   const SwitchCase *Found = nullptr;
4717   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4718        SC = SC->getNextSwitchCase()) {
4719     if (isa<DefaultStmt>(SC)) {
4720       Found = SC;
4721       continue;
4722     }
4723 
4724     const CaseStmt *CS = cast<CaseStmt>(SC);
4725     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4726     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4727                               : LHS;
4728     if (LHS <= Value && Value <= RHS) {
4729       Found = SC;
4730       break;
4731     }
4732   }
4733 
4734   if (!Found)
4735     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4736 
4737   // Search the switch body for the switch case and evaluate it from there.
4738   EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
4739   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4740     return ESR_Failed;
4741 
4742   switch (ESR) {
4743   case ESR_Break:
4744     return ESR_Succeeded;
4745   case ESR_Succeeded:
4746   case ESR_Continue:
4747   case ESR_Failed:
4748   case ESR_Returned:
4749     return ESR;
4750   case ESR_CaseNotFound:
4751     // This can only happen if the switch case is nested within a statement
4752     // expression. We have no intention of supporting that.
4753     Info.FFDiag(Found->getBeginLoc(),
4754                 diag::note_constexpr_stmt_expr_unsupported);
4755     return ESR_Failed;
4756   }
4757   llvm_unreachable("Invalid EvalStmtResult!");
4758 }
4759 
4760 // Evaluate a statement.
4761 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4762                                    const Stmt *S, const SwitchCase *Case) {
4763   if (!Info.nextStep(S))
4764     return ESR_Failed;
4765 
4766   // If we're hunting down a 'case' or 'default' label, recurse through
4767   // substatements until we hit the label.
4768   if (Case) {
4769     switch (S->getStmtClass()) {
4770     case Stmt::CompoundStmtClass:
4771       // FIXME: Precompute which substatement of a compound statement we
4772       // would jump to, and go straight there rather than performing a
4773       // linear scan each time.
4774     case Stmt::LabelStmtClass:
4775     case Stmt::AttributedStmtClass:
4776     case Stmt::DoStmtClass:
4777       break;
4778 
4779     case Stmt::CaseStmtClass:
4780     case Stmt::DefaultStmtClass:
4781       if (Case == S)
4782         Case = nullptr;
4783       break;
4784 
4785     case Stmt::IfStmtClass: {
4786       // FIXME: Precompute which side of an 'if' we would jump to, and go
4787       // straight there rather than scanning both sides.
4788       const IfStmt *IS = cast<IfStmt>(S);
4789 
4790       // Wrap the evaluation in a block scope, in case it's a DeclStmt
4791       // preceded by our switch label.
4792       BlockScopeRAII Scope(Info);
4793 
4794       // Step into the init statement in case it brings an (uninitialized)
4795       // variable into scope.
4796       if (const Stmt *Init = IS->getInit()) {
4797         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
4798         if (ESR != ESR_CaseNotFound) {
4799           assert(ESR != ESR_Succeeded);
4800           return ESR;
4801         }
4802       }
4803 
4804       // Condition variable must be initialized if it exists.
4805       // FIXME: We can skip evaluating the body if there's a condition
4806       // variable, as there can't be any case labels within it.
4807       // (The same is true for 'for' statements.)
4808 
4809       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
4810       if (ESR == ESR_Failed)
4811         return ESR;
4812       if (ESR != ESR_CaseNotFound)
4813         return Scope.destroy() ? ESR : ESR_Failed;
4814       if (!IS->getElse())
4815         return ESR_CaseNotFound;
4816 
4817       ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
4818       if (ESR == ESR_Failed)
4819         return ESR;
4820       if (ESR != ESR_CaseNotFound)
4821         return Scope.destroy() ? ESR : ESR_Failed;
4822       return ESR_CaseNotFound;
4823     }
4824 
4825     case Stmt::WhileStmtClass: {
4826       EvalStmtResult ESR =
4827           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4828       if (ESR != ESR_Continue)
4829         return ESR;
4830       break;
4831     }
4832 
4833     case Stmt::ForStmtClass: {
4834       const ForStmt *FS = cast<ForStmt>(S);
4835       BlockScopeRAII Scope(Info);
4836 
4837       // Step into the init statement in case it brings an (uninitialized)
4838       // variable into scope.
4839       if (const Stmt *Init = FS->getInit()) {
4840         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
4841         if (ESR != ESR_CaseNotFound) {
4842           assert(ESR != ESR_Succeeded);
4843           return ESR;
4844         }
4845       }
4846 
4847       EvalStmtResult ESR =
4848           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4849       if (ESR != ESR_Continue)
4850         return ESR;
4851       if (FS->getInc()) {
4852         FullExpressionRAII IncScope(Info);
4853         if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
4854           return ESR_Failed;
4855       }
4856       break;
4857     }
4858 
4859     case Stmt::DeclStmtClass: {
4860       // Start the lifetime of any uninitialized variables we encounter. They
4861       // might be used by the selected branch of the switch.
4862       const DeclStmt *DS = cast<DeclStmt>(S);
4863       for (const auto *D : DS->decls()) {
4864         if (const auto *VD = dyn_cast<VarDecl>(D)) {
4865           if (VD->hasLocalStorage() && !VD->getInit())
4866             if (!EvaluateVarDecl(Info, VD))
4867               return ESR_Failed;
4868           // FIXME: If the variable has initialization that can't be jumped
4869           // over, bail out of any immediately-surrounding compound-statement
4870           // too. There can't be any case labels here.
4871         }
4872       }
4873       return ESR_CaseNotFound;
4874     }
4875 
4876     default:
4877       return ESR_CaseNotFound;
4878     }
4879   }
4880 
4881   switch (S->getStmtClass()) {
4882   default:
4883     if (const Expr *E = dyn_cast<Expr>(S)) {
4884       // Don't bother evaluating beyond an expression-statement which couldn't
4885       // be evaluated.
4886       // FIXME: Do we need the FullExpressionRAII object here?
4887       // VisitExprWithCleanups should create one when necessary.
4888       FullExpressionRAII Scope(Info);
4889       if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
4890         return ESR_Failed;
4891       return ESR_Succeeded;
4892     }
4893 
4894     Info.FFDiag(S->getBeginLoc());
4895     return ESR_Failed;
4896 
4897   case Stmt::NullStmtClass:
4898     return ESR_Succeeded;
4899 
4900   case Stmt::DeclStmtClass: {
4901     const DeclStmt *DS = cast<DeclStmt>(S);
4902     for (const auto *D : DS->decls()) {
4903       // Each declaration initialization is its own full-expression.
4904       FullExpressionRAII Scope(Info);
4905       if (!EvaluateDecl(Info, D) && !Info.noteFailure())
4906         return ESR_Failed;
4907       if (!Scope.destroy())
4908         return ESR_Failed;
4909     }
4910     return ESR_Succeeded;
4911   }
4912 
4913   case Stmt::ReturnStmtClass: {
4914     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
4915     FullExpressionRAII Scope(Info);
4916     if (RetExpr &&
4917         !(Result.Slot
4918               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4919               : Evaluate(Result.Value, Info, RetExpr)))
4920       return ESR_Failed;
4921     return Scope.destroy() ? ESR_Returned : ESR_Failed;
4922   }
4923 
4924   case Stmt::CompoundStmtClass: {
4925     BlockScopeRAII Scope(Info);
4926 
4927     const CompoundStmt *CS = cast<CompoundStmt>(S);
4928     for (const auto *BI : CS->body()) {
4929       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
4930       if (ESR == ESR_Succeeded)
4931         Case = nullptr;
4932       else if (ESR != ESR_CaseNotFound) {
4933         if (ESR != ESR_Failed && !Scope.destroy())
4934           return ESR_Failed;
4935         return ESR;
4936       }
4937     }
4938     if (Case)
4939       return ESR_CaseNotFound;
4940     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4941   }
4942 
4943   case Stmt::IfStmtClass: {
4944     const IfStmt *IS = cast<IfStmt>(S);
4945 
4946     // Evaluate the condition, as either a var decl or as an expression.
4947     BlockScopeRAII Scope(Info);
4948     if (const Stmt *Init = IS->getInit()) {
4949       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4950       if (ESR != ESR_Succeeded) {
4951         if (ESR != ESR_Failed && !Scope.destroy())
4952           return ESR_Failed;
4953         return ESR;
4954       }
4955     }
4956     bool Cond;
4957     if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
4958       return ESR_Failed;
4959 
4960     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4961       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4962       if (ESR != ESR_Succeeded) {
4963         if (ESR != ESR_Failed && !Scope.destroy())
4964           return ESR_Failed;
4965         return ESR;
4966       }
4967     }
4968     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4969   }
4970 
4971   case Stmt::WhileStmtClass: {
4972     const WhileStmt *WS = cast<WhileStmt>(S);
4973     while (true) {
4974       BlockScopeRAII Scope(Info);
4975       bool Continue;
4976       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4977                         Continue))
4978         return ESR_Failed;
4979       if (!Continue)
4980         break;
4981 
4982       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4983       if (ESR != ESR_Continue) {
4984         if (ESR != ESR_Failed && !Scope.destroy())
4985           return ESR_Failed;
4986         return ESR;
4987       }
4988       if (!Scope.destroy())
4989         return ESR_Failed;
4990     }
4991     return ESR_Succeeded;
4992   }
4993 
4994   case Stmt::DoStmtClass: {
4995     const DoStmt *DS = cast<DoStmt>(S);
4996     bool Continue;
4997     do {
4998       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
4999       if (ESR != ESR_Continue)
5000         return ESR;
5001       Case = nullptr;
5002 
5003       FullExpressionRAII CondScope(Info);
5004       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5005           !CondScope.destroy())
5006         return ESR_Failed;
5007     } while (Continue);
5008     return ESR_Succeeded;
5009   }
5010 
5011   case Stmt::ForStmtClass: {
5012     const ForStmt *FS = cast<ForStmt>(S);
5013     BlockScopeRAII ForScope(Info);
5014     if (FS->getInit()) {
5015       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5016       if (ESR != ESR_Succeeded) {
5017         if (ESR != ESR_Failed && !ForScope.destroy())
5018           return ESR_Failed;
5019         return ESR;
5020       }
5021     }
5022     while (true) {
5023       BlockScopeRAII IterScope(Info);
5024       bool Continue = true;
5025       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5026                                          FS->getCond(), Continue))
5027         return ESR_Failed;
5028       if (!Continue)
5029         break;
5030 
5031       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5032       if (ESR != ESR_Continue) {
5033         if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5034           return ESR_Failed;
5035         return ESR;
5036       }
5037 
5038       if (FS->getInc()) {
5039         FullExpressionRAII IncScope(Info);
5040         if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
5041           return ESR_Failed;
5042       }
5043 
5044       if (!IterScope.destroy())
5045         return ESR_Failed;
5046     }
5047     return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5048   }
5049 
5050   case Stmt::CXXForRangeStmtClass: {
5051     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5052     BlockScopeRAII Scope(Info);
5053 
5054     // Evaluate the init-statement if present.
5055     if (FS->getInit()) {
5056       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5057       if (ESR != ESR_Succeeded) {
5058         if (ESR != ESR_Failed && !Scope.destroy())
5059           return ESR_Failed;
5060         return ESR;
5061       }
5062     }
5063 
5064     // Initialize the __range variable.
5065     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5066     if (ESR != ESR_Succeeded) {
5067       if (ESR != ESR_Failed && !Scope.destroy())
5068         return ESR_Failed;
5069       return ESR;
5070     }
5071 
5072     // Create the __begin and __end iterators.
5073     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5074     if (ESR != ESR_Succeeded) {
5075       if (ESR != ESR_Failed && !Scope.destroy())
5076         return ESR_Failed;
5077       return ESR;
5078     }
5079     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5080     if (ESR != ESR_Succeeded) {
5081       if (ESR != ESR_Failed && !Scope.destroy())
5082         return ESR_Failed;
5083       return ESR;
5084     }
5085 
5086     while (true) {
5087       // Condition: __begin != __end.
5088       {
5089         bool Continue = true;
5090         FullExpressionRAII CondExpr(Info);
5091         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5092           return ESR_Failed;
5093         if (!Continue)
5094           break;
5095       }
5096 
5097       // User's variable declaration, initialized by *__begin.
5098       BlockScopeRAII InnerScope(Info);
5099       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5100       if (ESR != ESR_Succeeded) {
5101         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5102           return ESR_Failed;
5103         return ESR;
5104       }
5105 
5106       // Loop body.
5107       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5108       if (ESR != ESR_Continue) {
5109         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5110           return ESR_Failed;
5111         return ESR;
5112       }
5113 
5114       // Increment: ++__begin
5115       if (!EvaluateIgnoredValue(Info, FS->getInc()))
5116         return ESR_Failed;
5117 
5118       if (!InnerScope.destroy())
5119         return ESR_Failed;
5120     }
5121 
5122     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5123   }
5124 
5125   case Stmt::SwitchStmtClass:
5126     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5127 
5128   case Stmt::ContinueStmtClass:
5129     return ESR_Continue;
5130 
5131   case Stmt::BreakStmtClass:
5132     return ESR_Break;
5133 
5134   case Stmt::LabelStmtClass:
5135     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5136 
5137   case Stmt::AttributedStmtClass:
5138     // As a general principle, C++11 attributes can be ignored without
5139     // any semantic impact.
5140     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
5141                         Case);
5142 
5143   case Stmt::CaseStmtClass:
5144   case Stmt::DefaultStmtClass:
5145     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5146   case Stmt::CXXTryStmtClass:
5147     // Evaluate try blocks by evaluating all sub statements.
5148     return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5149   }
5150 }
5151 
5152 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5153 /// default constructor. If so, we'll fold it whether or not it's marked as
5154 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
5155 /// so we need special handling.
5156 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5157                                            const CXXConstructorDecl *CD,
5158                                            bool IsValueInitialization) {
5159   if (!CD->isTrivial() || !CD->isDefaultConstructor())
5160     return false;
5161 
5162   // Value-initialization does not call a trivial default constructor, so such a
5163   // call is a core constant expression whether or not the constructor is
5164   // constexpr.
5165   if (!CD->isConstexpr() && !IsValueInitialization) {
5166     if (Info.getLangOpts().CPlusPlus11) {
5167       // FIXME: If DiagDecl is an implicitly-declared special member function,
5168       // we should be much more explicit about why it's not constexpr.
5169       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5170         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5171       Info.Note(CD->getLocation(), diag::note_declared_at);
5172     } else {
5173       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5174     }
5175   }
5176   return true;
5177 }
5178 
5179 /// CheckConstexprFunction - Check that a function can be called in a constant
5180 /// expression.
5181 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5182                                    const FunctionDecl *Declaration,
5183                                    const FunctionDecl *Definition,
5184                                    const Stmt *Body) {
5185   // Potential constant expressions can contain calls to declared, but not yet
5186   // defined, constexpr functions.
5187   if (Info.checkingPotentialConstantExpression() && !Definition &&
5188       Declaration->isConstexpr())
5189     return false;
5190 
5191   // Bail out if the function declaration itself is invalid.  We will
5192   // have produced a relevant diagnostic while parsing it, so just
5193   // note the problematic sub-expression.
5194   if (Declaration->isInvalidDecl()) {
5195     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5196     return false;
5197   }
5198 
5199   // DR1872: An instantiated virtual constexpr function can't be called in a
5200   // constant expression (prior to C++20). We can still constant-fold such a
5201   // call.
5202   if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5203       cast<CXXMethodDecl>(Declaration)->isVirtual())
5204     Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5205 
5206   if (Definition && Definition->isInvalidDecl()) {
5207     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5208     return false;
5209   }
5210 
5211   if (const auto *CtorDecl = dyn_cast_or_null<CXXConstructorDecl>(Definition)) {
5212     for (const auto *InitExpr : CtorDecl->inits()) {
5213       if (InitExpr->getInit() && InitExpr->getInit()->containsErrors())
5214         return false;
5215     }
5216   }
5217 
5218   // Can we evaluate this function call?
5219   if (Definition && Definition->isConstexpr() && Body)
5220     return true;
5221 
5222   if (Info.getLangOpts().CPlusPlus11) {
5223     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5224 
5225     // If this function is not constexpr because it is an inherited
5226     // non-constexpr constructor, diagnose that directly.
5227     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5228     if (CD && CD->isInheritingConstructor()) {
5229       auto *Inherited = CD->getInheritedConstructor().getConstructor();
5230       if (!Inherited->isConstexpr())
5231         DiagDecl = CD = Inherited;
5232     }
5233 
5234     // FIXME: If DiagDecl is an implicitly-declared special member function
5235     // or an inheriting constructor, we should be much more explicit about why
5236     // it's not constexpr.
5237     if (CD && CD->isInheritingConstructor())
5238       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5239         << CD->getInheritedConstructor().getConstructor()->getParent();
5240     else
5241       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5242         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5243     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5244   } else {
5245     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5246   }
5247   return false;
5248 }
5249 
5250 namespace {
5251 struct CheckDynamicTypeHandler {
5252   AccessKinds AccessKind;
5253   typedef bool result_type;
5254   bool failed() { return false; }
5255   bool found(APValue &Subobj, QualType SubobjType) { return true; }
5256   bool found(APSInt &Value, QualType SubobjType) { return true; }
5257   bool found(APFloat &Value, QualType SubobjType) { return true; }
5258 };
5259 } // end anonymous namespace
5260 
5261 /// Check that we can access the notional vptr of an object / determine its
5262 /// dynamic type.
5263 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5264                              AccessKinds AK, bool Polymorphic) {
5265   if (This.Designator.Invalid)
5266     return false;
5267 
5268   CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5269 
5270   if (!Obj)
5271     return false;
5272 
5273   if (!Obj.Value) {
5274     // The object is not usable in constant expressions, so we can't inspect
5275     // its value to see if it's in-lifetime or what the active union members
5276     // are. We can still check for a one-past-the-end lvalue.
5277     if (This.Designator.isOnePastTheEnd() ||
5278         This.Designator.isMostDerivedAnUnsizedArray()) {
5279       Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5280                          ? diag::note_constexpr_access_past_end
5281                          : diag::note_constexpr_access_unsized_array)
5282           << AK;
5283       return false;
5284     } else if (Polymorphic) {
5285       // Conservatively refuse to perform a polymorphic operation if we would
5286       // not be able to read a notional 'vptr' value.
5287       APValue Val;
5288       This.moveInto(Val);
5289       QualType StarThisType =
5290           Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5291       Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5292           << AK << Val.getAsString(Info.Ctx, StarThisType);
5293       return false;
5294     }
5295     return true;
5296   }
5297 
5298   CheckDynamicTypeHandler Handler{AK};
5299   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5300 }
5301 
5302 /// Check that the pointee of the 'this' pointer in a member function call is
5303 /// either within its lifetime or in its period of construction or destruction.
5304 static bool
5305 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5306                                      const LValue &This,
5307                                      const CXXMethodDecl *NamedMember) {
5308   return checkDynamicType(
5309       Info, E, This,
5310       isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5311 }
5312 
5313 struct DynamicType {
5314   /// The dynamic class type of the object.
5315   const CXXRecordDecl *Type;
5316   /// The corresponding path length in the lvalue.
5317   unsigned PathLength;
5318 };
5319 
5320 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5321                                              unsigned PathLength) {
5322   assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5323       Designator.Entries.size() && "invalid path length");
5324   return (PathLength == Designator.MostDerivedPathLength)
5325              ? Designator.MostDerivedType->getAsCXXRecordDecl()
5326              : getAsBaseClass(Designator.Entries[PathLength - 1]);
5327 }
5328 
5329 /// Determine the dynamic type of an object.
5330 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
5331                                                 LValue &This, AccessKinds AK) {
5332   // If we don't have an lvalue denoting an object of class type, there is no
5333   // meaningful dynamic type. (We consider objects of non-class type to have no
5334   // dynamic type.)
5335   if (!checkDynamicType(Info, E, This, AK, true))
5336     return None;
5337 
5338   // Refuse to compute a dynamic type in the presence of virtual bases. This
5339   // shouldn't happen other than in constant-folding situations, since literal
5340   // types can't have virtual bases.
5341   //
5342   // Note that consumers of DynamicType assume that the type has no virtual
5343   // bases, and will need modifications if this restriction is relaxed.
5344   const CXXRecordDecl *Class =
5345       This.Designator.MostDerivedType->getAsCXXRecordDecl();
5346   if (!Class || Class->getNumVBases()) {
5347     Info.FFDiag(E);
5348     return None;
5349   }
5350 
5351   // FIXME: For very deep class hierarchies, it might be beneficial to use a
5352   // binary search here instead. But the overwhelmingly common case is that
5353   // we're not in the middle of a constructor, so it probably doesn't matter
5354   // in practice.
5355   ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5356   for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5357        PathLength <= Path.size(); ++PathLength) {
5358     switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5359                                       Path.slice(0, PathLength))) {
5360     case ConstructionPhase::Bases:
5361     case ConstructionPhase::DestroyingBases:
5362       // We're constructing or destroying a base class. This is not the dynamic
5363       // type.
5364       break;
5365 
5366     case ConstructionPhase::None:
5367     case ConstructionPhase::AfterBases:
5368     case ConstructionPhase::AfterFields:
5369     case ConstructionPhase::Destroying:
5370       // We've finished constructing the base classes and not yet started
5371       // destroying them again, so this is the dynamic type.
5372       return DynamicType{getBaseClassType(This.Designator, PathLength),
5373                          PathLength};
5374     }
5375   }
5376 
5377   // CWG issue 1517: we're constructing a base class of the object described by
5378   // 'This', so that object has not yet begun its period of construction and
5379   // any polymorphic operation on it results in undefined behavior.
5380   Info.FFDiag(E);
5381   return None;
5382 }
5383 
5384 /// Perform virtual dispatch.
5385 static const CXXMethodDecl *HandleVirtualDispatch(
5386     EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5387     llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5388   Optional<DynamicType> DynType = ComputeDynamicType(
5389       Info, E, This,
5390       isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5391   if (!DynType)
5392     return nullptr;
5393 
5394   // Find the final overrider. It must be declared in one of the classes on the
5395   // path from the dynamic type to the static type.
5396   // FIXME: If we ever allow literal types to have virtual base classes, that
5397   // won't be true.
5398   const CXXMethodDecl *Callee = Found;
5399   unsigned PathLength = DynType->PathLength;
5400   for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5401     const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5402     const CXXMethodDecl *Overrider =
5403         Found->getCorrespondingMethodDeclaredInClass(Class, false);
5404     if (Overrider) {
5405       Callee = Overrider;
5406       break;
5407     }
5408   }
5409 
5410   // C++2a [class.abstract]p6:
5411   //   the effect of making a virtual call to a pure virtual function [...] is
5412   //   undefined
5413   if (Callee->isPure()) {
5414     Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5415     Info.Note(Callee->getLocation(), diag::note_declared_at);
5416     return nullptr;
5417   }
5418 
5419   // If necessary, walk the rest of the path to determine the sequence of
5420   // covariant adjustment steps to apply.
5421   if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5422                                        Found->getReturnType())) {
5423     CovariantAdjustmentPath.push_back(Callee->getReturnType());
5424     for (unsigned CovariantPathLength = PathLength + 1;
5425          CovariantPathLength != This.Designator.Entries.size();
5426          ++CovariantPathLength) {
5427       const CXXRecordDecl *NextClass =
5428           getBaseClassType(This.Designator, CovariantPathLength);
5429       const CXXMethodDecl *Next =
5430           Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5431       if (Next && !Info.Ctx.hasSameUnqualifiedType(
5432                       Next->getReturnType(), CovariantAdjustmentPath.back()))
5433         CovariantAdjustmentPath.push_back(Next->getReturnType());
5434     }
5435     if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5436                                          CovariantAdjustmentPath.back()))
5437       CovariantAdjustmentPath.push_back(Found->getReturnType());
5438   }
5439 
5440   // Perform 'this' adjustment.
5441   if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5442     return nullptr;
5443 
5444   return Callee;
5445 }
5446 
5447 /// Perform the adjustment from a value returned by a virtual function to
5448 /// a value of the statically expected type, which may be a pointer or
5449 /// reference to a base class of the returned type.
5450 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5451                                             APValue &Result,
5452                                             ArrayRef<QualType> Path) {
5453   assert(Result.isLValue() &&
5454          "unexpected kind of APValue for covariant return");
5455   if (Result.isNullPointer())
5456     return true;
5457 
5458   LValue LVal;
5459   LVal.setFrom(Info.Ctx, Result);
5460 
5461   const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5462   for (unsigned I = 1; I != Path.size(); ++I) {
5463     const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5464     assert(OldClass && NewClass && "unexpected kind of covariant return");
5465     if (OldClass != NewClass &&
5466         !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5467       return false;
5468     OldClass = NewClass;
5469   }
5470 
5471   LVal.moveInto(Result);
5472   return true;
5473 }
5474 
5475 /// Determine whether \p Base, which is known to be a direct base class of
5476 /// \p Derived, is a public base class.
5477 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5478                               const CXXRecordDecl *Base) {
5479   for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5480     auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5481     if (BaseClass && declaresSameEntity(BaseClass, Base))
5482       return BaseSpec.getAccessSpecifier() == AS_public;
5483   }
5484   llvm_unreachable("Base is not a direct base of Derived");
5485 }
5486 
5487 /// Apply the given dynamic cast operation on the provided lvalue.
5488 ///
5489 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
5490 /// to find a suitable target subobject.
5491 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5492                               LValue &Ptr) {
5493   // We can't do anything with a non-symbolic pointer value.
5494   SubobjectDesignator &D = Ptr.Designator;
5495   if (D.Invalid)
5496     return false;
5497 
5498   // C++ [expr.dynamic.cast]p6:
5499   //   If v is a null pointer value, the result is a null pointer value.
5500   if (Ptr.isNullPointer() && !E->isGLValue())
5501     return true;
5502 
5503   // For all the other cases, we need the pointer to point to an object within
5504   // its lifetime / period of construction / destruction, and we need to know
5505   // its dynamic type.
5506   Optional<DynamicType> DynType =
5507       ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5508   if (!DynType)
5509     return false;
5510 
5511   // C++ [expr.dynamic.cast]p7:
5512   //   If T is "pointer to cv void", then the result is a pointer to the most
5513   //   derived object
5514   if (E->getType()->isVoidPointerType())
5515     return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5516 
5517   const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5518   assert(C && "dynamic_cast target is not void pointer nor class");
5519   CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5520 
5521   auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5522     // C++ [expr.dynamic.cast]p9:
5523     if (!E->isGLValue()) {
5524       //   The value of a failed cast to pointer type is the null pointer value
5525       //   of the required result type.
5526       Ptr.setNull(Info.Ctx, E->getType());
5527       return true;
5528     }
5529 
5530     //   A failed cast to reference type throws [...] std::bad_cast.
5531     unsigned DiagKind;
5532     if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5533                    DynType->Type->isDerivedFrom(C)))
5534       DiagKind = 0;
5535     else if (!Paths || Paths->begin() == Paths->end())
5536       DiagKind = 1;
5537     else if (Paths->isAmbiguous(CQT))
5538       DiagKind = 2;
5539     else {
5540       assert(Paths->front().Access != AS_public && "why did the cast fail?");
5541       DiagKind = 3;
5542     }
5543     Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5544         << DiagKind << Ptr.Designator.getType(Info.Ctx)
5545         << Info.Ctx.getRecordType(DynType->Type)
5546         << E->getType().getUnqualifiedType();
5547     return false;
5548   };
5549 
5550   // Runtime check, phase 1:
5551   //   Walk from the base subobject towards the derived object looking for the
5552   //   target type.
5553   for (int PathLength = Ptr.Designator.Entries.size();
5554        PathLength >= (int)DynType->PathLength; --PathLength) {
5555     const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5556     if (declaresSameEntity(Class, C))
5557       return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5558     // We can only walk across public inheritance edges.
5559     if (PathLength > (int)DynType->PathLength &&
5560         !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5561                            Class))
5562       return RuntimeCheckFailed(nullptr);
5563   }
5564 
5565   // Runtime check, phase 2:
5566   //   Search the dynamic type for an unambiguous public base of type C.
5567   CXXBasePaths Paths(/*FindAmbiguities=*/true,
5568                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
5569   if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5570       Paths.front().Access == AS_public) {
5571     // Downcast to the dynamic type...
5572     if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5573       return false;
5574     // ... then upcast to the chosen base class subobject.
5575     for (CXXBasePathElement &Elem : Paths.front())
5576       if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5577         return false;
5578     return true;
5579   }
5580 
5581   // Otherwise, the runtime check fails.
5582   return RuntimeCheckFailed(&Paths);
5583 }
5584 
5585 namespace {
5586 struct StartLifetimeOfUnionMemberHandler {
5587   EvalInfo &Info;
5588   const Expr *LHSExpr;
5589   const FieldDecl *Field;
5590   bool DuringInit;
5591   bool Failed = false;
5592   static const AccessKinds AccessKind = AK_Assign;
5593 
5594   typedef bool result_type;
5595   bool failed() { return Failed; }
5596   bool found(APValue &Subobj, QualType SubobjType) {
5597     // We are supposed to perform no initialization but begin the lifetime of
5598     // the object. We interpret that as meaning to do what default
5599     // initialization of the object would do if all constructors involved were
5600     // trivial:
5601     //  * All base, non-variant member, and array element subobjects' lifetimes
5602     //    begin
5603     //  * No variant members' lifetimes begin
5604     //  * All scalar subobjects whose lifetimes begin have indeterminate values
5605     assert(SubobjType->isUnionType());
5606     if (declaresSameEntity(Subobj.getUnionField(), Field)) {
5607       // This union member is already active. If it's also in-lifetime, there's
5608       // nothing to do.
5609       if (Subobj.getUnionValue().hasValue())
5610         return true;
5611     } else if (DuringInit) {
5612       // We're currently in the process of initializing a different union
5613       // member.  If we carried on, that initialization would attempt to
5614       // store to an inactive union member, resulting in undefined behavior.
5615       Info.FFDiag(LHSExpr,
5616                   diag::note_constexpr_union_member_change_during_init);
5617       return false;
5618     }
5619     APValue Result;
5620     Failed = !getDefaultInitValue(Field->getType(), Result);
5621     Subobj.setUnion(Field, Result);
5622     return true;
5623   }
5624   bool found(APSInt &Value, QualType SubobjType) {
5625     llvm_unreachable("wrong value kind for union object");
5626   }
5627   bool found(APFloat &Value, QualType SubobjType) {
5628     llvm_unreachable("wrong value kind for union object");
5629   }
5630 };
5631 } // end anonymous namespace
5632 
5633 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5634 
5635 /// Handle a builtin simple-assignment or a call to a trivial assignment
5636 /// operator whose left-hand side might involve a union member access. If it
5637 /// does, implicitly start the lifetime of any accessed union elements per
5638 /// C++20 [class.union]5.
5639 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5640                                           const LValue &LHS) {
5641   if (LHS.InvalidBase || LHS.Designator.Invalid)
5642     return false;
5643 
5644   llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5645   // C++ [class.union]p5:
5646   //   define the set S(E) of subexpressions of E as follows:
5647   unsigned PathLength = LHS.Designator.Entries.size();
5648   for (const Expr *E = LHSExpr; E != nullptr;) {
5649     //   -- If E is of the form A.B, S(E) contains the elements of S(A)...
5650     if (auto *ME = dyn_cast<MemberExpr>(E)) {
5651       auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5652       // Note that we can't implicitly start the lifetime of a reference,
5653       // so we don't need to proceed any further if we reach one.
5654       if (!FD || FD->getType()->isReferenceType())
5655         break;
5656 
5657       //    ... and also contains A.B if B names a union member ...
5658       if (FD->getParent()->isUnion()) {
5659         //    ... of a non-class, non-array type, or of a class type with a
5660         //    trivial default constructor that is not deleted, or an array of
5661         //    such types.
5662         auto *RD =
5663             FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5664         if (!RD || RD->hasTrivialDefaultConstructor())
5665           UnionPathLengths.push_back({PathLength - 1, FD});
5666       }
5667 
5668       E = ME->getBase();
5669       --PathLength;
5670       assert(declaresSameEntity(FD,
5671                                 LHS.Designator.Entries[PathLength]
5672                                     .getAsBaseOrMember().getPointer()));
5673 
5674       //   -- If E is of the form A[B] and is interpreted as a built-in array
5675       //      subscripting operator, S(E) is [S(the array operand, if any)].
5676     } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5677       // Step over an ArrayToPointerDecay implicit cast.
5678       auto *Base = ASE->getBase()->IgnoreImplicit();
5679       if (!Base->getType()->isArrayType())
5680         break;
5681 
5682       E = Base;
5683       --PathLength;
5684 
5685     } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5686       // Step over a derived-to-base conversion.
5687       E = ICE->getSubExpr();
5688       if (ICE->getCastKind() == CK_NoOp)
5689         continue;
5690       if (ICE->getCastKind() != CK_DerivedToBase &&
5691           ICE->getCastKind() != CK_UncheckedDerivedToBase)
5692         break;
5693       // Walk path backwards as we walk up from the base to the derived class.
5694       for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
5695         --PathLength;
5696         (void)Elt;
5697         assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
5698                                   LHS.Designator.Entries[PathLength]
5699                                       .getAsBaseOrMember().getPointer()));
5700       }
5701 
5702     //   -- Otherwise, S(E) is empty.
5703     } else {
5704       break;
5705     }
5706   }
5707 
5708   // Common case: no unions' lifetimes are started.
5709   if (UnionPathLengths.empty())
5710     return true;
5711 
5712   //   if modification of X [would access an inactive union member], an object
5713   //   of the type of X is implicitly created
5714   CompleteObject Obj =
5715       findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
5716   if (!Obj)
5717     return false;
5718   for (std::pair<unsigned, const FieldDecl *> LengthAndField :
5719            llvm::reverse(UnionPathLengths)) {
5720     // Form a designator for the union object.
5721     SubobjectDesignator D = LHS.Designator;
5722     D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
5723 
5724     bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
5725                       ConstructionPhase::AfterBases;
5726     StartLifetimeOfUnionMemberHandler StartLifetime{
5727         Info, LHSExpr, LengthAndField.second, DuringInit};
5728     if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
5729       return false;
5730   }
5731 
5732   return true;
5733 }
5734 
5735 namespace {
5736 typedef SmallVector<APValue, 8> ArgVector;
5737 }
5738 
5739 /// EvaluateArgs - Evaluate the arguments to a function call.
5740 static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues,
5741                          EvalInfo &Info, const FunctionDecl *Callee) {
5742   bool Success = true;
5743   llvm::SmallBitVector ForbiddenNullArgs;
5744   if (Callee->hasAttr<NonNullAttr>()) {
5745     ForbiddenNullArgs.resize(Args.size());
5746     for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
5747       if (!Attr->args_size()) {
5748         ForbiddenNullArgs.set();
5749         break;
5750       } else
5751         for (auto Idx : Attr->args()) {
5752           unsigned ASTIdx = Idx.getASTIndex();
5753           if (ASTIdx >= Args.size())
5754             continue;
5755           ForbiddenNullArgs[ASTIdx] = 1;
5756         }
5757     }
5758   }
5759   // FIXME: This is the wrong evaluation order for an assignment operator
5760   // called via operator syntax.
5761   for (unsigned Idx = 0; Idx < Args.size(); Idx++) {
5762     if (!Evaluate(ArgValues[Idx], Info, Args[Idx])) {
5763       // If we're checking for a potential constant expression, evaluate all
5764       // initializers even if some of them fail.
5765       if (!Info.noteFailure())
5766         return false;
5767       Success = false;
5768     } else if (!ForbiddenNullArgs.empty() &&
5769                ForbiddenNullArgs[Idx] &&
5770                ArgValues[Idx].isLValue() &&
5771                ArgValues[Idx].isNullPointer()) {
5772       Info.CCEDiag(Args[Idx], diag::note_non_null_attribute_failed);
5773       if (!Info.noteFailure())
5774         return false;
5775       Success = false;
5776     }
5777   }
5778   return Success;
5779 }
5780 
5781 /// Evaluate a function call.
5782 static bool HandleFunctionCall(SourceLocation CallLoc,
5783                                const FunctionDecl *Callee, const LValue *This,
5784                                ArrayRef<const Expr*> Args, const Stmt *Body,
5785                                EvalInfo &Info, APValue &Result,
5786                                const LValue *ResultSlot) {
5787   ArgVector ArgValues(Args.size());
5788   if (!EvaluateArgs(Args, ArgValues, Info, Callee))
5789     return false;
5790 
5791   if (!Info.CheckCallLimit(CallLoc))
5792     return false;
5793 
5794   CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
5795 
5796   // For a trivial copy or move assignment, perform an APValue copy. This is
5797   // essential for unions, where the operations performed by the assignment
5798   // operator cannot be represented as statements.
5799   //
5800   // Skip this for non-union classes with no fields; in that case, the defaulted
5801   // copy/move does not actually read the object.
5802   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
5803   if (MD && MD->isDefaulted() &&
5804       (MD->getParent()->isUnion() ||
5805        (MD->isTrivial() &&
5806         isReadByLvalueToRvalueConversion(MD->getParent())))) {
5807     assert(This &&
5808            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
5809     LValue RHS;
5810     RHS.setFrom(Info.Ctx, ArgValues[0]);
5811     APValue RHSValue;
5812     if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), RHS,
5813                                         RHSValue, MD->getParent()->isUnion()))
5814       return false;
5815     if (Info.getLangOpts().CPlusPlus20 && MD->isTrivial() &&
5816         !HandleUnionActiveMemberChange(Info, Args[0], *This))
5817       return false;
5818     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
5819                           RHSValue))
5820       return false;
5821     This->moveInto(Result);
5822     return true;
5823   } else if (MD && isLambdaCallOperator(MD)) {
5824     // We're in a lambda; determine the lambda capture field maps unless we're
5825     // just constexpr checking a lambda's call operator. constexpr checking is
5826     // done before the captures have been added to the closure object (unless
5827     // we're inferring constexpr-ness), so we don't have access to them in this
5828     // case. But since we don't need the captures to constexpr check, we can
5829     // just ignore them.
5830     if (!Info.checkingPotentialConstantExpression())
5831       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
5832                                         Frame.LambdaThisCaptureField);
5833   }
5834 
5835   StmtResult Ret = {Result, ResultSlot};
5836   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
5837   if (ESR == ESR_Succeeded) {
5838     if (Callee->getReturnType()->isVoidType())
5839       return true;
5840     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
5841   }
5842   return ESR == ESR_Returned;
5843 }
5844 
5845 /// Evaluate a constructor call.
5846 static bool HandleConstructorCall(const Expr *E, const LValue &This,
5847                                   APValue *ArgValues,
5848                                   const CXXConstructorDecl *Definition,
5849                                   EvalInfo &Info, APValue &Result) {
5850   SourceLocation CallLoc = E->getExprLoc();
5851   if (!Info.CheckCallLimit(CallLoc))
5852     return false;
5853 
5854   const CXXRecordDecl *RD = Definition->getParent();
5855   if (RD->getNumVBases()) {
5856     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
5857     return false;
5858   }
5859 
5860   EvalInfo::EvaluatingConstructorRAII EvalObj(
5861       Info,
5862       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
5863       RD->getNumBases());
5864   CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
5865 
5866   // FIXME: Creating an APValue just to hold a nonexistent return value is
5867   // wasteful.
5868   APValue RetVal;
5869   StmtResult Ret = {RetVal, nullptr};
5870 
5871   // If it's a delegating constructor, delegate.
5872   if (Definition->isDelegatingConstructor()) {
5873     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
5874     {
5875       FullExpressionRAII InitScope(Info);
5876       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
5877           !InitScope.destroy())
5878         return false;
5879     }
5880     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
5881   }
5882 
5883   // For a trivial copy or move constructor, perform an APValue copy. This is
5884   // essential for unions (or classes with anonymous union members), where the
5885   // operations performed by the constructor cannot be represented by
5886   // ctor-initializers.
5887   //
5888   // Skip this for empty non-union classes; we should not perform an
5889   // lvalue-to-rvalue conversion on them because their copy constructor does not
5890   // actually read them.
5891   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
5892       (Definition->getParent()->isUnion() ||
5893        (Definition->isTrivial() &&
5894         isReadByLvalueToRvalueConversion(Definition->getParent())))) {
5895     LValue RHS;
5896     RHS.setFrom(Info.Ctx, ArgValues[0]);
5897     return handleLValueToRValueConversion(
5898         Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
5899         RHS, Result, Definition->getParent()->isUnion());
5900   }
5901 
5902   // Reserve space for the struct members.
5903   if (!Result.hasValue()) {
5904     if (!RD->isUnion())
5905       Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
5906                        std::distance(RD->field_begin(), RD->field_end()));
5907     else
5908       // A union starts with no active member.
5909       Result = APValue((const FieldDecl*)nullptr);
5910   }
5911 
5912   if (RD->isInvalidDecl()) return false;
5913   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5914 
5915   // A scope for temporaries lifetime-extended by reference members.
5916   BlockScopeRAII LifetimeExtendedScope(Info);
5917 
5918   bool Success = true;
5919   unsigned BasesSeen = 0;
5920 #ifndef NDEBUG
5921   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
5922 #endif
5923   CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
5924   auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
5925     // We might be initializing the same field again if this is an indirect
5926     // field initialization.
5927     if (FieldIt == RD->field_end() ||
5928         FieldIt->getFieldIndex() > FD->getFieldIndex()) {
5929       assert(Indirect && "fields out of order?");
5930       return;
5931     }
5932 
5933     // Default-initialize any fields with no explicit initializer.
5934     for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
5935       assert(FieldIt != RD->field_end() && "missing field?");
5936       if (!FieldIt->isUnnamedBitfield())
5937         Success &= getDefaultInitValue(
5938             FieldIt->getType(),
5939             Result.getStructField(FieldIt->getFieldIndex()));
5940     }
5941     ++FieldIt;
5942   };
5943   for (const auto *I : Definition->inits()) {
5944     LValue Subobject = This;
5945     LValue SubobjectParent = This;
5946     APValue *Value = &Result;
5947 
5948     // Determine the subobject to initialize.
5949     FieldDecl *FD = nullptr;
5950     if (I->isBaseInitializer()) {
5951       QualType BaseType(I->getBaseClass(), 0);
5952 #ifndef NDEBUG
5953       // Non-virtual base classes are initialized in the order in the class
5954       // definition. We have already checked for virtual base classes.
5955       assert(!BaseIt->isVirtual() && "virtual base for literal type");
5956       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
5957              "base class initializers not in expected order");
5958       ++BaseIt;
5959 #endif
5960       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
5961                                   BaseType->getAsCXXRecordDecl(), &Layout))
5962         return false;
5963       Value = &Result.getStructBase(BasesSeen++);
5964     } else if ((FD = I->getMember())) {
5965       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
5966         return false;
5967       if (RD->isUnion()) {
5968         Result = APValue(FD);
5969         Value = &Result.getUnionValue();
5970       } else {
5971         SkipToField(FD, false);
5972         Value = &Result.getStructField(FD->getFieldIndex());
5973       }
5974     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
5975       // Walk the indirect field decl's chain to find the object to initialize,
5976       // and make sure we've initialized every step along it.
5977       auto IndirectFieldChain = IFD->chain();
5978       for (auto *C : IndirectFieldChain) {
5979         FD = cast<FieldDecl>(C);
5980         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
5981         // Switch the union field if it differs. This happens if we had
5982         // preceding zero-initialization, and we're now initializing a union
5983         // subobject other than the first.
5984         // FIXME: In this case, the values of the other subobjects are
5985         // specified, since zero-initialization sets all padding bits to zero.
5986         if (!Value->hasValue() ||
5987             (Value->isUnion() && Value->getUnionField() != FD)) {
5988           if (CD->isUnion())
5989             *Value = APValue(FD);
5990           else
5991             // FIXME: This immediately starts the lifetime of all members of
5992             // an anonymous struct. It would be preferable to strictly start
5993             // member lifetime in initialization order.
5994             Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
5995         }
5996         // Store Subobject as its parent before updating it for the last element
5997         // in the chain.
5998         if (C == IndirectFieldChain.back())
5999           SubobjectParent = Subobject;
6000         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6001           return false;
6002         if (CD->isUnion())
6003           Value = &Value->getUnionValue();
6004         else {
6005           if (C == IndirectFieldChain.front() && !RD->isUnion())
6006             SkipToField(FD, true);
6007           Value = &Value->getStructField(FD->getFieldIndex());
6008         }
6009       }
6010     } else {
6011       llvm_unreachable("unknown base initializer kind");
6012     }
6013 
6014     // Need to override This for implicit field initializers as in this case
6015     // This refers to innermost anonymous struct/union containing initializer,
6016     // not to currently constructed class.
6017     const Expr *Init = I->getInit();
6018     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6019                                   isa<CXXDefaultInitExpr>(Init));
6020     FullExpressionRAII InitScope(Info);
6021     if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6022         (FD && FD->isBitField() &&
6023          !truncateBitfieldValue(Info, Init, *Value, FD))) {
6024       // If we're checking for a potential constant expression, evaluate all
6025       // initializers even if some of them fail.
6026       if (!Info.noteFailure())
6027         return false;
6028       Success = false;
6029     }
6030 
6031     // This is the point at which the dynamic type of the object becomes this
6032     // class type.
6033     if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6034       EvalObj.finishedConstructingBases();
6035   }
6036 
6037   // Default-initialize any remaining fields.
6038   if (!RD->isUnion()) {
6039     for (; FieldIt != RD->field_end(); ++FieldIt) {
6040       if (!FieldIt->isUnnamedBitfield())
6041         Success &= getDefaultInitValue(
6042             FieldIt->getType(),
6043             Result.getStructField(FieldIt->getFieldIndex()));
6044     }
6045   }
6046 
6047   EvalObj.finishedConstructingFields();
6048 
6049   return Success &&
6050          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6051          LifetimeExtendedScope.destroy();
6052 }
6053 
6054 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6055                                   ArrayRef<const Expr*> Args,
6056                                   const CXXConstructorDecl *Definition,
6057                                   EvalInfo &Info, APValue &Result) {
6058   ArgVector ArgValues(Args.size());
6059   if (!EvaluateArgs(Args, ArgValues, Info, Definition))
6060     return false;
6061 
6062   return HandleConstructorCall(E, This, ArgValues.data(), Definition,
6063                                Info, Result);
6064 }
6065 
6066 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
6067                                   const LValue &This, APValue &Value,
6068                                   QualType T) {
6069   // Objects can only be destroyed while they're within their lifetimes.
6070   // FIXME: We have no representation for whether an object of type nullptr_t
6071   // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6072   // as indeterminate instead?
6073   if (Value.isAbsent() && !T->isNullPtrType()) {
6074     APValue Printable;
6075     This.moveInto(Printable);
6076     Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
6077       << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6078     return false;
6079   }
6080 
6081   // Invent an expression for location purposes.
6082   // FIXME: We shouldn't need to do this.
6083   OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue);
6084 
6085   // For arrays, destroy elements right-to-left.
6086   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6087     uint64_t Size = CAT->getSize().getZExtValue();
6088     QualType ElemT = CAT->getElementType();
6089 
6090     LValue ElemLV = This;
6091     ElemLV.addArray(Info, &LocE, CAT);
6092     if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6093       return false;
6094 
6095     // Ensure that we have actual array elements available to destroy; the
6096     // destructors might mutate the value, so we can't run them on the array
6097     // filler.
6098     if (Size && Size > Value.getArrayInitializedElts())
6099       expandArray(Value, Value.getArraySize() - 1);
6100 
6101     for (; Size != 0; --Size) {
6102       APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6103       if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6104           !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
6105         return false;
6106     }
6107 
6108     // End the lifetime of this array now.
6109     Value = APValue();
6110     return true;
6111   }
6112 
6113   const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6114   if (!RD) {
6115     if (T.isDestructedType()) {
6116       Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
6117       return false;
6118     }
6119 
6120     Value = APValue();
6121     return true;
6122   }
6123 
6124   if (RD->getNumVBases()) {
6125     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6126     return false;
6127   }
6128 
6129   const CXXDestructorDecl *DD = RD->getDestructor();
6130   if (!DD && !RD->hasTrivialDestructor()) {
6131     Info.FFDiag(CallLoc);
6132     return false;
6133   }
6134 
6135   if (!DD || DD->isTrivial() ||
6136       (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6137     // A trivial destructor just ends the lifetime of the object. Check for
6138     // this case before checking for a body, because we might not bother
6139     // building a body for a trivial destructor. Note that it doesn't matter
6140     // whether the destructor is constexpr in this case; all trivial
6141     // destructors are constexpr.
6142     //
6143     // If an anonymous union would be destroyed, some enclosing destructor must
6144     // have been explicitly defined, and the anonymous union destruction should
6145     // have no effect.
6146     Value = APValue();
6147     return true;
6148   }
6149 
6150   if (!Info.CheckCallLimit(CallLoc))
6151     return false;
6152 
6153   const FunctionDecl *Definition = nullptr;
6154   const Stmt *Body = DD->getBody(Definition);
6155 
6156   if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
6157     return false;
6158 
6159   CallStackFrame Frame(Info, CallLoc, Definition, &This, nullptr);
6160 
6161   // We're now in the period of destruction of this object.
6162   unsigned BasesLeft = RD->getNumBases();
6163   EvalInfo::EvaluatingDestructorRAII EvalObj(
6164       Info,
6165       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6166   if (!EvalObj.DidInsert) {
6167     // C++2a [class.dtor]p19:
6168     //   the behavior is undefined if the destructor is invoked for an object
6169     //   whose lifetime has ended
6170     // (Note that formally the lifetime ends when the period of destruction
6171     // begins, even though certain uses of the object remain valid until the
6172     // period of destruction ends.)
6173     Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
6174     return false;
6175   }
6176 
6177   // FIXME: Creating an APValue just to hold a nonexistent return value is
6178   // wasteful.
6179   APValue RetVal;
6180   StmtResult Ret = {RetVal, nullptr};
6181   if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6182     return false;
6183 
6184   // A union destructor does not implicitly destroy its members.
6185   if (RD->isUnion())
6186     return true;
6187 
6188   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6189 
6190   // We don't have a good way to iterate fields in reverse, so collect all the
6191   // fields first and then walk them backwards.
6192   SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
6193   for (const FieldDecl *FD : llvm::reverse(Fields)) {
6194     if (FD->isUnnamedBitfield())
6195       continue;
6196 
6197     LValue Subobject = This;
6198     if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6199       return false;
6200 
6201     APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6202     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6203                                FD->getType()))
6204       return false;
6205   }
6206 
6207   if (BasesLeft != 0)
6208     EvalObj.startedDestroyingBases();
6209 
6210   // Destroy base classes in reverse order.
6211   for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6212     --BasesLeft;
6213 
6214     QualType BaseType = Base.getType();
6215     LValue Subobject = This;
6216     if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
6217                                 BaseType->getAsCXXRecordDecl(), &Layout))
6218       return false;
6219 
6220     APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
6221     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6222                                BaseType))
6223       return false;
6224   }
6225   assert(BasesLeft == 0 && "NumBases was wrong?");
6226 
6227   // The period of destruction ends now. The object is gone.
6228   Value = APValue();
6229   return true;
6230 }
6231 
6232 namespace {
6233 struct DestroyObjectHandler {
6234   EvalInfo &Info;
6235   const Expr *E;
6236   const LValue &This;
6237   const AccessKinds AccessKind;
6238 
6239   typedef bool result_type;
6240   bool failed() { return false; }
6241   bool found(APValue &Subobj, QualType SubobjType) {
6242     return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
6243                                  SubobjType);
6244   }
6245   bool found(APSInt &Value, QualType SubobjType) {
6246     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6247     return false;
6248   }
6249   bool found(APFloat &Value, QualType SubobjType) {
6250     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6251     return false;
6252   }
6253 };
6254 }
6255 
6256 /// Perform a destructor or pseudo-destructor call on the given object, which
6257 /// might in general not be a complete object.
6258 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6259                               const LValue &This, QualType ThisType) {
6260   CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6261   DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6262   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6263 }
6264 
6265 /// Destroy and end the lifetime of the given complete object.
6266 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6267                               APValue::LValueBase LVBase, APValue &Value,
6268                               QualType T) {
6269   // If we've had an unmodeled side-effect, we can't rely on mutable state
6270   // (such as the object we're about to destroy) being correct.
6271   if (Info.EvalStatus.HasSideEffects)
6272     return false;
6273 
6274   LValue LV;
6275   LV.set({LVBase});
6276   return HandleDestructionImpl(Info, Loc, LV, Value, T);
6277 }
6278 
6279 /// Perform a call to 'perator new' or to `__builtin_operator_new'.
6280 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6281                                   LValue &Result) {
6282   if (Info.checkingPotentialConstantExpression() ||
6283       Info.SpeculativeEvaluationDepth)
6284     return false;
6285 
6286   // This is permitted only within a call to std::allocator<T>::allocate.
6287   auto Caller = Info.getStdAllocatorCaller("allocate");
6288   if (!Caller) {
6289     Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
6290                                      ? diag::note_constexpr_new_untyped
6291                                      : diag::note_constexpr_new);
6292     return false;
6293   }
6294 
6295   QualType ElemType = Caller.ElemType;
6296   if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6297     Info.FFDiag(E->getExprLoc(),
6298                 diag::note_constexpr_new_not_complete_object_type)
6299         << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6300     return false;
6301   }
6302 
6303   APSInt ByteSize;
6304   if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6305     return false;
6306   bool IsNothrow = false;
6307   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6308     EvaluateIgnoredValue(Info, E->getArg(I));
6309     IsNothrow |= E->getType()->isNothrowT();
6310   }
6311 
6312   CharUnits ElemSize;
6313   if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6314     return false;
6315   APInt Size, Remainder;
6316   APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6317   APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6318   if (Remainder != 0) {
6319     // This likely indicates a bug in the implementation of 'std::allocator'.
6320     Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6321         << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6322     return false;
6323   }
6324 
6325   if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
6326     if (IsNothrow) {
6327       Result.setNull(Info.Ctx, E->getType());
6328       return true;
6329     }
6330 
6331     Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
6332     return false;
6333   }
6334 
6335   QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
6336                                                      ArrayType::Normal, 0);
6337   APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6338   *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6339   Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6340   return true;
6341 }
6342 
6343 static bool hasVirtualDestructor(QualType T) {
6344   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6345     if (CXXDestructorDecl *DD = RD->getDestructor())
6346       return DD->isVirtual();
6347   return false;
6348 }
6349 
6350 static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6351   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6352     if (CXXDestructorDecl *DD = RD->getDestructor())
6353       return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6354   return nullptr;
6355 }
6356 
6357 /// Check that the given object is a suitable pointer to a heap allocation that
6358 /// still exists and is of the right kind for the purpose of a deletion.
6359 ///
6360 /// On success, returns the heap allocation to deallocate. On failure, produces
6361 /// a diagnostic and returns None.
6362 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6363                                             const LValue &Pointer,
6364                                             DynAlloc::Kind DeallocKind) {
6365   auto PointerAsString = [&] {
6366     return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6367   };
6368 
6369   DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6370   if (!DA) {
6371     Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6372         << PointerAsString();
6373     if (Pointer.Base)
6374       NoteLValueLocation(Info, Pointer.Base);
6375     return None;
6376   }
6377 
6378   Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6379   if (!Alloc) {
6380     Info.FFDiag(E, diag::note_constexpr_double_delete);
6381     return None;
6382   }
6383 
6384   QualType AllocType = Pointer.Base.getDynamicAllocType();
6385   if (DeallocKind != (*Alloc)->getKind()) {
6386     Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6387         << DeallocKind << (*Alloc)->getKind() << AllocType;
6388     NoteLValueLocation(Info, Pointer.Base);
6389     return None;
6390   }
6391 
6392   bool Subobject = false;
6393   if (DeallocKind == DynAlloc::New) {
6394     Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6395                 Pointer.Designator.isOnePastTheEnd();
6396   } else {
6397     Subobject = Pointer.Designator.Entries.size() != 1 ||
6398                 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6399   }
6400   if (Subobject) {
6401     Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6402         << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6403     return None;
6404   }
6405 
6406   return Alloc;
6407 }
6408 
6409 // Perform a call to 'operator delete' or '__builtin_operator_delete'.
6410 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6411   if (Info.checkingPotentialConstantExpression() ||
6412       Info.SpeculativeEvaluationDepth)
6413     return false;
6414 
6415   // This is permitted only within a call to std::allocator<T>::deallocate.
6416   if (!Info.getStdAllocatorCaller("deallocate")) {
6417     Info.FFDiag(E->getExprLoc());
6418     return true;
6419   }
6420 
6421   LValue Pointer;
6422   if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6423     return false;
6424   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6425     EvaluateIgnoredValue(Info, E->getArg(I));
6426 
6427   if (Pointer.Designator.Invalid)
6428     return false;
6429 
6430   // Deleting a null pointer has no effect.
6431   if (Pointer.isNullPointer())
6432     return true;
6433 
6434   if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6435     return false;
6436 
6437   Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6438   return true;
6439 }
6440 
6441 //===----------------------------------------------------------------------===//
6442 // Generic Evaluation
6443 //===----------------------------------------------------------------------===//
6444 namespace {
6445 
6446 class BitCastBuffer {
6447   // FIXME: We're going to need bit-level granularity when we support
6448   // bit-fields.
6449   // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6450   // we don't support a host or target where that is the case. Still, we should
6451   // use a more generic type in case we ever do.
6452   SmallVector<Optional<unsigned char>, 32> Bytes;
6453 
6454   static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6455                 "Need at least 8 bit unsigned char");
6456 
6457   bool TargetIsLittleEndian;
6458 
6459 public:
6460   BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6461       : Bytes(Width.getQuantity()),
6462         TargetIsLittleEndian(TargetIsLittleEndian) {}
6463 
6464   LLVM_NODISCARD
6465   bool readObject(CharUnits Offset, CharUnits Width,
6466                   SmallVectorImpl<unsigned char> &Output) const {
6467     for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6468       // If a byte of an integer is uninitialized, then the whole integer is
6469       // uninitalized.
6470       if (!Bytes[I.getQuantity()])
6471         return false;
6472       Output.push_back(*Bytes[I.getQuantity()]);
6473     }
6474     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6475       std::reverse(Output.begin(), Output.end());
6476     return true;
6477   }
6478 
6479   void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6480     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6481       std::reverse(Input.begin(), Input.end());
6482 
6483     size_t Index = 0;
6484     for (unsigned char Byte : Input) {
6485       assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
6486       Bytes[Offset.getQuantity() + Index] = Byte;
6487       ++Index;
6488     }
6489   }
6490 
6491   size_t size() { return Bytes.size(); }
6492 };
6493 
6494 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6495 /// target would represent the value at runtime.
6496 class APValueToBufferConverter {
6497   EvalInfo &Info;
6498   BitCastBuffer Buffer;
6499   const CastExpr *BCE;
6500 
6501   APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6502                            const CastExpr *BCE)
6503       : Info(Info),
6504         Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6505         BCE(BCE) {}
6506 
6507   bool visit(const APValue &Val, QualType Ty) {
6508     return visit(Val, Ty, CharUnits::fromQuantity(0));
6509   }
6510 
6511   // Write out Val with type Ty into Buffer starting at Offset.
6512   bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6513     assert((size_t)Offset.getQuantity() <= Buffer.size());
6514 
6515     // As a special case, nullptr_t has an indeterminate value.
6516     if (Ty->isNullPtrType())
6517       return true;
6518 
6519     // Dig through Src to find the byte at SrcOffset.
6520     switch (Val.getKind()) {
6521     case APValue::Indeterminate:
6522     case APValue::None:
6523       return true;
6524 
6525     case APValue::Int:
6526       return visitInt(Val.getInt(), Ty, Offset);
6527     case APValue::Float:
6528       return visitFloat(Val.getFloat(), Ty, Offset);
6529     case APValue::Array:
6530       return visitArray(Val, Ty, Offset);
6531     case APValue::Struct:
6532       return visitRecord(Val, Ty, Offset);
6533 
6534     case APValue::ComplexInt:
6535     case APValue::ComplexFloat:
6536     case APValue::Vector:
6537     case APValue::FixedPoint:
6538       // FIXME: We should support these.
6539 
6540     case APValue::Union:
6541     case APValue::MemberPointer:
6542     case APValue::AddrLabelDiff: {
6543       Info.FFDiag(BCE->getBeginLoc(),
6544                   diag::note_constexpr_bit_cast_unsupported_type)
6545           << Ty;
6546       return false;
6547     }
6548 
6549     case APValue::LValue:
6550       llvm_unreachable("LValue subobject in bit_cast?");
6551     }
6552     llvm_unreachable("Unhandled APValue::ValueKind");
6553   }
6554 
6555   bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
6556     const RecordDecl *RD = Ty->getAsRecordDecl();
6557     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6558 
6559     // Visit the base classes.
6560     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6561       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6562         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6563         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6564 
6565         if (!visitRecord(Val.getStructBase(I), BS.getType(),
6566                          Layout.getBaseClassOffset(BaseDecl) + Offset))
6567           return false;
6568       }
6569     }
6570 
6571     // Visit the fields.
6572     unsigned FieldIdx = 0;
6573     for (FieldDecl *FD : RD->fields()) {
6574       if (FD->isBitField()) {
6575         Info.FFDiag(BCE->getBeginLoc(),
6576                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6577         return false;
6578       }
6579 
6580       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6581 
6582       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
6583              "only bit-fields can have sub-char alignment");
6584       CharUnits FieldOffset =
6585           Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
6586       QualType FieldTy = FD->getType();
6587       if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
6588         return false;
6589       ++FieldIdx;
6590     }
6591 
6592     return true;
6593   }
6594 
6595   bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
6596     const auto *CAT =
6597         dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
6598     if (!CAT)
6599       return false;
6600 
6601     CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
6602     unsigned NumInitializedElts = Val.getArrayInitializedElts();
6603     unsigned ArraySize = Val.getArraySize();
6604     // First, initialize the initialized elements.
6605     for (unsigned I = 0; I != NumInitializedElts; ++I) {
6606       const APValue &SubObj = Val.getArrayInitializedElt(I);
6607       if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
6608         return false;
6609     }
6610 
6611     // Next, initialize the rest of the array using the filler.
6612     if (Val.hasArrayFiller()) {
6613       const APValue &Filler = Val.getArrayFiller();
6614       for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
6615         if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
6616           return false;
6617       }
6618     }
6619 
6620     return true;
6621   }
6622 
6623   bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
6624     CharUnits Width = Info.Ctx.getTypeSizeInChars(Ty);
6625     SmallVector<unsigned char, 8> Bytes(Width.getQuantity());
6626     llvm::StoreIntToMemory(Val, &*Bytes.begin(), Width.getQuantity());
6627     Buffer.writeObject(Offset, Bytes);
6628     return true;
6629   }
6630 
6631   bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
6632     APSInt AsInt(Val.bitcastToAPInt());
6633     return visitInt(AsInt, Ty, Offset);
6634   }
6635 
6636 public:
6637   static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
6638                                          const CastExpr *BCE) {
6639     CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
6640     APValueToBufferConverter Converter(Info, DstSize, BCE);
6641     if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
6642       return None;
6643     return Converter.Buffer;
6644   }
6645 };
6646 
6647 /// Write an BitCastBuffer into an APValue.
6648 class BufferToAPValueConverter {
6649   EvalInfo &Info;
6650   const BitCastBuffer &Buffer;
6651   const CastExpr *BCE;
6652 
6653   BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
6654                            const CastExpr *BCE)
6655       : Info(Info), Buffer(Buffer), BCE(BCE) {}
6656 
6657   // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
6658   // with an invalid type, so anything left is a deficiency on our part (FIXME).
6659   // Ideally this will be unreachable.
6660   llvm::NoneType unsupportedType(QualType Ty) {
6661     Info.FFDiag(BCE->getBeginLoc(),
6662                 diag::note_constexpr_bit_cast_unsupported_type)
6663         << Ty;
6664     return None;
6665   }
6666 
6667   Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
6668                           const EnumType *EnumSugar = nullptr) {
6669     if (T->isNullPtrType()) {
6670       uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
6671       return APValue((Expr *)nullptr,
6672                      /*Offset=*/CharUnits::fromQuantity(NullValue),
6673                      APValue::NoLValuePath{}, /*IsNullPtr=*/true);
6674     }
6675 
6676     CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
6677     SmallVector<uint8_t, 8> Bytes;
6678     if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
6679       // If this is std::byte or unsigned char, then its okay to store an
6680       // indeterminate value.
6681       bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
6682       bool IsUChar =
6683           !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
6684                          T->isSpecificBuiltinType(BuiltinType::Char_U));
6685       if (!IsStdByte && !IsUChar) {
6686         QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
6687         Info.FFDiag(BCE->getExprLoc(),
6688                     diag::note_constexpr_bit_cast_indet_dest)
6689             << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
6690         return None;
6691       }
6692 
6693       return APValue::IndeterminateValue();
6694     }
6695 
6696     APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
6697     llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
6698 
6699     if (T->isIntegralOrEnumerationType()) {
6700       Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
6701       return APValue(Val);
6702     }
6703 
6704     if (T->isRealFloatingType()) {
6705       const llvm::fltSemantics &Semantics =
6706           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
6707       return APValue(APFloat(Semantics, Val));
6708     }
6709 
6710     return unsupportedType(QualType(T, 0));
6711   }
6712 
6713   Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
6714     const RecordDecl *RD = RTy->getAsRecordDecl();
6715     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6716 
6717     unsigned NumBases = 0;
6718     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6719       NumBases = CXXRD->getNumBases();
6720 
6721     APValue ResultVal(APValue::UninitStruct(), NumBases,
6722                       std::distance(RD->field_begin(), RD->field_end()));
6723 
6724     // Visit the base classes.
6725     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6726       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6727         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6728         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6729         if (BaseDecl->isEmpty() ||
6730             Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
6731           continue;
6732 
6733         Optional<APValue> SubObj = visitType(
6734             BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
6735         if (!SubObj)
6736           return None;
6737         ResultVal.getStructBase(I) = *SubObj;
6738       }
6739     }
6740 
6741     // Visit the fields.
6742     unsigned FieldIdx = 0;
6743     for (FieldDecl *FD : RD->fields()) {
6744       // FIXME: We don't currently support bit-fields. A lot of the logic for
6745       // this is in CodeGen, so we need to factor it around.
6746       if (FD->isBitField()) {
6747         Info.FFDiag(BCE->getBeginLoc(),
6748                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6749         return None;
6750       }
6751 
6752       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6753       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
6754 
6755       CharUnits FieldOffset =
6756           CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
6757           Offset;
6758       QualType FieldTy = FD->getType();
6759       Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
6760       if (!SubObj)
6761         return None;
6762       ResultVal.getStructField(FieldIdx) = *SubObj;
6763       ++FieldIdx;
6764     }
6765 
6766     return ResultVal;
6767   }
6768 
6769   Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
6770     QualType RepresentationType = Ty->getDecl()->getIntegerType();
6771     assert(!RepresentationType.isNull() &&
6772            "enum forward decl should be caught by Sema");
6773     const auto *AsBuiltin =
6774         RepresentationType.getCanonicalType()->castAs<BuiltinType>();
6775     // Recurse into the underlying type. Treat std::byte transparently as
6776     // unsigned char.
6777     return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
6778   }
6779 
6780   Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
6781     size_t Size = Ty->getSize().getLimitedValue();
6782     CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
6783 
6784     APValue ArrayValue(APValue::UninitArray(), Size, Size);
6785     for (size_t I = 0; I != Size; ++I) {
6786       Optional<APValue> ElementValue =
6787           visitType(Ty->getElementType(), Offset + I * ElementWidth);
6788       if (!ElementValue)
6789         return None;
6790       ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
6791     }
6792 
6793     return ArrayValue;
6794   }
6795 
6796   Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
6797     return unsupportedType(QualType(Ty, 0));
6798   }
6799 
6800   Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
6801     QualType Can = Ty.getCanonicalType();
6802 
6803     switch (Can->getTypeClass()) {
6804 #define TYPE(Class, Base)                                                      \
6805   case Type::Class:                                                            \
6806     return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
6807 #define ABSTRACT_TYPE(Class, Base)
6808 #define NON_CANONICAL_TYPE(Class, Base)                                        \
6809   case Type::Class:                                                            \
6810     llvm_unreachable("non-canonical type should be impossible!");
6811 #define DEPENDENT_TYPE(Class, Base)                                            \
6812   case Type::Class:                                                            \
6813     llvm_unreachable(                                                          \
6814         "dependent types aren't supported in the constant evaluator!");
6815 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)                            \
6816   case Type::Class:                                                            \
6817     llvm_unreachable("either dependent or not canonical!");
6818 #include "clang/AST/TypeNodes.inc"
6819     }
6820     llvm_unreachable("Unhandled Type::TypeClass");
6821   }
6822 
6823 public:
6824   // Pull out a full value of type DstType.
6825   static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
6826                                    const CastExpr *BCE) {
6827     BufferToAPValueConverter Converter(Info, Buffer, BCE);
6828     return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
6829   }
6830 };
6831 
6832 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
6833                                                  QualType Ty, EvalInfo *Info,
6834                                                  const ASTContext &Ctx,
6835                                                  bool CheckingDest) {
6836   Ty = Ty.getCanonicalType();
6837 
6838   auto diag = [&](int Reason) {
6839     if (Info)
6840       Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
6841           << CheckingDest << (Reason == 4) << Reason;
6842     return false;
6843   };
6844   auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
6845     if (Info)
6846       Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
6847           << NoteTy << Construct << Ty;
6848     return false;
6849   };
6850 
6851   if (Ty->isUnionType())
6852     return diag(0);
6853   if (Ty->isPointerType())
6854     return diag(1);
6855   if (Ty->isMemberPointerType())
6856     return diag(2);
6857   if (Ty.isVolatileQualified())
6858     return diag(3);
6859 
6860   if (RecordDecl *Record = Ty->getAsRecordDecl()) {
6861     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
6862       for (CXXBaseSpecifier &BS : CXXRD->bases())
6863         if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
6864                                                   CheckingDest))
6865           return note(1, BS.getType(), BS.getBeginLoc());
6866     }
6867     for (FieldDecl *FD : Record->fields()) {
6868       if (FD->getType()->isReferenceType())
6869         return diag(4);
6870       if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
6871                                                 CheckingDest))
6872         return note(0, FD->getType(), FD->getBeginLoc());
6873     }
6874   }
6875 
6876   if (Ty->isArrayType() &&
6877       !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
6878                                             Info, Ctx, CheckingDest))
6879     return false;
6880 
6881   return true;
6882 }
6883 
6884 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
6885                                              const ASTContext &Ctx,
6886                                              const CastExpr *BCE) {
6887   bool DestOK = checkBitCastConstexprEligibilityType(
6888       BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
6889   bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
6890                                 BCE->getBeginLoc(),
6891                                 BCE->getSubExpr()->getType(), Info, Ctx, false);
6892   return SourceOK;
6893 }
6894 
6895 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
6896                                         APValue &SourceValue,
6897                                         const CastExpr *BCE) {
6898   assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
6899          "no host or target supports non 8-bit chars");
6900   assert(SourceValue.isLValue() &&
6901          "LValueToRValueBitcast requires an lvalue operand!");
6902 
6903   if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
6904     return false;
6905 
6906   LValue SourceLValue;
6907   APValue SourceRValue;
6908   SourceLValue.setFrom(Info.Ctx, SourceValue);
6909   if (!handleLValueToRValueConversion(
6910           Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
6911           SourceRValue, /*WantObjectRepresentation=*/true))
6912     return false;
6913 
6914   // Read out SourceValue into a char buffer.
6915   Optional<BitCastBuffer> Buffer =
6916       APValueToBufferConverter::convert(Info, SourceRValue, BCE);
6917   if (!Buffer)
6918     return false;
6919 
6920   // Write out the buffer into a new APValue.
6921   Optional<APValue> MaybeDestValue =
6922       BufferToAPValueConverter::convert(Info, *Buffer, BCE);
6923   if (!MaybeDestValue)
6924     return false;
6925 
6926   DestValue = std::move(*MaybeDestValue);
6927   return true;
6928 }
6929 
6930 template <class Derived>
6931 class ExprEvaluatorBase
6932   : public ConstStmtVisitor<Derived, bool> {
6933 private:
6934   Derived &getDerived() { return static_cast<Derived&>(*this); }
6935   bool DerivedSuccess(const APValue &V, const Expr *E) {
6936     return getDerived().Success(V, E);
6937   }
6938   bool DerivedZeroInitialization(const Expr *E) {
6939     return getDerived().ZeroInitialization(E);
6940   }
6941 
6942   // Check whether a conditional operator with a non-constant condition is a
6943   // potential constant expression. If neither arm is a potential constant
6944   // expression, then the conditional operator is not either.
6945   template<typename ConditionalOperator>
6946   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
6947     assert(Info.checkingPotentialConstantExpression());
6948 
6949     // Speculatively evaluate both arms.
6950     SmallVector<PartialDiagnosticAt, 8> Diag;
6951     {
6952       SpeculativeEvaluationRAII Speculate(Info, &Diag);
6953       StmtVisitorTy::Visit(E->getFalseExpr());
6954       if (Diag.empty())
6955         return;
6956     }
6957 
6958     {
6959       SpeculativeEvaluationRAII Speculate(Info, &Diag);
6960       Diag.clear();
6961       StmtVisitorTy::Visit(E->getTrueExpr());
6962       if (Diag.empty())
6963         return;
6964     }
6965 
6966     Error(E, diag::note_constexpr_conditional_never_const);
6967   }
6968 
6969 
6970   template<typename ConditionalOperator>
6971   bool HandleConditionalOperator(const ConditionalOperator *E) {
6972     bool BoolResult;
6973     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
6974       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
6975         CheckPotentialConstantConditional(E);
6976         return false;
6977       }
6978       if (Info.noteFailure()) {
6979         StmtVisitorTy::Visit(E->getTrueExpr());
6980         StmtVisitorTy::Visit(E->getFalseExpr());
6981       }
6982       return false;
6983     }
6984 
6985     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
6986     return StmtVisitorTy::Visit(EvalExpr);
6987   }
6988 
6989 protected:
6990   EvalInfo &Info;
6991   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
6992   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
6993 
6994   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
6995     return Info.CCEDiag(E, D);
6996   }
6997 
6998   bool ZeroInitialization(const Expr *E) { return Error(E); }
6999 
7000 public:
7001   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
7002 
7003   EvalInfo &getEvalInfo() { return Info; }
7004 
7005   /// Report an evaluation error. This should only be called when an error is
7006   /// first discovered. When propagating an error, just return false.
7007   bool Error(const Expr *E, diag::kind D) {
7008     Info.FFDiag(E, D);
7009     return false;
7010   }
7011   bool Error(const Expr *E) {
7012     return Error(E, diag::note_invalid_subexpr_in_const_expr);
7013   }
7014 
7015   bool VisitStmt(const Stmt *) {
7016     llvm_unreachable("Expression evaluator should not be called on stmts");
7017   }
7018   bool VisitExpr(const Expr *E) {
7019     return Error(E);
7020   }
7021 
7022   bool VisitConstantExpr(const ConstantExpr *E) {
7023     if (E->hasAPValueResult())
7024       return DerivedSuccess(E->getAPValueResult(), E);
7025 
7026     return StmtVisitorTy::Visit(E->getSubExpr());
7027   }
7028 
7029   bool VisitParenExpr(const ParenExpr *E)
7030     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7031   bool VisitUnaryExtension(const UnaryOperator *E)
7032     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7033   bool VisitUnaryPlus(const UnaryOperator *E)
7034     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7035   bool VisitChooseExpr(const ChooseExpr *E)
7036     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
7037   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
7038     { return StmtVisitorTy::Visit(E->getResultExpr()); }
7039   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
7040     { return StmtVisitorTy::Visit(E->getReplacement()); }
7041   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7042     TempVersionRAII RAII(*Info.CurrentCall);
7043     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7044     return StmtVisitorTy::Visit(E->getExpr());
7045   }
7046   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7047     TempVersionRAII RAII(*Info.CurrentCall);
7048     // The initializer may not have been parsed yet, or might be erroneous.
7049     if (!E->getExpr())
7050       return Error(E);
7051     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7052     return StmtVisitorTy::Visit(E->getExpr());
7053   }
7054 
7055   bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7056     FullExpressionRAII Scope(Info);
7057     return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
7058   }
7059 
7060   // Temporaries are registered when created, so we don't care about
7061   // CXXBindTemporaryExpr.
7062   bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7063     return StmtVisitorTy::Visit(E->getSubExpr());
7064   }
7065 
7066   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7067     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7068     return static_cast<Derived*>(this)->VisitCastExpr(E);
7069   }
7070   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7071     if (!Info.Ctx.getLangOpts().CPlusPlus20)
7072       CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
7073     return static_cast<Derived*>(this)->VisitCastExpr(E);
7074   }
7075   bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7076     return static_cast<Derived*>(this)->VisitCastExpr(E);
7077   }
7078 
7079   bool VisitBinaryOperator(const BinaryOperator *E) {
7080     switch (E->getOpcode()) {
7081     default:
7082       return Error(E);
7083 
7084     case BO_Comma:
7085       VisitIgnoredValue(E->getLHS());
7086       return StmtVisitorTy::Visit(E->getRHS());
7087 
7088     case BO_PtrMemD:
7089     case BO_PtrMemI: {
7090       LValue Obj;
7091       if (!HandleMemberPointerAccess(Info, E, Obj))
7092         return false;
7093       APValue Result;
7094       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7095         return false;
7096       return DerivedSuccess(Result, E);
7097     }
7098     }
7099   }
7100 
7101   bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
7102     return StmtVisitorTy::Visit(E->getSemanticForm());
7103   }
7104 
7105   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7106     // Evaluate and cache the common expression. We treat it as a temporary,
7107     // even though it's not quite the same thing.
7108     LValue CommonLV;
7109     if (!Evaluate(Info.CurrentCall->createTemporary(
7110                       E->getOpaqueValue(),
7111                       getStorageType(Info.Ctx, E->getOpaqueValue()), false,
7112                       CommonLV),
7113                   Info, E->getCommon()))
7114       return false;
7115 
7116     return HandleConditionalOperator(E);
7117   }
7118 
7119   bool VisitConditionalOperator(const ConditionalOperator *E) {
7120     bool IsBcpCall = false;
7121     // If the condition (ignoring parens) is a __builtin_constant_p call,
7122     // the result is a constant expression if it can be folded without
7123     // side-effects. This is an important GNU extension. See GCC PR38377
7124     // for discussion.
7125     if (const CallExpr *CallCE =
7126           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7127       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7128         IsBcpCall = true;
7129 
7130     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7131     // constant expression; we can't check whether it's potentially foldable.
7132     // FIXME: We should instead treat __builtin_constant_p as non-constant if
7133     // it would return 'false' in this mode.
7134     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
7135       return false;
7136 
7137     FoldConstant Fold(Info, IsBcpCall);
7138     if (!HandleConditionalOperator(E)) {
7139       Fold.keepDiagnostics();
7140       return false;
7141     }
7142 
7143     return true;
7144   }
7145 
7146   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7147     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
7148       return DerivedSuccess(*Value, E);
7149 
7150     const Expr *Source = E->getSourceExpr();
7151     if (!Source)
7152       return Error(E);
7153     if (Source == E) { // sanity checking.
7154       assert(0 && "OpaqueValueExpr recursively refers to itself");
7155       return Error(E);
7156     }
7157     return StmtVisitorTy::Visit(Source);
7158   }
7159 
7160   bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7161     for (const Expr *SemE : E->semantics()) {
7162       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7163         // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7164         // result expression: there could be two different LValues that would
7165         // refer to the same object in that case, and we can't model that.
7166         if (SemE == E->getResultExpr())
7167           return Error(E);
7168 
7169         // Unique OVEs get evaluated if and when we encounter them when
7170         // emitting the rest of the semantic form, rather than eagerly.
7171         if (OVE->isUnique())
7172           continue;
7173 
7174         LValue LV;
7175         if (!Evaluate(Info.CurrentCall->createTemporary(
7176                           OVE, getStorageType(Info.Ctx, OVE), false, LV),
7177                       Info, OVE->getSourceExpr()))
7178           return false;
7179       } else if (SemE == E->getResultExpr()) {
7180         if (!StmtVisitorTy::Visit(SemE))
7181           return false;
7182       } else {
7183         if (!EvaluateIgnoredValue(Info, SemE))
7184           return false;
7185       }
7186     }
7187     return true;
7188   }
7189 
7190   bool VisitCallExpr(const CallExpr *E) {
7191     APValue Result;
7192     if (!handleCallExpr(E, Result, nullptr))
7193       return false;
7194     return DerivedSuccess(Result, E);
7195   }
7196 
7197   bool handleCallExpr(const CallExpr *E, APValue &Result,
7198                      const LValue *ResultSlot) {
7199     const Expr *Callee = E->getCallee()->IgnoreParens();
7200     QualType CalleeType = Callee->getType();
7201 
7202     const FunctionDecl *FD = nullptr;
7203     LValue *This = nullptr, ThisVal;
7204     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
7205     bool HasQualifier = false;
7206 
7207     // Extract function decl and 'this' pointer from the callee.
7208     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7209       const CXXMethodDecl *Member = nullptr;
7210       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7211         // Explicit bound member calls, such as x.f() or p->g();
7212         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7213           return false;
7214         Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7215         if (!Member)
7216           return Error(Callee);
7217         This = &ThisVal;
7218         HasQualifier = ME->hasQualifier();
7219       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
7220         // Indirect bound member calls ('.*' or '->*').
7221         const ValueDecl *D =
7222             HandleMemberPointerAccess(Info, BE, ThisVal, false);
7223         if (!D)
7224           return false;
7225         Member = dyn_cast<CXXMethodDecl>(D);
7226         if (!Member)
7227           return Error(Callee);
7228         This = &ThisVal;
7229       } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7230         if (!Info.getLangOpts().CPlusPlus20)
7231           Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7232         return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7233                HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7234       } else
7235         return Error(Callee);
7236       FD = Member;
7237     } else if (CalleeType->isFunctionPointerType()) {
7238       LValue Call;
7239       if (!EvaluatePointer(Callee, Call, Info))
7240         return false;
7241 
7242       if (!Call.getLValueOffset().isZero())
7243         return Error(Callee);
7244       FD = dyn_cast_or_null<FunctionDecl>(
7245                              Call.getLValueBase().dyn_cast<const ValueDecl*>());
7246       if (!FD)
7247         return Error(Callee);
7248       // Don't call function pointers which have been cast to some other type.
7249       // Per DR (no number yet), the caller and callee can differ in noexcept.
7250       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7251         CalleeType->getPointeeType(), FD->getType())) {
7252         return Error(E);
7253       }
7254 
7255       // Overloaded operator calls to member functions are represented as normal
7256       // calls with '*this' as the first argument.
7257       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7258       if (MD && !MD->isStatic()) {
7259         // FIXME: When selecting an implicit conversion for an overloaded
7260         // operator delete, we sometimes try to evaluate calls to conversion
7261         // operators without a 'this' parameter!
7262         if (Args.empty())
7263           return Error(E);
7264 
7265         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7266           return false;
7267         This = &ThisVal;
7268         Args = Args.slice(1);
7269       } else if (MD && MD->isLambdaStaticInvoker()) {
7270         // Map the static invoker for the lambda back to the call operator.
7271         // Conveniently, we don't have to slice out the 'this' argument (as is
7272         // being done for the non-static case), since a static member function
7273         // doesn't have an implicit argument passed in.
7274         const CXXRecordDecl *ClosureClass = MD->getParent();
7275         assert(
7276             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7277             "Number of captures must be zero for conversion to function-ptr");
7278 
7279         const CXXMethodDecl *LambdaCallOp =
7280             ClosureClass->getLambdaCallOperator();
7281 
7282         // Set 'FD', the function that will be called below, to the call
7283         // operator.  If the closure object represents a generic lambda, find
7284         // the corresponding specialization of the call operator.
7285 
7286         if (ClosureClass->isGenericLambda()) {
7287           assert(MD->isFunctionTemplateSpecialization() &&
7288                  "A generic lambda's static-invoker function must be a "
7289                  "template specialization");
7290           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7291           FunctionTemplateDecl *CallOpTemplate =
7292               LambdaCallOp->getDescribedFunctionTemplate();
7293           void *InsertPos = nullptr;
7294           FunctionDecl *CorrespondingCallOpSpecialization =
7295               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7296           assert(CorrespondingCallOpSpecialization &&
7297                  "We must always have a function call operator specialization "
7298                  "that corresponds to our static invoker specialization");
7299           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7300         } else
7301           FD = LambdaCallOp;
7302       } else if (FD->isReplaceableGlobalAllocationFunction()) {
7303         if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7304             FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7305           LValue Ptr;
7306           if (!HandleOperatorNewCall(Info, E, Ptr))
7307             return false;
7308           Ptr.moveInto(Result);
7309           return true;
7310         } else {
7311           return HandleOperatorDeleteCall(Info, E);
7312         }
7313       }
7314     } else
7315       return Error(E);
7316 
7317     SmallVector<QualType, 4> CovariantAdjustmentPath;
7318     if (This) {
7319       auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7320       if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
7321         // Perform virtual dispatch, if necessary.
7322         FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
7323                                    CovariantAdjustmentPath);
7324         if (!FD)
7325           return false;
7326       } else {
7327         // Check that the 'this' pointer points to an object of the right type.
7328         // FIXME: If this is an assignment operator call, we may need to change
7329         // the active union member before we check this.
7330         if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
7331           return false;
7332       }
7333     }
7334 
7335     // Destructor calls are different enough that they have their own codepath.
7336     if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
7337       assert(This && "no 'this' pointer for destructor call");
7338       return HandleDestruction(Info, E, *This,
7339                                Info.Ctx.getRecordType(DD->getParent()));
7340     }
7341 
7342     const FunctionDecl *Definition = nullptr;
7343     Stmt *Body = FD->getBody(Definition);
7344 
7345     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
7346         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
7347                             Result, ResultSlot))
7348       return false;
7349 
7350     if (!CovariantAdjustmentPath.empty() &&
7351         !HandleCovariantReturnAdjustment(Info, E, Result,
7352                                          CovariantAdjustmentPath))
7353       return false;
7354 
7355     return true;
7356   }
7357 
7358   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7359     return StmtVisitorTy::Visit(E->getInitializer());
7360   }
7361   bool VisitInitListExpr(const InitListExpr *E) {
7362     if (E->getNumInits() == 0)
7363       return DerivedZeroInitialization(E);
7364     if (E->getNumInits() == 1)
7365       return StmtVisitorTy::Visit(E->getInit(0));
7366     return Error(E);
7367   }
7368   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
7369     return DerivedZeroInitialization(E);
7370   }
7371   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
7372     return DerivedZeroInitialization(E);
7373   }
7374   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
7375     return DerivedZeroInitialization(E);
7376   }
7377 
7378   /// A member expression where the object is a prvalue is itself a prvalue.
7379   bool VisitMemberExpr(const MemberExpr *E) {
7380     assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
7381            "missing temporary materialization conversion");
7382     assert(!E->isArrow() && "missing call to bound member function?");
7383 
7384     APValue Val;
7385     if (!Evaluate(Val, Info, E->getBase()))
7386       return false;
7387 
7388     QualType BaseTy = E->getBase()->getType();
7389 
7390     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
7391     if (!FD) return Error(E);
7392     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
7393     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7394            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7395 
7396     // Note: there is no lvalue base here. But this case should only ever
7397     // happen in C or in C++98, where we cannot be evaluating a constexpr
7398     // constructor, which is the only case the base matters.
7399     CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
7400     SubobjectDesignator Designator(BaseTy);
7401     Designator.addDeclUnchecked(FD);
7402 
7403     APValue Result;
7404     return extractSubobject(Info, E, Obj, Designator, Result) &&
7405            DerivedSuccess(Result, E);
7406   }
7407 
7408   bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
7409     APValue Val;
7410     if (!Evaluate(Val, Info, E->getBase()))
7411       return false;
7412 
7413     if (Val.isVector()) {
7414       SmallVector<uint32_t, 4> Indices;
7415       E->getEncodedElementAccess(Indices);
7416       if (Indices.size() == 1) {
7417         // Return scalar.
7418         return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
7419       } else {
7420         // Construct new APValue vector.
7421         SmallVector<APValue, 4> Elts;
7422         for (unsigned I = 0; I < Indices.size(); ++I) {
7423           Elts.push_back(Val.getVectorElt(Indices[I]));
7424         }
7425         APValue VecResult(Elts.data(), Indices.size());
7426         return DerivedSuccess(VecResult, E);
7427       }
7428     }
7429 
7430     return false;
7431   }
7432 
7433   bool VisitCastExpr(const CastExpr *E) {
7434     switch (E->getCastKind()) {
7435     default:
7436       break;
7437 
7438     case CK_AtomicToNonAtomic: {
7439       APValue AtomicVal;
7440       // This does not need to be done in place even for class/array types:
7441       // atomic-to-non-atomic conversion implies copying the object
7442       // representation.
7443       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
7444         return false;
7445       return DerivedSuccess(AtomicVal, E);
7446     }
7447 
7448     case CK_NoOp:
7449     case CK_UserDefinedConversion:
7450       return StmtVisitorTy::Visit(E->getSubExpr());
7451 
7452     case CK_LValueToRValue: {
7453       LValue LVal;
7454       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
7455         return false;
7456       APValue RVal;
7457       // Note, we use the subexpression's type in order to retain cv-qualifiers.
7458       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7459                                           LVal, RVal))
7460         return false;
7461       return DerivedSuccess(RVal, E);
7462     }
7463     case CK_LValueToRValueBitCast: {
7464       APValue DestValue, SourceValue;
7465       if (!Evaluate(SourceValue, Info, E->getSubExpr()))
7466         return false;
7467       if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
7468         return false;
7469       return DerivedSuccess(DestValue, E);
7470     }
7471 
7472     case CK_AddressSpaceConversion: {
7473       APValue Value;
7474       if (!Evaluate(Value, Info, E->getSubExpr()))
7475         return false;
7476       return DerivedSuccess(Value, E);
7477     }
7478     }
7479 
7480     return Error(E);
7481   }
7482 
7483   bool VisitUnaryPostInc(const UnaryOperator *UO) {
7484     return VisitUnaryPostIncDec(UO);
7485   }
7486   bool VisitUnaryPostDec(const UnaryOperator *UO) {
7487     return VisitUnaryPostIncDec(UO);
7488   }
7489   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
7490     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7491       return Error(UO);
7492 
7493     LValue LVal;
7494     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
7495       return false;
7496     APValue RVal;
7497     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
7498                       UO->isIncrementOp(), &RVal))
7499       return false;
7500     return DerivedSuccess(RVal, UO);
7501   }
7502 
7503   bool VisitStmtExpr(const StmtExpr *E) {
7504     // We will have checked the full-expressions inside the statement expression
7505     // when they were completed, and don't need to check them again now.
7506     if (Info.checkingForUndefinedBehavior())
7507       return Error(E);
7508 
7509     const CompoundStmt *CS = E->getSubStmt();
7510     if (CS->body_empty())
7511       return true;
7512 
7513     BlockScopeRAII Scope(Info);
7514     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
7515                                            BE = CS->body_end();
7516          /**/; ++BI) {
7517       if (BI + 1 == BE) {
7518         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
7519         if (!FinalExpr) {
7520           Info.FFDiag((*BI)->getBeginLoc(),
7521                       diag::note_constexpr_stmt_expr_unsupported);
7522           return false;
7523         }
7524         return this->Visit(FinalExpr) && Scope.destroy();
7525       }
7526 
7527       APValue ReturnValue;
7528       StmtResult Result = { ReturnValue, nullptr };
7529       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
7530       if (ESR != ESR_Succeeded) {
7531         // FIXME: If the statement-expression terminated due to 'return',
7532         // 'break', or 'continue', it would be nice to propagate that to
7533         // the outer statement evaluation rather than bailing out.
7534         if (ESR != ESR_Failed)
7535           Info.FFDiag((*BI)->getBeginLoc(),
7536                       diag::note_constexpr_stmt_expr_unsupported);
7537         return false;
7538       }
7539     }
7540 
7541     llvm_unreachable("Return from function from the loop above.");
7542   }
7543 
7544   /// Visit a value which is evaluated, but whose value is ignored.
7545   void VisitIgnoredValue(const Expr *E) {
7546     EvaluateIgnoredValue(Info, E);
7547   }
7548 
7549   /// Potentially visit a MemberExpr's base expression.
7550   void VisitIgnoredBaseExpression(const Expr *E) {
7551     // While MSVC doesn't evaluate the base expression, it does diagnose the
7552     // presence of side-effecting behavior.
7553     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
7554       return;
7555     VisitIgnoredValue(E);
7556   }
7557 };
7558 
7559 } // namespace
7560 
7561 //===----------------------------------------------------------------------===//
7562 // Common base class for lvalue and temporary evaluation.
7563 //===----------------------------------------------------------------------===//
7564 namespace {
7565 template<class Derived>
7566 class LValueExprEvaluatorBase
7567   : public ExprEvaluatorBase<Derived> {
7568 protected:
7569   LValue &Result;
7570   bool InvalidBaseOK;
7571   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
7572   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
7573 
7574   bool Success(APValue::LValueBase B) {
7575     Result.set(B);
7576     return true;
7577   }
7578 
7579   bool evaluatePointer(const Expr *E, LValue &Result) {
7580     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
7581   }
7582 
7583 public:
7584   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
7585       : ExprEvaluatorBaseTy(Info), Result(Result),
7586         InvalidBaseOK(InvalidBaseOK) {}
7587 
7588   bool Success(const APValue &V, const Expr *E) {
7589     Result.setFrom(this->Info.Ctx, V);
7590     return true;
7591   }
7592 
7593   bool VisitMemberExpr(const MemberExpr *E) {
7594     // Handle non-static data members.
7595     QualType BaseTy;
7596     bool EvalOK;
7597     if (E->isArrow()) {
7598       EvalOK = evaluatePointer(E->getBase(), Result);
7599       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
7600     } else if (E->getBase()->isRValue()) {
7601       assert(E->getBase()->getType()->isRecordType());
7602       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
7603       BaseTy = E->getBase()->getType();
7604     } else {
7605       EvalOK = this->Visit(E->getBase());
7606       BaseTy = E->getBase()->getType();
7607     }
7608     if (!EvalOK) {
7609       if (!InvalidBaseOK)
7610         return false;
7611       Result.setInvalid(E);
7612       return true;
7613     }
7614 
7615     const ValueDecl *MD = E->getMemberDecl();
7616     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
7617       assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7618              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7619       (void)BaseTy;
7620       if (!HandleLValueMember(this->Info, E, Result, FD))
7621         return false;
7622     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
7623       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
7624         return false;
7625     } else
7626       return this->Error(E);
7627 
7628     if (MD->getType()->isReferenceType()) {
7629       APValue RefValue;
7630       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
7631                                           RefValue))
7632         return false;
7633       return Success(RefValue, E);
7634     }
7635     return true;
7636   }
7637 
7638   bool VisitBinaryOperator(const BinaryOperator *E) {
7639     switch (E->getOpcode()) {
7640     default:
7641       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7642 
7643     case BO_PtrMemD:
7644     case BO_PtrMemI:
7645       return HandleMemberPointerAccess(this->Info, E, Result);
7646     }
7647   }
7648 
7649   bool VisitCastExpr(const CastExpr *E) {
7650     switch (E->getCastKind()) {
7651     default:
7652       return ExprEvaluatorBaseTy::VisitCastExpr(E);
7653 
7654     case CK_DerivedToBase:
7655     case CK_UncheckedDerivedToBase:
7656       if (!this->Visit(E->getSubExpr()))
7657         return false;
7658 
7659       // Now figure out the necessary offset to add to the base LV to get from
7660       // the derived class to the base class.
7661       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
7662                                   Result);
7663     }
7664   }
7665 };
7666 }
7667 
7668 //===----------------------------------------------------------------------===//
7669 // LValue Evaluation
7670 //
7671 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
7672 // function designators (in C), decl references to void objects (in C), and
7673 // temporaries (if building with -Wno-address-of-temporary).
7674 //
7675 // LValue evaluation produces values comprising a base expression of one of the
7676 // following types:
7677 // - Declarations
7678 //  * VarDecl
7679 //  * FunctionDecl
7680 // - Literals
7681 //  * CompoundLiteralExpr in C (and in global scope in C++)
7682 //  * StringLiteral
7683 //  * PredefinedExpr
7684 //  * ObjCStringLiteralExpr
7685 //  * ObjCEncodeExpr
7686 //  * AddrLabelExpr
7687 //  * BlockExpr
7688 //  * CallExpr for a MakeStringConstant builtin
7689 // - typeid(T) expressions, as TypeInfoLValues
7690 // - Locals and temporaries
7691 //  * MaterializeTemporaryExpr
7692 //  * Any Expr, with a CallIndex indicating the function in which the temporary
7693 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
7694 //    from the AST (FIXME).
7695 //  * A MaterializeTemporaryExpr that has static storage duration, with no
7696 //    CallIndex, for a lifetime-extended temporary.
7697 //  * The ConstantExpr that is currently being evaluated during evaluation of an
7698 //    immediate invocation.
7699 // plus an offset in bytes.
7700 //===----------------------------------------------------------------------===//
7701 namespace {
7702 class LValueExprEvaluator
7703   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
7704 public:
7705   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
7706     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
7707 
7708   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
7709   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
7710 
7711   bool VisitDeclRefExpr(const DeclRefExpr *E);
7712   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
7713   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
7714   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
7715   bool VisitMemberExpr(const MemberExpr *E);
7716   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
7717   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
7718   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
7719   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
7720   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
7721   bool VisitUnaryDeref(const UnaryOperator *E);
7722   bool VisitUnaryReal(const UnaryOperator *E);
7723   bool VisitUnaryImag(const UnaryOperator *E);
7724   bool VisitUnaryPreInc(const UnaryOperator *UO) {
7725     return VisitUnaryPreIncDec(UO);
7726   }
7727   bool VisitUnaryPreDec(const UnaryOperator *UO) {
7728     return VisitUnaryPreIncDec(UO);
7729   }
7730   bool VisitBinAssign(const BinaryOperator *BO);
7731   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
7732 
7733   bool VisitCastExpr(const CastExpr *E) {
7734     switch (E->getCastKind()) {
7735     default:
7736       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
7737 
7738     case CK_LValueBitCast:
7739       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7740       if (!Visit(E->getSubExpr()))
7741         return false;
7742       Result.Designator.setInvalid();
7743       return true;
7744 
7745     case CK_BaseToDerived:
7746       if (!Visit(E->getSubExpr()))
7747         return false;
7748       return HandleBaseToDerivedCast(Info, E, Result);
7749 
7750     case CK_Dynamic:
7751       if (!Visit(E->getSubExpr()))
7752         return false;
7753       return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
7754     }
7755   }
7756 };
7757 } // end anonymous namespace
7758 
7759 /// Evaluate an expression as an lvalue. This can be legitimately called on
7760 /// expressions which are not glvalues, in three cases:
7761 ///  * function designators in C, and
7762 ///  * "extern void" objects
7763 ///  * @selector() expressions in Objective-C
7764 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
7765                            bool InvalidBaseOK) {
7766   assert(E->isGLValue() || E->getType()->isFunctionType() ||
7767          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
7768   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
7769 }
7770 
7771 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
7772   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
7773     return Success(FD);
7774   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
7775     return VisitVarDecl(E, VD);
7776   if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
7777     return Visit(BD->getBinding());
7778   if (const MSGuidDecl *GD = dyn_cast<MSGuidDecl>(E->getDecl()))
7779     return Success(GD);
7780   return Error(E);
7781 }
7782 
7783 
7784 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
7785 
7786   // If we are within a lambda's call operator, check whether the 'VD' referred
7787   // to within 'E' actually represents a lambda-capture that maps to a
7788   // data-member/field within the closure object, and if so, evaluate to the
7789   // field or what the field refers to.
7790   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
7791       isa<DeclRefExpr>(E) &&
7792       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
7793     // We don't always have a complete capture-map when checking or inferring if
7794     // the function call operator meets the requirements of a constexpr function
7795     // - but we don't need to evaluate the captures to determine constexprness
7796     // (dcl.constexpr C++17).
7797     if (Info.checkingPotentialConstantExpression())
7798       return false;
7799 
7800     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
7801       // Start with 'Result' referring to the complete closure object...
7802       Result = *Info.CurrentCall->This;
7803       // ... then update it to refer to the field of the closure object
7804       // that represents the capture.
7805       if (!HandleLValueMember(Info, E, Result, FD))
7806         return false;
7807       // And if the field is of reference type, update 'Result' to refer to what
7808       // the field refers to.
7809       if (FD->getType()->isReferenceType()) {
7810         APValue RVal;
7811         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
7812                                             RVal))
7813           return false;
7814         Result.setFrom(Info.Ctx, RVal);
7815       }
7816       return true;
7817     }
7818   }
7819   CallStackFrame *Frame = nullptr;
7820   if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
7821     // Only if a local variable was declared in the function currently being
7822     // evaluated, do we expect to be able to find its value in the current
7823     // frame. (Otherwise it was likely declared in an enclosing context and
7824     // could either have a valid evaluatable value (for e.g. a constexpr
7825     // variable) or be ill-formed (and trigger an appropriate evaluation
7826     // diagnostic)).
7827     if (Info.CurrentCall->Callee &&
7828         Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
7829       Frame = Info.CurrentCall;
7830     }
7831   }
7832 
7833   if (!VD->getType()->isReferenceType()) {
7834     if (Frame) {
7835       Result.set({VD, Frame->Index,
7836                   Info.CurrentCall->getCurrentTemporaryVersion(VD)});
7837       return true;
7838     }
7839     return Success(VD);
7840   }
7841 
7842   APValue *V;
7843   if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
7844     return false;
7845   if (!V->hasValue()) {
7846     // FIXME: Is it possible for V to be indeterminate here? If so, we should
7847     // adjust the diagnostic to say that.
7848     if (!Info.checkingPotentialConstantExpression())
7849       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
7850     return false;
7851   }
7852   return Success(*V, E);
7853 }
7854 
7855 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
7856     const MaterializeTemporaryExpr *E) {
7857   // Walk through the expression to find the materialized temporary itself.
7858   SmallVector<const Expr *, 2> CommaLHSs;
7859   SmallVector<SubobjectAdjustment, 2> Adjustments;
7860   const Expr *Inner =
7861       E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
7862 
7863   // If we passed any comma operators, evaluate their LHSs.
7864   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
7865     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
7866       return false;
7867 
7868   // A materialized temporary with static storage duration can appear within the
7869   // result of a constant expression evaluation, so we need to preserve its
7870   // value for use outside this evaluation.
7871   APValue *Value;
7872   if (E->getStorageDuration() == SD_Static) {
7873     Value = E->getOrCreateValue(true);
7874     *Value = APValue();
7875     Result.set(E);
7876   } else {
7877     Value = &Info.CurrentCall->createTemporary(
7878         E, E->getType(), E->getStorageDuration() == SD_Automatic, Result);
7879   }
7880 
7881   QualType Type = Inner->getType();
7882 
7883   // Materialize the temporary itself.
7884   if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
7885     *Value = APValue();
7886     return false;
7887   }
7888 
7889   // Adjust our lvalue to refer to the desired subobject.
7890   for (unsigned I = Adjustments.size(); I != 0; /**/) {
7891     --I;
7892     switch (Adjustments[I].Kind) {
7893     case SubobjectAdjustment::DerivedToBaseAdjustment:
7894       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
7895                                 Type, Result))
7896         return false;
7897       Type = Adjustments[I].DerivedToBase.BasePath->getType();
7898       break;
7899 
7900     case SubobjectAdjustment::FieldAdjustment:
7901       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
7902         return false;
7903       Type = Adjustments[I].Field->getType();
7904       break;
7905 
7906     case SubobjectAdjustment::MemberPointerAdjustment:
7907       if (!HandleMemberPointerAccess(this->Info, Type, Result,
7908                                      Adjustments[I].Ptr.RHS))
7909         return false;
7910       Type = Adjustments[I].Ptr.MPT->getPointeeType();
7911       break;
7912     }
7913   }
7914 
7915   return true;
7916 }
7917 
7918 bool
7919 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7920   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
7921          "lvalue compound literal in c++?");
7922   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
7923   // only see this when folding in C, so there's no standard to follow here.
7924   return Success(E);
7925 }
7926 
7927 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
7928   TypeInfoLValue TypeInfo;
7929 
7930   if (!E->isPotentiallyEvaluated()) {
7931     if (E->isTypeOperand())
7932       TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
7933     else
7934       TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
7935   } else {
7936     if (!Info.Ctx.getLangOpts().CPlusPlus20) {
7937       Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
7938         << E->getExprOperand()->getType()
7939         << E->getExprOperand()->getSourceRange();
7940     }
7941 
7942     if (!Visit(E->getExprOperand()))
7943       return false;
7944 
7945     Optional<DynamicType> DynType =
7946         ComputeDynamicType(Info, E, Result, AK_TypeId);
7947     if (!DynType)
7948       return false;
7949 
7950     TypeInfo =
7951         TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
7952   }
7953 
7954   return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
7955 }
7956 
7957 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
7958   return Success(E->getGuidDecl());
7959 }
7960 
7961 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
7962   // Handle static data members.
7963   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
7964     VisitIgnoredBaseExpression(E->getBase());
7965     return VisitVarDecl(E, VD);
7966   }
7967 
7968   // Handle static member functions.
7969   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
7970     if (MD->isStatic()) {
7971       VisitIgnoredBaseExpression(E->getBase());
7972       return Success(MD);
7973     }
7974   }
7975 
7976   // Handle non-static data members.
7977   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
7978 }
7979 
7980 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
7981   // FIXME: Deal with vectors as array subscript bases.
7982   if (E->getBase()->getType()->isVectorType())
7983     return Error(E);
7984 
7985   bool Success = true;
7986   if (!evaluatePointer(E->getBase(), Result)) {
7987     if (!Info.noteFailure())
7988       return false;
7989     Success = false;
7990   }
7991 
7992   APSInt Index;
7993   if (!EvaluateInteger(E->getIdx(), Index, Info))
7994     return false;
7995 
7996   return Success &&
7997          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
7998 }
7999 
8000 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
8001   return evaluatePointer(E->getSubExpr(), Result);
8002 }
8003 
8004 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8005   if (!Visit(E->getSubExpr()))
8006     return false;
8007   // __real is a no-op on scalar lvalues.
8008   if (E->getSubExpr()->getType()->isAnyComplexType())
8009     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
8010   return true;
8011 }
8012 
8013 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8014   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
8015          "lvalue __imag__ on scalar?");
8016   if (!Visit(E->getSubExpr()))
8017     return false;
8018   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
8019   return true;
8020 }
8021 
8022 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
8023   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8024     return Error(UO);
8025 
8026   if (!this->Visit(UO->getSubExpr()))
8027     return false;
8028 
8029   return handleIncDec(
8030       this->Info, UO, Result, UO->getSubExpr()->getType(),
8031       UO->isIncrementOp(), nullptr);
8032 }
8033 
8034 bool LValueExprEvaluator::VisitCompoundAssignOperator(
8035     const CompoundAssignOperator *CAO) {
8036   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8037     return Error(CAO);
8038 
8039   APValue RHS;
8040 
8041   // The overall lvalue result is the result of evaluating the LHS.
8042   if (!this->Visit(CAO->getLHS())) {
8043     if (Info.noteFailure())
8044       Evaluate(RHS, this->Info, CAO->getRHS());
8045     return false;
8046   }
8047 
8048   if (!Evaluate(RHS, this->Info, CAO->getRHS()))
8049     return false;
8050 
8051   return handleCompoundAssignment(
8052       this->Info, CAO,
8053       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
8054       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
8055 }
8056 
8057 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
8058   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8059     return Error(E);
8060 
8061   APValue NewVal;
8062 
8063   if (!this->Visit(E->getLHS())) {
8064     if (Info.noteFailure())
8065       Evaluate(NewVal, this->Info, E->getRHS());
8066     return false;
8067   }
8068 
8069   if (!Evaluate(NewVal, this->Info, E->getRHS()))
8070     return false;
8071 
8072   if (Info.getLangOpts().CPlusPlus20 &&
8073       !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
8074     return false;
8075 
8076   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
8077                           NewVal);
8078 }
8079 
8080 //===----------------------------------------------------------------------===//
8081 // Pointer Evaluation
8082 //===----------------------------------------------------------------------===//
8083 
8084 /// Attempts to compute the number of bytes available at the pointer
8085 /// returned by a function with the alloc_size attribute. Returns true if we
8086 /// were successful. Places an unsigned number into `Result`.
8087 ///
8088 /// This expects the given CallExpr to be a call to a function with an
8089 /// alloc_size attribute.
8090 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8091                                             const CallExpr *Call,
8092                                             llvm::APInt &Result) {
8093   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
8094 
8095   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
8096   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
8097   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
8098   if (Call->getNumArgs() <= SizeArgNo)
8099     return false;
8100 
8101   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
8102     Expr::EvalResult ExprResult;
8103     if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
8104       return false;
8105     Into = ExprResult.Val.getInt();
8106     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
8107       return false;
8108     Into = Into.zextOrSelf(BitsInSizeT);
8109     return true;
8110   };
8111 
8112   APSInt SizeOfElem;
8113   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
8114     return false;
8115 
8116   if (!AllocSize->getNumElemsParam().isValid()) {
8117     Result = std::move(SizeOfElem);
8118     return true;
8119   }
8120 
8121   APSInt NumberOfElems;
8122   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
8123   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
8124     return false;
8125 
8126   bool Overflow;
8127   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
8128   if (Overflow)
8129     return false;
8130 
8131   Result = std::move(BytesAvailable);
8132   return true;
8133 }
8134 
8135 /// Convenience function. LVal's base must be a call to an alloc_size
8136 /// function.
8137 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8138                                             const LValue &LVal,
8139                                             llvm::APInt &Result) {
8140   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8141          "Can't get the size of a non alloc_size function");
8142   const auto *Base = LVal.getLValueBase().get<const Expr *>();
8143   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
8144   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
8145 }
8146 
8147 /// Attempts to evaluate the given LValueBase as the result of a call to
8148 /// a function with the alloc_size attribute. If it was possible to do so, this
8149 /// function will return true, make Result's Base point to said function call,
8150 /// and mark Result's Base as invalid.
8151 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
8152                                       LValue &Result) {
8153   if (Base.isNull())
8154     return false;
8155 
8156   // Because we do no form of static analysis, we only support const variables.
8157   //
8158   // Additionally, we can't support parameters, nor can we support static
8159   // variables (in the latter case, use-before-assign isn't UB; in the former,
8160   // we have no clue what they'll be assigned to).
8161   const auto *VD =
8162       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
8163   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
8164     return false;
8165 
8166   const Expr *Init = VD->getAnyInitializer();
8167   if (!Init)
8168     return false;
8169 
8170   const Expr *E = Init->IgnoreParens();
8171   if (!tryUnwrapAllocSizeCall(E))
8172     return false;
8173 
8174   // Store E instead of E unwrapped so that the type of the LValue's base is
8175   // what the user wanted.
8176   Result.setInvalid(E);
8177 
8178   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
8179   Result.addUnsizedArray(Info, E, Pointee);
8180   return true;
8181 }
8182 
8183 namespace {
8184 class PointerExprEvaluator
8185   : public ExprEvaluatorBase<PointerExprEvaluator> {
8186   LValue &Result;
8187   bool InvalidBaseOK;
8188 
8189   bool Success(const Expr *E) {
8190     Result.set(E);
8191     return true;
8192   }
8193 
8194   bool evaluateLValue(const Expr *E, LValue &Result) {
8195     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
8196   }
8197 
8198   bool evaluatePointer(const Expr *E, LValue &Result) {
8199     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
8200   }
8201 
8202   bool visitNonBuiltinCallExpr(const CallExpr *E);
8203 public:
8204 
8205   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
8206       : ExprEvaluatorBaseTy(info), Result(Result),
8207         InvalidBaseOK(InvalidBaseOK) {}
8208 
8209   bool Success(const APValue &V, const Expr *E) {
8210     Result.setFrom(Info.Ctx, V);
8211     return true;
8212   }
8213   bool ZeroInitialization(const Expr *E) {
8214     Result.setNull(Info.Ctx, E->getType());
8215     return true;
8216   }
8217 
8218   bool VisitBinaryOperator(const BinaryOperator *E);
8219   bool VisitCastExpr(const CastExpr* E);
8220   bool VisitUnaryAddrOf(const UnaryOperator *E);
8221   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
8222       { return Success(E); }
8223   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
8224     if (E->isExpressibleAsConstantInitializer())
8225       return Success(E);
8226     if (Info.noteFailure())
8227       EvaluateIgnoredValue(Info, E->getSubExpr());
8228     return Error(E);
8229   }
8230   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
8231       { return Success(E); }
8232   bool VisitCallExpr(const CallExpr *E);
8233   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
8234   bool VisitBlockExpr(const BlockExpr *E) {
8235     if (!E->getBlockDecl()->hasCaptures())
8236       return Success(E);
8237     return Error(E);
8238   }
8239   bool VisitCXXThisExpr(const CXXThisExpr *E) {
8240     // Can't look at 'this' when checking a potential constant expression.
8241     if (Info.checkingPotentialConstantExpression())
8242       return false;
8243     if (!Info.CurrentCall->This) {
8244       if (Info.getLangOpts().CPlusPlus11)
8245         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
8246       else
8247         Info.FFDiag(E);
8248       return false;
8249     }
8250     Result = *Info.CurrentCall->This;
8251     // If we are inside a lambda's call operator, the 'this' expression refers
8252     // to the enclosing '*this' object (either by value or reference) which is
8253     // either copied into the closure object's field that represents the '*this'
8254     // or refers to '*this'.
8255     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
8256       // Ensure we actually have captured 'this'. (an error will have
8257       // been previously reported if not).
8258       if (!Info.CurrentCall->LambdaThisCaptureField)
8259         return false;
8260 
8261       // Update 'Result' to refer to the data member/field of the closure object
8262       // that represents the '*this' capture.
8263       if (!HandleLValueMember(Info, E, Result,
8264                              Info.CurrentCall->LambdaThisCaptureField))
8265         return false;
8266       // If we captured '*this' by reference, replace the field with its referent.
8267       if (Info.CurrentCall->LambdaThisCaptureField->getType()
8268               ->isPointerType()) {
8269         APValue RVal;
8270         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
8271                                             RVal))
8272           return false;
8273 
8274         Result.setFrom(Info.Ctx, RVal);
8275       }
8276     }
8277     return true;
8278   }
8279 
8280   bool VisitCXXNewExpr(const CXXNewExpr *E);
8281 
8282   bool VisitSourceLocExpr(const SourceLocExpr *E) {
8283     assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
8284     APValue LValResult = E->EvaluateInContext(
8285         Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8286     Result.setFrom(Info.Ctx, LValResult);
8287     return true;
8288   }
8289 
8290   // FIXME: Missing: @protocol, @selector
8291 };
8292 } // end anonymous namespace
8293 
8294 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
8295                             bool InvalidBaseOK) {
8296   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
8297   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8298 }
8299 
8300 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8301   if (E->getOpcode() != BO_Add &&
8302       E->getOpcode() != BO_Sub)
8303     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8304 
8305   const Expr *PExp = E->getLHS();
8306   const Expr *IExp = E->getRHS();
8307   if (IExp->getType()->isPointerType())
8308     std::swap(PExp, IExp);
8309 
8310   bool EvalPtrOK = evaluatePointer(PExp, Result);
8311   if (!EvalPtrOK && !Info.noteFailure())
8312     return false;
8313 
8314   llvm::APSInt Offset;
8315   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
8316     return false;
8317 
8318   if (E->getOpcode() == BO_Sub)
8319     negateAsSigned(Offset);
8320 
8321   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
8322   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
8323 }
8324 
8325 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8326   return evaluateLValue(E->getSubExpr(), Result);
8327 }
8328 
8329 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8330   const Expr *SubExpr = E->getSubExpr();
8331 
8332   switch (E->getCastKind()) {
8333   default:
8334     break;
8335   case CK_BitCast:
8336   case CK_CPointerToObjCPointerCast:
8337   case CK_BlockPointerToObjCPointerCast:
8338   case CK_AnyPointerToBlockPointerCast:
8339   case CK_AddressSpaceConversion:
8340     if (!Visit(SubExpr))
8341       return false;
8342     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
8343     // permitted in constant expressions in C++11. Bitcasts from cv void* are
8344     // also static_casts, but we disallow them as a resolution to DR1312.
8345     if (!E->getType()->isVoidPointerType()) {
8346       if (!Result.InvalidBase && !Result.Designator.Invalid &&
8347           !Result.IsNullPtr &&
8348           Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
8349                                           E->getType()->getPointeeType()) &&
8350           Info.getStdAllocatorCaller("allocate")) {
8351         // Inside a call to std::allocator::allocate and friends, we permit
8352         // casting from void* back to cv1 T* for a pointer that points to a
8353         // cv2 T.
8354       } else {
8355         Result.Designator.setInvalid();
8356         if (SubExpr->getType()->isVoidPointerType())
8357           CCEDiag(E, diag::note_constexpr_invalid_cast)
8358             << 3 << SubExpr->getType();
8359         else
8360           CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8361       }
8362     }
8363     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
8364       ZeroInitialization(E);
8365     return true;
8366 
8367   case CK_DerivedToBase:
8368   case CK_UncheckedDerivedToBase:
8369     if (!evaluatePointer(E->getSubExpr(), Result))
8370       return false;
8371     if (!Result.Base && Result.Offset.isZero())
8372       return true;
8373 
8374     // Now figure out the necessary offset to add to the base LV to get from
8375     // the derived class to the base class.
8376     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
8377                                   castAs<PointerType>()->getPointeeType(),
8378                                 Result);
8379 
8380   case CK_BaseToDerived:
8381     if (!Visit(E->getSubExpr()))
8382       return false;
8383     if (!Result.Base && Result.Offset.isZero())
8384       return true;
8385     return HandleBaseToDerivedCast(Info, E, Result);
8386 
8387   case CK_Dynamic:
8388     if (!Visit(E->getSubExpr()))
8389       return false;
8390     return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8391 
8392   case CK_NullToPointer:
8393     VisitIgnoredValue(E->getSubExpr());
8394     return ZeroInitialization(E);
8395 
8396   case CK_IntegralToPointer: {
8397     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8398 
8399     APValue Value;
8400     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
8401       break;
8402 
8403     if (Value.isInt()) {
8404       unsigned Size = Info.Ctx.getTypeSize(E->getType());
8405       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
8406       Result.Base = (Expr*)nullptr;
8407       Result.InvalidBase = false;
8408       Result.Offset = CharUnits::fromQuantity(N);
8409       Result.Designator.setInvalid();
8410       Result.IsNullPtr = false;
8411       return true;
8412     } else {
8413       // Cast is of an lvalue, no need to change value.
8414       Result.setFrom(Info.Ctx, Value);
8415       return true;
8416     }
8417   }
8418 
8419   case CK_ArrayToPointerDecay: {
8420     if (SubExpr->isGLValue()) {
8421       if (!evaluateLValue(SubExpr, Result))
8422         return false;
8423     } else {
8424       APValue &Value = Info.CurrentCall->createTemporary(
8425           SubExpr, SubExpr->getType(), false, Result);
8426       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
8427         return false;
8428     }
8429     // The result is a pointer to the first element of the array.
8430     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
8431     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
8432       Result.addArray(Info, E, CAT);
8433     else
8434       Result.addUnsizedArray(Info, E, AT->getElementType());
8435     return true;
8436   }
8437 
8438   case CK_FunctionToPointerDecay:
8439     return evaluateLValue(SubExpr, Result);
8440 
8441   case CK_LValueToRValue: {
8442     LValue LVal;
8443     if (!evaluateLValue(E->getSubExpr(), LVal))
8444       return false;
8445 
8446     APValue RVal;
8447     // Note, we use the subexpression's type in order to retain cv-qualifiers.
8448     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8449                                         LVal, RVal))
8450       return InvalidBaseOK &&
8451              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
8452     return Success(RVal, E);
8453   }
8454   }
8455 
8456   return ExprEvaluatorBaseTy::VisitCastExpr(E);
8457 }
8458 
8459 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
8460                                 UnaryExprOrTypeTrait ExprKind) {
8461   // C++ [expr.alignof]p3:
8462   //     When alignof is applied to a reference type, the result is the
8463   //     alignment of the referenced type.
8464   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
8465     T = Ref->getPointeeType();
8466 
8467   if (T.getQualifiers().hasUnaligned())
8468     return CharUnits::One();
8469 
8470   const bool AlignOfReturnsPreferred =
8471       Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
8472 
8473   // __alignof is defined to return the preferred alignment.
8474   // Before 8, clang returned the preferred alignment for alignof and _Alignof
8475   // as well.
8476   if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
8477     return Info.Ctx.toCharUnitsFromBits(
8478       Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
8479   // alignof and _Alignof are defined to return the ABI alignment.
8480   else if (ExprKind == UETT_AlignOf)
8481     return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
8482   else
8483     llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
8484 }
8485 
8486 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
8487                                 UnaryExprOrTypeTrait ExprKind) {
8488   E = E->IgnoreParens();
8489 
8490   // The kinds of expressions that we have special-case logic here for
8491   // should be kept up to date with the special checks for those
8492   // expressions in Sema.
8493 
8494   // alignof decl is always accepted, even if it doesn't make sense: we default
8495   // to 1 in those cases.
8496   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8497     return Info.Ctx.getDeclAlign(DRE->getDecl(),
8498                                  /*RefAsPointee*/true);
8499 
8500   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
8501     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
8502                                  /*RefAsPointee*/true);
8503 
8504   return GetAlignOfType(Info, E->getType(), ExprKind);
8505 }
8506 
8507 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
8508   if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
8509     return Info.Ctx.getDeclAlign(VD);
8510   if (const auto *E = Value.Base.dyn_cast<const Expr *>())
8511     return GetAlignOfExpr(Info, E, UETT_AlignOf);
8512   return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
8513 }
8514 
8515 /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
8516 /// __builtin_is_aligned and __builtin_assume_aligned.
8517 static bool getAlignmentArgument(const Expr *E, QualType ForType,
8518                                  EvalInfo &Info, APSInt &Alignment) {
8519   if (!EvaluateInteger(E, Alignment, Info))
8520     return false;
8521   if (Alignment < 0 || !Alignment.isPowerOf2()) {
8522     Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
8523     return false;
8524   }
8525   unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
8526   APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
8527   if (APSInt::compareValues(Alignment, MaxValue) > 0) {
8528     Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
8529         << MaxValue << ForType << Alignment;
8530     return false;
8531   }
8532   // Ensure both alignment and source value have the same bit width so that we
8533   // don't assert when computing the resulting value.
8534   APSInt ExtAlignment =
8535       APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
8536   assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
8537          "Alignment should not be changed by ext/trunc");
8538   Alignment = ExtAlignment;
8539   assert(Alignment.getBitWidth() == SrcWidth);
8540   return true;
8541 }
8542 
8543 // To be clear: this happily visits unsupported builtins. Better name welcomed.
8544 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
8545   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
8546     return true;
8547 
8548   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
8549     return false;
8550 
8551   Result.setInvalid(E);
8552   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
8553   Result.addUnsizedArray(Info, E, PointeeTy);
8554   return true;
8555 }
8556 
8557 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
8558   if (IsStringLiteralCall(E))
8559     return Success(E);
8560 
8561   if (unsigned BuiltinOp = E->getBuiltinCallee())
8562     return VisitBuiltinCallExpr(E, BuiltinOp);
8563 
8564   return visitNonBuiltinCallExpr(E);
8565 }
8566 
8567 // Determine if T is a character type for which we guarantee that
8568 // sizeof(T) == 1.
8569 static bool isOneByteCharacterType(QualType T) {
8570   return T->isCharType() || T->isChar8Type();
8571 }
8572 
8573 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8574                                                 unsigned BuiltinOp) {
8575   switch (BuiltinOp) {
8576   case Builtin::BI__builtin_addressof:
8577     return evaluateLValue(E->getArg(0), Result);
8578   case Builtin::BI__builtin_assume_aligned: {
8579     // We need to be very careful here because: if the pointer does not have the
8580     // asserted alignment, then the behavior is undefined, and undefined
8581     // behavior is non-constant.
8582     if (!evaluatePointer(E->getArg(0), Result))
8583       return false;
8584 
8585     LValue OffsetResult(Result);
8586     APSInt Alignment;
8587     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
8588                               Alignment))
8589       return false;
8590     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
8591 
8592     if (E->getNumArgs() > 2) {
8593       APSInt Offset;
8594       if (!EvaluateInteger(E->getArg(2), Offset, Info))
8595         return false;
8596 
8597       int64_t AdditionalOffset = -Offset.getZExtValue();
8598       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
8599     }
8600 
8601     // If there is a base object, then it must have the correct alignment.
8602     if (OffsetResult.Base) {
8603       CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
8604 
8605       if (BaseAlignment < Align) {
8606         Result.Designator.setInvalid();
8607         // FIXME: Add support to Diagnostic for long / long long.
8608         CCEDiag(E->getArg(0),
8609                 diag::note_constexpr_baa_insufficient_alignment) << 0
8610           << (unsigned)BaseAlignment.getQuantity()
8611           << (unsigned)Align.getQuantity();
8612         return false;
8613       }
8614     }
8615 
8616     // The offset must also have the correct alignment.
8617     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
8618       Result.Designator.setInvalid();
8619 
8620       (OffsetResult.Base
8621            ? CCEDiag(E->getArg(0),
8622                      diag::note_constexpr_baa_insufficient_alignment) << 1
8623            : CCEDiag(E->getArg(0),
8624                      diag::note_constexpr_baa_value_insufficient_alignment))
8625         << (int)OffsetResult.Offset.getQuantity()
8626         << (unsigned)Align.getQuantity();
8627       return false;
8628     }
8629 
8630     return true;
8631   }
8632   case Builtin::BI__builtin_align_up:
8633   case Builtin::BI__builtin_align_down: {
8634     if (!evaluatePointer(E->getArg(0), Result))
8635       return false;
8636     APSInt Alignment;
8637     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
8638                               Alignment))
8639       return false;
8640     CharUnits BaseAlignment = getBaseAlignment(Info, Result);
8641     CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
8642     // For align_up/align_down, we can return the same value if the alignment
8643     // is known to be greater or equal to the requested value.
8644     if (PtrAlign.getQuantity() >= Alignment)
8645       return true;
8646 
8647     // The alignment could be greater than the minimum at run-time, so we cannot
8648     // infer much about the resulting pointer value. One case is possible:
8649     // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
8650     // can infer the correct index if the requested alignment is smaller than
8651     // the base alignment so we can perform the computation on the offset.
8652     if (BaseAlignment.getQuantity() >= Alignment) {
8653       assert(Alignment.getBitWidth() <= 64 &&
8654              "Cannot handle > 64-bit address-space");
8655       uint64_t Alignment64 = Alignment.getZExtValue();
8656       CharUnits NewOffset = CharUnits::fromQuantity(
8657           BuiltinOp == Builtin::BI__builtin_align_down
8658               ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
8659               : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
8660       Result.adjustOffset(NewOffset - Result.Offset);
8661       // TODO: diagnose out-of-bounds values/only allow for arrays?
8662       return true;
8663     }
8664     // Otherwise, we cannot constant-evaluate the result.
8665     Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
8666         << Alignment;
8667     return false;
8668   }
8669   case Builtin::BI__builtin_operator_new:
8670     return HandleOperatorNewCall(Info, E, Result);
8671   case Builtin::BI__builtin_launder:
8672     return evaluatePointer(E->getArg(0), Result);
8673   case Builtin::BIstrchr:
8674   case Builtin::BIwcschr:
8675   case Builtin::BImemchr:
8676   case Builtin::BIwmemchr:
8677     if (Info.getLangOpts().CPlusPlus11)
8678       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8679         << /*isConstexpr*/0 << /*isConstructor*/0
8680         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
8681     else
8682       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
8683     LLVM_FALLTHROUGH;
8684   case Builtin::BI__builtin_strchr:
8685   case Builtin::BI__builtin_wcschr:
8686   case Builtin::BI__builtin_memchr:
8687   case Builtin::BI__builtin_char_memchr:
8688   case Builtin::BI__builtin_wmemchr: {
8689     if (!Visit(E->getArg(0)))
8690       return false;
8691     APSInt Desired;
8692     if (!EvaluateInteger(E->getArg(1), Desired, Info))
8693       return false;
8694     uint64_t MaxLength = uint64_t(-1);
8695     if (BuiltinOp != Builtin::BIstrchr &&
8696         BuiltinOp != Builtin::BIwcschr &&
8697         BuiltinOp != Builtin::BI__builtin_strchr &&
8698         BuiltinOp != Builtin::BI__builtin_wcschr) {
8699       APSInt N;
8700       if (!EvaluateInteger(E->getArg(2), N, Info))
8701         return false;
8702       MaxLength = N.getExtValue();
8703     }
8704     // We cannot find the value if there are no candidates to match against.
8705     if (MaxLength == 0u)
8706       return ZeroInitialization(E);
8707     if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
8708         Result.Designator.Invalid)
8709       return false;
8710     QualType CharTy = Result.Designator.getType(Info.Ctx);
8711     bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
8712                      BuiltinOp == Builtin::BI__builtin_memchr;
8713     assert(IsRawByte ||
8714            Info.Ctx.hasSameUnqualifiedType(
8715                CharTy, E->getArg(0)->getType()->getPointeeType()));
8716     // Pointers to const void may point to objects of incomplete type.
8717     if (IsRawByte && CharTy->isIncompleteType()) {
8718       Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
8719       return false;
8720     }
8721     // Give up on byte-oriented matching against multibyte elements.
8722     // FIXME: We can compare the bytes in the correct order.
8723     if (IsRawByte && !isOneByteCharacterType(CharTy)) {
8724       Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
8725           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
8726           << CharTy;
8727       return false;
8728     }
8729     // Figure out what value we're actually looking for (after converting to
8730     // the corresponding unsigned type if necessary).
8731     uint64_t DesiredVal;
8732     bool StopAtNull = false;
8733     switch (BuiltinOp) {
8734     case Builtin::BIstrchr:
8735     case Builtin::BI__builtin_strchr:
8736       // strchr compares directly to the passed integer, and therefore
8737       // always fails if given an int that is not a char.
8738       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
8739                                                   E->getArg(1)->getType(),
8740                                                   Desired),
8741                                Desired))
8742         return ZeroInitialization(E);
8743       StopAtNull = true;
8744       LLVM_FALLTHROUGH;
8745     case Builtin::BImemchr:
8746     case Builtin::BI__builtin_memchr:
8747     case Builtin::BI__builtin_char_memchr:
8748       // memchr compares by converting both sides to unsigned char. That's also
8749       // correct for strchr if we get this far (to cope with plain char being
8750       // unsigned in the strchr case).
8751       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
8752       break;
8753 
8754     case Builtin::BIwcschr:
8755     case Builtin::BI__builtin_wcschr:
8756       StopAtNull = true;
8757       LLVM_FALLTHROUGH;
8758     case Builtin::BIwmemchr:
8759     case Builtin::BI__builtin_wmemchr:
8760       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
8761       DesiredVal = Desired.getZExtValue();
8762       break;
8763     }
8764 
8765     for (; MaxLength; --MaxLength) {
8766       APValue Char;
8767       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
8768           !Char.isInt())
8769         return false;
8770       if (Char.getInt().getZExtValue() == DesiredVal)
8771         return true;
8772       if (StopAtNull && !Char.getInt())
8773         break;
8774       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
8775         return false;
8776     }
8777     // Not found: return nullptr.
8778     return ZeroInitialization(E);
8779   }
8780 
8781   case Builtin::BImemcpy:
8782   case Builtin::BImemmove:
8783   case Builtin::BIwmemcpy:
8784   case Builtin::BIwmemmove:
8785     if (Info.getLangOpts().CPlusPlus11)
8786       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8787         << /*isConstexpr*/0 << /*isConstructor*/0
8788         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
8789     else
8790       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
8791     LLVM_FALLTHROUGH;
8792   case Builtin::BI__builtin_memcpy:
8793   case Builtin::BI__builtin_memmove:
8794   case Builtin::BI__builtin_wmemcpy:
8795   case Builtin::BI__builtin_wmemmove: {
8796     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
8797                  BuiltinOp == Builtin::BIwmemmove ||
8798                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
8799                  BuiltinOp == Builtin::BI__builtin_wmemmove;
8800     bool Move = BuiltinOp == Builtin::BImemmove ||
8801                 BuiltinOp == Builtin::BIwmemmove ||
8802                 BuiltinOp == Builtin::BI__builtin_memmove ||
8803                 BuiltinOp == Builtin::BI__builtin_wmemmove;
8804 
8805     // The result of mem* is the first argument.
8806     if (!Visit(E->getArg(0)))
8807       return false;
8808     LValue Dest = Result;
8809 
8810     LValue Src;
8811     if (!EvaluatePointer(E->getArg(1), Src, Info))
8812       return false;
8813 
8814     APSInt N;
8815     if (!EvaluateInteger(E->getArg(2), N, Info))
8816       return false;
8817     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
8818 
8819     // If the size is zero, we treat this as always being a valid no-op.
8820     // (Even if one of the src and dest pointers is null.)
8821     if (!N)
8822       return true;
8823 
8824     // Otherwise, if either of the operands is null, we can't proceed. Don't
8825     // try to determine the type of the copied objects, because there aren't
8826     // any.
8827     if (!Src.Base || !Dest.Base) {
8828       APValue Val;
8829       (!Src.Base ? Src : Dest).moveInto(Val);
8830       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
8831           << Move << WChar << !!Src.Base
8832           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
8833       return false;
8834     }
8835     if (Src.Designator.Invalid || Dest.Designator.Invalid)
8836       return false;
8837 
8838     // We require that Src and Dest are both pointers to arrays of
8839     // trivially-copyable type. (For the wide version, the designator will be
8840     // invalid if the designated object is not a wchar_t.)
8841     QualType T = Dest.Designator.getType(Info.Ctx);
8842     QualType SrcT = Src.Designator.getType(Info.Ctx);
8843     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
8844       // FIXME: Consider using our bit_cast implementation to support this.
8845       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
8846       return false;
8847     }
8848     if (T->isIncompleteType()) {
8849       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
8850       return false;
8851     }
8852     if (!T.isTriviallyCopyableType(Info.Ctx)) {
8853       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
8854       return false;
8855     }
8856 
8857     // Figure out how many T's we're copying.
8858     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
8859     if (!WChar) {
8860       uint64_t Remainder;
8861       llvm::APInt OrigN = N;
8862       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
8863       if (Remainder) {
8864         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
8865             << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
8866             << (unsigned)TSize;
8867         return false;
8868       }
8869     }
8870 
8871     // Check that the copying will remain within the arrays, just so that we
8872     // can give a more meaningful diagnostic. This implicitly also checks that
8873     // N fits into 64 bits.
8874     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
8875     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
8876     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
8877       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
8878           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
8879           << N.toString(10, /*Signed*/false);
8880       return false;
8881     }
8882     uint64_t NElems = N.getZExtValue();
8883     uint64_t NBytes = NElems * TSize;
8884 
8885     // Check for overlap.
8886     int Direction = 1;
8887     if (HasSameBase(Src, Dest)) {
8888       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
8889       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
8890       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
8891         // Dest is inside the source region.
8892         if (!Move) {
8893           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
8894           return false;
8895         }
8896         // For memmove and friends, copy backwards.
8897         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
8898             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
8899           return false;
8900         Direction = -1;
8901       } else if (!Move && SrcOffset >= DestOffset &&
8902                  SrcOffset - DestOffset < NBytes) {
8903         // Src is inside the destination region for memcpy: invalid.
8904         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
8905         return false;
8906       }
8907     }
8908 
8909     while (true) {
8910       APValue Val;
8911       // FIXME: Set WantObjectRepresentation to true if we're copying a
8912       // char-like type?
8913       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
8914           !handleAssignment(Info, E, Dest, T, Val))
8915         return false;
8916       // Do not iterate past the last element; if we're copying backwards, that
8917       // might take us off the start of the array.
8918       if (--NElems == 0)
8919         return true;
8920       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
8921           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
8922         return false;
8923     }
8924   }
8925 
8926   default:
8927     break;
8928   }
8929 
8930   return visitNonBuiltinCallExpr(E);
8931 }
8932 
8933 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
8934                                      APValue &Result, const InitListExpr *ILE,
8935                                      QualType AllocType);
8936 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
8937                                           APValue &Result,
8938                                           const CXXConstructExpr *CCE,
8939                                           QualType AllocType);
8940 
8941 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
8942   if (!Info.getLangOpts().CPlusPlus20)
8943     Info.CCEDiag(E, diag::note_constexpr_new);
8944 
8945   // We cannot speculatively evaluate a delete expression.
8946   if (Info.SpeculativeEvaluationDepth)
8947     return false;
8948 
8949   FunctionDecl *OperatorNew = E->getOperatorNew();
8950 
8951   bool IsNothrow = false;
8952   bool IsPlacement = false;
8953   if (OperatorNew->isReservedGlobalPlacementOperator() &&
8954       Info.CurrentCall->isStdFunction() && !E->isArray()) {
8955     // FIXME Support array placement new.
8956     assert(E->getNumPlacementArgs() == 1);
8957     if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
8958       return false;
8959     if (Result.Designator.Invalid)
8960       return false;
8961     IsPlacement = true;
8962   } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
8963     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
8964         << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
8965     return false;
8966   } else if (E->getNumPlacementArgs()) {
8967     // The only new-placement list we support is of the form (std::nothrow).
8968     //
8969     // FIXME: There is no restriction on this, but it's not clear that any
8970     // other form makes any sense. We get here for cases such as:
8971     //
8972     //   new (std::align_val_t{N}) X(int)
8973     //
8974     // (which should presumably be valid only if N is a multiple of
8975     // alignof(int), and in any case can't be deallocated unless N is
8976     // alignof(X) and X has new-extended alignment).
8977     if (E->getNumPlacementArgs() != 1 ||
8978         !E->getPlacementArg(0)->getType()->isNothrowT())
8979       return Error(E, diag::note_constexpr_new_placement);
8980 
8981     LValue Nothrow;
8982     if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
8983       return false;
8984     IsNothrow = true;
8985   }
8986 
8987   const Expr *Init = E->getInitializer();
8988   const InitListExpr *ResizedArrayILE = nullptr;
8989   const CXXConstructExpr *ResizedArrayCCE = nullptr;
8990   bool ValueInit = false;
8991 
8992   QualType AllocType = E->getAllocatedType();
8993   if (Optional<const Expr*> ArraySize = E->getArraySize()) {
8994     const Expr *Stripped = *ArraySize;
8995     for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
8996          Stripped = ICE->getSubExpr())
8997       if (ICE->getCastKind() != CK_NoOp &&
8998           ICE->getCastKind() != CK_IntegralCast)
8999         break;
9000 
9001     llvm::APSInt ArrayBound;
9002     if (!EvaluateInteger(Stripped, ArrayBound, Info))
9003       return false;
9004 
9005     // C++ [expr.new]p9:
9006     //   The expression is erroneous if:
9007     //   -- [...] its value before converting to size_t [or] applying the
9008     //      second standard conversion sequence is less than zero
9009     if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
9010       if (IsNothrow)
9011         return ZeroInitialization(E);
9012 
9013       Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
9014           << ArrayBound << (*ArraySize)->getSourceRange();
9015       return false;
9016     }
9017 
9018     //   -- its value is such that the size of the allocated object would
9019     //      exceed the implementation-defined limit
9020     if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
9021                                                 ArrayBound) >
9022         ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
9023       if (IsNothrow)
9024         return ZeroInitialization(E);
9025 
9026       Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
9027         << ArrayBound << (*ArraySize)->getSourceRange();
9028       return false;
9029     }
9030 
9031     //   -- the new-initializer is a braced-init-list and the number of
9032     //      array elements for which initializers are provided [...]
9033     //      exceeds the number of elements to initialize
9034     if (!Init) {
9035       // No initialization is performed.
9036     } else if (isa<CXXScalarValueInitExpr>(Init) ||
9037                isa<ImplicitValueInitExpr>(Init)) {
9038       ValueInit = true;
9039     } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
9040       ResizedArrayCCE = CCE;
9041     } else {
9042       auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
9043       assert(CAT && "unexpected type for array initializer");
9044 
9045       unsigned Bits =
9046           std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
9047       llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits);
9048       llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits);
9049       if (InitBound.ugt(AllocBound)) {
9050         if (IsNothrow)
9051           return ZeroInitialization(E);
9052 
9053         Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
9054             << AllocBound.toString(10, /*Signed=*/false)
9055             << InitBound.toString(10, /*Signed=*/false)
9056             << (*ArraySize)->getSourceRange();
9057         return false;
9058       }
9059 
9060       // If the sizes differ, we must have an initializer list, and we need
9061       // special handling for this case when we initialize.
9062       if (InitBound != AllocBound)
9063         ResizedArrayILE = cast<InitListExpr>(Init);
9064     }
9065 
9066     AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
9067                                               ArrayType::Normal, 0);
9068   } else {
9069     assert(!AllocType->isArrayType() &&
9070            "array allocation with non-array new");
9071   }
9072 
9073   APValue *Val;
9074   if (IsPlacement) {
9075     AccessKinds AK = AK_Construct;
9076     struct FindObjectHandler {
9077       EvalInfo &Info;
9078       const Expr *E;
9079       QualType AllocType;
9080       const AccessKinds AccessKind;
9081       APValue *Value;
9082 
9083       typedef bool result_type;
9084       bool failed() { return false; }
9085       bool found(APValue &Subobj, QualType SubobjType) {
9086         // FIXME: Reject the cases where [basic.life]p8 would not permit the
9087         // old name of the object to be used to name the new object.
9088         if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
9089           Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
9090             SubobjType << AllocType;
9091           return false;
9092         }
9093         Value = &Subobj;
9094         return true;
9095       }
9096       bool found(APSInt &Value, QualType SubobjType) {
9097         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9098         return false;
9099       }
9100       bool found(APFloat &Value, QualType SubobjType) {
9101         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9102         return false;
9103       }
9104     } Handler = {Info, E, AllocType, AK, nullptr};
9105 
9106     CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
9107     if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
9108       return false;
9109 
9110     Val = Handler.Value;
9111 
9112     // [basic.life]p1:
9113     //   The lifetime of an object o of type T ends when [...] the storage
9114     //   which the object occupies is [...] reused by an object that is not
9115     //   nested within o (6.6.2).
9116     *Val = APValue();
9117   } else {
9118     // Perform the allocation and obtain a pointer to the resulting object.
9119     Val = Info.createHeapAlloc(E, AllocType, Result);
9120     if (!Val)
9121       return false;
9122   }
9123 
9124   if (ValueInit) {
9125     ImplicitValueInitExpr VIE(AllocType);
9126     if (!EvaluateInPlace(*Val, Info, Result, &VIE))
9127       return false;
9128   } else if (ResizedArrayILE) {
9129     if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
9130                                   AllocType))
9131       return false;
9132   } else if (ResizedArrayCCE) {
9133     if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
9134                                        AllocType))
9135       return false;
9136   } else if (Init) {
9137     if (!EvaluateInPlace(*Val, Info, Result, Init))
9138       return false;
9139   } else if (!getDefaultInitValue(AllocType, *Val)) {
9140     return false;
9141   }
9142 
9143   // Array new returns a pointer to the first element, not a pointer to the
9144   // array.
9145   if (auto *AT = AllocType->getAsArrayTypeUnsafe())
9146     Result.addArray(Info, E, cast<ConstantArrayType>(AT));
9147 
9148   return true;
9149 }
9150 //===----------------------------------------------------------------------===//
9151 // Member Pointer Evaluation
9152 //===----------------------------------------------------------------------===//
9153 
9154 namespace {
9155 class MemberPointerExprEvaluator
9156   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
9157   MemberPtr &Result;
9158 
9159   bool Success(const ValueDecl *D) {
9160     Result = MemberPtr(D);
9161     return true;
9162   }
9163 public:
9164 
9165   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
9166     : ExprEvaluatorBaseTy(Info), Result(Result) {}
9167 
9168   bool Success(const APValue &V, const Expr *E) {
9169     Result.setFrom(V);
9170     return true;
9171   }
9172   bool ZeroInitialization(const Expr *E) {
9173     return Success((const ValueDecl*)nullptr);
9174   }
9175 
9176   bool VisitCastExpr(const CastExpr *E);
9177   bool VisitUnaryAddrOf(const UnaryOperator *E);
9178 };
9179 } // end anonymous namespace
9180 
9181 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
9182                                   EvalInfo &Info) {
9183   assert(E->isRValue() && E->getType()->isMemberPointerType());
9184   return MemberPointerExprEvaluator(Info, Result).Visit(E);
9185 }
9186 
9187 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9188   switch (E->getCastKind()) {
9189   default:
9190     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9191 
9192   case CK_NullToMemberPointer:
9193     VisitIgnoredValue(E->getSubExpr());
9194     return ZeroInitialization(E);
9195 
9196   case CK_BaseToDerivedMemberPointer: {
9197     if (!Visit(E->getSubExpr()))
9198       return false;
9199     if (E->path_empty())
9200       return true;
9201     // Base-to-derived member pointer casts store the path in derived-to-base
9202     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
9203     // the wrong end of the derived->base arc, so stagger the path by one class.
9204     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
9205     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
9206          PathI != PathE; ++PathI) {
9207       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9208       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
9209       if (!Result.castToDerived(Derived))
9210         return Error(E);
9211     }
9212     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
9213     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
9214       return Error(E);
9215     return true;
9216   }
9217 
9218   case CK_DerivedToBaseMemberPointer:
9219     if (!Visit(E->getSubExpr()))
9220       return false;
9221     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9222          PathE = E->path_end(); PathI != PathE; ++PathI) {
9223       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9224       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9225       if (!Result.castToBase(Base))
9226         return Error(E);
9227     }
9228     return true;
9229   }
9230 }
9231 
9232 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9233   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
9234   // member can be formed.
9235   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
9236 }
9237 
9238 //===----------------------------------------------------------------------===//
9239 // Record Evaluation
9240 //===----------------------------------------------------------------------===//
9241 
9242 namespace {
9243   class RecordExprEvaluator
9244   : public ExprEvaluatorBase<RecordExprEvaluator> {
9245     const LValue &This;
9246     APValue &Result;
9247   public:
9248 
9249     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
9250       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
9251 
9252     bool Success(const APValue &V, const Expr *E) {
9253       Result = V;
9254       return true;
9255     }
9256     bool ZeroInitialization(const Expr *E) {
9257       return ZeroInitialization(E, E->getType());
9258     }
9259     bool ZeroInitialization(const Expr *E, QualType T);
9260 
9261     bool VisitCallExpr(const CallExpr *E) {
9262       return handleCallExpr(E, Result, &This);
9263     }
9264     bool VisitCastExpr(const CastExpr *E);
9265     bool VisitInitListExpr(const InitListExpr *E);
9266     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9267       return VisitCXXConstructExpr(E, E->getType());
9268     }
9269     bool VisitLambdaExpr(const LambdaExpr *E);
9270     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
9271     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
9272     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
9273     bool VisitBinCmp(const BinaryOperator *E);
9274   };
9275 }
9276 
9277 /// Perform zero-initialization on an object of non-union class type.
9278 /// C++11 [dcl.init]p5:
9279 ///  To zero-initialize an object or reference of type T means:
9280 ///    [...]
9281 ///    -- if T is a (possibly cv-qualified) non-union class type,
9282 ///       each non-static data member and each base-class subobject is
9283 ///       zero-initialized
9284 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
9285                                           const RecordDecl *RD,
9286                                           const LValue &This, APValue &Result) {
9287   assert(!RD->isUnion() && "Expected non-union class type");
9288   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
9289   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
9290                    std::distance(RD->field_begin(), RD->field_end()));
9291 
9292   if (RD->isInvalidDecl()) return false;
9293   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9294 
9295   if (CD) {
9296     unsigned Index = 0;
9297     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
9298            End = CD->bases_end(); I != End; ++I, ++Index) {
9299       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
9300       LValue Subobject = This;
9301       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
9302         return false;
9303       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
9304                                          Result.getStructBase(Index)))
9305         return false;
9306     }
9307   }
9308 
9309   for (const auto *I : RD->fields()) {
9310     // -- if T is a reference type, no initialization is performed.
9311     if (I->getType()->isReferenceType())
9312       continue;
9313 
9314     LValue Subobject = This;
9315     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
9316       return false;
9317 
9318     ImplicitValueInitExpr VIE(I->getType());
9319     if (!EvaluateInPlace(
9320           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
9321       return false;
9322   }
9323 
9324   return true;
9325 }
9326 
9327 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
9328   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
9329   if (RD->isInvalidDecl()) return false;
9330   if (RD->isUnion()) {
9331     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
9332     // object's first non-static named data member is zero-initialized
9333     RecordDecl::field_iterator I = RD->field_begin();
9334     if (I == RD->field_end()) {
9335       Result = APValue((const FieldDecl*)nullptr);
9336       return true;
9337     }
9338 
9339     LValue Subobject = This;
9340     if (!HandleLValueMember(Info, E, Subobject, *I))
9341       return false;
9342     Result = APValue(*I);
9343     ImplicitValueInitExpr VIE(I->getType());
9344     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
9345   }
9346 
9347   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
9348     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
9349     return false;
9350   }
9351 
9352   return HandleClassZeroInitialization(Info, E, RD, This, Result);
9353 }
9354 
9355 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
9356   switch (E->getCastKind()) {
9357   default:
9358     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9359 
9360   case CK_ConstructorConversion:
9361     return Visit(E->getSubExpr());
9362 
9363   case CK_DerivedToBase:
9364   case CK_UncheckedDerivedToBase: {
9365     APValue DerivedObject;
9366     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
9367       return false;
9368     if (!DerivedObject.isStruct())
9369       return Error(E->getSubExpr());
9370 
9371     // Derived-to-base rvalue conversion: just slice off the derived part.
9372     APValue *Value = &DerivedObject;
9373     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
9374     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9375          PathE = E->path_end(); PathI != PathE; ++PathI) {
9376       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
9377       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9378       Value = &Value->getStructBase(getBaseIndex(RD, Base));
9379       RD = Base;
9380     }
9381     Result = *Value;
9382     return true;
9383   }
9384   }
9385 }
9386 
9387 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9388   if (E->isTransparent())
9389     return Visit(E->getInit(0));
9390 
9391   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
9392   if (RD->isInvalidDecl()) return false;
9393   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9394   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
9395 
9396   EvalInfo::EvaluatingConstructorRAII EvalObj(
9397       Info,
9398       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
9399       CXXRD && CXXRD->getNumBases());
9400 
9401   if (RD->isUnion()) {
9402     const FieldDecl *Field = E->getInitializedFieldInUnion();
9403     Result = APValue(Field);
9404     if (!Field)
9405       return true;
9406 
9407     // If the initializer list for a union does not contain any elements, the
9408     // first element of the union is value-initialized.
9409     // FIXME: The element should be initialized from an initializer list.
9410     //        Is this difference ever observable for initializer lists which
9411     //        we don't build?
9412     ImplicitValueInitExpr VIE(Field->getType());
9413     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
9414 
9415     LValue Subobject = This;
9416     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
9417       return false;
9418 
9419     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9420     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9421                                   isa<CXXDefaultInitExpr>(InitExpr));
9422 
9423     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
9424   }
9425 
9426   if (!Result.hasValue())
9427     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
9428                      std::distance(RD->field_begin(), RD->field_end()));
9429   unsigned ElementNo = 0;
9430   bool Success = true;
9431 
9432   // Initialize base classes.
9433   if (CXXRD && CXXRD->getNumBases()) {
9434     for (const auto &Base : CXXRD->bases()) {
9435       assert(ElementNo < E->getNumInits() && "missing init for base class");
9436       const Expr *Init = E->getInit(ElementNo);
9437 
9438       LValue Subobject = This;
9439       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
9440         return false;
9441 
9442       APValue &FieldVal = Result.getStructBase(ElementNo);
9443       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
9444         if (!Info.noteFailure())
9445           return false;
9446         Success = false;
9447       }
9448       ++ElementNo;
9449     }
9450 
9451     EvalObj.finishedConstructingBases();
9452   }
9453 
9454   // Initialize members.
9455   for (const auto *Field : RD->fields()) {
9456     // Anonymous bit-fields are not considered members of the class for
9457     // purposes of aggregate initialization.
9458     if (Field->isUnnamedBitfield())
9459       continue;
9460 
9461     LValue Subobject = This;
9462 
9463     bool HaveInit = ElementNo < E->getNumInits();
9464 
9465     // FIXME: Diagnostics here should point to the end of the initializer
9466     // list, not the start.
9467     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
9468                             Subobject, Field, &Layout))
9469       return false;
9470 
9471     // Perform an implicit value-initialization for members beyond the end of
9472     // the initializer list.
9473     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
9474     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
9475 
9476     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9477     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9478                                   isa<CXXDefaultInitExpr>(Init));
9479 
9480     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9481     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
9482         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
9483                                                        FieldVal, Field))) {
9484       if (!Info.noteFailure())
9485         return false;
9486       Success = false;
9487     }
9488   }
9489 
9490   EvalObj.finishedConstructingFields();
9491 
9492   return Success;
9493 }
9494 
9495 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
9496                                                 QualType T) {
9497   // Note that E's type is not necessarily the type of our class here; we might
9498   // be initializing an array element instead.
9499   const CXXConstructorDecl *FD = E->getConstructor();
9500   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
9501 
9502   bool ZeroInit = E->requiresZeroInitialization();
9503   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
9504     // If we've already performed zero-initialization, we're already done.
9505     if (Result.hasValue())
9506       return true;
9507 
9508     if (ZeroInit)
9509       return ZeroInitialization(E, T);
9510 
9511     return getDefaultInitValue(T, Result);
9512   }
9513 
9514   const FunctionDecl *Definition = nullptr;
9515   auto Body = FD->getBody(Definition);
9516 
9517   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9518     return false;
9519 
9520   // Avoid materializing a temporary for an elidable copy/move constructor.
9521   if (E->isElidable() && !ZeroInit)
9522     if (const MaterializeTemporaryExpr *ME
9523           = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
9524       return Visit(ME->getSubExpr());
9525 
9526   if (ZeroInit && !ZeroInitialization(E, T))
9527     return false;
9528 
9529   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
9530   return HandleConstructorCall(E, This, Args,
9531                                cast<CXXConstructorDecl>(Definition), Info,
9532                                Result);
9533 }
9534 
9535 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
9536     const CXXInheritedCtorInitExpr *E) {
9537   if (!Info.CurrentCall) {
9538     assert(Info.checkingPotentialConstantExpression());
9539     return false;
9540   }
9541 
9542   const CXXConstructorDecl *FD = E->getConstructor();
9543   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
9544     return false;
9545 
9546   const FunctionDecl *Definition = nullptr;
9547   auto Body = FD->getBody(Definition);
9548 
9549   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9550     return false;
9551 
9552   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
9553                                cast<CXXConstructorDecl>(Definition), Info,
9554                                Result);
9555 }
9556 
9557 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
9558     const CXXStdInitializerListExpr *E) {
9559   const ConstantArrayType *ArrayType =
9560       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
9561 
9562   LValue Array;
9563   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
9564     return false;
9565 
9566   // Get a pointer to the first element of the array.
9567   Array.addArray(Info, E, ArrayType);
9568 
9569   auto InvalidType = [&] {
9570     Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
9571       << E->getType();
9572     return false;
9573   };
9574 
9575   // FIXME: Perform the checks on the field types in SemaInit.
9576   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
9577   RecordDecl::field_iterator Field = Record->field_begin();
9578   if (Field == Record->field_end())
9579     return InvalidType();
9580 
9581   // Start pointer.
9582   if (!Field->getType()->isPointerType() ||
9583       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
9584                             ArrayType->getElementType()))
9585     return InvalidType();
9586 
9587   // FIXME: What if the initializer_list type has base classes, etc?
9588   Result = APValue(APValue::UninitStruct(), 0, 2);
9589   Array.moveInto(Result.getStructField(0));
9590 
9591   if (++Field == Record->field_end())
9592     return InvalidType();
9593 
9594   if (Field->getType()->isPointerType() &&
9595       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
9596                            ArrayType->getElementType())) {
9597     // End pointer.
9598     if (!HandleLValueArrayAdjustment(Info, E, Array,
9599                                      ArrayType->getElementType(),
9600                                      ArrayType->getSize().getZExtValue()))
9601       return false;
9602     Array.moveInto(Result.getStructField(1));
9603   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
9604     // Length.
9605     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
9606   else
9607     return InvalidType();
9608 
9609   if (++Field != Record->field_end())
9610     return InvalidType();
9611 
9612   return true;
9613 }
9614 
9615 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
9616   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
9617   if (ClosureClass->isInvalidDecl())
9618     return false;
9619 
9620   const size_t NumFields =
9621       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
9622 
9623   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
9624                                             E->capture_init_end()) &&
9625          "The number of lambda capture initializers should equal the number of "
9626          "fields within the closure type");
9627 
9628   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
9629   // Iterate through all the lambda's closure object's fields and initialize
9630   // them.
9631   auto *CaptureInitIt = E->capture_init_begin();
9632   const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
9633   bool Success = true;
9634   for (const auto *Field : ClosureClass->fields()) {
9635     assert(CaptureInitIt != E->capture_init_end());
9636     // Get the initializer for this field
9637     Expr *const CurFieldInit = *CaptureInitIt++;
9638 
9639     // If there is no initializer, either this is a VLA or an error has
9640     // occurred.
9641     if (!CurFieldInit)
9642       return Error(E);
9643 
9644     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9645     if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
9646       if (!Info.keepEvaluatingAfterFailure())
9647         return false;
9648       Success = false;
9649     }
9650     ++CaptureIt;
9651   }
9652   return Success;
9653 }
9654 
9655 static bool EvaluateRecord(const Expr *E, const LValue &This,
9656                            APValue &Result, EvalInfo &Info) {
9657   assert(E->isRValue() && E->getType()->isRecordType() &&
9658          "can't evaluate expression as a record rvalue");
9659   return RecordExprEvaluator(Info, This, Result).Visit(E);
9660 }
9661 
9662 //===----------------------------------------------------------------------===//
9663 // Temporary Evaluation
9664 //
9665 // Temporaries are represented in the AST as rvalues, but generally behave like
9666 // lvalues. The full-object of which the temporary is a subobject is implicitly
9667 // materialized so that a reference can bind to it.
9668 //===----------------------------------------------------------------------===//
9669 namespace {
9670 class TemporaryExprEvaluator
9671   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
9672 public:
9673   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
9674     LValueExprEvaluatorBaseTy(Info, Result, false) {}
9675 
9676   /// Visit an expression which constructs the value of this temporary.
9677   bool VisitConstructExpr(const Expr *E) {
9678     APValue &Value =
9679         Info.CurrentCall->createTemporary(E, E->getType(), false, Result);
9680     return EvaluateInPlace(Value, Info, Result, E);
9681   }
9682 
9683   bool VisitCastExpr(const CastExpr *E) {
9684     switch (E->getCastKind()) {
9685     default:
9686       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
9687 
9688     case CK_ConstructorConversion:
9689       return VisitConstructExpr(E->getSubExpr());
9690     }
9691   }
9692   bool VisitInitListExpr(const InitListExpr *E) {
9693     return VisitConstructExpr(E);
9694   }
9695   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9696     return VisitConstructExpr(E);
9697   }
9698   bool VisitCallExpr(const CallExpr *E) {
9699     return VisitConstructExpr(E);
9700   }
9701   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
9702     return VisitConstructExpr(E);
9703   }
9704   bool VisitLambdaExpr(const LambdaExpr *E) {
9705     return VisitConstructExpr(E);
9706   }
9707 };
9708 } // end anonymous namespace
9709 
9710 /// Evaluate an expression of record type as a temporary.
9711 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
9712   assert(E->isRValue() && E->getType()->isRecordType());
9713   return TemporaryExprEvaluator(Info, Result).Visit(E);
9714 }
9715 
9716 //===----------------------------------------------------------------------===//
9717 // Vector Evaluation
9718 //===----------------------------------------------------------------------===//
9719 
9720 namespace {
9721   class VectorExprEvaluator
9722   : public ExprEvaluatorBase<VectorExprEvaluator> {
9723     APValue &Result;
9724   public:
9725 
9726     VectorExprEvaluator(EvalInfo &info, APValue &Result)
9727       : ExprEvaluatorBaseTy(info), Result(Result) {}
9728 
9729     bool Success(ArrayRef<APValue> V, const Expr *E) {
9730       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
9731       // FIXME: remove this APValue copy.
9732       Result = APValue(V.data(), V.size());
9733       return true;
9734     }
9735     bool Success(const APValue &V, const Expr *E) {
9736       assert(V.isVector());
9737       Result = V;
9738       return true;
9739     }
9740     bool ZeroInitialization(const Expr *E);
9741 
9742     bool VisitUnaryReal(const UnaryOperator *E)
9743       { return Visit(E->getSubExpr()); }
9744     bool VisitCastExpr(const CastExpr* E);
9745     bool VisitInitListExpr(const InitListExpr *E);
9746     bool VisitUnaryImag(const UnaryOperator *E);
9747     bool VisitBinaryOperator(const BinaryOperator *E);
9748     // FIXME: Missing: unary -, unary ~, conditional operator (for GNU
9749     //                 conditional select), shufflevector, ExtVectorElementExpr
9750   };
9751 } // end anonymous namespace
9752 
9753 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
9754   assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
9755   return VectorExprEvaluator(Info, Result).Visit(E);
9756 }
9757 
9758 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
9759   const VectorType *VTy = E->getType()->castAs<VectorType>();
9760   unsigned NElts = VTy->getNumElements();
9761 
9762   const Expr *SE = E->getSubExpr();
9763   QualType SETy = SE->getType();
9764 
9765   switch (E->getCastKind()) {
9766   case CK_VectorSplat: {
9767     APValue Val = APValue();
9768     if (SETy->isIntegerType()) {
9769       APSInt IntResult;
9770       if (!EvaluateInteger(SE, IntResult, Info))
9771         return false;
9772       Val = APValue(std::move(IntResult));
9773     } else if (SETy->isRealFloatingType()) {
9774       APFloat FloatResult(0.0);
9775       if (!EvaluateFloat(SE, FloatResult, Info))
9776         return false;
9777       Val = APValue(std::move(FloatResult));
9778     } else {
9779       return Error(E);
9780     }
9781 
9782     // Splat and create vector APValue.
9783     SmallVector<APValue, 4> Elts(NElts, Val);
9784     return Success(Elts, E);
9785   }
9786   case CK_BitCast: {
9787     // Evaluate the operand into an APInt we can extract from.
9788     llvm::APInt SValInt;
9789     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
9790       return false;
9791     // Extract the elements
9792     QualType EltTy = VTy->getElementType();
9793     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
9794     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
9795     SmallVector<APValue, 4> Elts;
9796     if (EltTy->isRealFloatingType()) {
9797       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
9798       unsigned FloatEltSize = EltSize;
9799       if (&Sem == &APFloat::x87DoubleExtended())
9800         FloatEltSize = 80;
9801       for (unsigned i = 0; i < NElts; i++) {
9802         llvm::APInt Elt;
9803         if (BigEndian)
9804           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
9805         else
9806           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
9807         Elts.push_back(APValue(APFloat(Sem, Elt)));
9808       }
9809     } else if (EltTy->isIntegerType()) {
9810       for (unsigned i = 0; i < NElts; i++) {
9811         llvm::APInt Elt;
9812         if (BigEndian)
9813           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
9814         else
9815           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
9816         Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
9817       }
9818     } else {
9819       return Error(E);
9820     }
9821     return Success(Elts, E);
9822   }
9823   default:
9824     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9825   }
9826 }
9827 
9828 bool
9829 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9830   const VectorType *VT = E->getType()->castAs<VectorType>();
9831   unsigned NumInits = E->getNumInits();
9832   unsigned NumElements = VT->getNumElements();
9833 
9834   QualType EltTy = VT->getElementType();
9835   SmallVector<APValue, 4> Elements;
9836 
9837   // The number of initializers can be less than the number of
9838   // vector elements. For OpenCL, this can be due to nested vector
9839   // initialization. For GCC compatibility, missing trailing elements
9840   // should be initialized with zeroes.
9841   unsigned CountInits = 0, CountElts = 0;
9842   while (CountElts < NumElements) {
9843     // Handle nested vector initialization.
9844     if (CountInits < NumInits
9845         && E->getInit(CountInits)->getType()->isVectorType()) {
9846       APValue v;
9847       if (!EvaluateVector(E->getInit(CountInits), v, Info))
9848         return Error(E);
9849       unsigned vlen = v.getVectorLength();
9850       for (unsigned j = 0; j < vlen; j++)
9851         Elements.push_back(v.getVectorElt(j));
9852       CountElts += vlen;
9853     } else if (EltTy->isIntegerType()) {
9854       llvm::APSInt sInt(32);
9855       if (CountInits < NumInits) {
9856         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
9857           return false;
9858       } else // trailing integer zero.
9859         sInt = Info.Ctx.MakeIntValue(0, EltTy);
9860       Elements.push_back(APValue(sInt));
9861       CountElts++;
9862     } else {
9863       llvm::APFloat f(0.0);
9864       if (CountInits < NumInits) {
9865         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
9866           return false;
9867       } else // trailing float zero.
9868         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
9869       Elements.push_back(APValue(f));
9870       CountElts++;
9871     }
9872     CountInits++;
9873   }
9874   return Success(Elements, E);
9875 }
9876 
9877 bool
9878 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
9879   const auto *VT = E->getType()->castAs<VectorType>();
9880   QualType EltTy = VT->getElementType();
9881   APValue ZeroElement;
9882   if (EltTy->isIntegerType())
9883     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
9884   else
9885     ZeroElement =
9886         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
9887 
9888   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
9889   return Success(Elements, E);
9890 }
9891 
9892 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9893   VisitIgnoredValue(E->getSubExpr());
9894   return ZeroInitialization(E);
9895 }
9896 
9897 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9898   BinaryOperatorKind Op = E->getOpcode();
9899   assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
9900          "Operation not supported on vector types");
9901 
9902   if (Op == BO_Comma)
9903     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9904 
9905   Expr *LHS = E->getLHS();
9906   Expr *RHS = E->getRHS();
9907 
9908   assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
9909          "Must both be vector types");
9910   // Checking JUST the types are the same would be fine, except shifts don't
9911   // need to have their types be the same (since you always shift by an int).
9912   assert(LHS->getType()->getAs<VectorType>()->getNumElements() ==
9913              E->getType()->getAs<VectorType>()->getNumElements() &&
9914          RHS->getType()->getAs<VectorType>()->getNumElements() ==
9915              E->getType()->getAs<VectorType>()->getNumElements() &&
9916          "All operands must be the same size.");
9917 
9918   APValue LHSValue;
9919   APValue RHSValue;
9920   bool LHSOK = Evaluate(LHSValue, Info, LHS);
9921   if (!LHSOK && !Info.noteFailure())
9922     return false;
9923   if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
9924     return false;
9925 
9926   if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
9927     return false;
9928 
9929   return Success(LHSValue, E);
9930 }
9931 
9932 //===----------------------------------------------------------------------===//
9933 // Array Evaluation
9934 //===----------------------------------------------------------------------===//
9935 
9936 namespace {
9937   class ArrayExprEvaluator
9938   : public ExprEvaluatorBase<ArrayExprEvaluator> {
9939     const LValue &This;
9940     APValue &Result;
9941   public:
9942 
9943     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
9944       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
9945 
9946     bool Success(const APValue &V, const Expr *E) {
9947       assert(V.isArray() && "expected array");
9948       Result = V;
9949       return true;
9950     }
9951 
9952     bool ZeroInitialization(const Expr *E) {
9953       const ConstantArrayType *CAT =
9954           Info.Ctx.getAsConstantArrayType(E->getType());
9955       if (!CAT) {
9956         if (E->getType()->isIncompleteArrayType()) {
9957           // We can be asked to zero-initialize a flexible array member; this
9958           // is represented as an ImplicitValueInitExpr of incomplete array
9959           // type. In this case, the array has zero elements.
9960           Result = APValue(APValue::UninitArray(), 0, 0);
9961           return true;
9962         }
9963         // FIXME: We could handle VLAs here.
9964         return Error(E);
9965       }
9966 
9967       Result = APValue(APValue::UninitArray(), 0,
9968                        CAT->getSize().getZExtValue());
9969       if (!Result.hasArrayFiller()) return true;
9970 
9971       // Zero-initialize all elements.
9972       LValue Subobject = This;
9973       Subobject.addArray(Info, E, CAT);
9974       ImplicitValueInitExpr VIE(CAT->getElementType());
9975       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
9976     }
9977 
9978     bool VisitCallExpr(const CallExpr *E) {
9979       return handleCallExpr(E, Result, &This);
9980     }
9981     bool VisitInitListExpr(const InitListExpr *E,
9982                            QualType AllocType = QualType());
9983     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
9984     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
9985     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
9986                                const LValue &Subobject,
9987                                APValue *Value, QualType Type);
9988     bool VisitStringLiteral(const StringLiteral *E,
9989                             QualType AllocType = QualType()) {
9990       expandStringLiteral(Info, E, Result, AllocType);
9991       return true;
9992     }
9993   };
9994 } // end anonymous namespace
9995 
9996 static bool EvaluateArray(const Expr *E, const LValue &This,
9997                           APValue &Result, EvalInfo &Info) {
9998   assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
9999   return ArrayExprEvaluator(Info, This, Result).Visit(E);
10000 }
10001 
10002 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10003                                      APValue &Result, const InitListExpr *ILE,
10004                                      QualType AllocType) {
10005   assert(ILE->isRValue() && ILE->getType()->isArrayType() &&
10006          "not an array rvalue");
10007   return ArrayExprEvaluator(Info, This, Result)
10008       .VisitInitListExpr(ILE, AllocType);
10009 }
10010 
10011 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10012                                           APValue &Result,
10013                                           const CXXConstructExpr *CCE,
10014                                           QualType AllocType) {
10015   assert(CCE->isRValue() && CCE->getType()->isArrayType() &&
10016          "not an array rvalue");
10017   return ArrayExprEvaluator(Info, This, Result)
10018       .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
10019 }
10020 
10021 // Return true iff the given array filler may depend on the element index.
10022 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
10023   // For now, just allow non-class value-initialization and initialization
10024   // lists comprised of them.
10025   if (isa<ImplicitValueInitExpr>(FillerExpr))
10026     return false;
10027   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
10028     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
10029       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
10030         return true;
10031     }
10032     return false;
10033   }
10034   return true;
10035 }
10036 
10037 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
10038                                            QualType AllocType) {
10039   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
10040       AllocType.isNull() ? E->getType() : AllocType);
10041   if (!CAT)
10042     return Error(E);
10043 
10044   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
10045   // an appropriately-typed string literal enclosed in braces.
10046   if (E->isStringLiteralInit()) {
10047     auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens());
10048     // FIXME: Support ObjCEncodeExpr here once we support it in
10049     // ArrayExprEvaluator generally.
10050     if (!SL)
10051       return Error(E);
10052     return VisitStringLiteral(SL, AllocType);
10053   }
10054 
10055   bool Success = true;
10056 
10057   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
10058          "zero-initialized array shouldn't have any initialized elts");
10059   APValue Filler;
10060   if (Result.isArray() && Result.hasArrayFiller())
10061     Filler = Result.getArrayFiller();
10062 
10063   unsigned NumEltsToInit = E->getNumInits();
10064   unsigned NumElts = CAT->getSize().getZExtValue();
10065   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
10066 
10067   // If the initializer might depend on the array index, run it for each
10068   // array element.
10069   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
10070     NumEltsToInit = NumElts;
10071 
10072   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
10073                           << NumEltsToInit << ".\n");
10074 
10075   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
10076 
10077   // If the array was previously zero-initialized, preserve the
10078   // zero-initialized values.
10079   if (Filler.hasValue()) {
10080     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
10081       Result.getArrayInitializedElt(I) = Filler;
10082     if (Result.hasArrayFiller())
10083       Result.getArrayFiller() = Filler;
10084   }
10085 
10086   LValue Subobject = This;
10087   Subobject.addArray(Info, E, CAT);
10088   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
10089     const Expr *Init =
10090         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
10091     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10092                          Info, Subobject, Init) ||
10093         !HandleLValueArrayAdjustment(Info, Init, Subobject,
10094                                      CAT->getElementType(), 1)) {
10095       if (!Info.noteFailure())
10096         return false;
10097       Success = false;
10098     }
10099   }
10100 
10101   if (!Result.hasArrayFiller())
10102     return Success;
10103 
10104   // If we get here, we have a trivial filler, which we can just evaluate
10105   // once and splat over the rest of the array elements.
10106   assert(FillerExpr && "no array filler for incomplete init list");
10107   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
10108                          FillerExpr) && Success;
10109 }
10110 
10111 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
10112   LValue CommonLV;
10113   if (E->getCommonExpr() &&
10114       !Evaluate(Info.CurrentCall->createTemporary(
10115                     E->getCommonExpr(),
10116                     getStorageType(Info.Ctx, E->getCommonExpr()), false,
10117                     CommonLV),
10118                 Info, E->getCommonExpr()->getSourceExpr()))
10119     return false;
10120 
10121   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
10122 
10123   uint64_t Elements = CAT->getSize().getZExtValue();
10124   Result = APValue(APValue::UninitArray(), Elements, Elements);
10125 
10126   LValue Subobject = This;
10127   Subobject.addArray(Info, E, CAT);
10128 
10129   bool Success = true;
10130   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
10131     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10132                          Info, Subobject, E->getSubExpr()) ||
10133         !HandleLValueArrayAdjustment(Info, E, Subobject,
10134                                      CAT->getElementType(), 1)) {
10135       if (!Info.noteFailure())
10136         return false;
10137       Success = false;
10138     }
10139   }
10140 
10141   return Success;
10142 }
10143 
10144 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
10145   return VisitCXXConstructExpr(E, This, &Result, E->getType());
10146 }
10147 
10148 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10149                                                const LValue &Subobject,
10150                                                APValue *Value,
10151                                                QualType Type) {
10152   bool HadZeroInit = Value->hasValue();
10153 
10154   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
10155     unsigned N = CAT->getSize().getZExtValue();
10156 
10157     // Preserve the array filler if we had prior zero-initialization.
10158     APValue Filler =
10159       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
10160                                              : APValue();
10161 
10162     *Value = APValue(APValue::UninitArray(), N, N);
10163 
10164     if (HadZeroInit)
10165       for (unsigned I = 0; I != N; ++I)
10166         Value->getArrayInitializedElt(I) = Filler;
10167 
10168     // Initialize the elements.
10169     LValue ArrayElt = Subobject;
10170     ArrayElt.addArray(Info, E, CAT);
10171     for (unsigned I = 0; I != N; ++I)
10172       if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
10173                                  CAT->getElementType()) ||
10174           !HandleLValueArrayAdjustment(Info, E, ArrayElt,
10175                                        CAT->getElementType(), 1))
10176         return false;
10177 
10178     return true;
10179   }
10180 
10181   if (!Type->isRecordType())
10182     return Error(E);
10183 
10184   return RecordExprEvaluator(Info, Subobject, *Value)
10185              .VisitCXXConstructExpr(E, Type);
10186 }
10187 
10188 //===----------------------------------------------------------------------===//
10189 // Integer Evaluation
10190 //
10191 // As a GNU extension, we support casting pointers to sufficiently-wide integer
10192 // types and back in constant folding. Integer values are thus represented
10193 // either as an integer-valued APValue, or as an lvalue-valued APValue.
10194 //===----------------------------------------------------------------------===//
10195 
10196 namespace {
10197 class IntExprEvaluator
10198         : public ExprEvaluatorBase<IntExprEvaluator> {
10199   APValue &Result;
10200 public:
10201   IntExprEvaluator(EvalInfo &info, APValue &result)
10202       : ExprEvaluatorBaseTy(info), Result(result) {}
10203 
10204   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
10205     assert(E->getType()->isIntegralOrEnumerationType() &&
10206            "Invalid evaluation result.");
10207     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
10208            "Invalid evaluation result.");
10209     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10210            "Invalid evaluation result.");
10211     Result = APValue(SI);
10212     return true;
10213   }
10214   bool Success(const llvm::APSInt &SI, const Expr *E) {
10215     return Success(SI, E, Result);
10216   }
10217 
10218   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
10219     assert(E->getType()->isIntegralOrEnumerationType() &&
10220            "Invalid evaluation result.");
10221     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10222            "Invalid evaluation result.");
10223     Result = APValue(APSInt(I));
10224     Result.getInt().setIsUnsigned(
10225                             E->getType()->isUnsignedIntegerOrEnumerationType());
10226     return true;
10227   }
10228   bool Success(const llvm::APInt &I, const Expr *E) {
10229     return Success(I, E, Result);
10230   }
10231 
10232   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
10233     assert(E->getType()->isIntegralOrEnumerationType() &&
10234            "Invalid evaluation result.");
10235     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
10236     return true;
10237   }
10238   bool Success(uint64_t Value, const Expr *E) {
10239     return Success(Value, E, Result);
10240   }
10241 
10242   bool Success(CharUnits Size, const Expr *E) {
10243     return Success(Size.getQuantity(), E);
10244   }
10245 
10246   bool Success(const APValue &V, const Expr *E) {
10247     if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
10248       Result = V;
10249       return true;
10250     }
10251     return Success(V.getInt(), E);
10252   }
10253 
10254   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
10255 
10256   //===--------------------------------------------------------------------===//
10257   //                            Visitor Methods
10258   //===--------------------------------------------------------------------===//
10259 
10260   bool VisitIntegerLiteral(const IntegerLiteral *E) {
10261     return Success(E->getValue(), E);
10262   }
10263   bool VisitCharacterLiteral(const CharacterLiteral *E) {
10264     return Success(E->getValue(), E);
10265   }
10266 
10267   bool CheckReferencedDecl(const Expr *E, const Decl *D);
10268   bool VisitDeclRefExpr(const DeclRefExpr *E) {
10269     if (CheckReferencedDecl(E, E->getDecl()))
10270       return true;
10271 
10272     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
10273   }
10274   bool VisitMemberExpr(const MemberExpr *E) {
10275     if (CheckReferencedDecl(E, E->getMemberDecl())) {
10276       VisitIgnoredBaseExpression(E->getBase());
10277       return true;
10278     }
10279 
10280     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
10281   }
10282 
10283   bool VisitCallExpr(const CallExpr *E);
10284   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
10285   bool VisitBinaryOperator(const BinaryOperator *E);
10286   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
10287   bool VisitUnaryOperator(const UnaryOperator *E);
10288 
10289   bool VisitCastExpr(const CastExpr* E);
10290   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
10291 
10292   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
10293     return Success(E->getValue(), E);
10294   }
10295 
10296   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
10297     return Success(E->getValue(), E);
10298   }
10299 
10300   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
10301     if (Info.ArrayInitIndex == uint64_t(-1)) {
10302       // We were asked to evaluate this subexpression independent of the
10303       // enclosing ArrayInitLoopExpr. We can't do that.
10304       Info.FFDiag(E);
10305       return false;
10306     }
10307     return Success(Info.ArrayInitIndex, E);
10308   }
10309 
10310   // Note, GNU defines __null as an integer, not a pointer.
10311   bool VisitGNUNullExpr(const GNUNullExpr *E) {
10312     return ZeroInitialization(E);
10313   }
10314 
10315   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
10316     return Success(E->getValue(), E);
10317   }
10318 
10319   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
10320     return Success(E->getValue(), E);
10321   }
10322 
10323   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
10324     return Success(E->getValue(), E);
10325   }
10326 
10327   bool VisitUnaryReal(const UnaryOperator *E);
10328   bool VisitUnaryImag(const UnaryOperator *E);
10329 
10330   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
10331   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
10332   bool VisitSourceLocExpr(const SourceLocExpr *E);
10333   bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
10334   bool VisitRequiresExpr(const RequiresExpr *E);
10335   // FIXME: Missing: array subscript of vector, member of vector
10336 };
10337 
10338 class FixedPointExprEvaluator
10339     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
10340   APValue &Result;
10341 
10342  public:
10343   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
10344       : ExprEvaluatorBaseTy(info), Result(result) {}
10345 
10346   bool Success(const llvm::APInt &I, const Expr *E) {
10347     return Success(
10348         APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10349   }
10350 
10351   bool Success(uint64_t Value, const Expr *E) {
10352     return Success(
10353         APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10354   }
10355 
10356   bool Success(const APValue &V, const Expr *E) {
10357     return Success(V.getFixedPoint(), E);
10358   }
10359 
10360   bool Success(const APFixedPoint &V, const Expr *E) {
10361     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
10362     assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10363            "Invalid evaluation result.");
10364     Result = APValue(V);
10365     return true;
10366   }
10367 
10368   //===--------------------------------------------------------------------===//
10369   //                            Visitor Methods
10370   //===--------------------------------------------------------------------===//
10371 
10372   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
10373     return Success(E->getValue(), E);
10374   }
10375 
10376   bool VisitCastExpr(const CastExpr *E);
10377   bool VisitUnaryOperator(const UnaryOperator *E);
10378   bool VisitBinaryOperator(const BinaryOperator *E);
10379 };
10380 } // end anonymous namespace
10381 
10382 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
10383 /// produce either the integer value or a pointer.
10384 ///
10385 /// GCC has a heinous extension which folds casts between pointer types and
10386 /// pointer-sized integral types. We support this by allowing the evaluation of
10387 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
10388 /// Some simple arithmetic on such values is supported (they are treated much
10389 /// like char*).
10390 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
10391                                     EvalInfo &Info) {
10392   assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
10393   return IntExprEvaluator(Info, Result).Visit(E);
10394 }
10395 
10396 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
10397   APValue Val;
10398   if (!EvaluateIntegerOrLValue(E, Val, Info))
10399     return false;
10400   if (!Val.isInt()) {
10401     // FIXME: It would be better to produce the diagnostic for casting
10402     //        a pointer to an integer.
10403     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10404     return false;
10405   }
10406   Result = Val.getInt();
10407   return true;
10408 }
10409 
10410 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
10411   APValue Evaluated = E->EvaluateInContext(
10412       Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
10413   return Success(Evaluated, E);
10414 }
10415 
10416 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
10417                                EvalInfo &Info) {
10418   if (E->getType()->isFixedPointType()) {
10419     APValue Val;
10420     if (!FixedPointExprEvaluator(Info, Val).Visit(E))
10421       return false;
10422     if (!Val.isFixedPoint())
10423       return false;
10424 
10425     Result = Val.getFixedPoint();
10426     return true;
10427   }
10428   return false;
10429 }
10430 
10431 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
10432                                         EvalInfo &Info) {
10433   if (E->getType()->isIntegerType()) {
10434     auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
10435     APSInt Val;
10436     if (!EvaluateInteger(E, Val, Info))
10437       return false;
10438     Result = APFixedPoint(Val, FXSema);
10439     return true;
10440   } else if (E->getType()->isFixedPointType()) {
10441     return EvaluateFixedPoint(E, Result, Info);
10442   }
10443   return false;
10444 }
10445 
10446 /// Check whether the given declaration can be directly converted to an integral
10447 /// rvalue. If not, no diagnostic is produced; there are other things we can
10448 /// try.
10449 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
10450   // Enums are integer constant exprs.
10451   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
10452     // Check for signedness/width mismatches between E type and ECD value.
10453     bool SameSign = (ECD->getInitVal().isSigned()
10454                      == E->getType()->isSignedIntegerOrEnumerationType());
10455     bool SameWidth = (ECD->getInitVal().getBitWidth()
10456                       == Info.Ctx.getIntWidth(E->getType()));
10457     if (SameSign && SameWidth)
10458       return Success(ECD->getInitVal(), E);
10459     else {
10460       // Get rid of mismatch (otherwise Success assertions will fail)
10461       // by computing a new value matching the type of E.
10462       llvm::APSInt Val = ECD->getInitVal();
10463       if (!SameSign)
10464         Val.setIsSigned(!ECD->getInitVal().isSigned());
10465       if (!SameWidth)
10466         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
10467       return Success(Val, E);
10468     }
10469   }
10470   return false;
10471 }
10472 
10473 /// Values returned by __builtin_classify_type, chosen to match the values
10474 /// produced by GCC's builtin.
10475 enum class GCCTypeClass {
10476   None = -1,
10477   Void = 0,
10478   Integer = 1,
10479   // GCC reserves 2 for character types, but instead classifies them as
10480   // integers.
10481   Enum = 3,
10482   Bool = 4,
10483   Pointer = 5,
10484   // GCC reserves 6 for references, but appears to never use it (because
10485   // expressions never have reference type, presumably).
10486   PointerToDataMember = 7,
10487   RealFloat = 8,
10488   Complex = 9,
10489   // GCC reserves 10 for functions, but does not use it since GCC version 6 due
10490   // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
10491   // GCC claims to reserve 11 for pointers to member functions, but *actually*
10492   // uses 12 for that purpose, same as for a class or struct. Maybe it
10493   // internally implements a pointer to member as a struct?  Who knows.
10494   PointerToMemberFunction = 12, // Not a bug, see above.
10495   ClassOrStruct = 12,
10496   Union = 13,
10497   // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
10498   // decay to pointer. (Prior to version 6 it was only used in C++ mode).
10499   // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
10500   // literals.
10501 };
10502 
10503 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
10504 /// as GCC.
10505 static GCCTypeClass
10506 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
10507   assert(!T->isDependentType() && "unexpected dependent type");
10508 
10509   QualType CanTy = T.getCanonicalType();
10510   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
10511 
10512   switch (CanTy->getTypeClass()) {
10513 #define TYPE(ID, BASE)
10514 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
10515 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
10516 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
10517 #include "clang/AST/TypeNodes.inc"
10518   case Type::Auto:
10519   case Type::DeducedTemplateSpecialization:
10520       llvm_unreachable("unexpected non-canonical or dependent type");
10521 
10522   case Type::Builtin:
10523     switch (BT->getKind()) {
10524 #define BUILTIN_TYPE(ID, SINGLETON_ID)
10525 #define SIGNED_TYPE(ID, SINGLETON_ID) \
10526     case BuiltinType::ID: return GCCTypeClass::Integer;
10527 #define FLOATING_TYPE(ID, SINGLETON_ID) \
10528     case BuiltinType::ID: return GCCTypeClass::RealFloat;
10529 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
10530     case BuiltinType::ID: break;
10531 #include "clang/AST/BuiltinTypes.def"
10532     case BuiltinType::Void:
10533       return GCCTypeClass::Void;
10534 
10535     case BuiltinType::Bool:
10536       return GCCTypeClass::Bool;
10537 
10538     case BuiltinType::Char_U:
10539     case BuiltinType::UChar:
10540     case BuiltinType::WChar_U:
10541     case BuiltinType::Char8:
10542     case BuiltinType::Char16:
10543     case BuiltinType::Char32:
10544     case BuiltinType::UShort:
10545     case BuiltinType::UInt:
10546     case BuiltinType::ULong:
10547     case BuiltinType::ULongLong:
10548     case BuiltinType::UInt128:
10549       return GCCTypeClass::Integer;
10550 
10551     case BuiltinType::UShortAccum:
10552     case BuiltinType::UAccum:
10553     case BuiltinType::ULongAccum:
10554     case BuiltinType::UShortFract:
10555     case BuiltinType::UFract:
10556     case BuiltinType::ULongFract:
10557     case BuiltinType::SatUShortAccum:
10558     case BuiltinType::SatUAccum:
10559     case BuiltinType::SatULongAccum:
10560     case BuiltinType::SatUShortFract:
10561     case BuiltinType::SatUFract:
10562     case BuiltinType::SatULongFract:
10563       return GCCTypeClass::None;
10564 
10565     case BuiltinType::NullPtr:
10566 
10567     case BuiltinType::ObjCId:
10568     case BuiltinType::ObjCClass:
10569     case BuiltinType::ObjCSel:
10570 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
10571     case BuiltinType::Id:
10572 #include "clang/Basic/OpenCLImageTypes.def"
10573 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
10574     case BuiltinType::Id:
10575 #include "clang/Basic/OpenCLExtensionTypes.def"
10576     case BuiltinType::OCLSampler:
10577     case BuiltinType::OCLEvent:
10578     case BuiltinType::OCLClkEvent:
10579     case BuiltinType::OCLQueue:
10580     case BuiltinType::OCLReserveID:
10581 #define SVE_TYPE(Name, Id, SingletonId) \
10582     case BuiltinType::Id:
10583 #include "clang/Basic/AArch64SVEACLETypes.def"
10584       return GCCTypeClass::None;
10585 
10586     case BuiltinType::Dependent:
10587       llvm_unreachable("unexpected dependent type");
10588     };
10589     llvm_unreachable("unexpected placeholder type");
10590 
10591   case Type::Enum:
10592     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
10593 
10594   case Type::Pointer:
10595   case Type::ConstantArray:
10596   case Type::VariableArray:
10597   case Type::IncompleteArray:
10598   case Type::FunctionNoProto:
10599   case Type::FunctionProto:
10600     return GCCTypeClass::Pointer;
10601 
10602   case Type::MemberPointer:
10603     return CanTy->isMemberDataPointerType()
10604                ? GCCTypeClass::PointerToDataMember
10605                : GCCTypeClass::PointerToMemberFunction;
10606 
10607   case Type::Complex:
10608     return GCCTypeClass::Complex;
10609 
10610   case Type::Record:
10611     return CanTy->isUnionType() ? GCCTypeClass::Union
10612                                 : GCCTypeClass::ClassOrStruct;
10613 
10614   case Type::Atomic:
10615     // GCC classifies _Atomic T the same as T.
10616     return EvaluateBuiltinClassifyType(
10617         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
10618 
10619   case Type::BlockPointer:
10620   case Type::Vector:
10621   case Type::ExtVector:
10622   case Type::ConstantMatrix:
10623   case Type::ObjCObject:
10624   case Type::ObjCInterface:
10625   case Type::ObjCObjectPointer:
10626   case Type::Pipe:
10627   case Type::ExtInt:
10628     // GCC classifies vectors as None. We follow its lead and classify all
10629     // other types that don't fit into the regular classification the same way.
10630     return GCCTypeClass::None;
10631 
10632   case Type::LValueReference:
10633   case Type::RValueReference:
10634     llvm_unreachable("invalid type for expression");
10635   }
10636 
10637   llvm_unreachable("unexpected type class");
10638 }
10639 
10640 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
10641 /// as GCC.
10642 static GCCTypeClass
10643 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
10644   // If no argument was supplied, default to None. This isn't
10645   // ideal, however it is what gcc does.
10646   if (E->getNumArgs() == 0)
10647     return GCCTypeClass::None;
10648 
10649   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
10650   // being an ICE, but still folds it to a constant using the type of the first
10651   // argument.
10652   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
10653 }
10654 
10655 /// EvaluateBuiltinConstantPForLValue - Determine the result of
10656 /// __builtin_constant_p when applied to the given pointer.
10657 ///
10658 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
10659 /// or it points to the first character of a string literal.
10660 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
10661   APValue::LValueBase Base = LV.getLValueBase();
10662   if (Base.isNull()) {
10663     // A null base is acceptable.
10664     return true;
10665   } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
10666     if (!isa<StringLiteral>(E))
10667       return false;
10668     return LV.getLValueOffset().isZero();
10669   } else if (Base.is<TypeInfoLValue>()) {
10670     // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
10671     // evaluate to true.
10672     return true;
10673   } else {
10674     // Any other base is not constant enough for GCC.
10675     return false;
10676   }
10677 }
10678 
10679 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
10680 /// GCC as we can manage.
10681 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
10682   // This evaluation is not permitted to have side-effects, so evaluate it in
10683   // a speculative evaluation context.
10684   SpeculativeEvaluationRAII SpeculativeEval(Info);
10685 
10686   // Constant-folding is always enabled for the operand of __builtin_constant_p
10687   // (even when the enclosing evaluation context otherwise requires a strict
10688   // language-specific constant expression).
10689   FoldConstant Fold(Info, true);
10690 
10691   QualType ArgType = Arg->getType();
10692 
10693   // __builtin_constant_p always has one operand. The rules which gcc follows
10694   // are not precisely documented, but are as follows:
10695   //
10696   //  - If the operand is of integral, floating, complex or enumeration type,
10697   //    and can be folded to a known value of that type, it returns 1.
10698   //  - If the operand can be folded to a pointer to the first character
10699   //    of a string literal (or such a pointer cast to an integral type)
10700   //    or to a null pointer or an integer cast to a pointer, it returns 1.
10701   //
10702   // Otherwise, it returns 0.
10703   //
10704   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
10705   // its support for this did not work prior to GCC 9 and is not yet well
10706   // understood.
10707   if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
10708       ArgType->isAnyComplexType() || ArgType->isPointerType() ||
10709       ArgType->isNullPtrType()) {
10710     APValue V;
10711     if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
10712       Fold.keepDiagnostics();
10713       return false;
10714     }
10715 
10716     // For a pointer (possibly cast to integer), there are special rules.
10717     if (V.getKind() == APValue::LValue)
10718       return EvaluateBuiltinConstantPForLValue(V);
10719 
10720     // Otherwise, any constant value is good enough.
10721     return V.hasValue();
10722   }
10723 
10724   // Anything else isn't considered to be sufficiently constant.
10725   return false;
10726 }
10727 
10728 /// Retrieves the "underlying object type" of the given expression,
10729 /// as used by __builtin_object_size.
10730 static QualType getObjectType(APValue::LValueBase B) {
10731   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
10732     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
10733       return VD->getType();
10734   } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
10735     if (isa<CompoundLiteralExpr>(E))
10736       return E->getType();
10737   } else if (B.is<TypeInfoLValue>()) {
10738     return B.getTypeInfoType();
10739   } else if (B.is<DynamicAllocLValue>()) {
10740     return B.getDynamicAllocType();
10741   }
10742 
10743   return QualType();
10744 }
10745 
10746 /// A more selective version of E->IgnoreParenCasts for
10747 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
10748 /// to change the type of E.
10749 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
10750 ///
10751 /// Always returns an RValue with a pointer representation.
10752 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
10753   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
10754 
10755   auto *NoParens = E->IgnoreParens();
10756   auto *Cast = dyn_cast<CastExpr>(NoParens);
10757   if (Cast == nullptr)
10758     return NoParens;
10759 
10760   // We only conservatively allow a few kinds of casts, because this code is
10761   // inherently a simple solution that seeks to support the common case.
10762   auto CastKind = Cast->getCastKind();
10763   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
10764       CastKind != CK_AddressSpaceConversion)
10765     return NoParens;
10766 
10767   auto *SubExpr = Cast->getSubExpr();
10768   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
10769     return NoParens;
10770   return ignorePointerCastsAndParens(SubExpr);
10771 }
10772 
10773 /// Checks to see if the given LValue's Designator is at the end of the LValue's
10774 /// record layout. e.g.
10775 ///   struct { struct { int a, b; } fst, snd; } obj;
10776 ///   obj.fst   // no
10777 ///   obj.snd   // yes
10778 ///   obj.fst.a // no
10779 ///   obj.fst.b // no
10780 ///   obj.snd.a // no
10781 ///   obj.snd.b // yes
10782 ///
10783 /// Please note: this function is specialized for how __builtin_object_size
10784 /// views "objects".
10785 ///
10786 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
10787 /// correct result, it will always return true.
10788 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
10789   assert(!LVal.Designator.Invalid);
10790 
10791   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
10792     const RecordDecl *Parent = FD->getParent();
10793     Invalid = Parent->isInvalidDecl();
10794     if (Invalid || Parent->isUnion())
10795       return true;
10796     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
10797     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
10798   };
10799 
10800   auto &Base = LVal.getLValueBase();
10801   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
10802     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
10803       bool Invalid;
10804       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
10805         return Invalid;
10806     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
10807       for (auto *FD : IFD->chain()) {
10808         bool Invalid;
10809         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
10810           return Invalid;
10811       }
10812     }
10813   }
10814 
10815   unsigned I = 0;
10816   QualType BaseType = getType(Base);
10817   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
10818     // If we don't know the array bound, conservatively assume we're looking at
10819     // the final array element.
10820     ++I;
10821     if (BaseType->isIncompleteArrayType())
10822       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
10823     else
10824       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
10825   }
10826 
10827   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
10828     const auto &Entry = LVal.Designator.Entries[I];
10829     if (BaseType->isArrayType()) {
10830       // Because __builtin_object_size treats arrays as objects, we can ignore
10831       // the index iff this is the last array in the Designator.
10832       if (I + 1 == E)
10833         return true;
10834       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
10835       uint64_t Index = Entry.getAsArrayIndex();
10836       if (Index + 1 != CAT->getSize())
10837         return false;
10838       BaseType = CAT->getElementType();
10839     } else if (BaseType->isAnyComplexType()) {
10840       const auto *CT = BaseType->castAs<ComplexType>();
10841       uint64_t Index = Entry.getAsArrayIndex();
10842       if (Index != 1)
10843         return false;
10844       BaseType = CT->getElementType();
10845     } else if (auto *FD = getAsField(Entry)) {
10846       bool Invalid;
10847       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
10848         return Invalid;
10849       BaseType = FD->getType();
10850     } else {
10851       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
10852       return false;
10853     }
10854   }
10855   return true;
10856 }
10857 
10858 /// Tests to see if the LValue has a user-specified designator (that isn't
10859 /// necessarily valid). Note that this always returns 'true' if the LValue has
10860 /// an unsized array as its first designator entry, because there's currently no
10861 /// way to tell if the user typed *foo or foo[0].
10862 static bool refersToCompleteObject(const LValue &LVal) {
10863   if (LVal.Designator.Invalid)
10864     return false;
10865 
10866   if (!LVal.Designator.Entries.empty())
10867     return LVal.Designator.isMostDerivedAnUnsizedArray();
10868 
10869   if (!LVal.InvalidBase)
10870     return true;
10871 
10872   // If `E` is a MemberExpr, then the first part of the designator is hiding in
10873   // the LValueBase.
10874   const auto *E = LVal.Base.dyn_cast<const Expr *>();
10875   return !E || !isa<MemberExpr>(E);
10876 }
10877 
10878 /// Attempts to detect a user writing into a piece of memory that's impossible
10879 /// to figure out the size of by just using types.
10880 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
10881   const SubobjectDesignator &Designator = LVal.Designator;
10882   // Notes:
10883   // - Users can only write off of the end when we have an invalid base. Invalid
10884   //   bases imply we don't know where the memory came from.
10885   // - We used to be a bit more aggressive here; we'd only be conservative if
10886   //   the array at the end was flexible, or if it had 0 or 1 elements. This
10887   //   broke some common standard library extensions (PR30346), but was
10888   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
10889   //   with some sort of list. OTOH, it seems that GCC is always
10890   //   conservative with the last element in structs (if it's an array), so our
10891   //   current behavior is more compatible than an explicit list approach would
10892   //   be.
10893   return LVal.InvalidBase &&
10894          Designator.Entries.size() == Designator.MostDerivedPathLength &&
10895          Designator.MostDerivedIsArrayElement &&
10896          isDesignatorAtObjectEnd(Ctx, LVal);
10897 }
10898 
10899 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
10900 /// Fails if the conversion would cause loss of precision.
10901 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
10902                                             CharUnits &Result) {
10903   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
10904   if (Int.ugt(CharUnitsMax))
10905     return false;
10906   Result = CharUnits::fromQuantity(Int.getZExtValue());
10907   return true;
10908 }
10909 
10910 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
10911 /// determine how many bytes exist from the beginning of the object to either
10912 /// the end of the current subobject, or the end of the object itself, depending
10913 /// on what the LValue looks like + the value of Type.
10914 ///
10915 /// If this returns false, the value of Result is undefined.
10916 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
10917                                unsigned Type, const LValue &LVal,
10918                                CharUnits &EndOffset) {
10919   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
10920 
10921   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
10922     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
10923       return false;
10924     return HandleSizeof(Info, ExprLoc, Ty, Result);
10925   };
10926 
10927   // We want to evaluate the size of the entire object. This is a valid fallback
10928   // for when Type=1 and the designator is invalid, because we're asked for an
10929   // upper-bound.
10930   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
10931     // Type=3 wants a lower bound, so we can't fall back to this.
10932     if (Type == 3 && !DetermineForCompleteObject)
10933       return false;
10934 
10935     llvm::APInt APEndOffset;
10936     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
10937         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
10938       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
10939 
10940     if (LVal.InvalidBase)
10941       return false;
10942 
10943     QualType BaseTy = getObjectType(LVal.getLValueBase());
10944     return CheckedHandleSizeof(BaseTy, EndOffset);
10945   }
10946 
10947   // We want to evaluate the size of a subobject.
10948   const SubobjectDesignator &Designator = LVal.Designator;
10949 
10950   // The following is a moderately common idiom in C:
10951   //
10952   // struct Foo { int a; char c[1]; };
10953   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
10954   // strcpy(&F->c[0], Bar);
10955   //
10956   // In order to not break too much legacy code, we need to support it.
10957   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
10958     // If we can resolve this to an alloc_size call, we can hand that back,
10959     // because we know for certain how many bytes there are to write to.
10960     llvm::APInt APEndOffset;
10961     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
10962         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
10963       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
10964 
10965     // If we cannot determine the size of the initial allocation, then we can't
10966     // given an accurate upper-bound. However, we are still able to give
10967     // conservative lower-bounds for Type=3.
10968     if (Type == 1)
10969       return false;
10970   }
10971 
10972   CharUnits BytesPerElem;
10973   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
10974     return false;
10975 
10976   // According to the GCC documentation, we want the size of the subobject
10977   // denoted by the pointer. But that's not quite right -- what we actually
10978   // want is the size of the immediately-enclosing array, if there is one.
10979   int64_t ElemsRemaining;
10980   if (Designator.MostDerivedIsArrayElement &&
10981       Designator.Entries.size() == Designator.MostDerivedPathLength) {
10982     uint64_t ArraySize = Designator.getMostDerivedArraySize();
10983     uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
10984     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
10985   } else {
10986     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
10987   }
10988 
10989   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
10990   return true;
10991 }
10992 
10993 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
10994 /// returns true and stores the result in @p Size.
10995 ///
10996 /// If @p WasError is non-null, this will report whether the failure to evaluate
10997 /// is to be treated as an Error in IntExprEvaluator.
10998 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
10999                                          EvalInfo &Info, uint64_t &Size) {
11000   // Determine the denoted object.
11001   LValue LVal;
11002   {
11003     // The operand of __builtin_object_size is never evaluated for side-effects.
11004     // If there are any, but we can determine the pointed-to object anyway, then
11005     // ignore the side-effects.
11006     SpeculativeEvaluationRAII SpeculativeEval(Info);
11007     IgnoreSideEffectsRAII Fold(Info);
11008 
11009     if (E->isGLValue()) {
11010       // It's possible for us to be given GLValues if we're called via
11011       // Expr::tryEvaluateObjectSize.
11012       APValue RVal;
11013       if (!EvaluateAsRValue(Info, E, RVal))
11014         return false;
11015       LVal.setFrom(Info.Ctx, RVal);
11016     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
11017                                 /*InvalidBaseOK=*/true))
11018       return false;
11019   }
11020 
11021   // If we point to before the start of the object, there are no accessible
11022   // bytes.
11023   if (LVal.getLValueOffset().isNegative()) {
11024     Size = 0;
11025     return true;
11026   }
11027 
11028   CharUnits EndOffset;
11029   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
11030     return false;
11031 
11032   // If we've fallen outside of the end offset, just pretend there's nothing to
11033   // write to/read from.
11034   if (EndOffset <= LVal.getLValueOffset())
11035     Size = 0;
11036   else
11037     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
11038   return true;
11039 }
11040 
11041 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
11042   if (unsigned BuiltinOp = E->getBuiltinCallee())
11043     return VisitBuiltinCallExpr(E, BuiltinOp);
11044 
11045   return ExprEvaluatorBaseTy::VisitCallExpr(E);
11046 }
11047 
11048 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
11049                                      APValue &Val, APSInt &Alignment) {
11050   QualType SrcTy = E->getArg(0)->getType();
11051   if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
11052     return false;
11053   // Even though we are evaluating integer expressions we could get a pointer
11054   // argument for the __builtin_is_aligned() case.
11055   if (SrcTy->isPointerType()) {
11056     LValue Ptr;
11057     if (!EvaluatePointer(E->getArg(0), Ptr, Info))
11058       return false;
11059     Ptr.moveInto(Val);
11060   } else if (!SrcTy->isIntegralOrEnumerationType()) {
11061     Info.FFDiag(E->getArg(0));
11062     return false;
11063   } else {
11064     APSInt SrcInt;
11065     if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
11066       return false;
11067     assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
11068            "Bit widths must be the same");
11069     Val = APValue(SrcInt);
11070   }
11071   assert(Val.hasValue());
11072   return true;
11073 }
11074 
11075 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
11076                                             unsigned BuiltinOp) {
11077   switch (BuiltinOp) {
11078   default:
11079     return ExprEvaluatorBaseTy::VisitCallExpr(E);
11080 
11081   case Builtin::BI__builtin_dynamic_object_size:
11082   case Builtin::BI__builtin_object_size: {
11083     // The type was checked when we built the expression.
11084     unsigned Type =
11085         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11086     assert(Type <= 3 && "unexpected type");
11087 
11088     uint64_t Size;
11089     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
11090       return Success(Size, E);
11091 
11092     if (E->getArg(0)->HasSideEffects(Info.Ctx))
11093       return Success((Type & 2) ? 0 : -1, E);
11094 
11095     // Expression had no side effects, but we couldn't statically determine the
11096     // size of the referenced object.
11097     switch (Info.EvalMode) {
11098     case EvalInfo::EM_ConstantExpression:
11099     case EvalInfo::EM_ConstantFold:
11100     case EvalInfo::EM_IgnoreSideEffects:
11101       // Leave it to IR generation.
11102       return Error(E);
11103     case EvalInfo::EM_ConstantExpressionUnevaluated:
11104       // Reduce it to a constant now.
11105       return Success((Type & 2) ? 0 : -1, E);
11106     }
11107 
11108     llvm_unreachable("unexpected EvalMode");
11109   }
11110 
11111   case Builtin::BI__builtin_os_log_format_buffer_size: {
11112     analyze_os_log::OSLogBufferLayout Layout;
11113     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
11114     return Success(Layout.size().getQuantity(), E);
11115   }
11116 
11117   case Builtin::BI__builtin_is_aligned: {
11118     APValue Src;
11119     APSInt Alignment;
11120     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11121       return false;
11122     if (Src.isLValue()) {
11123       // If we evaluated a pointer, check the minimum known alignment.
11124       LValue Ptr;
11125       Ptr.setFrom(Info.Ctx, Src);
11126       CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
11127       CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
11128       // We can return true if the known alignment at the computed offset is
11129       // greater than the requested alignment.
11130       assert(PtrAlign.isPowerOfTwo());
11131       assert(Alignment.isPowerOf2());
11132       if (PtrAlign.getQuantity() >= Alignment)
11133         return Success(1, E);
11134       // If the alignment is not known to be sufficient, some cases could still
11135       // be aligned at run time. However, if the requested alignment is less or
11136       // equal to the base alignment and the offset is not aligned, we know that
11137       // the run-time value can never be aligned.
11138       if (BaseAlignment.getQuantity() >= Alignment &&
11139           PtrAlign.getQuantity() < Alignment)
11140         return Success(0, E);
11141       // Otherwise we can't infer whether the value is sufficiently aligned.
11142       // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
11143       //  in cases where we can't fully evaluate the pointer.
11144       Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
11145           << Alignment;
11146       return false;
11147     }
11148     assert(Src.isInt());
11149     return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
11150   }
11151   case Builtin::BI__builtin_align_up: {
11152     APValue Src;
11153     APSInt Alignment;
11154     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11155       return false;
11156     if (!Src.isInt())
11157       return Error(E);
11158     APSInt AlignedVal =
11159         APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
11160                Src.getInt().isUnsigned());
11161     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11162     return Success(AlignedVal, E);
11163   }
11164   case Builtin::BI__builtin_align_down: {
11165     APValue Src;
11166     APSInt Alignment;
11167     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11168       return false;
11169     if (!Src.isInt())
11170       return Error(E);
11171     APSInt AlignedVal =
11172         APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
11173     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11174     return Success(AlignedVal, E);
11175   }
11176 
11177   case Builtin::BI__builtin_bswap16:
11178   case Builtin::BI__builtin_bswap32:
11179   case Builtin::BI__builtin_bswap64: {
11180     APSInt Val;
11181     if (!EvaluateInteger(E->getArg(0), Val, Info))
11182       return false;
11183 
11184     return Success(Val.byteSwap(), E);
11185   }
11186 
11187   case Builtin::BI__builtin_classify_type:
11188     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
11189 
11190   case Builtin::BI__builtin_clrsb:
11191   case Builtin::BI__builtin_clrsbl:
11192   case Builtin::BI__builtin_clrsbll: {
11193     APSInt Val;
11194     if (!EvaluateInteger(E->getArg(0), Val, Info))
11195       return false;
11196 
11197     return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
11198   }
11199 
11200   case Builtin::BI__builtin_clz:
11201   case Builtin::BI__builtin_clzl:
11202   case Builtin::BI__builtin_clzll:
11203   case Builtin::BI__builtin_clzs: {
11204     APSInt Val;
11205     if (!EvaluateInteger(E->getArg(0), Val, Info))
11206       return false;
11207     if (!Val)
11208       return Error(E);
11209 
11210     return Success(Val.countLeadingZeros(), E);
11211   }
11212 
11213   case Builtin::BI__builtin_constant_p: {
11214     const Expr *Arg = E->getArg(0);
11215     if (EvaluateBuiltinConstantP(Info, Arg))
11216       return Success(true, E);
11217     if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
11218       // Outside a constant context, eagerly evaluate to false in the presence
11219       // of side-effects in order to avoid -Wunsequenced false-positives in
11220       // a branch on __builtin_constant_p(expr).
11221       return Success(false, E);
11222     }
11223     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11224     return false;
11225   }
11226 
11227   case Builtin::BI__builtin_is_constant_evaluated: {
11228     const auto *Callee = Info.CurrentCall->getCallee();
11229     if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
11230         (Info.CallStackDepth == 1 ||
11231          (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
11232           Callee->getIdentifier() &&
11233           Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
11234       // FIXME: Find a better way to avoid duplicated diagnostics.
11235       if (Info.EvalStatus.Diag)
11236         Info.report((Info.CallStackDepth == 1) ? E->getExprLoc()
11237                                                : Info.CurrentCall->CallLoc,
11238                     diag::warn_is_constant_evaluated_always_true_constexpr)
11239             << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
11240                                          : "std::is_constant_evaluated");
11241     }
11242 
11243     return Success(Info.InConstantContext, E);
11244   }
11245 
11246   case Builtin::BI__builtin_ctz:
11247   case Builtin::BI__builtin_ctzl:
11248   case Builtin::BI__builtin_ctzll:
11249   case Builtin::BI__builtin_ctzs: {
11250     APSInt Val;
11251     if (!EvaluateInteger(E->getArg(0), Val, Info))
11252       return false;
11253     if (!Val)
11254       return Error(E);
11255 
11256     return Success(Val.countTrailingZeros(), E);
11257   }
11258 
11259   case Builtin::BI__builtin_eh_return_data_regno: {
11260     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11261     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
11262     return Success(Operand, E);
11263   }
11264 
11265   case Builtin::BI__builtin_expect:
11266   case Builtin::BI__builtin_expect_with_probability:
11267     return Visit(E->getArg(0));
11268 
11269   case Builtin::BI__builtin_ffs:
11270   case Builtin::BI__builtin_ffsl:
11271   case Builtin::BI__builtin_ffsll: {
11272     APSInt Val;
11273     if (!EvaluateInteger(E->getArg(0), Val, Info))
11274       return false;
11275 
11276     unsigned N = Val.countTrailingZeros();
11277     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
11278   }
11279 
11280   case Builtin::BI__builtin_fpclassify: {
11281     APFloat Val(0.0);
11282     if (!EvaluateFloat(E->getArg(5), Val, Info))
11283       return false;
11284     unsigned Arg;
11285     switch (Val.getCategory()) {
11286     case APFloat::fcNaN: Arg = 0; break;
11287     case APFloat::fcInfinity: Arg = 1; break;
11288     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
11289     case APFloat::fcZero: Arg = 4; break;
11290     }
11291     return Visit(E->getArg(Arg));
11292   }
11293 
11294   case Builtin::BI__builtin_isinf_sign: {
11295     APFloat Val(0.0);
11296     return EvaluateFloat(E->getArg(0), Val, Info) &&
11297            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
11298   }
11299 
11300   case Builtin::BI__builtin_isinf: {
11301     APFloat Val(0.0);
11302     return EvaluateFloat(E->getArg(0), Val, Info) &&
11303            Success(Val.isInfinity() ? 1 : 0, E);
11304   }
11305 
11306   case Builtin::BI__builtin_isfinite: {
11307     APFloat Val(0.0);
11308     return EvaluateFloat(E->getArg(0), Val, Info) &&
11309            Success(Val.isFinite() ? 1 : 0, E);
11310   }
11311 
11312   case Builtin::BI__builtin_isnan: {
11313     APFloat Val(0.0);
11314     return EvaluateFloat(E->getArg(0), Val, Info) &&
11315            Success(Val.isNaN() ? 1 : 0, E);
11316   }
11317 
11318   case Builtin::BI__builtin_isnormal: {
11319     APFloat Val(0.0);
11320     return EvaluateFloat(E->getArg(0), Val, Info) &&
11321            Success(Val.isNormal() ? 1 : 0, E);
11322   }
11323 
11324   case Builtin::BI__builtin_parity:
11325   case Builtin::BI__builtin_parityl:
11326   case Builtin::BI__builtin_parityll: {
11327     APSInt Val;
11328     if (!EvaluateInteger(E->getArg(0), Val, Info))
11329       return false;
11330 
11331     return Success(Val.countPopulation() % 2, E);
11332   }
11333 
11334   case Builtin::BI__builtin_popcount:
11335   case Builtin::BI__builtin_popcountl:
11336   case Builtin::BI__builtin_popcountll: {
11337     APSInt Val;
11338     if (!EvaluateInteger(E->getArg(0), Val, Info))
11339       return false;
11340 
11341     return Success(Val.countPopulation(), E);
11342   }
11343 
11344   case Builtin::BIstrlen:
11345   case Builtin::BIwcslen:
11346     // A call to strlen is not a constant expression.
11347     if (Info.getLangOpts().CPlusPlus11)
11348       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11349         << /*isConstexpr*/0 << /*isConstructor*/0
11350         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11351     else
11352       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11353     LLVM_FALLTHROUGH;
11354   case Builtin::BI__builtin_strlen:
11355   case Builtin::BI__builtin_wcslen: {
11356     // As an extension, we support __builtin_strlen() as a constant expression,
11357     // and support folding strlen() to a constant.
11358     LValue String;
11359     if (!EvaluatePointer(E->getArg(0), String, Info))
11360       return false;
11361 
11362     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
11363 
11364     // Fast path: if it's a string literal, search the string value.
11365     if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
11366             String.getLValueBase().dyn_cast<const Expr *>())) {
11367       // The string literal may have embedded null characters. Find the first
11368       // one and truncate there.
11369       StringRef Str = S->getBytes();
11370       int64_t Off = String.Offset.getQuantity();
11371       if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
11372           S->getCharByteWidth() == 1 &&
11373           // FIXME: Add fast-path for wchar_t too.
11374           Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
11375         Str = Str.substr(Off);
11376 
11377         StringRef::size_type Pos = Str.find(0);
11378         if (Pos != StringRef::npos)
11379           Str = Str.substr(0, Pos);
11380 
11381         return Success(Str.size(), E);
11382       }
11383 
11384       // Fall through to slow path to issue appropriate diagnostic.
11385     }
11386 
11387     // Slow path: scan the bytes of the string looking for the terminating 0.
11388     for (uint64_t Strlen = 0; /**/; ++Strlen) {
11389       APValue Char;
11390       if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
11391           !Char.isInt())
11392         return false;
11393       if (!Char.getInt())
11394         return Success(Strlen, E);
11395       if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
11396         return false;
11397     }
11398   }
11399 
11400   case Builtin::BIstrcmp:
11401   case Builtin::BIwcscmp:
11402   case Builtin::BIstrncmp:
11403   case Builtin::BIwcsncmp:
11404   case Builtin::BImemcmp:
11405   case Builtin::BIbcmp:
11406   case Builtin::BIwmemcmp:
11407     // A call to strlen is not a constant expression.
11408     if (Info.getLangOpts().CPlusPlus11)
11409       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11410         << /*isConstexpr*/0 << /*isConstructor*/0
11411         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11412     else
11413       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11414     LLVM_FALLTHROUGH;
11415   case Builtin::BI__builtin_strcmp:
11416   case Builtin::BI__builtin_wcscmp:
11417   case Builtin::BI__builtin_strncmp:
11418   case Builtin::BI__builtin_wcsncmp:
11419   case Builtin::BI__builtin_memcmp:
11420   case Builtin::BI__builtin_bcmp:
11421   case Builtin::BI__builtin_wmemcmp: {
11422     LValue String1, String2;
11423     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
11424         !EvaluatePointer(E->getArg(1), String2, Info))
11425       return false;
11426 
11427     uint64_t MaxLength = uint64_t(-1);
11428     if (BuiltinOp != Builtin::BIstrcmp &&
11429         BuiltinOp != Builtin::BIwcscmp &&
11430         BuiltinOp != Builtin::BI__builtin_strcmp &&
11431         BuiltinOp != Builtin::BI__builtin_wcscmp) {
11432       APSInt N;
11433       if (!EvaluateInteger(E->getArg(2), N, Info))
11434         return false;
11435       MaxLength = N.getExtValue();
11436     }
11437 
11438     // Empty substrings compare equal by definition.
11439     if (MaxLength == 0u)
11440       return Success(0, E);
11441 
11442     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11443         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11444         String1.Designator.Invalid || String2.Designator.Invalid)
11445       return false;
11446 
11447     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
11448     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
11449 
11450     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
11451                      BuiltinOp == Builtin::BIbcmp ||
11452                      BuiltinOp == Builtin::BI__builtin_memcmp ||
11453                      BuiltinOp == Builtin::BI__builtin_bcmp;
11454 
11455     assert(IsRawByte ||
11456            (Info.Ctx.hasSameUnqualifiedType(
11457                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
11458             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
11459 
11460     // For memcmp, allow comparing any arrays of '[[un]signed] char' or
11461     // 'char8_t', but no other types.
11462     if (IsRawByte &&
11463         !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
11464       // FIXME: Consider using our bit_cast implementation to support this.
11465       Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
11466           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
11467           << CharTy1 << CharTy2;
11468       return false;
11469     }
11470 
11471     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
11472       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
11473              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
11474              Char1.isInt() && Char2.isInt();
11475     };
11476     const auto &AdvanceElems = [&] {
11477       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
11478              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
11479     };
11480 
11481     bool StopAtNull =
11482         (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
11483          BuiltinOp != Builtin::BIwmemcmp &&
11484          BuiltinOp != Builtin::BI__builtin_memcmp &&
11485          BuiltinOp != Builtin::BI__builtin_bcmp &&
11486          BuiltinOp != Builtin::BI__builtin_wmemcmp);
11487     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
11488                   BuiltinOp == Builtin::BIwcsncmp ||
11489                   BuiltinOp == Builtin::BIwmemcmp ||
11490                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
11491                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
11492                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
11493 
11494     for (; MaxLength; --MaxLength) {
11495       APValue Char1, Char2;
11496       if (!ReadCurElems(Char1, Char2))
11497         return false;
11498       if (Char1.getInt().ne(Char2.getInt())) {
11499         if (IsWide) // wmemcmp compares with wchar_t signedness.
11500           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
11501         // memcmp always compares unsigned chars.
11502         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
11503       }
11504       if (StopAtNull && !Char1.getInt())
11505         return Success(0, E);
11506       assert(!(StopAtNull && !Char2.getInt()));
11507       if (!AdvanceElems())
11508         return false;
11509     }
11510     // We hit the strncmp / memcmp limit.
11511     return Success(0, E);
11512   }
11513 
11514   case Builtin::BI__atomic_always_lock_free:
11515   case Builtin::BI__atomic_is_lock_free:
11516   case Builtin::BI__c11_atomic_is_lock_free: {
11517     APSInt SizeVal;
11518     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
11519       return false;
11520 
11521     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
11522     // of two less than or equal to the maximum inline atomic width, we know it
11523     // is lock-free.  If the size isn't a power of two, or greater than the
11524     // maximum alignment where we promote atomics, we know it is not lock-free
11525     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
11526     // the answer can only be determined at runtime; for example, 16-byte
11527     // atomics have lock-free implementations on some, but not all,
11528     // x86-64 processors.
11529 
11530     // Check power-of-two.
11531     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
11532     if (Size.isPowerOfTwo()) {
11533       // Check against inlining width.
11534       unsigned InlineWidthBits =
11535           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
11536       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
11537         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
11538             Size == CharUnits::One() ||
11539             E->getArg(1)->isNullPointerConstant(Info.Ctx,
11540                                                 Expr::NPC_NeverValueDependent))
11541           // OK, we will inline appropriately-aligned operations of this size,
11542           // and _Atomic(T) is appropriately-aligned.
11543           return Success(1, E);
11544 
11545         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
11546           castAs<PointerType>()->getPointeeType();
11547         if (!PointeeType->isIncompleteType() &&
11548             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
11549           // OK, we will inline operations on this object.
11550           return Success(1, E);
11551         }
11552       }
11553     }
11554 
11555     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
11556         Success(0, E) : Error(E);
11557   }
11558   case Builtin::BIomp_is_initial_device:
11559     // We can decide statically which value the runtime would return if called.
11560     return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
11561   case Builtin::BI__builtin_add_overflow:
11562   case Builtin::BI__builtin_sub_overflow:
11563   case Builtin::BI__builtin_mul_overflow:
11564   case Builtin::BI__builtin_sadd_overflow:
11565   case Builtin::BI__builtin_uadd_overflow:
11566   case Builtin::BI__builtin_uaddl_overflow:
11567   case Builtin::BI__builtin_uaddll_overflow:
11568   case Builtin::BI__builtin_usub_overflow:
11569   case Builtin::BI__builtin_usubl_overflow:
11570   case Builtin::BI__builtin_usubll_overflow:
11571   case Builtin::BI__builtin_umul_overflow:
11572   case Builtin::BI__builtin_umull_overflow:
11573   case Builtin::BI__builtin_umulll_overflow:
11574   case Builtin::BI__builtin_saddl_overflow:
11575   case Builtin::BI__builtin_saddll_overflow:
11576   case Builtin::BI__builtin_ssub_overflow:
11577   case Builtin::BI__builtin_ssubl_overflow:
11578   case Builtin::BI__builtin_ssubll_overflow:
11579   case Builtin::BI__builtin_smul_overflow:
11580   case Builtin::BI__builtin_smull_overflow:
11581   case Builtin::BI__builtin_smulll_overflow: {
11582     LValue ResultLValue;
11583     APSInt LHS, RHS;
11584 
11585     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
11586     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
11587         !EvaluateInteger(E->getArg(1), RHS, Info) ||
11588         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
11589       return false;
11590 
11591     APSInt Result;
11592     bool DidOverflow = false;
11593 
11594     // If the types don't have to match, enlarge all 3 to the largest of them.
11595     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
11596         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
11597         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
11598       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
11599                       ResultType->isSignedIntegerOrEnumerationType();
11600       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
11601                       ResultType->isSignedIntegerOrEnumerationType();
11602       uint64_t LHSSize = LHS.getBitWidth();
11603       uint64_t RHSSize = RHS.getBitWidth();
11604       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
11605       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
11606 
11607       // Add an additional bit if the signedness isn't uniformly agreed to. We
11608       // could do this ONLY if there is a signed and an unsigned that both have
11609       // MaxBits, but the code to check that is pretty nasty.  The issue will be
11610       // caught in the shrink-to-result later anyway.
11611       if (IsSigned && !AllSigned)
11612         ++MaxBits;
11613 
11614       LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
11615       RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
11616       Result = APSInt(MaxBits, !IsSigned);
11617     }
11618 
11619     // Find largest int.
11620     switch (BuiltinOp) {
11621     default:
11622       llvm_unreachable("Invalid value for BuiltinOp");
11623     case Builtin::BI__builtin_add_overflow:
11624     case Builtin::BI__builtin_sadd_overflow:
11625     case Builtin::BI__builtin_saddl_overflow:
11626     case Builtin::BI__builtin_saddll_overflow:
11627     case Builtin::BI__builtin_uadd_overflow:
11628     case Builtin::BI__builtin_uaddl_overflow:
11629     case Builtin::BI__builtin_uaddll_overflow:
11630       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
11631                               : LHS.uadd_ov(RHS, DidOverflow);
11632       break;
11633     case Builtin::BI__builtin_sub_overflow:
11634     case Builtin::BI__builtin_ssub_overflow:
11635     case Builtin::BI__builtin_ssubl_overflow:
11636     case Builtin::BI__builtin_ssubll_overflow:
11637     case Builtin::BI__builtin_usub_overflow:
11638     case Builtin::BI__builtin_usubl_overflow:
11639     case Builtin::BI__builtin_usubll_overflow:
11640       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
11641                               : LHS.usub_ov(RHS, DidOverflow);
11642       break;
11643     case Builtin::BI__builtin_mul_overflow:
11644     case Builtin::BI__builtin_smul_overflow:
11645     case Builtin::BI__builtin_smull_overflow:
11646     case Builtin::BI__builtin_smulll_overflow:
11647     case Builtin::BI__builtin_umul_overflow:
11648     case Builtin::BI__builtin_umull_overflow:
11649     case Builtin::BI__builtin_umulll_overflow:
11650       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
11651                               : LHS.umul_ov(RHS, DidOverflow);
11652       break;
11653     }
11654 
11655     // In the case where multiple sizes are allowed, truncate and see if
11656     // the values are the same.
11657     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
11658         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
11659         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
11660       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
11661       // since it will give us the behavior of a TruncOrSelf in the case where
11662       // its parameter <= its size.  We previously set Result to be at least the
11663       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
11664       // will work exactly like TruncOrSelf.
11665       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
11666       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
11667 
11668       if (!APSInt::isSameValue(Temp, Result))
11669         DidOverflow = true;
11670       Result = Temp;
11671     }
11672 
11673     APValue APV{Result};
11674     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
11675       return false;
11676     return Success(DidOverflow, E);
11677   }
11678   }
11679 }
11680 
11681 /// Determine whether this is a pointer past the end of the complete
11682 /// object referred to by the lvalue.
11683 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
11684                                             const LValue &LV) {
11685   // A null pointer can be viewed as being "past the end" but we don't
11686   // choose to look at it that way here.
11687   if (!LV.getLValueBase())
11688     return false;
11689 
11690   // If the designator is valid and refers to a subobject, we're not pointing
11691   // past the end.
11692   if (!LV.getLValueDesignator().Invalid &&
11693       !LV.getLValueDesignator().isOnePastTheEnd())
11694     return false;
11695 
11696   // A pointer to an incomplete type might be past-the-end if the type's size is
11697   // zero.  We cannot tell because the type is incomplete.
11698   QualType Ty = getType(LV.getLValueBase());
11699   if (Ty->isIncompleteType())
11700     return true;
11701 
11702   // We're a past-the-end pointer if we point to the byte after the object,
11703   // no matter what our type or path is.
11704   auto Size = Ctx.getTypeSizeInChars(Ty);
11705   return LV.getLValueOffset() == Size;
11706 }
11707 
11708 namespace {
11709 
11710 /// Data recursive integer evaluator of certain binary operators.
11711 ///
11712 /// We use a data recursive algorithm for binary operators so that we are able
11713 /// to handle extreme cases of chained binary operators without causing stack
11714 /// overflow.
11715 class DataRecursiveIntBinOpEvaluator {
11716   struct EvalResult {
11717     APValue Val;
11718     bool Failed;
11719 
11720     EvalResult() : Failed(false) { }
11721 
11722     void swap(EvalResult &RHS) {
11723       Val.swap(RHS.Val);
11724       Failed = RHS.Failed;
11725       RHS.Failed = false;
11726     }
11727   };
11728 
11729   struct Job {
11730     const Expr *E;
11731     EvalResult LHSResult; // meaningful only for binary operator expression.
11732     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
11733 
11734     Job() = default;
11735     Job(Job &&) = default;
11736 
11737     void startSpeculativeEval(EvalInfo &Info) {
11738       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
11739     }
11740 
11741   private:
11742     SpeculativeEvaluationRAII SpecEvalRAII;
11743   };
11744 
11745   SmallVector<Job, 16> Queue;
11746 
11747   IntExprEvaluator &IntEval;
11748   EvalInfo &Info;
11749   APValue &FinalResult;
11750 
11751 public:
11752   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
11753     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
11754 
11755   /// True if \param E is a binary operator that we are going to handle
11756   /// data recursively.
11757   /// We handle binary operators that are comma, logical, or that have operands
11758   /// with integral or enumeration type.
11759   static bool shouldEnqueue(const BinaryOperator *E) {
11760     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
11761            (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
11762             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
11763             E->getRHS()->getType()->isIntegralOrEnumerationType());
11764   }
11765 
11766   bool Traverse(const BinaryOperator *E) {
11767     enqueue(E);
11768     EvalResult PrevResult;
11769     while (!Queue.empty())
11770       process(PrevResult);
11771 
11772     if (PrevResult.Failed) return false;
11773 
11774     FinalResult.swap(PrevResult.Val);
11775     return true;
11776   }
11777 
11778 private:
11779   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
11780     return IntEval.Success(Value, E, Result);
11781   }
11782   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
11783     return IntEval.Success(Value, E, Result);
11784   }
11785   bool Error(const Expr *E) {
11786     return IntEval.Error(E);
11787   }
11788   bool Error(const Expr *E, diag::kind D) {
11789     return IntEval.Error(E, D);
11790   }
11791 
11792   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
11793     return Info.CCEDiag(E, D);
11794   }
11795 
11796   // Returns true if visiting the RHS is necessary, false otherwise.
11797   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
11798                          bool &SuppressRHSDiags);
11799 
11800   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
11801                   const BinaryOperator *E, APValue &Result);
11802 
11803   void EvaluateExpr(const Expr *E, EvalResult &Result) {
11804     Result.Failed = !Evaluate(Result.Val, Info, E);
11805     if (Result.Failed)
11806       Result.Val = APValue();
11807   }
11808 
11809   void process(EvalResult &Result);
11810 
11811   void enqueue(const Expr *E) {
11812     E = E->IgnoreParens();
11813     Queue.resize(Queue.size()+1);
11814     Queue.back().E = E;
11815     Queue.back().Kind = Job::AnyExprKind;
11816   }
11817 };
11818 
11819 }
11820 
11821 bool DataRecursiveIntBinOpEvaluator::
11822        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
11823                          bool &SuppressRHSDiags) {
11824   if (E->getOpcode() == BO_Comma) {
11825     // Ignore LHS but note if we could not evaluate it.
11826     if (LHSResult.Failed)
11827       return Info.noteSideEffect();
11828     return true;
11829   }
11830 
11831   if (E->isLogicalOp()) {
11832     bool LHSAsBool;
11833     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
11834       // We were able to evaluate the LHS, see if we can get away with not
11835       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
11836       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
11837         Success(LHSAsBool, E, LHSResult.Val);
11838         return false; // Ignore RHS
11839       }
11840     } else {
11841       LHSResult.Failed = true;
11842 
11843       // Since we weren't able to evaluate the left hand side, it
11844       // might have had side effects.
11845       if (!Info.noteSideEffect())
11846         return false;
11847 
11848       // We can't evaluate the LHS; however, sometimes the result
11849       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
11850       // Don't ignore RHS and suppress diagnostics from this arm.
11851       SuppressRHSDiags = true;
11852     }
11853 
11854     return true;
11855   }
11856 
11857   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
11858          E->getRHS()->getType()->isIntegralOrEnumerationType());
11859 
11860   if (LHSResult.Failed && !Info.noteFailure())
11861     return false; // Ignore RHS;
11862 
11863   return true;
11864 }
11865 
11866 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
11867                                     bool IsSub) {
11868   // Compute the new offset in the appropriate width, wrapping at 64 bits.
11869   // FIXME: When compiling for a 32-bit target, we should use 32-bit
11870   // offsets.
11871   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
11872   CharUnits &Offset = LVal.getLValueOffset();
11873   uint64_t Offset64 = Offset.getQuantity();
11874   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
11875   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
11876                                          : Offset64 + Index64);
11877 }
11878 
11879 bool DataRecursiveIntBinOpEvaluator::
11880        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
11881                   const BinaryOperator *E, APValue &Result) {
11882   if (E->getOpcode() == BO_Comma) {
11883     if (RHSResult.Failed)
11884       return false;
11885     Result = RHSResult.Val;
11886     return true;
11887   }
11888 
11889   if (E->isLogicalOp()) {
11890     bool lhsResult, rhsResult;
11891     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
11892     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
11893 
11894     if (LHSIsOK) {
11895       if (RHSIsOK) {
11896         if (E->getOpcode() == BO_LOr)
11897           return Success(lhsResult || rhsResult, E, Result);
11898         else
11899           return Success(lhsResult && rhsResult, E, Result);
11900       }
11901     } else {
11902       if (RHSIsOK) {
11903         // We can't evaluate the LHS; however, sometimes the result
11904         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
11905         if (rhsResult == (E->getOpcode() == BO_LOr))
11906           return Success(rhsResult, E, Result);
11907       }
11908     }
11909 
11910     return false;
11911   }
11912 
11913   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
11914          E->getRHS()->getType()->isIntegralOrEnumerationType());
11915 
11916   if (LHSResult.Failed || RHSResult.Failed)
11917     return false;
11918 
11919   const APValue &LHSVal = LHSResult.Val;
11920   const APValue &RHSVal = RHSResult.Val;
11921 
11922   // Handle cases like (unsigned long)&a + 4.
11923   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
11924     Result = LHSVal;
11925     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
11926     return true;
11927   }
11928 
11929   // Handle cases like 4 + (unsigned long)&a
11930   if (E->getOpcode() == BO_Add &&
11931       RHSVal.isLValue() && LHSVal.isInt()) {
11932     Result = RHSVal;
11933     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
11934     return true;
11935   }
11936 
11937   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
11938     // Handle (intptr_t)&&A - (intptr_t)&&B.
11939     if (!LHSVal.getLValueOffset().isZero() ||
11940         !RHSVal.getLValueOffset().isZero())
11941       return false;
11942     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
11943     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
11944     if (!LHSExpr || !RHSExpr)
11945       return false;
11946     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
11947     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
11948     if (!LHSAddrExpr || !RHSAddrExpr)
11949       return false;
11950     // Make sure both labels come from the same function.
11951     if (LHSAddrExpr->getLabel()->getDeclContext() !=
11952         RHSAddrExpr->getLabel()->getDeclContext())
11953       return false;
11954     Result = APValue(LHSAddrExpr, RHSAddrExpr);
11955     return true;
11956   }
11957 
11958   // All the remaining cases expect both operands to be an integer
11959   if (!LHSVal.isInt() || !RHSVal.isInt())
11960     return Error(E);
11961 
11962   // Set up the width and signedness manually, in case it can't be deduced
11963   // from the operation we're performing.
11964   // FIXME: Don't do this in the cases where we can deduce it.
11965   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
11966                E->getType()->isUnsignedIntegerOrEnumerationType());
11967   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
11968                          RHSVal.getInt(), Value))
11969     return false;
11970   return Success(Value, E, Result);
11971 }
11972 
11973 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
11974   Job &job = Queue.back();
11975 
11976   switch (job.Kind) {
11977     case Job::AnyExprKind: {
11978       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
11979         if (shouldEnqueue(Bop)) {
11980           job.Kind = Job::BinOpKind;
11981           enqueue(Bop->getLHS());
11982           return;
11983         }
11984       }
11985 
11986       EvaluateExpr(job.E, Result);
11987       Queue.pop_back();
11988       return;
11989     }
11990 
11991     case Job::BinOpKind: {
11992       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
11993       bool SuppressRHSDiags = false;
11994       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
11995         Queue.pop_back();
11996         return;
11997       }
11998       if (SuppressRHSDiags)
11999         job.startSpeculativeEval(Info);
12000       job.LHSResult.swap(Result);
12001       job.Kind = Job::BinOpVisitedLHSKind;
12002       enqueue(Bop->getRHS());
12003       return;
12004     }
12005 
12006     case Job::BinOpVisitedLHSKind: {
12007       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12008       EvalResult RHS;
12009       RHS.swap(Result);
12010       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
12011       Queue.pop_back();
12012       return;
12013     }
12014   }
12015 
12016   llvm_unreachable("Invalid Job::Kind!");
12017 }
12018 
12019 namespace {
12020 /// Used when we determine that we should fail, but can keep evaluating prior to
12021 /// noting that we had a failure.
12022 class DelayedNoteFailureRAII {
12023   EvalInfo &Info;
12024   bool NoteFailure;
12025 
12026 public:
12027   DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
12028       : Info(Info), NoteFailure(NoteFailure) {}
12029   ~DelayedNoteFailureRAII() {
12030     if (NoteFailure) {
12031       bool ContinueAfterFailure = Info.noteFailure();
12032       (void)ContinueAfterFailure;
12033       assert(ContinueAfterFailure &&
12034              "Shouldn't have kept evaluating on failure.");
12035     }
12036   }
12037 };
12038 
12039 enum class CmpResult {
12040   Unequal,
12041   Less,
12042   Equal,
12043   Greater,
12044   Unordered,
12045 };
12046 }
12047 
12048 template <class SuccessCB, class AfterCB>
12049 static bool
12050 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
12051                                  SuccessCB &&Success, AfterCB &&DoAfter) {
12052   assert(E->isComparisonOp() && "expected comparison operator");
12053   assert((E->getOpcode() == BO_Cmp ||
12054           E->getType()->isIntegralOrEnumerationType()) &&
12055          "unsupported binary expression evaluation");
12056   auto Error = [&](const Expr *E) {
12057     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12058     return false;
12059   };
12060 
12061   bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
12062   bool IsEquality = E->isEqualityOp();
12063 
12064   QualType LHSTy = E->getLHS()->getType();
12065   QualType RHSTy = E->getRHS()->getType();
12066 
12067   if (LHSTy->isIntegralOrEnumerationType() &&
12068       RHSTy->isIntegralOrEnumerationType()) {
12069     APSInt LHS, RHS;
12070     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
12071     if (!LHSOK && !Info.noteFailure())
12072       return false;
12073     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
12074       return false;
12075     if (LHS < RHS)
12076       return Success(CmpResult::Less, E);
12077     if (LHS > RHS)
12078       return Success(CmpResult::Greater, E);
12079     return Success(CmpResult::Equal, E);
12080   }
12081 
12082   if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
12083     APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
12084     APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
12085 
12086     bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
12087     if (!LHSOK && !Info.noteFailure())
12088       return false;
12089     if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
12090       return false;
12091     if (LHSFX < RHSFX)
12092       return Success(CmpResult::Less, E);
12093     if (LHSFX > RHSFX)
12094       return Success(CmpResult::Greater, E);
12095     return Success(CmpResult::Equal, E);
12096   }
12097 
12098   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
12099     ComplexValue LHS, RHS;
12100     bool LHSOK;
12101     if (E->isAssignmentOp()) {
12102       LValue LV;
12103       EvaluateLValue(E->getLHS(), LV, Info);
12104       LHSOK = false;
12105     } else if (LHSTy->isRealFloatingType()) {
12106       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
12107       if (LHSOK) {
12108         LHS.makeComplexFloat();
12109         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
12110       }
12111     } else {
12112       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
12113     }
12114     if (!LHSOK && !Info.noteFailure())
12115       return false;
12116 
12117     if (E->getRHS()->getType()->isRealFloatingType()) {
12118       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
12119         return false;
12120       RHS.makeComplexFloat();
12121       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
12122     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
12123       return false;
12124 
12125     if (LHS.isComplexFloat()) {
12126       APFloat::cmpResult CR_r =
12127         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
12128       APFloat::cmpResult CR_i =
12129         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
12130       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
12131       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12132     } else {
12133       assert(IsEquality && "invalid complex comparison");
12134       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
12135                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
12136       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12137     }
12138   }
12139 
12140   if (LHSTy->isRealFloatingType() &&
12141       RHSTy->isRealFloatingType()) {
12142     APFloat RHS(0.0), LHS(0.0);
12143 
12144     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
12145     if (!LHSOK && !Info.noteFailure())
12146       return false;
12147 
12148     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
12149       return false;
12150 
12151     assert(E->isComparisonOp() && "Invalid binary operator!");
12152     auto GetCmpRes = [&]() {
12153       switch (LHS.compare(RHS)) {
12154       case APFloat::cmpEqual:
12155         return CmpResult::Equal;
12156       case APFloat::cmpLessThan:
12157         return CmpResult::Less;
12158       case APFloat::cmpGreaterThan:
12159         return CmpResult::Greater;
12160       case APFloat::cmpUnordered:
12161         return CmpResult::Unordered;
12162       }
12163       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
12164     };
12165     return Success(GetCmpRes(), E);
12166   }
12167 
12168   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
12169     LValue LHSValue, RHSValue;
12170 
12171     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12172     if (!LHSOK && !Info.noteFailure())
12173       return false;
12174 
12175     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12176       return false;
12177 
12178     // Reject differing bases from the normal codepath; we special-case
12179     // comparisons to null.
12180     if (!HasSameBase(LHSValue, RHSValue)) {
12181       // Inequalities and subtractions between unrelated pointers have
12182       // unspecified or undefined behavior.
12183       if (!IsEquality) {
12184         Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified);
12185         return false;
12186       }
12187       // A constant address may compare equal to the address of a symbol.
12188       // The one exception is that address of an object cannot compare equal
12189       // to a null pointer constant.
12190       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
12191           (!RHSValue.Base && !RHSValue.Offset.isZero()))
12192         return Error(E);
12193       // It's implementation-defined whether distinct literals will have
12194       // distinct addresses. In clang, the result of such a comparison is
12195       // unspecified, so it is not a constant expression. However, we do know
12196       // that the address of a literal will be non-null.
12197       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
12198           LHSValue.Base && RHSValue.Base)
12199         return Error(E);
12200       // We can't tell whether weak symbols will end up pointing to the same
12201       // object.
12202       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
12203         return Error(E);
12204       // We can't compare the address of the start of one object with the
12205       // past-the-end address of another object, per C++ DR1652.
12206       if ((LHSValue.Base && LHSValue.Offset.isZero() &&
12207            isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
12208           (RHSValue.Base && RHSValue.Offset.isZero() &&
12209            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
12210         return Error(E);
12211       // We can't tell whether an object is at the same address as another
12212       // zero sized object.
12213       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
12214           (LHSValue.Base && isZeroSized(RHSValue)))
12215         return Error(E);
12216       return Success(CmpResult::Unequal, E);
12217     }
12218 
12219     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12220     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12221 
12222     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12223     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12224 
12225     // C++11 [expr.rel]p3:
12226     //   Pointers to void (after pointer conversions) can be compared, with a
12227     //   result defined as follows: If both pointers represent the same
12228     //   address or are both the null pointer value, the result is true if the
12229     //   operator is <= or >= and false otherwise; otherwise the result is
12230     //   unspecified.
12231     // We interpret this as applying to pointers to *cv* void.
12232     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
12233       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
12234 
12235     // C++11 [expr.rel]p2:
12236     // - If two pointers point to non-static data members of the same object,
12237     //   or to subobjects or array elements fo such members, recursively, the
12238     //   pointer to the later declared member compares greater provided the
12239     //   two members have the same access control and provided their class is
12240     //   not a union.
12241     //   [...]
12242     // - Otherwise pointer comparisons are unspecified.
12243     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
12244       bool WasArrayIndex;
12245       unsigned Mismatch = FindDesignatorMismatch(
12246           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
12247       // At the point where the designators diverge, the comparison has a
12248       // specified value if:
12249       //  - we are comparing array indices
12250       //  - we are comparing fields of a union, or fields with the same access
12251       // Otherwise, the result is unspecified and thus the comparison is not a
12252       // constant expression.
12253       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
12254           Mismatch < RHSDesignator.Entries.size()) {
12255         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
12256         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
12257         if (!LF && !RF)
12258           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
12259         else if (!LF)
12260           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12261               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
12262               << RF->getParent() << RF;
12263         else if (!RF)
12264           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12265               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
12266               << LF->getParent() << LF;
12267         else if (!LF->getParent()->isUnion() &&
12268                  LF->getAccess() != RF->getAccess())
12269           Info.CCEDiag(E,
12270                        diag::note_constexpr_pointer_comparison_differing_access)
12271               << LF << LF->getAccess() << RF << RF->getAccess()
12272               << LF->getParent();
12273       }
12274     }
12275 
12276     // The comparison here must be unsigned, and performed with the same
12277     // width as the pointer.
12278     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
12279     uint64_t CompareLHS = LHSOffset.getQuantity();
12280     uint64_t CompareRHS = RHSOffset.getQuantity();
12281     assert(PtrSize <= 64 && "Unexpected pointer width");
12282     uint64_t Mask = ~0ULL >> (64 - PtrSize);
12283     CompareLHS &= Mask;
12284     CompareRHS &= Mask;
12285 
12286     // If there is a base and this is a relational operator, we can only
12287     // compare pointers within the object in question; otherwise, the result
12288     // depends on where the object is located in memory.
12289     if (!LHSValue.Base.isNull() && IsRelational) {
12290       QualType BaseTy = getType(LHSValue.Base);
12291       if (BaseTy->isIncompleteType())
12292         return Error(E);
12293       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
12294       uint64_t OffsetLimit = Size.getQuantity();
12295       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
12296         return Error(E);
12297     }
12298 
12299     if (CompareLHS < CompareRHS)
12300       return Success(CmpResult::Less, E);
12301     if (CompareLHS > CompareRHS)
12302       return Success(CmpResult::Greater, E);
12303     return Success(CmpResult::Equal, E);
12304   }
12305 
12306   if (LHSTy->isMemberPointerType()) {
12307     assert(IsEquality && "unexpected member pointer operation");
12308     assert(RHSTy->isMemberPointerType() && "invalid comparison");
12309 
12310     MemberPtr LHSValue, RHSValue;
12311 
12312     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
12313     if (!LHSOK && !Info.noteFailure())
12314       return false;
12315 
12316     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12317       return false;
12318 
12319     // C++11 [expr.eq]p2:
12320     //   If both operands are null, they compare equal. Otherwise if only one is
12321     //   null, they compare unequal.
12322     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
12323       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
12324       return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12325     }
12326 
12327     //   Otherwise if either is a pointer to a virtual member function, the
12328     //   result is unspecified.
12329     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
12330       if (MD->isVirtual())
12331         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12332     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
12333       if (MD->isVirtual())
12334         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12335 
12336     //   Otherwise they compare equal if and only if they would refer to the
12337     //   same member of the same most derived object or the same subobject if
12338     //   they were dereferenced with a hypothetical object of the associated
12339     //   class type.
12340     bool Equal = LHSValue == RHSValue;
12341     return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12342   }
12343 
12344   if (LHSTy->isNullPtrType()) {
12345     assert(E->isComparisonOp() && "unexpected nullptr operation");
12346     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
12347     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
12348     // are compared, the result is true of the operator is <=, >= or ==, and
12349     // false otherwise.
12350     return Success(CmpResult::Equal, E);
12351   }
12352 
12353   return DoAfter();
12354 }
12355 
12356 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
12357   if (!CheckLiteralType(Info, E))
12358     return false;
12359 
12360   auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12361     ComparisonCategoryResult CCR;
12362     switch (CR) {
12363     case CmpResult::Unequal:
12364       llvm_unreachable("should never produce Unequal for three-way comparison");
12365     case CmpResult::Less:
12366       CCR = ComparisonCategoryResult::Less;
12367       break;
12368     case CmpResult::Equal:
12369       CCR = ComparisonCategoryResult::Equal;
12370       break;
12371     case CmpResult::Greater:
12372       CCR = ComparisonCategoryResult::Greater;
12373       break;
12374     case CmpResult::Unordered:
12375       CCR = ComparisonCategoryResult::Unordered;
12376       break;
12377     }
12378     // Evaluation succeeded. Lookup the information for the comparison category
12379     // type and fetch the VarDecl for the result.
12380     const ComparisonCategoryInfo &CmpInfo =
12381         Info.Ctx.CompCategories.getInfoForType(E->getType());
12382     const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
12383     // Check and evaluate the result as a constant expression.
12384     LValue LV;
12385     LV.set(VD);
12386     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
12387       return false;
12388     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
12389   };
12390   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12391     return ExprEvaluatorBaseTy::VisitBinCmp(E);
12392   });
12393 }
12394 
12395 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12396   // We don't call noteFailure immediately because the assignment happens after
12397   // we evaluate LHS and RHS.
12398   if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
12399     return Error(E);
12400 
12401   DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
12402   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
12403     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
12404 
12405   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
12406           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
12407          "DataRecursiveIntBinOpEvaluator should have handled integral types");
12408 
12409   if (E->isComparisonOp()) {
12410     // Evaluate builtin binary comparisons by evaluating them as three-way
12411     // comparisons and then translating the result.
12412     auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12413       assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
12414              "should only produce Unequal for equality comparisons");
12415       bool IsEqual   = CR == CmpResult::Equal,
12416            IsLess    = CR == CmpResult::Less,
12417            IsGreater = CR == CmpResult::Greater;
12418       auto Op = E->getOpcode();
12419       switch (Op) {
12420       default:
12421         llvm_unreachable("unsupported binary operator");
12422       case BO_EQ:
12423       case BO_NE:
12424         return Success(IsEqual == (Op == BO_EQ), E);
12425       case BO_LT:
12426         return Success(IsLess, E);
12427       case BO_GT:
12428         return Success(IsGreater, E);
12429       case BO_LE:
12430         return Success(IsEqual || IsLess, E);
12431       case BO_GE:
12432         return Success(IsEqual || IsGreater, E);
12433       }
12434     };
12435     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12436       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12437     });
12438   }
12439 
12440   QualType LHSTy = E->getLHS()->getType();
12441   QualType RHSTy = E->getRHS()->getType();
12442 
12443   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
12444       E->getOpcode() == BO_Sub) {
12445     LValue LHSValue, RHSValue;
12446 
12447     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12448     if (!LHSOK && !Info.noteFailure())
12449       return false;
12450 
12451     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12452       return false;
12453 
12454     // Reject differing bases from the normal codepath; we special-case
12455     // comparisons to null.
12456     if (!HasSameBase(LHSValue, RHSValue)) {
12457       // Handle &&A - &&B.
12458       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
12459         return Error(E);
12460       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
12461       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
12462       if (!LHSExpr || !RHSExpr)
12463         return Error(E);
12464       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12465       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12466       if (!LHSAddrExpr || !RHSAddrExpr)
12467         return Error(E);
12468       // Make sure both labels come from the same function.
12469       if (LHSAddrExpr->getLabel()->getDeclContext() !=
12470           RHSAddrExpr->getLabel()->getDeclContext())
12471         return Error(E);
12472       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
12473     }
12474     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12475     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12476 
12477     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12478     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12479 
12480     // C++11 [expr.add]p6:
12481     //   Unless both pointers point to elements of the same array object, or
12482     //   one past the last element of the array object, the behavior is
12483     //   undefined.
12484     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
12485         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
12486                                 RHSDesignator))
12487       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
12488 
12489     QualType Type = E->getLHS()->getType();
12490     QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
12491 
12492     CharUnits ElementSize;
12493     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
12494       return false;
12495 
12496     // As an extension, a type may have zero size (empty struct or union in
12497     // C, array of zero length). Pointer subtraction in such cases has
12498     // undefined behavior, so is not constant.
12499     if (ElementSize.isZero()) {
12500       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
12501           << ElementType;
12502       return false;
12503     }
12504 
12505     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
12506     // and produce incorrect results when it overflows. Such behavior
12507     // appears to be non-conforming, but is common, so perhaps we should
12508     // assume the standard intended for such cases to be undefined behavior
12509     // and check for them.
12510 
12511     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
12512     // overflow in the final conversion to ptrdiff_t.
12513     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
12514     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
12515     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
12516                     false);
12517     APSInt TrueResult = (LHS - RHS) / ElemSize;
12518     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
12519 
12520     if (Result.extend(65) != TrueResult &&
12521         !HandleOverflow(Info, E, TrueResult, E->getType()))
12522       return false;
12523     return Success(Result, E);
12524   }
12525 
12526   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12527 }
12528 
12529 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
12530 /// a result as the expression's type.
12531 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
12532                                     const UnaryExprOrTypeTraitExpr *E) {
12533   switch(E->getKind()) {
12534   case UETT_PreferredAlignOf:
12535   case UETT_AlignOf: {
12536     if (E->isArgumentType())
12537       return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
12538                      E);
12539     else
12540       return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
12541                      E);
12542   }
12543 
12544   case UETT_VecStep: {
12545     QualType Ty = E->getTypeOfArgument();
12546 
12547     if (Ty->isVectorType()) {
12548       unsigned n = Ty->castAs<VectorType>()->getNumElements();
12549 
12550       // The vec_step built-in functions that take a 3-component
12551       // vector return 4. (OpenCL 1.1 spec 6.11.12)
12552       if (n == 3)
12553         n = 4;
12554 
12555       return Success(n, E);
12556     } else
12557       return Success(1, E);
12558   }
12559 
12560   case UETT_SizeOf: {
12561     QualType SrcTy = E->getTypeOfArgument();
12562     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
12563     //   the result is the size of the referenced type."
12564     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
12565       SrcTy = Ref->getPointeeType();
12566 
12567     CharUnits Sizeof;
12568     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
12569       return false;
12570     return Success(Sizeof, E);
12571   }
12572   case UETT_OpenMPRequiredSimdAlign:
12573     assert(E->isArgumentType());
12574     return Success(
12575         Info.Ctx.toCharUnitsFromBits(
12576                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
12577             .getQuantity(),
12578         E);
12579   }
12580 
12581   llvm_unreachable("unknown expr/type trait");
12582 }
12583 
12584 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
12585   CharUnits Result;
12586   unsigned n = OOE->getNumComponents();
12587   if (n == 0)
12588     return Error(OOE);
12589   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
12590   for (unsigned i = 0; i != n; ++i) {
12591     OffsetOfNode ON = OOE->getComponent(i);
12592     switch (ON.getKind()) {
12593     case OffsetOfNode::Array: {
12594       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
12595       APSInt IdxResult;
12596       if (!EvaluateInteger(Idx, IdxResult, Info))
12597         return false;
12598       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
12599       if (!AT)
12600         return Error(OOE);
12601       CurrentType = AT->getElementType();
12602       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
12603       Result += IdxResult.getSExtValue() * ElementSize;
12604       break;
12605     }
12606 
12607     case OffsetOfNode::Field: {
12608       FieldDecl *MemberDecl = ON.getField();
12609       const RecordType *RT = CurrentType->getAs<RecordType>();
12610       if (!RT)
12611         return Error(OOE);
12612       RecordDecl *RD = RT->getDecl();
12613       if (RD->isInvalidDecl()) return false;
12614       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
12615       unsigned i = MemberDecl->getFieldIndex();
12616       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
12617       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
12618       CurrentType = MemberDecl->getType().getNonReferenceType();
12619       break;
12620     }
12621 
12622     case OffsetOfNode::Identifier:
12623       llvm_unreachable("dependent __builtin_offsetof");
12624 
12625     case OffsetOfNode::Base: {
12626       CXXBaseSpecifier *BaseSpec = ON.getBase();
12627       if (BaseSpec->isVirtual())
12628         return Error(OOE);
12629 
12630       // Find the layout of the class whose base we are looking into.
12631       const RecordType *RT = CurrentType->getAs<RecordType>();
12632       if (!RT)
12633         return Error(OOE);
12634       RecordDecl *RD = RT->getDecl();
12635       if (RD->isInvalidDecl()) return false;
12636       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
12637 
12638       // Find the base class itself.
12639       CurrentType = BaseSpec->getType();
12640       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
12641       if (!BaseRT)
12642         return Error(OOE);
12643 
12644       // Add the offset to the base.
12645       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
12646       break;
12647     }
12648     }
12649   }
12650   return Success(Result, OOE);
12651 }
12652 
12653 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12654   switch (E->getOpcode()) {
12655   default:
12656     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
12657     // See C99 6.6p3.
12658     return Error(E);
12659   case UO_Extension:
12660     // FIXME: Should extension allow i-c-e extension expressions in its scope?
12661     // If so, we could clear the diagnostic ID.
12662     return Visit(E->getSubExpr());
12663   case UO_Plus:
12664     // The result is just the value.
12665     return Visit(E->getSubExpr());
12666   case UO_Minus: {
12667     if (!Visit(E->getSubExpr()))
12668       return false;
12669     if (!Result.isInt()) return Error(E);
12670     const APSInt &Value = Result.getInt();
12671     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
12672         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
12673                         E->getType()))
12674       return false;
12675     return Success(-Value, E);
12676   }
12677   case UO_Not: {
12678     if (!Visit(E->getSubExpr()))
12679       return false;
12680     if (!Result.isInt()) return Error(E);
12681     return Success(~Result.getInt(), E);
12682   }
12683   case UO_LNot: {
12684     bool bres;
12685     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
12686       return false;
12687     return Success(!bres, E);
12688   }
12689   }
12690 }
12691 
12692 /// HandleCast - This is used to evaluate implicit or explicit casts where the
12693 /// result type is integer.
12694 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
12695   const Expr *SubExpr = E->getSubExpr();
12696   QualType DestType = E->getType();
12697   QualType SrcType = SubExpr->getType();
12698 
12699   switch (E->getCastKind()) {
12700   case CK_BaseToDerived:
12701   case CK_DerivedToBase:
12702   case CK_UncheckedDerivedToBase:
12703   case CK_Dynamic:
12704   case CK_ToUnion:
12705   case CK_ArrayToPointerDecay:
12706   case CK_FunctionToPointerDecay:
12707   case CK_NullToPointer:
12708   case CK_NullToMemberPointer:
12709   case CK_BaseToDerivedMemberPointer:
12710   case CK_DerivedToBaseMemberPointer:
12711   case CK_ReinterpretMemberPointer:
12712   case CK_ConstructorConversion:
12713   case CK_IntegralToPointer:
12714   case CK_ToVoid:
12715   case CK_VectorSplat:
12716   case CK_IntegralToFloating:
12717   case CK_FloatingCast:
12718   case CK_CPointerToObjCPointerCast:
12719   case CK_BlockPointerToObjCPointerCast:
12720   case CK_AnyPointerToBlockPointerCast:
12721   case CK_ObjCObjectLValueCast:
12722   case CK_FloatingRealToComplex:
12723   case CK_FloatingComplexToReal:
12724   case CK_FloatingComplexCast:
12725   case CK_FloatingComplexToIntegralComplex:
12726   case CK_IntegralRealToComplex:
12727   case CK_IntegralComplexCast:
12728   case CK_IntegralComplexToFloatingComplex:
12729   case CK_BuiltinFnToFnPtr:
12730   case CK_ZeroToOCLOpaqueType:
12731   case CK_NonAtomicToAtomic:
12732   case CK_AddressSpaceConversion:
12733   case CK_IntToOCLSampler:
12734   case CK_FixedPointCast:
12735   case CK_IntegralToFixedPoint:
12736     llvm_unreachable("invalid cast kind for integral value");
12737 
12738   case CK_BitCast:
12739   case CK_Dependent:
12740   case CK_LValueBitCast:
12741   case CK_ARCProduceObject:
12742   case CK_ARCConsumeObject:
12743   case CK_ARCReclaimReturnedObject:
12744   case CK_ARCExtendBlockObject:
12745   case CK_CopyAndAutoreleaseBlockObject:
12746     return Error(E);
12747 
12748   case CK_UserDefinedConversion:
12749   case CK_LValueToRValue:
12750   case CK_AtomicToNonAtomic:
12751   case CK_NoOp:
12752   case CK_LValueToRValueBitCast:
12753     return ExprEvaluatorBaseTy::VisitCastExpr(E);
12754 
12755   case CK_MemberPointerToBoolean:
12756   case CK_PointerToBoolean:
12757   case CK_IntegralToBoolean:
12758   case CK_FloatingToBoolean:
12759   case CK_BooleanToSignedIntegral:
12760   case CK_FloatingComplexToBoolean:
12761   case CK_IntegralComplexToBoolean: {
12762     bool BoolResult;
12763     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
12764       return false;
12765     uint64_t IntResult = BoolResult;
12766     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
12767       IntResult = (uint64_t)-1;
12768     return Success(IntResult, E);
12769   }
12770 
12771   case CK_FixedPointToIntegral: {
12772     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
12773     if (!EvaluateFixedPoint(SubExpr, Src, Info))
12774       return false;
12775     bool Overflowed;
12776     llvm::APSInt Result = Src.convertToInt(
12777         Info.Ctx.getIntWidth(DestType),
12778         DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
12779     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
12780       return false;
12781     return Success(Result, E);
12782   }
12783 
12784   case CK_FixedPointToBoolean: {
12785     // Unsigned padding does not affect this.
12786     APValue Val;
12787     if (!Evaluate(Val, Info, SubExpr))
12788       return false;
12789     return Success(Val.getFixedPoint().getBoolValue(), E);
12790   }
12791 
12792   case CK_IntegralCast: {
12793     if (!Visit(SubExpr))
12794       return false;
12795 
12796     if (!Result.isInt()) {
12797       // Allow casts of address-of-label differences if they are no-ops
12798       // or narrowing.  (The narrowing case isn't actually guaranteed to
12799       // be constant-evaluatable except in some narrow cases which are hard
12800       // to detect here.  We let it through on the assumption the user knows
12801       // what they are doing.)
12802       if (Result.isAddrLabelDiff())
12803         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
12804       // Only allow casts of lvalues if they are lossless.
12805       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
12806     }
12807 
12808     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
12809                                       Result.getInt()), E);
12810   }
12811 
12812   case CK_PointerToIntegral: {
12813     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
12814 
12815     LValue LV;
12816     if (!EvaluatePointer(SubExpr, LV, Info))
12817       return false;
12818 
12819     if (LV.getLValueBase()) {
12820       // Only allow based lvalue casts if they are lossless.
12821       // FIXME: Allow a larger integer size than the pointer size, and allow
12822       // narrowing back down to pointer width in subsequent integral casts.
12823       // FIXME: Check integer type's active bits, not its type size.
12824       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
12825         return Error(E);
12826 
12827       LV.Designator.setInvalid();
12828       LV.moveInto(Result);
12829       return true;
12830     }
12831 
12832     APSInt AsInt;
12833     APValue V;
12834     LV.moveInto(V);
12835     if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
12836       llvm_unreachable("Can't cast this!");
12837 
12838     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
12839   }
12840 
12841   case CK_IntegralComplexToReal: {
12842     ComplexValue C;
12843     if (!EvaluateComplex(SubExpr, C, Info))
12844       return false;
12845     return Success(C.getComplexIntReal(), E);
12846   }
12847 
12848   case CK_FloatingToIntegral: {
12849     APFloat F(0.0);
12850     if (!EvaluateFloat(SubExpr, F, Info))
12851       return false;
12852 
12853     APSInt Value;
12854     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
12855       return false;
12856     return Success(Value, E);
12857   }
12858   }
12859 
12860   llvm_unreachable("unknown cast resulting in integral value");
12861 }
12862 
12863 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
12864   if (E->getSubExpr()->getType()->isAnyComplexType()) {
12865     ComplexValue LV;
12866     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
12867       return false;
12868     if (!LV.isComplexInt())
12869       return Error(E);
12870     return Success(LV.getComplexIntReal(), E);
12871   }
12872 
12873   return Visit(E->getSubExpr());
12874 }
12875 
12876 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
12877   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
12878     ComplexValue LV;
12879     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
12880       return false;
12881     if (!LV.isComplexInt())
12882       return Error(E);
12883     return Success(LV.getComplexIntImag(), E);
12884   }
12885 
12886   VisitIgnoredValue(E->getSubExpr());
12887   return Success(0, E);
12888 }
12889 
12890 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
12891   return Success(E->getPackLength(), E);
12892 }
12893 
12894 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
12895   return Success(E->getValue(), E);
12896 }
12897 
12898 bool IntExprEvaluator::VisitConceptSpecializationExpr(
12899        const ConceptSpecializationExpr *E) {
12900   return Success(E->isSatisfied(), E);
12901 }
12902 
12903 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
12904   return Success(E->isSatisfied(), E);
12905 }
12906 
12907 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12908   switch (E->getOpcode()) {
12909     default:
12910       // Invalid unary operators
12911       return Error(E);
12912     case UO_Plus:
12913       // The result is just the value.
12914       return Visit(E->getSubExpr());
12915     case UO_Minus: {
12916       if (!Visit(E->getSubExpr())) return false;
12917       if (!Result.isFixedPoint())
12918         return Error(E);
12919       bool Overflowed;
12920       APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
12921       if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
12922         return false;
12923       return Success(Negated, E);
12924     }
12925     case UO_LNot: {
12926       bool bres;
12927       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
12928         return false;
12929       return Success(!bres, E);
12930     }
12931   }
12932 }
12933 
12934 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
12935   const Expr *SubExpr = E->getSubExpr();
12936   QualType DestType = E->getType();
12937   assert(DestType->isFixedPointType() &&
12938          "Expected destination type to be a fixed point type");
12939   auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
12940 
12941   switch (E->getCastKind()) {
12942   case CK_FixedPointCast: {
12943     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
12944     if (!EvaluateFixedPoint(SubExpr, Src, Info))
12945       return false;
12946     bool Overflowed;
12947     APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
12948     if (Overflowed) {
12949       if (Info.checkingForUndefinedBehavior())
12950         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
12951                                          diag::warn_fixedpoint_constant_overflow)
12952           << Result.toString() << E->getType();
12953       else if (!HandleOverflow(Info, E, Result, E->getType()))
12954         return false;
12955     }
12956     return Success(Result, E);
12957   }
12958   case CK_IntegralToFixedPoint: {
12959     APSInt Src;
12960     if (!EvaluateInteger(SubExpr, Src, Info))
12961       return false;
12962 
12963     bool Overflowed;
12964     APFixedPoint IntResult = APFixedPoint::getFromIntValue(
12965         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
12966 
12967     if (Overflowed) {
12968       if (Info.checkingForUndefinedBehavior())
12969         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
12970                                          diag::warn_fixedpoint_constant_overflow)
12971           << IntResult.toString() << E->getType();
12972       else if (!HandleOverflow(Info, E, IntResult, E->getType()))
12973         return false;
12974     }
12975 
12976     return Success(IntResult, E);
12977   }
12978   case CK_NoOp:
12979   case CK_LValueToRValue:
12980     return ExprEvaluatorBaseTy::VisitCastExpr(E);
12981   default:
12982     return Error(E);
12983   }
12984 }
12985 
12986 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12987   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
12988     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12989 
12990   const Expr *LHS = E->getLHS();
12991   const Expr *RHS = E->getRHS();
12992   FixedPointSemantics ResultFXSema =
12993       Info.Ctx.getFixedPointSemantics(E->getType());
12994 
12995   APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
12996   if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
12997     return false;
12998   APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
12999   if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
13000     return false;
13001 
13002   bool OpOverflow = false, ConversionOverflow = false;
13003   APFixedPoint Result(LHSFX.getSemantics());
13004   switch (E->getOpcode()) {
13005   case BO_Add: {
13006     Result = LHSFX.add(RHSFX, &OpOverflow)
13007                   .convert(ResultFXSema, &ConversionOverflow);
13008     break;
13009   }
13010   case BO_Sub: {
13011     Result = LHSFX.sub(RHSFX, &OpOverflow)
13012                   .convert(ResultFXSema, &ConversionOverflow);
13013     break;
13014   }
13015   case BO_Mul: {
13016     Result = LHSFX.mul(RHSFX, &OpOverflow)
13017                   .convert(ResultFXSema, &ConversionOverflow);
13018     break;
13019   }
13020   case BO_Div: {
13021     if (RHSFX.getValue() == 0) {
13022       Info.FFDiag(E, diag::note_expr_divide_by_zero);
13023       return false;
13024     }
13025     Result = LHSFX.div(RHSFX, &OpOverflow)
13026                   .convert(ResultFXSema, &ConversionOverflow);
13027     break;
13028   }
13029   case BO_Shl:
13030   case BO_Shr: {
13031     FixedPointSemantics LHSSema = LHSFX.getSemantics();
13032     llvm::APSInt RHSVal = RHSFX.getValue();
13033 
13034     unsigned ShiftBW =
13035         LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
13036     unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
13037     // Embedded-C 4.1.6.2.2:
13038     //   The right operand must be nonnegative and less than the total number
13039     //   of (nonpadding) bits of the fixed-point operand ...
13040     if (RHSVal.isNegative())
13041       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
13042     else if (Amt != RHSVal)
13043       Info.CCEDiag(E, diag::note_constexpr_large_shift)
13044           << RHSVal << E->getType() << ShiftBW;
13045 
13046     if (E->getOpcode() == BO_Shl)
13047       Result = LHSFX.shl(Amt, &OpOverflow);
13048     else
13049       Result = LHSFX.shr(Amt, &OpOverflow);
13050     break;
13051   }
13052   default:
13053     return false;
13054   }
13055   if (OpOverflow || ConversionOverflow) {
13056     if (Info.checkingForUndefinedBehavior())
13057       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13058                                        diag::warn_fixedpoint_constant_overflow)
13059         << Result.toString() << E->getType();
13060     else if (!HandleOverflow(Info, E, Result, E->getType()))
13061       return false;
13062   }
13063   return Success(Result, E);
13064 }
13065 
13066 //===----------------------------------------------------------------------===//
13067 // Float Evaluation
13068 //===----------------------------------------------------------------------===//
13069 
13070 namespace {
13071 class FloatExprEvaluator
13072   : public ExprEvaluatorBase<FloatExprEvaluator> {
13073   APFloat &Result;
13074 public:
13075   FloatExprEvaluator(EvalInfo &info, APFloat &result)
13076     : ExprEvaluatorBaseTy(info), Result(result) {}
13077 
13078   bool Success(const APValue &V, const Expr *e) {
13079     Result = V.getFloat();
13080     return true;
13081   }
13082 
13083   bool ZeroInitialization(const Expr *E) {
13084     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
13085     return true;
13086   }
13087 
13088   bool VisitCallExpr(const CallExpr *E);
13089 
13090   bool VisitUnaryOperator(const UnaryOperator *E);
13091   bool VisitBinaryOperator(const BinaryOperator *E);
13092   bool VisitFloatingLiteral(const FloatingLiteral *E);
13093   bool VisitCastExpr(const CastExpr *E);
13094 
13095   bool VisitUnaryReal(const UnaryOperator *E);
13096   bool VisitUnaryImag(const UnaryOperator *E);
13097 
13098   // FIXME: Missing: array subscript of vector, member of vector
13099 };
13100 } // end anonymous namespace
13101 
13102 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
13103   assert(E->isRValue() && E->getType()->isRealFloatingType());
13104   return FloatExprEvaluator(Info, Result).Visit(E);
13105 }
13106 
13107 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
13108                                   QualType ResultTy,
13109                                   const Expr *Arg,
13110                                   bool SNaN,
13111                                   llvm::APFloat &Result) {
13112   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
13113   if (!S) return false;
13114 
13115   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
13116 
13117   llvm::APInt fill;
13118 
13119   // Treat empty strings as if they were zero.
13120   if (S->getString().empty())
13121     fill = llvm::APInt(32, 0);
13122   else if (S->getString().getAsInteger(0, fill))
13123     return false;
13124 
13125   if (Context.getTargetInfo().isNan2008()) {
13126     if (SNaN)
13127       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13128     else
13129       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13130   } else {
13131     // Prior to IEEE 754-2008, architectures were allowed to choose whether
13132     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
13133     // a different encoding to what became a standard in 2008, and for pre-
13134     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
13135     // sNaN. This is now known as "legacy NaN" encoding.
13136     if (SNaN)
13137       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13138     else
13139       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13140   }
13141 
13142   return true;
13143 }
13144 
13145 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
13146   switch (E->getBuiltinCallee()) {
13147   default:
13148     return ExprEvaluatorBaseTy::VisitCallExpr(E);
13149 
13150   case Builtin::BI__builtin_huge_val:
13151   case Builtin::BI__builtin_huge_valf:
13152   case Builtin::BI__builtin_huge_vall:
13153   case Builtin::BI__builtin_huge_valf128:
13154   case Builtin::BI__builtin_inf:
13155   case Builtin::BI__builtin_inff:
13156   case Builtin::BI__builtin_infl:
13157   case Builtin::BI__builtin_inff128: {
13158     const llvm::fltSemantics &Sem =
13159       Info.Ctx.getFloatTypeSemantics(E->getType());
13160     Result = llvm::APFloat::getInf(Sem);
13161     return true;
13162   }
13163 
13164   case Builtin::BI__builtin_nans:
13165   case Builtin::BI__builtin_nansf:
13166   case Builtin::BI__builtin_nansl:
13167   case Builtin::BI__builtin_nansf128:
13168     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13169                                true, Result))
13170       return Error(E);
13171     return true;
13172 
13173   case Builtin::BI__builtin_nan:
13174   case Builtin::BI__builtin_nanf:
13175   case Builtin::BI__builtin_nanl:
13176   case Builtin::BI__builtin_nanf128:
13177     // If this is __builtin_nan() turn this into a nan, otherwise we
13178     // can't constant fold it.
13179     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13180                                false, Result))
13181       return Error(E);
13182     return true;
13183 
13184   case Builtin::BI__builtin_fabs:
13185   case Builtin::BI__builtin_fabsf:
13186   case Builtin::BI__builtin_fabsl:
13187   case Builtin::BI__builtin_fabsf128:
13188     if (!EvaluateFloat(E->getArg(0), Result, Info))
13189       return false;
13190 
13191     if (Result.isNegative())
13192       Result.changeSign();
13193     return true;
13194 
13195   // FIXME: Builtin::BI__builtin_powi
13196   // FIXME: Builtin::BI__builtin_powif
13197   // FIXME: Builtin::BI__builtin_powil
13198 
13199   case Builtin::BI__builtin_copysign:
13200   case Builtin::BI__builtin_copysignf:
13201   case Builtin::BI__builtin_copysignl:
13202   case Builtin::BI__builtin_copysignf128: {
13203     APFloat RHS(0.);
13204     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
13205         !EvaluateFloat(E->getArg(1), RHS, Info))
13206       return false;
13207     Result.copySign(RHS);
13208     return true;
13209   }
13210   }
13211 }
13212 
13213 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13214   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13215     ComplexValue CV;
13216     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13217       return false;
13218     Result = CV.FloatReal;
13219     return true;
13220   }
13221 
13222   return Visit(E->getSubExpr());
13223 }
13224 
13225 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13226   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13227     ComplexValue CV;
13228     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13229       return false;
13230     Result = CV.FloatImag;
13231     return true;
13232   }
13233 
13234   VisitIgnoredValue(E->getSubExpr());
13235   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
13236   Result = llvm::APFloat::getZero(Sem);
13237   return true;
13238 }
13239 
13240 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13241   switch (E->getOpcode()) {
13242   default: return Error(E);
13243   case UO_Plus:
13244     return EvaluateFloat(E->getSubExpr(), Result, Info);
13245   case UO_Minus:
13246     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
13247       return false;
13248     Result.changeSign();
13249     return true;
13250   }
13251 }
13252 
13253 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13254   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13255     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13256 
13257   APFloat RHS(0.0);
13258   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
13259   if (!LHSOK && !Info.noteFailure())
13260     return false;
13261   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
13262          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
13263 }
13264 
13265 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
13266   Result = E->getValue();
13267   return true;
13268 }
13269 
13270 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
13271   const Expr* SubExpr = E->getSubExpr();
13272 
13273   switch (E->getCastKind()) {
13274   default:
13275     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13276 
13277   case CK_IntegralToFloating: {
13278     APSInt IntResult;
13279     return EvaluateInteger(SubExpr, IntResult, Info) &&
13280            HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
13281                                 E->getType(), Result);
13282   }
13283 
13284   case CK_FloatingCast: {
13285     if (!Visit(SubExpr))
13286       return false;
13287     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
13288                                   Result);
13289   }
13290 
13291   case CK_FloatingComplexToReal: {
13292     ComplexValue V;
13293     if (!EvaluateComplex(SubExpr, V, Info))
13294       return false;
13295     Result = V.getComplexFloatReal();
13296     return true;
13297   }
13298   }
13299 }
13300 
13301 //===----------------------------------------------------------------------===//
13302 // Complex Evaluation (for float and integer)
13303 //===----------------------------------------------------------------------===//
13304 
13305 namespace {
13306 class ComplexExprEvaluator
13307   : public ExprEvaluatorBase<ComplexExprEvaluator> {
13308   ComplexValue &Result;
13309 
13310 public:
13311   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
13312     : ExprEvaluatorBaseTy(info), Result(Result) {}
13313 
13314   bool Success(const APValue &V, const Expr *e) {
13315     Result.setFrom(V);
13316     return true;
13317   }
13318 
13319   bool ZeroInitialization(const Expr *E);
13320 
13321   //===--------------------------------------------------------------------===//
13322   //                            Visitor Methods
13323   //===--------------------------------------------------------------------===//
13324 
13325   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
13326   bool VisitCastExpr(const CastExpr *E);
13327   bool VisitBinaryOperator(const BinaryOperator *E);
13328   bool VisitUnaryOperator(const UnaryOperator *E);
13329   bool VisitInitListExpr(const InitListExpr *E);
13330   bool VisitCallExpr(const CallExpr *E);
13331 };
13332 } // end anonymous namespace
13333 
13334 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
13335                             EvalInfo &Info) {
13336   assert(E->isRValue() && E->getType()->isAnyComplexType());
13337   return ComplexExprEvaluator(Info, Result).Visit(E);
13338 }
13339 
13340 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
13341   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
13342   if (ElemTy->isRealFloatingType()) {
13343     Result.makeComplexFloat();
13344     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
13345     Result.FloatReal = Zero;
13346     Result.FloatImag = Zero;
13347   } else {
13348     Result.makeComplexInt();
13349     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
13350     Result.IntReal = Zero;
13351     Result.IntImag = Zero;
13352   }
13353   return true;
13354 }
13355 
13356 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
13357   const Expr* SubExpr = E->getSubExpr();
13358 
13359   if (SubExpr->getType()->isRealFloatingType()) {
13360     Result.makeComplexFloat();
13361     APFloat &Imag = Result.FloatImag;
13362     if (!EvaluateFloat(SubExpr, Imag, Info))
13363       return false;
13364 
13365     Result.FloatReal = APFloat(Imag.getSemantics());
13366     return true;
13367   } else {
13368     assert(SubExpr->getType()->isIntegerType() &&
13369            "Unexpected imaginary literal.");
13370 
13371     Result.makeComplexInt();
13372     APSInt &Imag = Result.IntImag;
13373     if (!EvaluateInteger(SubExpr, Imag, Info))
13374       return false;
13375 
13376     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
13377     return true;
13378   }
13379 }
13380 
13381 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
13382 
13383   switch (E->getCastKind()) {
13384   case CK_BitCast:
13385   case CK_BaseToDerived:
13386   case CK_DerivedToBase:
13387   case CK_UncheckedDerivedToBase:
13388   case CK_Dynamic:
13389   case CK_ToUnion:
13390   case CK_ArrayToPointerDecay:
13391   case CK_FunctionToPointerDecay:
13392   case CK_NullToPointer:
13393   case CK_NullToMemberPointer:
13394   case CK_BaseToDerivedMemberPointer:
13395   case CK_DerivedToBaseMemberPointer:
13396   case CK_MemberPointerToBoolean:
13397   case CK_ReinterpretMemberPointer:
13398   case CK_ConstructorConversion:
13399   case CK_IntegralToPointer:
13400   case CK_PointerToIntegral:
13401   case CK_PointerToBoolean:
13402   case CK_ToVoid:
13403   case CK_VectorSplat:
13404   case CK_IntegralCast:
13405   case CK_BooleanToSignedIntegral:
13406   case CK_IntegralToBoolean:
13407   case CK_IntegralToFloating:
13408   case CK_FloatingToIntegral:
13409   case CK_FloatingToBoolean:
13410   case CK_FloatingCast:
13411   case CK_CPointerToObjCPointerCast:
13412   case CK_BlockPointerToObjCPointerCast:
13413   case CK_AnyPointerToBlockPointerCast:
13414   case CK_ObjCObjectLValueCast:
13415   case CK_FloatingComplexToReal:
13416   case CK_FloatingComplexToBoolean:
13417   case CK_IntegralComplexToReal:
13418   case CK_IntegralComplexToBoolean:
13419   case CK_ARCProduceObject:
13420   case CK_ARCConsumeObject:
13421   case CK_ARCReclaimReturnedObject:
13422   case CK_ARCExtendBlockObject:
13423   case CK_CopyAndAutoreleaseBlockObject:
13424   case CK_BuiltinFnToFnPtr:
13425   case CK_ZeroToOCLOpaqueType:
13426   case CK_NonAtomicToAtomic:
13427   case CK_AddressSpaceConversion:
13428   case CK_IntToOCLSampler:
13429   case CK_FixedPointCast:
13430   case CK_FixedPointToBoolean:
13431   case CK_FixedPointToIntegral:
13432   case CK_IntegralToFixedPoint:
13433     llvm_unreachable("invalid cast kind for complex value");
13434 
13435   case CK_LValueToRValue:
13436   case CK_AtomicToNonAtomic:
13437   case CK_NoOp:
13438   case CK_LValueToRValueBitCast:
13439     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13440 
13441   case CK_Dependent:
13442   case CK_LValueBitCast:
13443   case CK_UserDefinedConversion:
13444     return Error(E);
13445 
13446   case CK_FloatingRealToComplex: {
13447     APFloat &Real = Result.FloatReal;
13448     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
13449       return false;
13450 
13451     Result.makeComplexFloat();
13452     Result.FloatImag = APFloat(Real.getSemantics());
13453     return true;
13454   }
13455 
13456   case CK_FloatingComplexCast: {
13457     if (!Visit(E->getSubExpr()))
13458       return false;
13459 
13460     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13461     QualType From
13462       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13463 
13464     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
13465            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
13466   }
13467 
13468   case CK_FloatingComplexToIntegralComplex: {
13469     if (!Visit(E->getSubExpr()))
13470       return false;
13471 
13472     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13473     QualType From
13474       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13475     Result.makeComplexInt();
13476     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
13477                                 To, Result.IntReal) &&
13478            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
13479                                 To, Result.IntImag);
13480   }
13481 
13482   case CK_IntegralRealToComplex: {
13483     APSInt &Real = Result.IntReal;
13484     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
13485       return false;
13486 
13487     Result.makeComplexInt();
13488     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
13489     return true;
13490   }
13491 
13492   case CK_IntegralComplexCast: {
13493     if (!Visit(E->getSubExpr()))
13494       return false;
13495 
13496     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13497     QualType From
13498       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13499 
13500     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
13501     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
13502     return true;
13503   }
13504 
13505   case CK_IntegralComplexToFloatingComplex: {
13506     if (!Visit(E->getSubExpr()))
13507       return false;
13508 
13509     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13510     QualType From
13511       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13512     Result.makeComplexFloat();
13513     return HandleIntToFloatCast(Info, E, From, Result.IntReal,
13514                                 To, Result.FloatReal) &&
13515            HandleIntToFloatCast(Info, E, From, Result.IntImag,
13516                                 To, Result.FloatImag);
13517   }
13518   }
13519 
13520   llvm_unreachable("unknown cast resulting in complex value");
13521 }
13522 
13523 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13524   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13525     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13526 
13527   // Track whether the LHS or RHS is real at the type system level. When this is
13528   // the case we can simplify our evaluation strategy.
13529   bool LHSReal = false, RHSReal = false;
13530 
13531   bool LHSOK;
13532   if (E->getLHS()->getType()->isRealFloatingType()) {
13533     LHSReal = true;
13534     APFloat &Real = Result.FloatReal;
13535     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
13536     if (LHSOK) {
13537       Result.makeComplexFloat();
13538       Result.FloatImag = APFloat(Real.getSemantics());
13539     }
13540   } else {
13541     LHSOK = Visit(E->getLHS());
13542   }
13543   if (!LHSOK && !Info.noteFailure())
13544     return false;
13545 
13546   ComplexValue RHS;
13547   if (E->getRHS()->getType()->isRealFloatingType()) {
13548     RHSReal = true;
13549     APFloat &Real = RHS.FloatReal;
13550     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
13551       return false;
13552     RHS.makeComplexFloat();
13553     RHS.FloatImag = APFloat(Real.getSemantics());
13554   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
13555     return false;
13556 
13557   assert(!(LHSReal && RHSReal) &&
13558          "Cannot have both operands of a complex operation be real.");
13559   switch (E->getOpcode()) {
13560   default: return Error(E);
13561   case BO_Add:
13562     if (Result.isComplexFloat()) {
13563       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
13564                                        APFloat::rmNearestTiesToEven);
13565       if (LHSReal)
13566         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
13567       else if (!RHSReal)
13568         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
13569                                          APFloat::rmNearestTiesToEven);
13570     } else {
13571       Result.getComplexIntReal() += RHS.getComplexIntReal();
13572       Result.getComplexIntImag() += RHS.getComplexIntImag();
13573     }
13574     break;
13575   case BO_Sub:
13576     if (Result.isComplexFloat()) {
13577       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
13578                                             APFloat::rmNearestTiesToEven);
13579       if (LHSReal) {
13580         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
13581         Result.getComplexFloatImag().changeSign();
13582       } else if (!RHSReal) {
13583         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
13584                                               APFloat::rmNearestTiesToEven);
13585       }
13586     } else {
13587       Result.getComplexIntReal() -= RHS.getComplexIntReal();
13588       Result.getComplexIntImag() -= RHS.getComplexIntImag();
13589     }
13590     break;
13591   case BO_Mul:
13592     if (Result.isComplexFloat()) {
13593       // This is an implementation of complex multiplication according to the
13594       // constraints laid out in C11 Annex G. The implementation uses the
13595       // following naming scheme:
13596       //   (a + ib) * (c + id)
13597       ComplexValue LHS = Result;
13598       APFloat &A = LHS.getComplexFloatReal();
13599       APFloat &B = LHS.getComplexFloatImag();
13600       APFloat &C = RHS.getComplexFloatReal();
13601       APFloat &D = RHS.getComplexFloatImag();
13602       APFloat &ResR = Result.getComplexFloatReal();
13603       APFloat &ResI = Result.getComplexFloatImag();
13604       if (LHSReal) {
13605         assert(!RHSReal && "Cannot have two real operands for a complex op!");
13606         ResR = A * C;
13607         ResI = A * D;
13608       } else if (RHSReal) {
13609         ResR = C * A;
13610         ResI = C * B;
13611       } else {
13612         // In the fully general case, we need to handle NaNs and infinities
13613         // robustly.
13614         APFloat AC = A * C;
13615         APFloat BD = B * D;
13616         APFloat AD = A * D;
13617         APFloat BC = B * C;
13618         ResR = AC - BD;
13619         ResI = AD + BC;
13620         if (ResR.isNaN() && ResI.isNaN()) {
13621           bool Recalc = false;
13622           if (A.isInfinity() || B.isInfinity()) {
13623             A = APFloat::copySign(
13624                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
13625             B = APFloat::copySign(
13626                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
13627             if (C.isNaN())
13628               C = APFloat::copySign(APFloat(C.getSemantics()), C);
13629             if (D.isNaN())
13630               D = APFloat::copySign(APFloat(D.getSemantics()), D);
13631             Recalc = true;
13632           }
13633           if (C.isInfinity() || D.isInfinity()) {
13634             C = APFloat::copySign(
13635                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
13636             D = APFloat::copySign(
13637                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
13638             if (A.isNaN())
13639               A = APFloat::copySign(APFloat(A.getSemantics()), A);
13640             if (B.isNaN())
13641               B = APFloat::copySign(APFloat(B.getSemantics()), B);
13642             Recalc = true;
13643           }
13644           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
13645                           AD.isInfinity() || BC.isInfinity())) {
13646             if (A.isNaN())
13647               A = APFloat::copySign(APFloat(A.getSemantics()), A);
13648             if (B.isNaN())
13649               B = APFloat::copySign(APFloat(B.getSemantics()), B);
13650             if (C.isNaN())
13651               C = APFloat::copySign(APFloat(C.getSemantics()), C);
13652             if (D.isNaN())
13653               D = APFloat::copySign(APFloat(D.getSemantics()), D);
13654             Recalc = true;
13655           }
13656           if (Recalc) {
13657             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
13658             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
13659           }
13660         }
13661       }
13662     } else {
13663       ComplexValue LHS = Result;
13664       Result.getComplexIntReal() =
13665         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
13666          LHS.getComplexIntImag() * RHS.getComplexIntImag());
13667       Result.getComplexIntImag() =
13668         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
13669          LHS.getComplexIntImag() * RHS.getComplexIntReal());
13670     }
13671     break;
13672   case BO_Div:
13673     if (Result.isComplexFloat()) {
13674       // This is an implementation of complex division according to the
13675       // constraints laid out in C11 Annex G. The implementation uses the
13676       // following naming scheme:
13677       //   (a + ib) / (c + id)
13678       ComplexValue LHS = Result;
13679       APFloat &A = LHS.getComplexFloatReal();
13680       APFloat &B = LHS.getComplexFloatImag();
13681       APFloat &C = RHS.getComplexFloatReal();
13682       APFloat &D = RHS.getComplexFloatImag();
13683       APFloat &ResR = Result.getComplexFloatReal();
13684       APFloat &ResI = Result.getComplexFloatImag();
13685       if (RHSReal) {
13686         ResR = A / C;
13687         ResI = B / C;
13688       } else {
13689         if (LHSReal) {
13690           // No real optimizations we can do here, stub out with zero.
13691           B = APFloat::getZero(A.getSemantics());
13692         }
13693         int DenomLogB = 0;
13694         APFloat MaxCD = maxnum(abs(C), abs(D));
13695         if (MaxCD.isFinite()) {
13696           DenomLogB = ilogb(MaxCD);
13697           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
13698           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
13699         }
13700         APFloat Denom = C * C + D * D;
13701         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
13702                       APFloat::rmNearestTiesToEven);
13703         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
13704                       APFloat::rmNearestTiesToEven);
13705         if (ResR.isNaN() && ResI.isNaN()) {
13706           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
13707             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
13708             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
13709           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
13710                      D.isFinite()) {
13711             A = APFloat::copySign(
13712                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
13713             B = APFloat::copySign(
13714                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
13715             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
13716             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
13717           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
13718             C = APFloat::copySign(
13719                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
13720             D = APFloat::copySign(
13721                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
13722             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
13723             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
13724           }
13725         }
13726       }
13727     } else {
13728       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
13729         return Error(E, diag::note_expr_divide_by_zero);
13730 
13731       ComplexValue LHS = Result;
13732       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
13733         RHS.getComplexIntImag() * RHS.getComplexIntImag();
13734       Result.getComplexIntReal() =
13735         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
13736          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
13737       Result.getComplexIntImag() =
13738         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
13739          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
13740     }
13741     break;
13742   }
13743 
13744   return true;
13745 }
13746 
13747 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13748   // Get the operand value into 'Result'.
13749   if (!Visit(E->getSubExpr()))
13750     return false;
13751 
13752   switch (E->getOpcode()) {
13753   default:
13754     return Error(E);
13755   case UO_Extension:
13756     return true;
13757   case UO_Plus:
13758     // The result is always just the subexpr.
13759     return true;
13760   case UO_Minus:
13761     if (Result.isComplexFloat()) {
13762       Result.getComplexFloatReal().changeSign();
13763       Result.getComplexFloatImag().changeSign();
13764     }
13765     else {
13766       Result.getComplexIntReal() = -Result.getComplexIntReal();
13767       Result.getComplexIntImag() = -Result.getComplexIntImag();
13768     }
13769     return true;
13770   case UO_Not:
13771     if (Result.isComplexFloat())
13772       Result.getComplexFloatImag().changeSign();
13773     else
13774       Result.getComplexIntImag() = -Result.getComplexIntImag();
13775     return true;
13776   }
13777 }
13778 
13779 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
13780   if (E->getNumInits() == 2) {
13781     if (E->getType()->isComplexType()) {
13782       Result.makeComplexFloat();
13783       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
13784         return false;
13785       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
13786         return false;
13787     } else {
13788       Result.makeComplexInt();
13789       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
13790         return false;
13791       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
13792         return false;
13793     }
13794     return true;
13795   }
13796   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
13797 }
13798 
13799 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
13800   switch (E->getBuiltinCallee()) {
13801   case Builtin::BI__builtin_complex:
13802     Result.makeComplexFloat();
13803     if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
13804       return false;
13805     if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
13806       return false;
13807     return true;
13808 
13809   default:
13810     break;
13811   }
13812 
13813   return ExprEvaluatorBaseTy::VisitCallExpr(E);
13814 }
13815 
13816 //===----------------------------------------------------------------------===//
13817 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
13818 // implicit conversion.
13819 //===----------------------------------------------------------------------===//
13820 
13821 namespace {
13822 class AtomicExprEvaluator :
13823     public ExprEvaluatorBase<AtomicExprEvaluator> {
13824   const LValue *This;
13825   APValue &Result;
13826 public:
13827   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
13828       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
13829 
13830   bool Success(const APValue &V, const Expr *E) {
13831     Result = V;
13832     return true;
13833   }
13834 
13835   bool ZeroInitialization(const Expr *E) {
13836     ImplicitValueInitExpr VIE(
13837         E->getType()->castAs<AtomicType>()->getValueType());
13838     // For atomic-qualified class (and array) types in C++, initialize the
13839     // _Atomic-wrapped subobject directly, in-place.
13840     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
13841                 : Evaluate(Result, Info, &VIE);
13842   }
13843 
13844   bool VisitCastExpr(const CastExpr *E) {
13845     switch (E->getCastKind()) {
13846     default:
13847       return ExprEvaluatorBaseTy::VisitCastExpr(E);
13848     case CK_NonAtomicToAtomic:
13849       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
13850                   : Evaluate(Result, Info, E->getSubExpr());
13851     }
13852   }
13853 };
13854 } // end anonymous namespace
13855 
13856 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
13857                            EvalInfo &Info) {
13858   assert(E->isRValue() && E->getType()->isAtomicType());
13859   return AtomicExprEvaluator(Info, This, Result).Visit(E);
13860 }
13861 
13862 //===----------------------------------------------------------------------===//
13863 // Void expression evaluation, primarily for a cast to void on the LHS of a
13864 // comma operator
13865 //===----------------------------------------------------------------------===//
13866 
13867 namespace {
13868 class VoidExprEvaluator
13869   : public ExprEvaluatorBase<VoidExprEvaluator> {
13870 public:
13871   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
13872 
13873   bool Success(const APValue &V, const Expr *e) { return true; }
13874 
13875   bool ZeroInitialization(const Expr *E) { return true; }
13876 
13877   bool VisitCastExpr(const CastExpr *E) {
13878     switch (E->getCastKind()) {
13879     default:
13880       return ExprEvaluatorBaseTy::VisitCastExpr(E);
13881     case CK_ToVoid:
13882       VisitIgnoredValue(E->getSubExpr());
13883       return true;
13884     }
13885   }
13886 
13887   bool VisitCallExpr(const CallExpr *E) {
13888     switch (E->getBuiltinCallee()) {
13889     case Builtin::BI__assume:
13890     case Builtin::BI__builtin_assume:
13891       // The argument is not evaluated!
13892       return true;
13893 
13894     case Builtin::BI__builtin_operator_delete:
13895       return HandleOperatorDeleteCall(Info, E);
13896 
13897     default:
13898       break;
13899     }
13900 
13901     return ExprEvaluatorBaseTy::VisitCallExpr(E);
13902   }
13903 
13904   bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
13905 };
13906 } // end anonymous namespace
13907 
13908 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
13909   // We cannot speculatively evaluate a delete expression.
13910   if (Info.SpeculativeEvaluationDepth)
13911     return false;
13912 
13913   FunctionDecl *OperatorDelete = E->getOperatorDelete();
13914   if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
13915     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
13916         << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
13917     return false;
13918   }
13919 
13920   const Expr *Arg = E->getArgument();
13921 
13922   LValue Pointer;
13923   if (!EvaluatePointer(Arg, Pointer, Info))
13924     return false;
13925   if (Pointer.Designator.Invalid)
13926     return false;
13927 
13928   // Deleting a null pointer has no effect.
13929   if (Pointer.isNullPointer()) {
13930     // This is the only case where we need to produce an extension warning:
13931     // the only other way we can succeed is if we find a dynamic allocation,
13932     // and we will have warned when we allocated it in that case.
13933     if (!Info.getLangOpts().CPlusPlus20)
13934       Info.CCEDiag(E, diag::note_constexpr_new);
13935     return true;
13936   }
13937 
13938   Optional<DynAlloc *> Alloc = CheckDeleteKind(
13939       Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
13940   if (!Alloc)
13941     return false;
13942   QualType AllocType = Pointer.Base.getDynamicAllocType();
13943 
13944   // For the non-array case, the designator must be empty if the static type
13945   // does not have a virtual destructor.
13946   if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
13947       !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
13948     Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
13949         << Arg->getType()->getPointeeType() << AllocType;
13950     return false;
13951   }
13952 
13953   // For a class type with a virtual destructor, the selected operator delete
13954   // is the one looked up when building the destructor.
13955   if (!E->isArrayForm() && !E->isGlobalDelete()) {
13956     const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
13957     if (VirtualDelete &&
13958         !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
13959       Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
13960           << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
13961       return false;
13962     }
13963   }
13964 
13965   if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
13966                          (*Alloc)->Value, AllocType))
13967     return false;
13968 
13969   if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
13970     // The element was already erased. This means the destructor call also
13971     // deleted the object.
13972     // FIXME: This probably results in undefined behavior before we get this
13973     // far, and should be diagnosed elsewhere first.
13974     Info.FFDiag(E, diag::note_constexpr_double_delete);
13975     return false;
13976   }
13977 
13978   return true;
13979 }
13980 
13981 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
13982   assert(E->isRValue() && E->getType()->isVoidType());
13983   return VoidExprEvaluator(Info).Visit(E);
13984 }
13985 
13986 //===----------------------------------------------------------------------===//
13987 // Top level Expr::EvaluateAsRValue method.
13988 //===----------------------------------------------------------------------===//
13989 
13990 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
13991   // In C, function designators are not lvalues, but we evaluate them as if they
13992   // are.
13993   QualType T = E->getType();
13994   if (E->isGLValue() || T->isFunctionType()) {
13995     LValue LV;
13996     if (!EvaluateLValue(E, LV, Info))
13997       return false;
13998     LV.moveInto(Result);
13999   } else if (T->isVectorType()) {
14000     if (!EvaluateVector(E, Result, Info))
14001       return false;
14002   } else if (T->isIntegralOrEnumerationType()) {
14003     if (!IntExprEvaluator(Info, Result).Visit(E))
14004       return false;
14005   } else if (T->hasPointerRepresentation()) {
14006     LValue LV;
14007     if (!EvaluatePointer(E, LV, Info))
14008       return false;
14009     LV.moveInto(Result);
14010   } else if (T->isRealFloatingType()) {
14011     llvm::APFloat F(0.0);
14012     if (!EvaluateFloat(E, F, Info))
14013       return false;
14014     Result = APValue(F);
14015   } else if (T->isAnyComplexType()) {
14016     ComplexValue C;
14017     if (!EvaluateComplex(E, C, Info))
14018       return false;
14019     C.moveInto(Result);
14020   } else if (T->isFixedPointType()) {
14021     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
14022   } else if (T->isMemberPointerType()) {
14023     MemberPtr P;
14024     if (!EvaluateMemberPointer(E, P, Info))
14025       return false;
14026     P.moveInto(Result);
14027     return true;
14028   } else if (T->isArrayType()) {
14029     LValue LV;
14030     APValue &Value =
14031         Info.CurrentCall->createTemporary(E, T, false, LV);
14032     if (!EvaluateArray(E, LV, Value, Info))
14033       return false;
14034     Result = Value;
14035   } else if (T->isRecordType()) {
14036     LValue LV;
14037     APValue &Value = Info.CurrentCall->createTemporary(E, T, false, LV);
14038     if (!EvaluateRecord(E, LV, Value, Info))
14039       return false;
14040     Result = Value;
14041   } else if (T->isVoidType()) {
14042     if (!Info.getLangOpts().CPlusPlus11)
14043       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
14044         << E->getType();
14045     if (!EvaluateVoid(E, Info))
14046       return false;
14047   } else if (T->isAtomicType()) {
14048     QualType Unqual = T.getAtomicUnqualifiedType();
14049     if (Unqual->isArrayType() || Unqual->isRecordType()) {
14050       LValue LV;
14051       APValue &Value = Info.CurrentCall->createTemporary(E, Unqual, false, LV);
14052       if (!EvaluateAtomic(E, &LV, Value, Info))
14053         return false;
14054     } else {
14055       if (!EvaluateAtomic(E, nullptr, Result, Info))
14056         return false;
14057     }
14058   } else if (Info.getLangOpts().CPlusPlus11) {
14059     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
14060     return false;
14061   } else {
14062     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
14063     return false;
14064   }
14065 
14066   return true;
14067 }
14068 
14069 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
14070 /// cases, the in-place evaluation is essential, since later initializers for
14071 /// an object can indirectly refer to subobjects which were initialized earlier.
14072 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
14073                             const Expr *E, bool AllowNonLiteralTypes) {
14074   assert(!E->isValueDependent());
14075 
14076   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
14077     return false;
14078 
14079   if (E->isRValue()) {
14080     // Evaluate arrays and record types in-place, so that later initializers can
14081     // refer to earlier-initialized members of the object.
14082     QualType T = E->getType();
14083     if (T->isArrayType())
14084       return EvaluateArray(E, This, Result, Info);
14085     else if (T->isRecordType())
14086       return EvaluateRecord(E, This, Result, Info);
14087     else if (T->isAtomicType()) {
14088       QualType Unqual = T.getAtomicUnqualifiedType();
14089       if (Unqual->isArrayType() || Unqual->isRecordType())
14090         return EvaluateAtomic(E, &This, Result, Info);
14091     }
14092   }
14093 
14094   // For any other type, in-place evaluation is unimportant.
14095   return Evaluate(Result, Info, E);
14096 }
14097 
14098 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
14099 /// lvalue-to-rvalue cast if it is an lvalue.
14100 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
14101   if (Info.EnableNewConstInterp) {
14102     if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
14103       return false;
14104   } else {
14105     if (E->getType().isNull())
14106       return false;
14107 
14108     if (!CheckLiteralType(Info, E))
14109       return false;
14110 
14111     if (!::Evaluate(Result, Info, E))
14112       return false;
14113 
14114     if (E->isGLValue()) {
14115       LValue LV;
14116       LV.setFrom(Info.Ctx, Result);
14117       if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
14118         return false;
14119     }
14120   }
14121 
14122   // Check this core constant expression is a constant expression.
14123   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result) &&
14124          CheckMemoryLeaks(Info);
14125 }
14126 
14127 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
14128                                  const ASTContext &Ctx, bool &IsConst) {
14129   // Fast-path evaluations of integer literals, since we sometimes see files
14130   // containing vast quantities of these.
14131   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
14132     Result.Val = APValue(APSInt(L->getValue(),
14133                                 L->getType()->isUnsignedIntegerType()));
14134     IsConst = true;
14135     return true;
14136   }
14137 
14138   // This case should be rare, but we need to check it before we check on
14139   // the type below.
14140   if (Exp->getType().isNull()) {
14141     IsConst = false;
14142     return true;
14143   }
14144 
14145   // FIXME: Evaluating values of large array and record types can cause
14146   // performance problems. Only do so in C++11 for now.
14147   if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
14148                           Exp->getType()->isRecordType()) &&
14149       !Ctx.getLangOpts().CPlusPlus11) {
14150     IsConst = false;
14151     return true;
14152   }
14153   return false;
14154 }
14155 
14156 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
14157                                       Expr::SideEffectsKind SEK) {
14158   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
14159          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
14160 }
14161 
14162 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
14163                              const ASTContext &Ctx, EvalInfo &Info) {
14164   bool IsConst;
14165   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
14166     return IsConst;
14167 
14168   return EvaluateAsRValue(Info, E, Result.Val);
14169 }
14170 
14171 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
14172                           const ASTContext &Ctx,
14173                           Expr::SideEffectsKind AllowSideEffects,
14174                           EvalInfo &Info) {
14175   if (!E->getType()->isIntegralOrEnumerationType())
14176     return false;
14177 
14178   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
14179       !ExprResult.Val.isInt() ||
14180       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14181     return false;
14182 
14183   return true;
14184 }
14185 
14186 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
14187                                  const ASTContext &Ctx,
14188                                  Expr::SideEffectsKind AllowSideEffects,
14189                                  EvalInfo &Info) {
14190   if (!E->getType()->isFixedPointType())
14191     return false;
14192 
14193   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
14194     return false;
14195 
14196   if (!ExprResult.Val.isFixedPoint() ||
14197       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14198     return false;
14199 
14200   return true;
14201 }
14202 
14203 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
14204 /// any crazy technique (that has nothing to do with language standards) that
14205 /// we want to.  If this function returns true, it returns the folded constant
14206 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
14207 /// will be applied to the result.
14208 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
14209                             bool InConstantContext) const {
14210   assert(!isValueDependent() &&
14211          "Expression evaluator can't be called on a dependent expression.");
14212   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14213   Info.InConstantContext = InConstantContext;
14214   return ::EvaluateAsRValue(this, Result, Ctx, Info);
14215 }
14216 
14217 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
14218                                       bool InConstantContext) const {
14219   assert(!isValueDependent() &&
14220          "Expression evaluator can't be called on a dependent expression.");
14221   EvalResult Scratch;
14222   return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
14223          HandleConversionToBool(Scratch.Val, Result);
14224 }
14225 
14226 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
14227                          SideEffectsKind AllowSideEffects,
14228                          bool InConstantContext) const {
14229   assert(!isValueDependent() &&
14230          "Expression evaluator can't be called on a dependent expression.");
14231   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14232   Info.InConstantContext = InConstantContext;
14233   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
14234 }
14235 
14236 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
14237                                 SideEffectsKind AllowSideEffects,
14238                                 bool InConstantContext) const {
14239   assert(!isValueDependent() &&
14240          "Expression evaluator can't be called on a dependent expression.");
14241   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14242   Info.InConstantContext = InConstantContext;
14243   return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
14244 }
14245 
14246 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
14247                            SideEffectsKind AllowSideEffects,
14248                            bool InConstantContext) const {
14249   assert(!isValueDependent() &&
14250          "Expression evaluator can't be called on a dependent expression.");
14251 
14252   if (!getType()->isRealFloatingType())
14253     return false;
14254 
14255   EvalResult ExprResult;
14256   if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
14257       !ExprResult.Val.isFloat() ||
14258       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14259     return false;
14260 
14261   Result = ExprResult.Val.getFloat();
14262   return true;
14263 }
14264 
14265 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
14266                             bool InConstantContext) const {
14267   assert(!isValueDependent() &&
14268          "Expression evaluator can't be called on a dependent expression.");
14269 
14270   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
14271   Info.InConstantContext = InConstantContext;
14272   LValue LV;
14273   CheckedTemporaries CheckedTemps;
14274   if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
14275       Result.HasSideEffects ||
14276       !CheckLValueConstantExpression(Info, getExprLoc(),
14277                                      Ctx.getLValueReferenceType(getType()), LV,
14278                                      Expr::EvaluateForCodeGen, CheckedTemps))
14279     return false;
14280 
14281   LV.moveInto(Result.Val);
14282   return true;
14283 }
14284 
14285 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
14286                                   const ASTContext &Ctx, bool InPlace) const {
14287   assert(!isValueDependent() &&
14288          "Expression evaluator can't be called on a dependent expression.");
14289 
14290   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
14291   EvalInfo Info(Ctx, Result, EM);
14292   Info.InConstantContext = true;
14293 
14294   if (InPlace) {
14295     Info.setEvaluatingDecl(this, Result.Val);
14296     LValue LVal;
14297     LVal.set(this);
14298     if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
14299         Result.HasSideEffects)
14300       return false;
14301   } else if (!::Evaluate(Result.Val, Info, this) || Result.HasSideEffects)
14302     return false;
14303 
14304   if (!Info.discardCleanups())
14305     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14306 
14307   return CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
14308                                  Result.Val, Usage) &&
14309          CheckMemoryLeaks(Info);
14310 }
14311 
14312 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
14313                                  const VarDecl *VD,
14314                             SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
14315   assert(!isValueDependent() &&
14316          "Expression evaluator can't be called on a dependent expression.");
14317 
14318   // FIXME: Evaluating initializers for large array and record types can cause
14319   // performance problems. Only do so in C++11 for now.
14320   if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
14321       !Ctx.getLangOpts().CPlusPlus11)
14322     return false;
14323 
14324   Expr::EvalStatus EStatus;
14325   EStatus.Diag = &Notes;
14326 
14327   EvalInfo Info(Ctx, EStatus, VD->isConstexpr()
14328                                       ? EvalInfo::EM_ConstantExpression
14329                                       : EvalInfo::EM_ConstantFold);
14330   Info.setEvaluatingDecl(VD, Value);
14331   Info.InConstantContext = true;
14332 
14333   SourceLocation DeclLoc = VD->getLocation();
14334   QualType DeclTy = VD->getType();
14335 
14336   if (Info.EnableNewConstInterp) {
14337     auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
14338     if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
14339       return false;
14340   } else {
14341     LValue LVal;
14342     LVal.set(VD);
14343 
14344     if (!EvaluateInPlace(Value, Info, LVal, this,
14345                          /*AllowNonLiteralTypes=*/true) ||
14346         EStatus.HasSideEffects)
14347       return false;
14348 
14349     // At this point, any lifetime-extended temporaries are completely
14350     // initialized.
14351     Info.performLifetimeExtension();
14352 
14353     if (!Info.discardCleanups())
14354       llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14355   }
14356   return CheckConstantExpression(Info, DeclLoc, DeclTy, Value) &&
14357          CheckMemoryLeaks(Info);
14358 }
14359 
14360 bool VarDecl::evaluateDestruction(
14361     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
14362   Expr::EvalStatus EStatus;
14363   EStatus.Diag = &Notes;
14364 
14365   // Make a copy of the value for the destructor to mutate, if we know it.
14366   // Otherwise, treat the value as default-initialized; if the destructor works
14367   // anyway, then the destruction is constant (and must be essentially empty).
14368   APValue DestroyedValue;
14369   if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
14370     DestroyedValue = *getEvaluatedValue();
14371   else if (!getDefaultInitValue(getType(), DestroyedValue))
14372     return false;
14373 
14374   EvalInfo Info(getASTContext(), EStatus, EvalInfo::EM_ConstantExpression);
14375   Info.setEvaluatingDecl(this, DestroyedValue,
14376                          EvalInfo::EvaluatingDeclKind::Dtor);
14377   Info.InConstantContext = true;
14378 
14379   SourceLocation DeclLoc = getLocation();
14380   QualType DeclTy = getType();
14381 
14382   LValue LVal;
14383   LVal.set(this);
14384 
14385   if (!HandleDestruction(Info, DeclLoc, LVal.Base, DestroyedValue, DeclTy) ||
14386       EStatus.HasSideEffects)
14387     return false;
14388 
14389   if (!Info.discardCleanups())
14390     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14391 
14392   ensureEvaluatedStmt()->HasConstantDestruction = true;
14393   return true;
14394 }
14395 
14396 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
14397 /// constant folded, but discard the result.
14398 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
14399   assert(!isValueDependent() &&
14400          "Expression evaluator can't be called on a dependent expression.");
14401 
14402   EvalResult Result;
14403   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
14404          !hasUnacceptableSideEffect(Result, SEK);
14405 }
14406 
14407 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
14408                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
14409   assert(!isValueDependent() &&
14410          "Expression evaluator can't be called on a dependent expression.");
14411 
14412   EvalResult EVResult;
14413   EVResult.Diag = Diag;
14414   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14415   Info.InConstantContext = true;
14416 
14417   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
14418   (void)Result;
14419   assert(Result && "Could not evaluate expression");
14420   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
14421 
14422   return EVResult.Val.getInt();
14423 }
14424 
14425 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
14426     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
14427   assert(!isValueDependent() &&
14428          "Expression evaluator can't be called on a dependent expression.");
14429 
14430   EvalResult EVResult;
14431   EVResult.Diag = Diag;
14432   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14433   Info.InConstantContext = true;
14434   Info.CheckingForUndefinedBehavior = true;
14435 
14436   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
14437   (void)Result;
14438   assert(Result && "Could not evaluate expression");
14439   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
14440 
14441   return EVResult.Val.getInt();
14442 }
14443 
14444 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
14445   assert(!isValueDependent() &&
14446          "Expression evaluator can't be called on a dependent expression.");
14447 
14448   bool IsConst;
14449   EvalResult EVResult;
14450   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
14451     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14452     Info.CheckingForUndefinedBehavior = true;
14453     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
14454   }
14455 }
14456 
14457 bool Expr::EvalResult::isGlobalLValue() const {
14458   assert(Val.isLValue());
14459   return IsGlobalLValue(Val.getLValueBase());
14460 }
14461 
14462 
14463 /// isIntegerConstantExpr - this recursive routine will test if an expression is
14464 /// an integer constant expression.
14465 
14466 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
14467 /// comma, etc
14468 
14469 // CheckICE - This function does the fundamental ICE checking: the returned
14470 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
14471 // and a (possibly null) SourceLocation indicating the location of the problem.
14472 //
14473 // Note that to reduce code duplication, this helper does no evaluation
14474 // itself; the caller checks whether the expression is evaluatable, and
14475 // in the rare cases where CheckICE actually cares about the evaluated
14476 // value, it calls into Evaluate.
14477 
14478 namespace {
14479 
14480 enum ICEKind {
14481   /// This expression is an ICE.
14482   IK_ICE,
14483   /// This expression is not an ICE, but if it isn't evaluated, it's
14484   /// a legal subexpression for an ICE. This return value is used to handle
14485   /// the comma operator in C99 mode, and non-constant subexpressions.
14486   IK_ICEIfUnevaluated,
14487   /// This expression is not an ICE, and is not a legal subexpression for one.
14488   IK_NotICE
14489 };
14490 
14491 struct ICEDiag {
14492   ICEKind Kind;
14493   SourceLocation Loc;
14494 
14495   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
14496 };
14497 
14498 }
14499 
14500 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
14501 
14502 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
14503 
14504 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
14505   Expr::EvalResult EVResult;
14506   Expr::EvalStatus Status;
14507   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
14508 
14509   Info.InConstantContext = true;
14510   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
14511       !EVResult.Val.isInt())
14512     return ICEDiag(IK_NotICE, E->getBeginLoc());
14513 
14514   return NoDiag();
14515 }
14516 
14517 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
14518   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
14519   if (!E->getType()->isIntegralOrEnumerationType())
14520     return ICEDiag(IK_NotICE, E->getBeginLoc());
14521 
14522   switch (E->getStmtClass()) {
14523 #define ABSTRACT_STMT(Node)
14524 #define STMT(Node, Base) case Expr::Node##Class:
14525 #define EXPR(Node, Base)
14526 #include "clang/AST/StmtNodes.inc"
14527   case Expr::PredefinedExprClass:
14528   case Expr::FloatingLiteralClass:
14529   case Expr::ImaginaryLiteralClass:
14530   case Expr::StringLiteralClass:
14531   case Expr::ArraySubscriptExprClass:
14532   case Expr::MatrixSubscriptExprClass:
14533   case Expr::OMPArraySectionExprClass:
14534   case Expr::OMPArrayShapingExprClass:
14535   case Expr::OMPIteratorExprClass:
14536   case Expr::MemberExprClass:
14537   case Expr::CompoundAssignOperatorClass:
14538   case Expr::CompoundLiteralExprClass:
14539   case Expr::ExtVectorElementExprClass:
14540   case Expr::DesignatedInitExprClass:
14541   case Expr::ArrayInitLoopExprClass:
14542   case Expr::ArrayInitIndexExprClass:
14543   case Expr::NoInitExprClass:
14544   case Expr::DesignatedInitUpdateExprClass:
14545   case Expr::ImplicitValueInitExprClass:
14546   case Expr::ParenListExprClass:
14547   case Expr::VAArgExprClass:
14548   case Expr::AddrLabelExprClass:
14549   case Expr::StmtExprClass:
14550   case Expr::CXXMemberCallExprClass:
14551   case Expr::CUDAKernelCallExprClass:
14552   case Expr::CXXAddrspaceCastExprClass:
14553   case Expr::CXXDynamicCastExprClass:
14554   case Expr::CXXTypeidExprClass:
14555   case Expr::CXXUuidofExprClass:
14556   case Expr::MSPropertyRefExprClass:
14557   case Expr::MSPropertySubscriptExprClass:
14558   case Expr::CXXNullPtrLiteralExprClass:
14559   case Expr::UserDefinedLiteralClass:
14560   case Expr::CXXThisExprClass:
14561   case Expr::CXXThrowExprClass:
14562   case Expr::CXXNewExprClass:
14563   case Expr::CXXDeleteExprClass:
14564   case Expr::CXXPseudoDestructorExprClass:
14565   case Expr::UnresolvedLookupExprClass:
14566   case Expr::TypoExprClass:
14567   case Expr::RecoveryExprClass:
14568   case Expr::DependentScopeDeclRefExprClass:
14569   case Expr::CXXConstructExprClass:
14570   case Expr::CXXInheritedCtorInitExprClass:
14571   case Expr::CXXStdInitializerListExprClass:
14572   case Expr::CXXBindTemporaryExprClass:
14573   case Expr::ExprWithCleanupsClass:
14574   case Expr::CXXTemporaryObjectExprClass:
14575   case Expr::CXXUnresolvedConstructExprClass:
14576   case Expr::CXXDependentScopeMemberExprClass:
14577   case Expr::UnresolvedMemberExprClass:
14578   case Expr::ObjCStringLiteralClass:
14579   case Expr::ObjCBoxedExprClass:
14580   case Expr::ObjCArrayLiteralClass:
14581   case Expr::ObjCDictionaryLiteralClass:
14582   case Expr::ObjCEncodeExprClass:
14583   case Expr::ObjCMessageExprClass:
14584   case Expr::ObjCSelectorExprClass:
14585   case Expr::ObjCProtocolExprClass:
14586   case Expr::ObjCIvarRefExprClass:
14587   case Expr::ObjCPropertyRefExprClass:
14588   case Expr::ObjCSubscriptRefExprClass:
14589   case Expr::ObjCIsaExprClass:
14590   case Expr::ObjCAvailabilityCheckExprClass:
14591   case Expr::ShuffleVectorExprClass:
14592   case Expr::ConvertVectorExprClass:
14593   case Expr::BlockExprClass:
14594   case Expr::NoStmtClass:
14595   case Expr::OpaqueValueExprClass:
14596   case Expr::PackExpansionExprClass:
14597   case Expr::SubstNonTypeTemplateParmPackExprClass:
14598   case Expr::FunctionParmPackExprClass:
14599   case Expr::AsTypeExprClass:
14600   case Expr::ObjCIndirectCopyRestoreExprClass:
14601   case Expr::MaterializeTemporaryExprClass:
14602   case Expr::PseudoObjectExprClass:
14603   case Expr::AtomicExprClass:
14604   case Expr::LambdaExprClass:
14605   case Expr::CXXFoldExprClass:
14606   case Expr::CoawaitExprClass:
14607   case Expr::DependentCoawaitExprClass:
14608   case Expr::CoyieldExprClass:
14609     return ICEDiag(IK_NotICE, E->getBeginLoc());
14610 
14611   case Expr::InitListExprClass: {
14612     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
14613     // form "T x = { a };" is equivalent to "T x = a;".
14614     // Unless we're initializing a reference, T is a scalar as it is known to be
14615     // of integral or enumeration type.
14616     if (E->isRValue())
14617       if (cast<InitListExpr>(E)->getNumInits() == 1)
14618         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
14619     return ICEDiag(IK_NotICE, E->getBeginLoc());
14620   }
14621 
14622   case Expr::SizeOfPackExprClass:
14623   case Expr::GNUNullExprClass:
14624   case Expr::SourceLocExprClass:
14625     return NoDiag();
14626 
14627   case Expr::SubstNonTypeTemplateParmExprClass:
14628     return
14629       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
14630 
14631   case Expr::ConstantExprClass:
14632     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
14633 
14634   case Expr::ParenExprClass:
14635     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
14636   case Expr::GenericSelectionExprClass:
14637     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
14638   case Expr::IntegerLiteralClass:
14639   case Expr::FixedPointLiteralClass:
14640   case Expr::CharacterLiteralClass:
14641   case Expr::ObjCBoolLiteralExprClass:
14642   case Expr::CXXBoolLiteralExprClass:
14643   case Expr::CXXScalarValueInitExprClass:
14644   case Expr::TypeTraitExprClass:
14645   case Expr::ConceptSpecializationExprClass:
14646   case Expr::RequiresExprClass:
14647   case Expr::ArrayTypeTraitExprClass:
14648   case Expr::ExpressionTraitExprClass:
14649   case Expr::CXXNoexceptExprClass:
14650     return NoDiag();
14651   case Expr::CallExprClass:
14652   case Expr::CXXOperatorCallExprClass: {
14653     // C99 6.6/3 allows function calls within unevaluated subexpressions of
14654     // constant expressions, but they can never be ICEs because an ICE cannot
14655     // contain an operand of (pointer to) function type.
14656     const CallExpr *CE = cast<CallExpr>(E);
14657     if (CE->getBuiltinCallee())
14658       return CheckEvalInICE(E, Ctx);
14659     return ICEDiag(IK_NotICE, E->getBeginLoc());
14660   }
14661   case Expr::CXXRewrittenBinaryOperatorClass:
14662     return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
14663                     Ctx);
14664   case Expr::DeclRefExprClass: {
14665     if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
14666       return NoDiag();
14667     const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
14668     if (Ctx.getLangOpts().CPlusPlus &&
14669         D && IsConstNonVolatile(D->getType())) {
14670       // Parameter variables are never constants.  Without this check,
14671       // getAnyInitializer() can find a default argument, which leads
14672       // to chaos.
14673       if (isa<ParmVarDecl>(D))
14674         return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
14675 
14676       // C++ 7.1.5.1p2
14677       //   A variable of non-volatile const-qualified integral or enumeration
14678       //   type initialized by an ICE can be used in ICEs.
14679       if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
14680         if (!Dcl->getType()->isIntegralOrEnumerationType())
14681           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
14682 
14683         const VarDecl *VD;
14684         // Look for a declaration of this variable that has an initializer, and
14685         // check whether it is an ICE.
14686         if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
14687           return NoDiag();
14688         else
14689           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
14690       }
14691     }
14692     return ICEDiag(IK_NotICE, E->getBeginLoc());
14693   }
14694   case Expr::UnaryOperatorClass: {
14695     const UnaryOperator *Exp = cast<UnaryOperator>(E);
14696     switch (Exp->getOpcode()) {
14697     case UO_PostInc:
14698     case UO_PostDec:
14699     case UO_PreInc:
14700     case UO_PreDec:
14701     case UO_AddrOf:
14702     case UO_Deref:
14703     case UO_Coawait:
14704       // C99 6.6/3 allows increment and decrement within unevaluated
14705       // subexpressions of constant expressions, but they can never be ICEs
14706       // because an ICE cannot contain an lvalue operand.
14707       return ICEDiag(IK_NotICE, E->getBeginLoc());
14708     case UO_Extension:
14709     case UO_LNot:
14710     case UO_Plus:
14711     case UO_Minus:
14712     case UO_Not:
14713     case UO_Real:
14714     case UO_Imag:
14715       return CheckICE(Exp->getSubExpr(), Ctx);
14716     }
14717     llvm_unreachable("invalid unary operator class");
14718   }
14719   case Expr::OffsetOfExprClass: {
14720     // Note that per C99, offsetof must be an ICE. And AFAIK, using
14721     // EvaluateAsRValue matches the proposed gcc behavior for cases like
14722     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
14723     // compliance: we should warn earlier for offsetof expressions with
14724     // array subscripts that aren't ICEs, and if the array subscripts
14725     // are ICEs, the value of the offsetof must be an integer constant.
14726     return CheckEvalInICE(E, Ctx);
14727   }
14728   case Expr::UnaryExprOrTypeTraitExprClass: {
14729     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
14730     if ((Exp->getKind() ==  UETT_SizeOf) &&
14731         Exp->getTypeOfArgument()->isVariableArrayType())
14732       return ICEDiag(IK_NotICE, E->getBeginLoc());
14733     return NoDiag();
14734   }
14735   case Expr::BinaryOperatorClass: {
14736     const BinaryOperator *Exp = cast<BinaryOperator>(E);
14737     switch (Exp->getOpcode()) {
14738     case BO_PtrMemD:
14739     case BO_PtrMemI:
14740     case BO_Assign:
14741     case BO_MulAssign:
14742     case BO_DivAssign:
14743     case BO_RemAssign:
14744     case BO_AddAssign:
14745     case BO_SubAssign:
14746     case BO_ShlAssign:
14747     case BO_ShrAssign:
14748     case BO_AndAssign:
14749     case BO_XorAssign:
14750     case BO_OrAssign:
14751       // C99 6.6/3 allows assignments within unevaluated subexpressions of
14752       // constant expressions, but they can never be ICEs because an ICE cannot
14753       // contain an lvalue operand.
14754       return ICEDiag(IK_NotICE, E->getBeginLoc());
14755 
14756     case BO_Mul:
14757     case BO_Div:
14758     case BO_Rem:
14759     case BO_Add:
14760     case BO_Sub:
14761     case BO_Shl:
14762     case BO_Shr:
14763     case BO_LT:
14764     case BO_GT:
14765     case BO_LE:
14766     case BO_GE:
14767     case BO_EQ:
14768     case BO_NE:
14769     case BO_And:
14770     case BO_Xor:
14771     case BO_Or:
14772     case BO_Comma:
14773     case BO_Cmp: {
14774       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
14775       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
14776       if (Exp->getOpcode() == BO_Div ||
14777           Exp->getOpcode() == BO_Rem) {
14778         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
14779         // we don't evaluate one.
14780         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
14781           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
14782           if (REval == 0)
14783             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
14784           if (REval.isSigned() && REval.isAllOnesValue()) {
14785             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
14786             if (LEval.isMinSignedValue())
14787               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
14788           }
14789         }
14790       }
14791       if (Exp->getOpcode() == BO_Comma) {
14792         if (Ctx.getLangOpts().C99) {
14793           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
14794           // if it isn't evaluated.
14795           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
14796             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
14797         } else {
14798           // In both C89 and C++, commas in ICEs are illegal.
14799           return ICEDiag(IK_NotICE, E->getBeginLoc());
14800         }
14801       }
14802       return Worst(LHSResult, RHSResult);
14803     }
14804     case BO_LAnd:
14805     case BO_LOr: {
14806       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
14807       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
14808       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
14809         // Rare case where the RHS has a comma "side-effect"; we need
14810         // to actually check the condition to see whether the side
14811         // with the comma is evaluated.
14812         if ((Exp->getOpcode() == BO_LAnd) !=
14813             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
14814           return RHSResult;
14815         return NoDiag();
14816       }
14817 
14818       return Worst(LHSResult, RHSResult);
14819     }
14820     }
14821     llvm_unreachable("invalid binary operator kind");
14822   }
14823   case Expr::ImplicitCastExprClass:
14824   case Expr::CStyleCastExprClass:
14825   case Expr::CXXFunctionalCastExprClass:
14826   case Expr::CXXStaticCastExprClass:
14827   case Expr::CXXReinterpretCastExprClass:
14828   case Expr::CXXConstCastExprClass:
14829   case Expr::ObjCBridgedCastExprClass: {
14830     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
14831     if (isa<ExplicitCastExpr>(E)) {
14832       if (const FloatingLiteral *FL
14833             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
14834         unsigned DestWidth = Ctx.getIntWidth(E->getType());
14835         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
14836         APSInt IgnoredVal(DestWidth, !DestSigned);
14837         bool Ignored;
14838         // If the value does not fit in the destination type, the behavior is
14839         // undefined, so we are not required to treat it as a constant
14840         // expression.
14841         if (FL->getValue().convertToInteger(IgnoredVal,
14842                                             llvm::APFloat::rmTowardZero,
14843                                             &Ignored) & APFloat::opInvalidOp)
14844           return ICEDiag(IK_NotICE, E->getBeginLoc());
14845         return NoDiag();
14846       }
14847     }
14848     switch (cast<CastExpr>(E)->getCastKind()) {
14849     case CK_LValueToRValue:
14850     case CK_AtomicToNonAtomic:
14851     case CK_NonAtomicToAtomic:
14852     case CK_NoOp:
14853     case CK_IntegralToBoolean:
14854     case CK_IntegralCast:
14855       return CheckICE(SubExpr, Ctx);
14856     default:
14857       return ICEDiag(IK_NotICE, E->getBeginLoc());
14858     }
14859   }
14860   case Expr::BinaryConditionalOperatorClass: {
14861     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
14862     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
14863     if (CommonResult.Kind == IK_NotICE) return CommonResult;
14864     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
14865     if (FalseResult.Kind == IK_NotICE) return FalseResult;
14866     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
14867     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
14868         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
14869     return FalseResult;
14870   }
14871   case Expr::ConditionalOperatorClass: {
14872     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
14873     // If the condition (ignoring parens) is a __builtin_constant_p call,
14874     // then only the true side is actually considered in an integer constant
14875     // expression, and it is fully evaluated.  This is an important GNU
14876     // extension.  See GCC PR38377 for discussion.
14877     if (const CallExpr *CallCE
14878         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
14879       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
14880         return CheckEvalInICE(E, Ctx);
14881     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
14882     if (CondResult.Kind == IK_NotICE)
14883       return CondResult;
14884 
14885     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
14886     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
14887 
14888     if (TrueResult.Kind == IK_NotICE)
14889       return TrueResult;
14890     if (FalseResult.Kind == IK_NotICE)
14891       return FalseResult;
14892     if (CondResult.Kind == IK_ICEIfUnevaluated)
14893       return CondResult;
14894     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
14895       return NoDiag();
14896     // Rare case where the diagnostics depend on which side is evaluated
14897     // Note that if we get here, CondResult is 0, and at least one of
14898     // TrueResult and FalseResult is non-zero.
14899     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
14900       return FalseResult;
14901     return TrueResult;
14902   }
14903   case Expr::CXXDefaultArgExprClass:
14904     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
14905   case Expr::CXXDefaultInitExprClass:
14906     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
14907   case Expr::ChooseExprClass: {
14908     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
14909   }
14910   case Expr::BuiltinBitCastExprClass: {
14911     if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
14912       return ICEDiag(IK_NotICE, E->getBeginLoc());
14913     return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
14914   }
14915   }
14916 
14917   llvm_unreachable("Invalid StmtClass!");
14918 }
14919 
14920 /// Evaluate an expression as a C++11 integral constant expression.
14921 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
14922                                                     const Expr *E,
14923                                                     llvm::APSInt *Value,
14924                                                     SourceLocation *Loc) {
14925   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
14926     if (Loc) *Loc = E->getExprLoc();
14927     return false;
14928   }
14929 
14930   APValue Result;
14931   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
14932     return false;
14933 
14934   if (!Result.isInt()) {
14935     if (Loc) *Loc = E->getExprLoc();
14936     return false;
14937   }
14938 
14939   if (Value) *Value = Result.getInt();
14940   return true;
14941 }
14942 
14943 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
14944                                  SourceLocation *Loc) const {
14945   assert(!isValueDependent() &&
14946          "Expression evaluator can't be called on a dependent expression.");
14947 
14948   if (Ctx.getLangOpts().CPlusPlus11)
14949     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
14950 
14951   ICEDiag D = CheckICE(this, Ctx);
14952   if (D.Kind != IK_ICE) {
14953     if (Loc) *Loc = D.Loc;
14954     return false;
14955   }
14956   return true;
14957 }
14958 
14959 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx,
14960                                                     SourceLocation *Loc,
14961                                                     bool isEvaluated) const {
14962   assert(!isValueDependent() &&
14963          "Expression evaluator can't be called on a dependent expression.");
14964 
14965   APSInt Value;
14966 
14967   if (Ctx.getLangOpts().CPlusPlus11) {
14968     if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc))
14969       return Value;
14970     return None;
14971   }
14972 
14973   if (!isIntegerConstantExpr(Ctx, Loc))
14974     return None;
14975 
14976   // The only possible side-effects here are due to UB discovered in the
14977   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
14978   // required to treat the expression as an ICE, so we produce the folded
14979   // value.
14980   EvalResult ExprResult;
14981   Expr::EvalStatus Status;
14982   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
14983   Info.InConstantContext = true;
14984 
14985   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
14986     llvm_unreachable("ICE cannot be evaluated!");
14987 
14988   return ExprResult.Val.getInt();
14989 }
14990 
14991 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
14992   assert(!isValueDependent() &&
14993          "Expression evaluator can't be called on a dependent expression.");
14994 
14995   return CheckICE(this, Ctx).Kind == IK_ICE;
14996 }
14997 
14998 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
14999                                SourceLocation *Loc) const {
15000   assert(!isValueDependent() &&
15001          "Expression evaluator can't be called on a dependent expression.");
15002 
15003   // We support this checking in C++98 mode in order to diagnose compatibility
15004   // issues.
15005   assert(Ctx.getLangOpts().CPlusPlus);
15006 
15007   // Build evaluation settings.
15008   Expr::EvalStatus Status;
15009   SmallVector<PartialDiagnosticAt, 8> Diags;
15010   Status.Diag = &Diags;
15011   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15012 
15013   APValue Scratch;
15014   bool IsConstExpr =
15015       ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
15016       // FIXME: We don't produce a diagnostic for this, but the callers that
15017       // call us on arbitrary full-expressions should generally not care.
15018       Info.discardCleanups() && !Status.HasSideEffects;
15019 
15020   if (!Diags.empty()) {
15021     IsConstExpr = false;
15022     if (Loc) *Loc = Diags[0].first;
15023   } else if (!IsConstExpr) {
15024     // FIXME: This shouldn't happen.
15025     if (Loc) *Loc = getExprLoc();
15026   }
15027 
15028   return IsConstExpr;
15029 }
15030 
15031 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
15032                                     const FunctionDecl *Callee,
15033                                     ArrayRef<const Expr*> Args,
15034                                     const Expr *This) const {
15035   assert(!isValueDependent() &&
15036          "Expression evaluator can't be called on a dependent expression.");
15037 
15038   Expr::EvalStatus Status;
15039   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
15040   Info.InConstantContext = true;
15041 
15042   LValue ThisVal;
15043   const LValue *ThisPtr = nullptr;
15044   if (This) {
15045 #ifndef NDEBUG
15046     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
15047     assert(MD && "Don't provide `this` for non-methods.");
15048     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
15049 #endif
15050     if (!This->isValueDependent() &&
15051         EvaluateObjectArgument(Info, This, ThisVal) &&
15052         !Info.EvalStatus.HasSideEffects)
15053       ThisPtr = &ThisVal;
15054 
15055     // Ignore any side-effects from a failed evaluation. This is safe because
15056     // they can't interfere with any other argument evaluation.
15057     Info.EvalStatus.HasSideEffects = false;
15058   }
15059 
15060   ArgVector ArgValues(Args.size());
15061   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
15062        I != E; ++I) {
15063     if ((*I)->isValueDependent() ||
15064         !Evaluate(ArgValues[I - Args.begin()], Info, *I) ||
15065         Info.EvalStatus.HasSideEffects)
15066       // If evaluation fails, throw away the argument entirely.
15067       ArgValues[I - Args.begin()] = APValue();
15068 
15069     // Ignore any side-effects from a failed evaluation. This is safe because
15070     // they can't interfere with any other argument evaluation.
15071     Info.EvalStatus.HasSideEffects = false;
15072   }
15073 
15074   // Parameter cleanups happen in the caller and are not part of this
15075   // evaluation.
15076   Info.discardCleanups();
15077   Info.EvalStatus.HasSideEffects = false;
15078 
15079   // Build fake call to Callee.
15080   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
15081                        ArgValues.data());
15082   // FIXME: Missing ExprWithCleanups in enable_if conditions?
15083   FullExpressionRAII Scope(Info);
15084   return Evaluate(Value, Info, this) && Scope.destroy() &&
15085          !Info.EvalStatus.HasSideEffects;
15086 }
15087 
15088 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
15089                                    SmallVectorImpl<
15090                                      PartialDiagnosticAt> &Diags) {
15091   // FIXME: It would be useful to check constexpr function templates, but at the
15092   // moment the constant expression evaluator cannot cope with the non-rigorous
15093   // ASTs which we build for dependent expressions.
15094   if (FD->isDependentContext())
15095     return true;
15096 
15097   // Bail out if a constexpr constructor has an initializer that contains an
15098   // error. We deliberately don't produce a diagnostic, as we have produced a
15099   // relevant diagnostic when parsing the error initializer.
15100   if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
15101     for (const auto *InitExpr : Ctor->inits()) {
15102       if (InitExpr->getInit() && InitExpr->getInit()->containsErrors())
15103         return false;
15104     }
15105   }
15106   Expr::EvalStatus Status;
15107   Status.Diag = &Diags;
15108 
15109   EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
15110   Info.InConstantContext = true;
15111   Info.CheckingPotentialConstantExpression = true;
15112 
15113   // The constexpr VM attempts to compile all methods to bytecode here.
15114   if (Info.EnableNewConstInterp) {
15115     Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
15116     return Diags.empty();
15117   }
15118 
15119   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
15120   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
15121 
15122   // Fabricate an arbitrary expression on the stack and pretend that it
15123   // is a temporary being used as the 'this' pointer.
15124   LValue This;
15125   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
15126   This.set({&VIE, Info.CurrentCall->Index});
15127 
15128   ArrayRef<const Expr*> Args;
15129 
15130   APValue Scratch;
15131   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
15132     // Evaluate the call as a constant initializer, to allow the construction
15133     // of objects of non-literal types.
15134     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
15135     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
15136   } else {
15137     SourceLocation Loc = FD->getLocation();
15138     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
15139                        Args, FD->getBody(), Info, Scratch, nullptr);
15140   }
15141 
15142   return Diags.empty();
15143 }
15144 
15145 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
15146                                               const FunctionDecl *FD,
15147                                               SmallVectorImpl<
15148                                                 PartialDiagnosticAt> &Diags) {
15149   assert(!E->isValueDependent() &&
15150          "Expression evaluator can't be called on a dependent expression.");
15151 
15152   Expr::EvalStatus Status;
15153   Status.Diag = &Diags;
15154 
15155   EvalInfo Info(FD->getASTContext(), Status,
15156                 EvalInfo::EM_ConstantExpressionUnevaluated);
15157   Info.InConstantContext = true;
15158   Info.CheckingPotentialConstantExpression = true;
15159 
15160   // Fabricate a call stack frame to give the arguments a plausible cover story.
15161   ArrayRef<const Expr*> Args;
15162   ArgVector ArgValues(0);
15163   bool Success = EvaluateArgs(Args, ArgValues, Info, FD);
15164   (void)Success;
15165   assert(Success &&
15166          "Failed to set up arguments for potential constant evaluation");
15167   CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
15168 
15169   APValue ResultScratch;
15170   Evaluate(ResultScratch, Info, E);
15171   return Diags.empty();
15172 }
15173 
15174 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
15175                                  unsigned Type) const {
15176   if (!getType()->isPointerType())
15177     return false;
15178 
15179   Expr::EvalStatus Status;
15180   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
15181   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
15182 }
15183