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     return isa<FunctionDecl>(D);
1899   }
1900 
1901   if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
1902     return true;
1903 
1904   const Expr *E = B.get<const Expr*>();
1905   switch (E->getStmtClass()) {
1906   default:
1907     return false;
1908   case Expr::CompoundLiteralExprClass: {
1909     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1910     return CLE->isFileScope() && CLE->isLValue();
1911   }
1912   case Expr::MaterializeTemporaryExprClass:
1913     // A materialized temporary might have been lifetime-extended to static
1914     // storage duration.
1915     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1916   // A string literal has static storage duration.
1917   case Expr::StringLiteralClass:
1918   case Expr::PredefinedExprClass:
1919   case Expr::ObjCStringLiteralClass:
1920   case Expr::ObjCEncodeExprClass:
1921   case Expr::CXXUuidofExprClass:
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       NoteLValueLocation(Info, Base);
2059     } else {
2060       Info.FFDiag(Loc);
2061     }
2062     // Don't allow references to temporaries to escape.
2063     return false;
2064   }
2065   assert((Info.checkingPotentialConstantExpression() ||
2066           LVal.getLValueCallIndex() == 0) &&
2067          "have call index for global lvalue");
2068 
2069   if (Base.is<DynamicAllocLValue>()) {
2070     Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2071         << IsReferenceType << !Designator.Entries.empty();
2072     NoteLValueLocation(Info, Base);
2073     return false;
2074   }
2075 
2076   if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
2077     if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
2078       // Check if this is a thread-local variable.
2079       if (Var->getTLSKind())
2080         // FIXME: Diagnostic!
2081         return false;
2082 
2083       // A dllimport variable never acts like a constant.
2084       if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
2085         // FIXME: Diagnostic!
2086         return false;
2087     }
2088     if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
2089       // __declspec(dllimport) must be handled very carefully:
2090       // We must never initialize an expression with the thunk in C++.
2091       // Doing otherwise would allow the same id-expression to yield
2092       // different addresses for the same function in different translation
2093       // units.  However, this means that we must dynamically initialize the
2094       // expression with the contents of the import address table at runtime.
2095       //
2096       // The C language has no notion of ODR; furthermore, it has no notion of
2097       // dynamic initialization.  This means that we are permitted to
2098       // perform initialization with the address of the thunk.
2099       if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
2100           FD->hasAttr<DLLImportAttr>())
2101         // FIXME: Diagnostic!
2102         return false;
2103     }
2104   } else if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(
2105                  Base.dyn_cast<const Expr *>())) {
2106     if (CheckedTemps.insert(MTE).second) {
2107       QualType TempType = getType(Base);
2108       if (TempType.isDestructedType()) {
2109         Info.FFDiag(MTE->getExprLoc(),
2110                     diag::note_constexpr_unsupported_tempoarary_nontrivial_dtor)
2111             << TempType;
2112         return false;
2113       }
2114 
2115       APValue *V = MTE->getOrCreateValue(false);
2116       assert(V && "evasluation result refers to uninitialised temporary");
2117       if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2118                                  Info, MTE->getExprLoc(), TempType, *V,
2119                                  Usage, SourceLocation(), CheckedTemps))
2120         return false;
2121     }
2122   }
2123 
2124   // Allow address constant expressions to be past-the-end pointers. This is
2125   // an extension: the standard requires them to point to an object.
2126   if (!IsReferenceType)
2127     return true;
2128 
2129   // A reference constant expression must refer to an object.
2130   if (!Base) {
2131     // FIXME: diagnostic
2132     Info.CCEDiag(Loc);
2133     return true;
2134   }
2135 
2136   // Does this refer one past the end of some object?
2137   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2138     const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2139     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2140       << !Designator.Entries.empty() << !!VD << VD;
2141     NoteLValueLocation(Info, Base);
2142   }
2143 
2144   return true;
2145 }
2146 
2147 /// Member pointers are constant expressions unless they point to a
2148 /// non-virtual dllimport member function.
2149 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2150                                                  SourceLocation Loc,
2151                                                  QualType Type,
2152                                                  const APValue &Value,
2153                                                  Expr::ConstExprUsage Usage) {
2154   const ValueDecl *Member = Value.getMemberPointerDecl();
2155   const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2156   if (!FD)
2157     return true;
2158   if (FD->isConsteval()) {
2159     Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2160     Info.Note(FD->getLocation(), diag::note_declared_at);
2161     return false;
2162   }
2163   return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
2164          !FD->hasAttr<DLLImportAttr>();
2165 }
2166 
2167 /// Check that this core constant expression is of literal type, and if not,
2168 /// produce an appropriate diagnostic.
2169 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2170                              const LValue *This = nullptr) {
2171   if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
2172     return true;
2173 
2174   // C++1y: A constant initializer for an object o [...] may also invoke
2175   // constexpr constructors for o and its subobjects even if those objects
2176   // are of non-literal class types.
2177   //
2178   // C++11 missed this detail for aggregates, so classes like this:
2179   //   struct foo_t { union { int i; volatile int j; } u; };
2180   // are not (obviously) initializable like so:
2181   //   __attribute__((__require_constant_initialization__))
2182   //   static const foo_t x = {{0}};
2183   // because "i" is a subobject with non-literal initialization (due to the
2184   // volatile member of the union). See:
2185   //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2186   // Therefore, we use the C++1y behavior.
2187   if (This && Info.EvaluatingDecl == This->getLValueBase())
2188     return true;
2189 
2190   // Prvalue constant expressions must be of literal types.
2191   if (Info.getLangOpts().CPlusPlus11)
2192     Info.FFDiag(E, diag::note_constexpr_nonliteral)
2193       << E->getType();
2194   else
2195     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2196   return false;
2197 }
2198 
2199 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2200                                   EvalInfo &Info, SourceLocation DiagLoc,
2201                                   QualType Type, const APValue &Value,
2202                                   Expr::ConstExprUsage Usage,
2203                                   SourceLocation SubobjectLoc,
2204                                   CheckedTemporaries &CheckedTemps) {
2205   if (!Value.hasValue()) {
2206     Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2207       << true << Type;
2208     if (SubobjectLoc.isValid())
2209       Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2210     return false;
2211   }
2212 
2213   // We allow _Atomic(T) to be initialized from anything that T can be
2214   // initialized from.
2215   if (const AtomicType *AT = Type->getAs<AtomicType>())
2216     Type = AT->getValueType();
2217 
2218   // Core issue 1454: For a literal constant expression of array or class type,
2219   // each subobject of its value shall have been initialized by a constant
2220   // expression.
2221   if (Value.isArray()) {
2222     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2223     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2224       if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2225                                  Value.getArrayInitializedElt(I), Usage,
2226                                  SubobjectLoc, CheckedTemps))
2227         return false;
2228     }
2229     if (!Value.hasArrayFiller())
2230       return true;
2231     return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2232                                  Value.getArrayFiller(), Usage, SubobjectLoc,
2233                                  CheckedTemps);
2234   }
2235   if (Value.isUnion() && Value.getUnionField()) {
2236     return CheckEvaluationResult(
2237         CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2238         Value.getUnionValue(), Usage, Value.getUnionField()->getLocation(),
2239         CheckedTemps);
2240   }
2241   if (Value.isStruct()) {
2242     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2243     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2244       unsigned BaseIndex = 0;
2245       for (const CXXBaseSpecifier &BS : CD->bases()) {
2246         if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2247                                    Value.getStructBase(BaseIndex), Usage,
2248                                    BS.getBeginLoc(), CheckedTemps))
2249           return false;
2250         ++BaseIndex;
2251       }
2252     }
2253     for (const auto *I : RD->fields()) {
2254       if (I->isUnnamedBitfield())
2255         continue;
2256 
2257       if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2258                                  Value.getStructField(I->getFieldIndex()),
2259                                  Usage, I->getLocation(), CheckedTemps))
2260         return false;
2261     }
2262   }
2263 
2264   if (Value.isLValue() &&
2265       CERK == CheckEvaluationResultKind::ConstantExpression) {
2266     LValue LVal;
2267     LVal.setFrom(Info.Ctx, Value);
2268     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage,
2269                                          CheckedTemps);
2270   }
2271 
2272   if (Value.isMemberPointer() &&
2273       CERK == CheckEvaluationResultKind::ConstantExpression)
2274     return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
2275 
2276   // Everything else is fine.
2277   return true;
2278 }
2279 
2280 /// Check that this core constant expression value is a valid value for a
2281 /// constant expression. If not, report an appropriate diagnostic. Does not
2282 /// check that the expression is of literal type.
2283 static bool
2284 CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
2285                         const APValue &Value,
2286                         Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
2287   CheckedTemporaries CheckedTemps;
2288   return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2289                                Info, DiagLoc, Type, Value, Usage,
2290                                SourceLocation(), CheckedTemps);
2291 }
2292 
2293 /// Check that this evaluated value is fully-initialized and can be loaded by
2294 /// an lvalue-to-rvalue conversion.
2295 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2296                                   QualType Type, const APValue &Value) {
2297   CheckedTemporaries CheckedTemps;
2298   return CheckEvaluationResult(
2299       CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2300       Expr::EvaluateForCodeGen, SourceLocation(), CheckedTemps);
2301 }
2302 
2303 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2304 /// "the allocated storage is deallocated within the evaluation".
2305 static bool CheckMemoryLeaks(EvalInfo &Info) {
2306   if (!Info.HeapAllocs.empty()) {
2307     // We can still fold to a constant despite a compile-time memory leak,
2308     // so long as the heap allocation isn't referenced in the result (we check
2309     // that in CheckConstantExpression).
2310     Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2311                  diag::note_constexpr_memory_leak)
2312         << unsigned(Info.HeapAllocs.size() - 1);
2313   }
2314   return true;
2315 }
2316 
2317 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2318   // A null base expression indicates a null pointer.  These are always
2319   // evaluatable, and they are false unless the offset is zero.
2320   if (!Value.getLValueBase()) {
2321     Result = !Value.getLValueOffset().isZero();
2322     return true;
2323   }
2324 
2325   // We have a non-null base.  These are generally known to be true, but if it's
2326   // a weak declaration it can be null at runtime.
2327   Result = true;
2328   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2329   return !Decl || !Decl->isWeak();
2330 }
2331 
2332 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2333   switch (Val.getKind()) {
2334   case APValue::None:
2335   case APValue::Indeterminate:
2336     return false;
2337   case APValue::Int:
2338     Result = Val.getInt().getBoolValue();
2339     return true;
2340   case APValue::FixedPoint:
2341     Result = Val.getFixedPoint().getBoolValue();
2342     return true;
2343   case APValue::Float:
2344     Result = !Val.getFloat().isZero();
2345     return true;
2346   case APValue::ComplexInt:
2347     Result = Val.getComplexIntReal().getBoolValue() ||
2348              Val.getComplexIntImag().getBoolValue();
2349     return true;
2350   case APValue::ComplexFloat:
2351     Result = !Val.getComplexFloatReal().isZero() ||
2352              !Val.getComplexFloatImag().isZero();
2353     return true;
2354   case APValue::LValue:
2355     return EvalPointerValueAsBool(Val, Result);
2356   case APValue::MemberPointer:
2357     Result = Val.getMemberPointerDecl();
2358     return true;
2359   case APValue::Vector:
2360   case APValue::Array:
2361   case APValue::Struct:
2362   case APValue::Union:
2363   case APValue::AddrLabelDiff:
2364     return false;
2365   }
2366 
2367   llvm_unreachable("unknown APValue kind");
2368 }
2369 
2370 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2371                                        EvalInfo &Info) {
2372   assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
2373   APValue Val;
2374   if (!Evaluate(Val, Info, E))
2375     return false;
2376   return HandleConversionToBool(Val, Result);
2377 }
2378 
2379 template<typename T>
2380 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2381                            const T &SrcValue, QualType DestType) {
2382   Info.CCEDiag(E, diag::note_constexpr_overflow)
2383     << SrcValue << DestType;
2384   return Info.noteUndefinedBehavior();
2385 }
2386 
2387 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2388                                  QualType SrcType, const APFloat &Value,
2389                                  QualType DestType, APSInt &Result) {
2390   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2391   // Determine whether we are converting to unsigned or signed.
2392   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2393 
2394   Result = APSInt(DestWidth, !DestSigned);
2395   bool ignored;
2396   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2397       & APFloat::opInvalidOp)
2398     return HandleOverflow(Info, E, Value, DestType);
2399   return true;
2400 }
2401 
2402 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2403                                    QualType SrcType, QualType DestType,
2404                                    APFloat &Result) {
2405   APFloat Value = Result;
2406   bool ignored;
2407   Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2408                  APFloat::rmNearestTiesToEven, &ignored);
2409   return true;
2410 }
2411 
2412 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2413                                  QualType DestType, QualType SrcType,
2414                                  const APSInt &Value) {
2415   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2416   // Figure out if this is a truncate, extend or noop cast.
2417   // If the input is signed, do a sign extend, noop, or truncate.
2418   APSInt Result = Value.extOrTrunc(DestWidth);
2419   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2420   if (DestType->isBooleanType())
2421     Result = Value.getBoolValue();
2422   return Result;
2423 }
2424 
2425 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2426                                  QualType SrcType, const APSInt &Value,
2427                                  QualType DestType, APFloat &Result) {
2428   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2429   Result.convertFromAPInt(Value, Value.isSigned(),
2430                           APFloat::rmNearestTiesToEven);
2431   return true;
2432 }
2433 
2434 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2435                                   APValue &Value, const FieldDecl *FD) {
2436   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2437 
2438   if (!Value.isInt()) {
2439     // Trying to store a pointer-cast-to-integer into a bitfield.
2440     // FIXME: In this case, we should provide the diagnostic for casting
2441     // a pointer to an integer.
2442     assert(Value.isLValue() && "integral value neither int nor lvalue?");
2443     Info.FFDiag(E);
2444     return false;
2445   }
2446 
2447   APSInt &Int = Value.getInt();
2448   unsigned OldBitWidth = Int.getBitWidth();
2449   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2450   if (NewBitWidth < OldBitWidth)
2451     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2452   return true;
2453 }
2454 
2455 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2456                                   llvm::APInt &Res) {
2457   APValue SVal;
2458   if (!Evaluate(SVal, Info, E))
2459     return false;
2460   if (SVal.isInt()) {
2461     Res = SVal.getInt();
2462     return true;
2463   }
2464   if (SVal.isFloat()) {
2465     Res = SVal.getFloat().bitcastToAPInt();
2466     return true;
2467   }
2468   if (SVal.isVector()) {
2469     QualType VecTy = E->getType();
2470     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2471     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2472     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2473     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2474     Res = llvm::APInt::getNullValue(VecSize);
2475     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2476       APValue &Elt = SVal.getVectorElt(i);
2477       llvm::APInt EltAsInt;
2478       if (Elt.isInt()) {
2479         EltAsInt = Elt.getInt();
2480       } else if (Elt.isFloat()) {
2481         EltAsInt = Elt.getFloat().bitcastToAPInt();
2482       } else {
2483         // Don't try to handle vectors of anything other than int or float
2484         // (not sure if it's possible to hit this case).
2485         Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2486         return false;
2487       }
2488       unsigned BaseEltSize = EltAsInt.getBitWidth();
2489       if (BigEndian)
2490         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2491       else
2492         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2493     }
2494     return true;
2495   }
2496   // Give up if the input isn't an int, float, or vector.  For example, we
2497   // reject "(v4i16)(intptr_t)&a".
2498   Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2499   return false;
2500 }
2501 
2502 /// Perform the given integer operation, which is known to need at most BitWidth
2503 /// bits, and check for overflow in the original type (if that type was not an
2504 /// unsigned type).
2505 template<typename Operation>
2506 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2507                                  const APSInt &LHS, const APSInt &RHS,
2508                                  unsigned BitWidth, Operation Op,
2509                                  APSInt &Result) {
2510   if (LHS.isUnsigned()) {
2511     Result = Op(LHS, RHS);
2512     return true;
2513   }
2514 
2515   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2516   Result = Value.trunc(LHS.getBitWidth());
2517   if (Result.extend(BitWidth) != Value) {
2518     if (Info.checkingForUndefinedBehavior())
2519       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2520                                        diag::warn_integer_constant_overflow)
2521           << Result.toString(10) << E->getType();
2522     else
2523       return HandleOverflow(Info, E, Value, E->getType());
2524   }
2525   return true;
2526 }
2527 
2528 /// Perform the given binary integer operation.
2529 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2530                               BinaryOperatorKind Opcode, APSInt RHS,
2531                               APSInt &Result) {
2532   switch (Opcode) {
2533   default:
2534     Info.FFDiag(E);
2535     return false;
2536   case BO_Mul:
2537     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2538                                 std::multiplies<APSInt>(), Result);
2539   case BO_Add:
2540     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2541                                 std::plus<APSInt>(), Result);
2542   case BO_Sub:
2543     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2544                                 std::minus<APSInt>(), Result);
2545   case BO_And: Result = LHS & RHS; return true;
2546   case BO_Xor: Result = LHS ^ RHS; return true;
2547   case BO_Or:  Result = LHS | RHS; return true;
2548   case BO_Div:
2549   case BO_Rem:
2550     if (RHS == 0) {
2551       Info.FFDiag(E, diag::note_expr_divide_by_zero);
2552       return false;
2553     }
2554     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2555     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2556     // this operation and gives the two's complement result.
2557     if (RHS.isNegative() && RHS.isAllOnesValue() &&
2558         LHS.isSigned() && LHS.isMinSignedValue())
2559       return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2560                             E->getType());
2561     return true;
2562   case BO_Shl: {
2563     if (Info.getLangOpts().OpenCL)
2564       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2565       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2566                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2567                     RHS.isUnsigned());
2568     else if (RHS.isSigned() && RHS.isNegative()) {
2569       // During constant-folding, a negative shift is an opposite shift. Such
2570       // a shift is not a constant expression.
2571       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2572       RHS = -RHS;
2573       goto shift_right;
2574     }
2575   shift_left:
2576     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2577     // the shifted type.
2578     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2579     if (SA != RHS) {
2580       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2581         << RHS << E->getType() << LHS.getBitWidth();
2582     } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus2a) {
2583       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2584       // operand, and must not overflow the corresponding unsigned type.
2585       // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2586       // E1 x 2^E2 module 2^N.
2587       if (LHS.isNegative())
2588         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2589       else if (LHS.countLeadingZeros() < SA)
2590         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2591     }
2592     Result = LHS << SA;
2593     return true;
2594   }
2595   case BO_Shr: {
2596     if (Info.getLangOpts().OpenCL)
2597       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2598       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2599                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2600                     RHS.isUnsigned());
2601     else if (RHS.isSigned() && RHS.isNegative()) {
2602       // During constant-folding, a negative shift is an opposite shift. Such a
2603       // shift is not a constant expression.
2604       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2605       RHS = -RHS;
2606       goto shift_left;
2607     }
2608   shift_right:
2609     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2610     // shifted type.
2611     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2612     if (SA != RHS)
2613       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2614         << RHS << E->getType() << LHS.getBitWidth();
2615     Result = LHS >> SA;
2616     return true;
2617   }
2618 
2619   case BO_LT: Result = LHS < RHS; return true;
2620   case BO_GT: Result = LHS > RHS; return true;
2621   case BO_LE: Result = LHS <= RHS; return true;
2622   case BO_GE: Result = LHS >= RHS; return true;
2623   case BO_EQ: Result = LHS == RHS; return true;
2624   case BO_NE: Result = LHS != RHS; return true;
2625   case BO_Cmp:
2626     llvm_unreachable("BO_Cmp should be handled elsewhere");
2627   }
2628 }
2629 
2630 /// Perform the given binary floating-point operation, in-place, on LHS.
2631 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2632                                   APFloat &LHS, BinaryOperatorKind Opcode,
2633                                   const APFloat &RHS) {
2634   switch (Opcode) {
2635   default:
2636     Info.FFDiag(E);
2637     return false;
2638   case BO_Mul:
2639     LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2640     break;
2641   case BO_Add:
2642     LHS.add(RHS, APFloat::rmNearestTiesToEven);
2643     break;
2644   case BO_Sub:
2645     LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2646     break;
2647   case BO_Div:
2648     // [expr.mul]p4:
2649     //   If the second operand of / or % is zero the behavior is undefined.
2650     if (RHS.isZero())
2651       Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2652     LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2653     break;
2654   }
2655 
2656   // [expr.pre]p4:
2657   //   If during the evaluation of an expression, the result is not
2658   //   mathematically defined [...], the behavior is undefined.
2659   // FIXME: C++ rules require us to not conform to IEEE 754 here.
2660   if (LHS.isNaN()) {
2661     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2662     return Info.noteUndefinedBehavior();
2663   }
2664   return true;
2665 }
2666 
2667 /// Cast an lvalue referring to a base subobject to a derived class, by
2668 /// truncating the lvalue's path to the given length.
2669 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2670                                const RecordDecl *TruncatedType,
2671                                unsigned TruncatedElements) {
2672   SubobjectDesignator &D = Result.Designator;
2673 
2674   // Check we actually point to a derived class object.
2675   if (TruncatedElements == D.Entries.size())
2676     return true;
2677   assert(TruncatedElements >= D.MostDerivedPathLength &&
2678          "not casting to a derived class");
2679   if (!Result.checkSubobject(Info, E, CSK_Derived))
2680     return false;
2681 
2682   // Truncate the path to the subobject, and remove any derived-to-base offsets.
2683   const RecordDecl *RD = TruncatedType;
2684   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
2685     if (RD->isInvalidDecl()) return false;
2686     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2687     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
2688     if (isVirtualBaseClass(D.Entries[I]))
2689       Result.Offset -= Layout.getVBaseClassOffset(Base);
2690     else
2691       Result.Offset -= Layout.getBaseClassOffset(Base);
2692     RD = Base;
2693   }
2694   D.Entries.resize(TruncatedElements);
2695   return true;
2696 }
2697 
2698 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2699                                    const CXXRecordDecl *Derived,
2700                                    const CXXRecordDecl *Base,
2701                                    const ASTRecordLayout *RL = nullptr) {
2702   if (!RL) {
2703     if (Derived->isInvalidDecl()) return false;
2704     RL = &Info.Ctx.getASTRecordLayout(Derived);
2705   }
2706 
2707   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
2708   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
2709   return true;
2710 }
2711 
2712 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2713                              const CXXRecordDecl *DerivedDecl,
2714                              const CXXBaseSpecifier *Base) {
2715   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2716 
2717   if (!Base->isVirtual())
2718     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
2719 
2720   SubobjectDesignator &D = Obj.Designator;
2721   if (D.Invalid)
2722     return false;
2723 
2724   // Extract most-derived object and corresponding type.
2725   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2726   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2727     return false;
2728 
2729   // Find the virtual base class.
2730   if (DerivedDecl->isInvalidDecl()) return false;
2731   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2732   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
2733   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
2734   return true;
2735 }
2736 
2737 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2738                                  QualType Type, LValue &Result) {
2739   for (CastExpr::path_const_iterator PathI = E->path_begin(),
2740                                      PathE = E->path_end();
2741        PathI != PathE; ++PathI) {
2742     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2743                           *PathI))
2744       return false;
2745     Type = (*PathI)->getType();
2746   }
2747   return true;
2748 }
2749 
2750 /// Cast an lvalue referring to a derived class to a known base subobject.
2751 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
2752                             const CXXRecordDecl *DerivedRD,
2753                             const CXXRecordDecl *BaseRD) {
2754   CXXBasePaths Paths(/*FindAmbiguities=*/false,
2755                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
2756   if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
2757     llvm_unreachable("Class must be derived from the passed in base class!");
2758 
2759   for (CXXBasePathElement &Elem : Paths.front())
2760     if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
2761       return false;
2762   return true;
2763 }
2764 
2765 /// Update LVal to refer to the given field, which must be a member of the type
2766 /// currently described by LVal.
2767 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
2768                                const FieldDecl *FD,
2769                                const ASTRecordLayout *RL = nullptr) {
2770   if (!RL) {
2771     if (FD->getParent()->isInvalidDecl()) return false;
2772     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
2773   }
2774 
2775   unsigned I = FD->getFieldIndex();
2776   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
2777   LVal.addDecl(Info, E, FD);
2778   return true;
2779 }
2780 
2781 /// Update LVal to refer to the given indirect field.
2782 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
2783                                        LValue &LVal,
2784                                        const IndirectFieldDecl *IFD) {
2785   for (const auto *C : IFD->chain())
2786     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
2787       return false;
2788   return true;
2789 }
2790 
2791 /// Get the size of the given type in char units.
2792 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2793                          QualType Type, CharUnits &Size) {
2794   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2795   // extension.
2796   if (Type->isVoidType() || Type->isFunctionType()) {
2797     Size = CharUnits::One();
2798     return true;
2799   }
2800 
2801   if (Type->isDependentType()) {
2802     Info.FFDiag(Loc);
2803     return false;
2804   }
2805 
2806   if (!Type->isConstantSizeType()) {
2807     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2808     // FIXME: Better diagnostic.
2809     Info.FFDiag(Loc);
2810     return false;
2811   }
2812 
2813   Size = Info.Ctx.getTypeSizeInChars(Type);
2814   return true;
2815 }
2816 
2817 /// Update a pointer value to model pointer arithmetic.
2818 /// \param Info - Information about the ongoing evaluation.
2819 /// \param E - The expression being evaluated, for diagnostic purposes.
2820 /// \param LVal - The pointer value to be updated.
2821 /// \param EltTy - The pointee type represented by LVal.
2822 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
2823 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2824                                         LValue &LVal, QualType EltTy,
2825                                         APSInt Adjustment) {
2826   CharUnits SizeOfPointee;
2827   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
2828     return false;
2829 
2830   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
2831   return true;
2832 }
2833 
2834 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2835                                         LValue &LVal, QualType EltTy,
2836                                         int64_t Adjustment) {
2837   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2838                                      APSInt::get(Adjustment));
2839 }
2840 
2841 /// Update an lvalue to refer to a component of a complex number.
2842 /// \param Info - Information about the ongoing evaluation.
2843 /// \param LVal - The lvalue to be updated.
2844 /// \param EltTy - The complex number's component type.
2845 /// \param Imag - False for the real component, true for the imaginary.
2846 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2847                                        LValue &LVal, QualType EltTy,
2848                                        bool Imag) {
2849   if (Imag) {
2850     CharUnits SizeOfComponent;
2851     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2852       return false;
2853     LVal.Offset += SizeOfComponent;
2854   }
2855   LVal.addComplex(Info, E, EltTy, Imag);
2856   return true;
2857 }
2858 
2859 /// Try to evaluate the initializer for a variable declaration.
2860 ///
2861 /// \param Info   Information about the ongoing evaluation.
2862 /// \param E      An expression to be used when printing diagnostics.
2863 /// \param VD     The variable whose initializer should be obtained.
2864 /// \param Frame  The frame in which the variable was created. Must be null
2865 ///               if this variable is not local to the evaluation.
2866 /// \param Result Filled in with a pointer to the value of the variable.
2867 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2868                                 const VarDecl *VD, CallStackFrame *Frame,
2869                                 APValue *&Result, const LValue *LVal) {
2870 
2871   // If this is a parameter to an active constexpr function call, perform
2872   // argument substitution.
2873   if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
2874     // Assume arguments of a potential constant expression are unknown
2875     // constant expressions.
2876     if (Info.checkingPotentialConstantExpression())
2877       return false;
2878     if (!Frame || !Frame->Arguments) {
2879       Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2880       return false;
2881     }
2882     Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
2883     return true;
2884   }
2885 
2886   // If this is a local variable, dig out its value.
2887   if (Frame) {
2888     Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2889                   : Frame->getCurrentTemporary(VD);
2890     if (!Result) {
2891       // Assume variables referenced within a lambda's call operator that were
2892       // not declared within the call operator are captures and during checking
2893       // of a potential constant expression, assume they are unknown constant
2894       // expressions.
2895       assert(isLambdaCallOperator(Frame->Callee) &&
2896              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2897              "missing value for local variable");
2898       if (Info.checkingPotentialConstantExpression())
2899         return false;
2900       // FIXME: implement capture evaluation during constant expr evaluation.
2901       Info.FFDiag(E->getBeginLoc(),
2902                   diag::note_unimplemented_constexpr_lambda_feature_ast)
2903           << "captures not currently allowed";
2904       return false;
2905     }
2906     return true;
2907   }
2908 
2909   // Dig out the initializer, and use the declaration which it's attached to.
2910   const Expr *Init = VD->getAnyInitializer(VD);
2911   if (!Init || Init->isValueDependent()) {
2912     // If we're checking a potential constant expression, the variable could be
2913     // initialized later.
2914     if (!Info.checkingPotentialConstantExpression())
2915       Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2916     return false;
2917   }
2918 
2919   // If we're currently evaluating the initializer of this declaration, use that
2920   // in-flight value.
2921   if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
2922     Result = Info.EvaluatingDeclValue;
2923     return true;
2924   }
2925 
2926   // Never evaluate the initializer of a weak variable. We can't be sure that
2927   // this is the definition which will be used.
2928   if (VD->isWeak()) {
2929     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2930     return false;
2931   }
2932 
2933   // Check that we can fold the initializer. In C++, we will have already done
2934   // this in the cases where it matters for conformance.
2935   SmallVector<PartialDiagnosticAt, 8> Notes;
2936   if (!VD->evaluateValue(Notes)) {
2937     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
2938               Notes.size() + 1) << VD;
2939     Info.Note(VD->getLocation(), diag::note_declared_at);
2940     Info.addNotes(Notes);
2941     return false;
2942   } else if (!VD->checkInitIsICE()) {
2943     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
2944                  Notes.size() + 1) << VD;
2945     Info.Note(VD->getLocation(), diag::note_declared_at);
2946     Info.addNotes(Notes);
2947   }
2948 
2949   Result = VD->getEvaluatedValue();
2950   return true;
2951 }
2952 
2953 static bool IsConstNonVolatile(QualType T) {
2954   Qualifiers Quals = T.getQualifiers();
2955   return Quals.hasConst() && !Quals.hasVolatile();
2956 }
2957 
2958 /// Get the base index of the given base class within an APValue representing
2959 /// the given derived class.
2960 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2961                              const CXXRecordDecl *Base) {
2962   Base = Base->getCanonicalDecl();
2963   unsigned Index = 0;
2964   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2965          E = Derived->bases_end(); I != E; ++I, ++Index) {
2966     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2967       return Index;
2968   }
2969 
2970   llvm_unreachable("base class missing from derived class's bases list");
2971 }
2972 
2973 /// Extract the value of a character from a string literal.
2974 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2975                                             uint64_t Index) {
2976   assert(!isa<SourceLocExpr>(Lit) &&
2977          "SourceLocExpr should have already been converted to a StringLiteral");
2978 
2979   // FIXME: Support MakeStringConstant
2980   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2981     std::string Str;
2982     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2983     assert(Index <= Str.size() && "Index too large");
2984     return APSInt::getUnsigned(Str.c_str()[Index]);
2985   }
2986 
2987   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2988     Lit = PE->getFunctionName();
2989   const StringLiteral *S = cast<StringLiteral>(Lit);
2990   const ConstantArrayType *CAT =
2991       Info.Ctx.getAsConstantArrayType(S->getType());
2992   assert(CAT && "string literal isn't an array");
2993   QualType CharType = CAT->getElementType();
2994   assert(CharType->isIntegerType() && "unexpected character type");
2995 
2996   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2997                CharType->isUnsignedIntegerType());
2998   if (Index < S->getLength())
2999     Value = S->getCodeUnit(Index);
3000   return Value;
3001 }
3002 
3003 // Expand a string literal into an array of characters.
3004 //
3005 // FIXME: This is inefficient; we should probably introduce something similar
3006 // to the LLVM ConstantDataArray to make this cheaper.
3007 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3008                                 APValue &Result,
3009                                 QualType AllocType = QualType()) {
3010   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3011       AllocType.isNull() ? S->getType() : AllocType);
3012   assert(CAT && "string literal isn't an array");
3013   QualType CharType = CAT->getElementType();
3014   assert(CharType->isIntegerType() && "unexpected character type");
3015 
3016   unsigned Elts = CAT->getSize().getZExtValue();
3017   Result = APValue(APValue::UninitArray(),
3018                    std::min(S->getLength(), Elts), Elts);
3019   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3020                CharType->isUnsignedIntegerType());
3021   if (Result.hasArrayFiller())
3022     Result.getArrayFiller() = APValue(Value);
3023   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3024     Value = S->getCodeUnit(I);
3025     Result.getArrayInitializedElt(I) = APValue(Value);
3026   }
3027 }
3028 
3029 // Expand an array so that it has more than Index filled elements.
3030 static void expandArray(APValue &Array, unsigned Index) {
3031   unsigned Size = Array.getArraySize();
3032   assert(Index < Size);
3033 
3034   // Always at least double the number of elements for which we store a value.
3035   unsigned OldElts = Array.getArrayInitializedElts();
3036   unsigned NewElts = std::max(Index+1, OldElts * 2);
3037   NewElts = std::min(Size, std::max(NewElts, 8u));
3038 
3039   // Copy the data across.
3040   APValue NewValue(APValue::UninitArray(), NewElts, Size);
3041   for (unsigned I = 0; I != OldElts; ++I)
3042     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3043   for (unsigned I = OldElts; I != NewElts; ++I)
3044     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3045   if (NewValue.hasArrayFiller())
3046     NewValue.getArrayFiller() = Array.getArrayFiller();
3047   Array.swap(NewValue);
3048 }
3049 
3050 /// Determine whether a type would actually be read by an lvalue-to-rvalue
3051 /// conversion. If it's of class type, we may assume that the copy operation
3052 /// is trivial. Note that this is never true for a union type with fields
3053 /// (because the copy always "reads" the active member) and always true for
3054 /// a non-class type.
3055 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3056 static bool isReadByLvalueToRvalueConversion(QualType T) {
3057   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3058   return !RD || isReadByLvalueToRvalueConversion(RD);
3059 }
3060 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3061   // FIXME: A trivial copy of a union copies the object representation, even if
3062   // the union is empty.
3063   if (RD->isUnion())
3064     return !RD->field_empty();
3065   if (RD->isEmpty())
3066     return false;
3067 
3068   for (auto *Field : RD->fields())
3069     if (!Field->isUnnamedBitfield() &&
3070         isReadByLvalueToRvalueConversion(Field->getType()))
3071       return true;
3072 
3073   for (auto &BaseSpec : RD->bases())
3074     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3075       return true;
3076 
3077   return false;
3078 }
3079 
3080 /// Diagnose an attempt to read from any unreadable field within the specified
3081 /// type, which might be a class type.
3082 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3083                                   QualType T) {
3084   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3085   if (!RD)
3086     return false;
3087 
3088   if (!RD->hasMutableFields())
3089     return false;
3090 
3091   for (auto *Field : RD->fields()) {
3092     // If we're actually going to read this field in some way, then it can't
3093     // be mutable. If we're in a union, then assigning to a mutable field
3094     // (even an empty one) can change the active member, so that's not OK.
3095     // FIXME: Add core issue number for the union case.
3096     if (Field->isMutable() &&
3097         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3098       Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3099       Info.Note(Field->getLocation(), diag::note_declared_at);
3100       return true;
3101     }
3102 
3103     if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3104       return true;
3105   }
3106 
3107   for (auto &BaseSpec : RD->bases())
3108     if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3109       return true;
3110 
3111   // All mutable fields were empty, and thus not actually read.
3112   return false;
3113 }
3114 
3115 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3116                                         APValue::LValueBase Base,
3117                                         bool MutableSubobject = false) {
3118   // A temporary we created.
3119   if (Base.getCallIndex())
3120     return true;
3121 
3122   auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3123   if (!Evaluating)
3124     return false;
3125 
3126   auto *BaseD = Base.dyn_cast<const ValueDecl*>();
3127 
3128   switch (Info.IsEvaluatingDecl) {
3129   case EvalInfo::EvaluatingDeclKind::None:
3130     return false;
3131 
3132   case EvalInfo::EvaluatingDeclKind::Ctor:
3133     // The variable whose initializer we're evaluating.
3134     if (BaseD)
3135       return declaresSameEntity(Evaluating, BaseD);
3136 
3137     // A temporary lifetime-extended by the variable whose initializer we're
3138     // evaluating.
3139     if (auto *BaseE = Base.dyn_cast<const Expr *>())
3140       if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3141         return declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating);
3142     return false;
3143 
3144   case EvalInfo::EvaluatingDeclKind::Dtor:
3145     // C++2a [expr.const]p6:
3146     //   [during constant destruction] the lifetime of a and its non-mutable
3147     //   subobjects (but not its mutable subobjects) [are] considered to start
3148     //   within e.
3149     //
3150     // FIXME: We can meaningfully extend this to cover non-const objects, but
3151     // we will need special handling: we should be able to access only
3152     // subobjects of such objects that are themselves declared const.
3153     if (!BaseD ||
3154         !(BaseD->getType().isConstQualified() ||
3155           BaseD->getType()->isReferenceType()) ||
3156         MutableSubobject)
3157       return false;
3158     return declaresSameEntity(Evaluating, BaseD);
3159   }
3160 
3161   llvm_unreachable("unknown evaluating decl kind");
3162 }
3163 
3164 namespace {
3165 /// A handle to a complete object (an object that is not a subobject of
3166 /// another object).
3167 struct CompleteObject {
3168   /// The identity of the object.
3169   APValue::LValueBase Base;
3170   /// The value of the complete object.
3171   APValue *Value;
3172   /// The type of the complete object.
3173   QualType Type;
3174 
3175   CompleteObject() : Value(nullptr) {}
3176   CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3177       : Base(Base), Value(Value), Type(Type) {}
3178 
3179   bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3180     // If this isn't a "real" access (eg, if it's just accessing the type
3181     // info), allow it. We assume the type doesn't change dynamically for
3182     // subobjects of constexpr objects (even though we'd hit UB here if it
3183     // did). FIXME: Is this right?
3184     if (!isAnyAccess(AK))
3185       return true;
3186 
3187     // In C++14 onwards, it is permitted to read a mutable member whose
3188     // lifetime began within the evaluation.
3189     // FIXME: Should we also allow this in C++11?
3190     if (!Info.getLangOpts().CPlusPlus14)
3191       return false;
3192     return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3193   }
3194 
3195   explicit operator bool() const { return !Type.isNull(); }
3196 };
3197 } // end anonymous namespace
3198 
3199 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3200                                  bool IsMutable = false) {
3201   // C++ [basic.type.qualifier]p1:
3202   // - A const object is an object of type const T or a non-mutable subobject
3203   //   of a const object.
3204   if (ObjType.isConstQualified() && !IsMutable)
3205     SubobjType.addConst();
3206   // - A volatile object is an object of type const T or a subobject of a
3207   //   volatile object.
3208   if (ObjType.isVolatileQualified())
3209     SubobjType.addVolatile();
3210   return SubobjType;
3211 }
3212 
3213 /// Find the designated sub-object of an rvalue.
3214 template<typename SubobjectHandler>
3215 typename SubobjectHandler::result_type
3216 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3217               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3218   if (Sub.Invalid)
3219     // A diagnostic will have already been produced.
3220     return handler.failed();
3221   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3222     if (Info.getLangOpts().CPlusPlus11)
3223       Info.FFDiag(E, Sub.isOnePastTheEnd()
3224                          ? diag::note_constexpr_access_past_end
3225                          : diag::note_constexpr_access_unsized_array)
3226           << handler.AccessKind;
3227     else
3228       Info.FFDiag(E);
3229     return handler.failed();
3230   }
3231 
3232   APValue *O = Obj.Value;
3233   QualType ObjType = Obj.Type;
3234   const FieldDecl *LastField = nullptr;
3235   const FieldDecl *VolatileField = nullptr;
3236 
3237   // Walk the designator's path to find the subobject.
3238   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3239     // Reading an indeterminate value is undefined, but assigning over one is OK.
3240     if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3241         (O->isIndeterminate() &&
3242          !isValidIndeterminateAccess(handler.AccessKind))) {
3243       if (!Info.checkingPotentialConstantExpression())
3244         Info.FFDiag(E, diag::note_constexpr_access_uninit)
3245             << handler.AccessKind << O->isIndeterminate();
3246       return handler.failed();
3247     }
3248 
3249     // C++ [class.ctor]p5, C++ [class.dtor]p5:
3250     //    const and volatile semantics are not applied on an object under
3251     //    {con,de}struction.
3252     if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3253         ObjType->isRecordType() &&
3254         Info.isEvaluatingCtorDtor(
3255             Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3256                                          Sub.Entries.begin() + I)) !=
3257                           ConstructionPhase::None) {
3258       ObjType = Info.Ctx.getCanonicalType(ObjType);
3259       ObjType.removeLocalConst();
3260       ObjType.removeLocalVolatile();
3261     }
3262 
3263     // If this is our last pass, check that the final object type is OK.
3264     if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3265       // Accesses to volatile objects are prohibited.
3266       if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3267         if (Info.getLangOpts().CPlusPlus) {
3268           int DiagKind;
3269           SourceLocation Loc;
3270           const NamedDecl *Decl = nullptr;
3271           if (VolatileField) {
3272             DiagKind = 2;
3273             Loc = VolatileField->getLocation();
3274             Decl = VolatileField;
3275           } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3276             DiagKind = 1;
3277             Loc = VD->getLocation();
3278             Decl = VD;
3279           } else {
3280             DiagKind = 0;
3281             if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3282               Loc = E->getExprLoc();
3283           }
3284           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3285               << handler.AccessKind << DiagKind << Decl;
3286           Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3287         } else {
3288           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3289         }
3290         return handler.failed();
3291       }
3292 
3293       // If we are reading an object of class type, there may still be more
3294       // things we need to check: if there are any mutable subobjects, we
3295       // cannot perform this read. (This only happens when performing a trivial
3296       // copy or assignment.)
3297       if (ObjType->isRecordType() &&
3298           !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3299           diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3300         return handler.failed();
3301     }
3302 
3303     if (I == N) {
3304       if (!handler.found(*O, ObjType))
3305         return false;
3306 
3307       // If we modified a bit-field, truncate it to the right width.
3308       if (isModification(handler.AccessKind) &&
3309           LastField && LastField->isBitField() &&
3310           !truncateBitfieldValue(Info, E, *O, LastField))
3311         return false;
3312 
3313       return true;
3314     }
3315 
3316     LastField = nullptr;
3317     if (ObjType->isArrayType()) {
3318       // Next subobject is an array element.
3319       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3320       assert(CAT && "vla in literal type?");
3321       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3322       if (CAT->getSize().ule(Index)) {
3323         // Note, it should not be possible to form a pointer with a valid
3324         // designator which points more than one past the end of the array.
3325         if (Info.getLangOpts().CPlusPlus11)
3326           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3327             << handler.AccessKind;
3328         else
3329           Info.FFDiag(E);
3330         return handler.failed();
3331       }
3332 
3333       ObjType = CAT->getElementType();
3334 
3335       if (O->getArrayInitializedElts() > Index)
3336         O = &O->getArrayInitializedElt(Index);
3337       else if (!isRead(handler.AccessKind)) {
3338         expandArray(*O, Index);
3339         O = &O->getArrayInitializedElt(Index);
3340       } else
3341         O = &O->getArrayFiller();
3342     } else if (ObjType->isAnyComplexType()) {
3343       // Next subobject is a complex number.
3344       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3345       if (Index > 1) {
3346         if (Info.getLangOpts().CPlusPlus11)
3347           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3348             << handler.AccessKind;
3349         else
3350           Info.FFDiag(E);
3351         return handler.failed();
3352       }
3353 
3354       ObjType = getSubobjectType(
3355           ObjType, ObjType->castAs<ComplexType>()->getElementType());
3356 
3357       assert(I == N - 1 && "extracting subobject of scalar?");
3358       if (O->isComplexInt()) {
3359         return handler.found(Index ? O->getComplexIntImag()
3360                                    : O->getComplexIntReal(), ObjType);
3361       } else {
3362         assert(O->isComplexFloat());
3363         return handler.found(Index ? O->getComplexFloatImag()
3364                                    : O->getComplexFloatReal(), ObjType);
3365       }
3366     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3367       if (Field->isMutable() &&
3368           !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3369         Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3370           << handler.AccessKind << Field;
3371         Info.Note(Field->getLocation(), diag::note_declared_at);
3372         return handler.failed();
3373       }
3374 
3375       // Next subobject is a class, struct or union field.
3376       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3377       if (RD->isUnion()) {
3378         const FieldDecl *UnionField = O->getUnionField();
3379         if (!UnionField ||
3380             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3381           if (I == N - 1 && handler.AccessKind == AK_Construct) {
3382             // Placement new onto an inactive union member makes it active.
3383             O->setUnion(Field, APValue());
3384           } else {
3385             // FIXME: If O->getUnionValue() is absent, report that there's no
3386             // active union member rather than reporting the prior active union
3387             // member. We'll need to fix nullptr_t to not use APValue() as its
3388             // representation first.
3389             Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3390                 << handler.AccessKind << Field << !UnionField << UnionField;
3391             return handler.failed();
3392           }
3393         }
3394         O = &O->getUnionValue();
3395       } else
3396         O = &O->getStructField(Field->getFieldIndex());
3397 
3398       ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3399       LastField = Field;
3400       if (Field->getType().isVolatileQualified())
3401         VolatileField = Field;
3402     } else {
3403       // Next subobject is a base class.
3404       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3405       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3406       O = &O->getStructBase(getBaseIndex(Derived, Base));
3407 
3408       ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3409     }
3410   }
3411 }
3412 
3413 namespace {
3414 struct ExtractSubobjectHandler {
3415   EvalInfo &Info;
3416   const Expr *E;
3417   APValue &Result;
3418   const AccessKinds AccessKind;
3419 
3420   typedef bool result_type;
3421   bool failed() { return false; }
3422   bool found(APValue &Subobj, QualType SubobjType) {
3423     Result = Subobj;
3424     if (AccessKind == AK_ReadObjectRepresentation)
3425       return true;
3426     return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3427   }
3428   bool found(APSInt &Value, QualType SubobjType) {
3429     Result = APValue(Value);
3430     return true;
3431   }
3432   bool found(APFloat &Value, QualType SubobjType) {
3433     Result = APValue(Value);
3434     return true;
3435   }
3436 };
3437 } // end anonymous namespace
3438 
3439 /// Extract the designated sub-object of an rvalue.
3440 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3441                              const CompleteObject &Obj,
3442                              const SubobjectDesignator &Sub, APValue &Result,
3443                              AccessKinds AK = AK_Read) {
3444   assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3445   ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3446   return findSubobject(Info, E, Obj, Sub, Handler);
3447 }
3448 
3449 namespace {
3450 struct ModifySubobjectHandler {
3451   EvalInfo &Info;
3452   APValue &NewVal;
3453   const Expr *E;
3454 
3455   typedef bool result_type;
3456   static const AccessKinds AccessKind = AK_Assign;
3457 
3458   bool checkConst(QualType QT) {
3459     // Assigning to a const object has undefined behavior.
3460     if (QT.isConstQualified()) {
3461       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3462       return false;
3463     }
3464     return true;
3465   }
3466 
3467   bool failed() { return false; }
3468   bool found(APValue &Subobj, QualType SubobjType) {
3469     if (!checkConst(SubobjType))
3470       return false;
3471     // We've been given ownership of NewVal, so just swap it in.
3472     Subobj.swap(NewVal);
3473     return true;
3474   }
3475   bool found(APSInt &Value, QualType SubobjType) {
3476     if (!checkConst(SubobjType))
3477       return false;
3478     if (!NewVal.isInt()) {
3479       // Maybe trying to write a cast pointer value into a complex?
3480       Info.FFDiag(E);
3481       return false;
3482     }
3483     Value = NewVal.getInt();
3484     return true;
3485   }
3486   bool found(APFloat &Value, QualType SubobjType) {
3487     if (!checkConst(SubobjType))
3488       return false;
3489     Value = NewVal.getFloat();
3490     return true;
3491   }
3492 };
3493 } // end anonymous namespace
3494 
3495 const AccessKinds ModifySubobjectHandler::AccessKind;
3496 
3497 /// Update the designated sub-object of an rvalue to the given value.
3498 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3499                             const CompleteObject &Obj,
3500                             const SubobjectDesignator &Sub,
3501                             APValue &NewVal) {
3502   ModifySubobjectHandler Handler = { Info, NewVal, E };
3503   return findSubobject(Info, E, Obj, Sub, Handler);
3504 }
3505 
3506 /// Find the position where two subobject designators diverge, or equivalently
3507 /// the length of the common initial subsequence.
3508 static unsigned FindDesignatorMismatch(QualType ObjType,
3509                                        const SubobjectDesignator &A,
3510                                        const SubobjectDesignator &B,
3511                                        bool &WasArrayIndex) {
3512   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3513   for (/**/; I != N; ++I) {
3514     if (!ObjType.isNull() &&
3515         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3516       // Next subobject is an array element.
3517       if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3518         WasArrayIndex = true;
3519         return I;
3520       }
3521       if (ObjType->isAnyComplexType())
3522         ObjType = ObjType->castAs<ComplexType>()->getElementType();
3523       else
3524         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3525     } else {
3526       if (A.Entries[I].getAsBaseOrMember() !=
3527           B.Entries[I].getAsBaseOrMember()) {
3528         WasArrayIndex = false;
3529         return I;
3530       }
3531       if (const FieldDecl *FD = getAsField(A.Entries[I]))
3532         // Next subobject is a field.
3533         ObjType = FD->getType();
3534       else
3535         // Next subobject is a base class.
3536         ObjType = QualType();
3537     }
3538   }
3539   WasArrayIndex = false;
3540   return I;
3541 }
3542 
3543 /// Determine whether the given subobject designators refer to elements of the
3544 /// same array object.
3545 static bool AreElementsOfSameArray(QualType ObjType,
3546                                    const SubobjectDesignator &A,
3547                                    const SubobjectDesignator &B) {
3548   if (A.Entries.size() != B.Entries.size())
3549     return false;
3550 
3551   bool IsArray = A.MostDerivedIsArrayElement;
3552   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3553     // A is a subobject of the array element.
3554     return false;
3555 
3556   // If A (and B) designates an array element, the last entry will be the array
3557   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3558   // of length 1' case, and the entire path must match.
3559   bool WasArrayIndex;
3560   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3561   return CommonLength >= A.Entries.size() - IsArray;
3562 }
3563 
3564 /// Find the complete object to which an LValue refers.
3565 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3566                                          AccessKinds AK, const LValue &LVal,
3567                                          QualType LValType) {
3568   if (LVal.InvalidBase) {
3569     Info.FFDiag(E);
3570     return CompleteObject();
3571   }
3572 
3573   if (!LVal.Base) {
3574     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3575     return CompleteObject();
3576   }
3577 
3578   CallStackFrame *Frame = nullptr;
3579   unsigned Depth = 0;
3580   if (LVal.getLValueCallIndex()) {
3581     std::tie(Frame, Depth) =
3582         Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3583     if (!Frame) {
3584       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3585         << AK << LVal.Base.is<const ValueDecl*>();
3586       NoteLValueLocation(Info, LVal.Base);
3587       return CompleteObject();
3588     }
3589   }
3590 
3591   bool IsAccess = isAnyAccess(AK);
3592 
3593   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3594   // is not a constant expression (even if the object is non-volatile). We also
3595   // apply this rule to C++98, in order to conform to the expected 'volatile'
3596   // semantics.
3597   if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
3598     if (Info.getLangOpts().CPlusPlus)
3599       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3600         << AK << LValType;
3601     else
3602       Info.FFDiag(E);
3603     return CompleteObject();
3604   }
3605 
3606   // Compute value storage location and type of base object.
3607   APValue *BaseVal = nullptr;
3608   QualType BaseType = getType(LVal.Base);
3609 
3610   if (const ConstantExpr *CE =
3611           dyn_cast_or_null<ConstantExpr>(LVal.Base.dyn_cast<const Expr *>())) {
3612     /// Nested immediate invocation have been previously removed so if we found
3613     /// a ConstantExpr it can only be the EvaluatingDecl.
3614     assert(CE->isImmediateInvocation() && CE == Info.EvaluatingDecl);
3615     (void)CE;
3616     BaseVal = Info.EvaluatingDeclValue;
3617   } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
3618     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3619     // In C++11, constexpr, non-volatile variables initialized with constant
3620     // expressions are constant expressions too. Inside constexpr functions,
3621     // parameters are constant expressions even if they're non-const.
3622     // In C++1y, objects local to a constant expression (those with a Frame) are
3623     // both readable and writable inside constant expressions.
3624     // In C, such things can also be folded, although they are not ICEs.
3625     const VarDecl *VD = dyn_cast<VarDecl>(D);
3626     if (VD) {
3627       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3628         VD = VDef;
3629     }
3630     if (!VD || VD->isInvalidDecl()) {
3631       Info.FFDiag(E);
3632       return CompleteObject();
3633     }
3634 
3635     // Unless we're looking at a local variable or argument in a constexpr call,
3636     // the variable we're reading must be const.
3637     if (!Frame) {
3638       if (Info.getLangOpts().CPlusPlus14 &&
3639           lifetimeStartedInEvaluation(Info, LVal.Base)) {
3640         // OK, we can read and modify an object if we're in the process of
3641         // evaluating its initializer, because its lifetime began in this
3642         // evaluation.
3643       } else if (isModification(AK)) {
3644         // All the remaining cases do not permit modification of the object.
3645         Info.FFDiag(E, diag::note_constexpr_modify_global);
3646         return CompleteObject();
3647       } else if (VD->isConstexpr()) {
3648         // OK, we can read this variable.
3649       } else if (BaseType->isIntegralOrEnumerationType()) {
3650         // In OpenCL if a variable is in constant address space it is a const
3651         // value.
3652         if (!(BaseType.isConstQualified() ||
3653               (Info.getLangOpts().OpenCL &&
3654                BaseType.getAddressSpace() == LangAS::opencl_constant))) {
3655           if (!IsAccess)
3656             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3657           if (Info.getLangOpts().CPlusPlus) {
3658             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
3659             Info.Note(VD->getLocation(), diag::note_declared_at);
3660           } else {
3661             Info.FFDiag(E);
3662           }
3663           return CompleteObject();
3664         }
3665       } else if (!IsAccess) {
3666         return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3667       } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3668         // We support folding of const floating-point types, in order to make
3669         // static const data members of such types (supported as an extension)
3670         // more useful.
3671         if (Info.getLangOpts().CPlusPlus11) {
3672           Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3673           Info.Note(VD->getLocation(), diag::note_declared_at);
3674         } else {
3675           Info.CCEDiag(E);
3676         }
3677       } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3678         Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3679         // Keep evaluating to see what we can do.
3680       } else {
3681         // FIXME: Allow folding of values of any literal type in all languages.
3682         if (Info.checkingPotentialConstantExpression() &&
3683             VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3684           // The definition of this variable could be constexpr. We can't
3685           // access it right now, but may be able to in future.
3686         } else if (Info.getLangOpts().CPlusPlus11) {
3687           Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3688           Info.Note(VD->getLocation(), diag::note_declared_at);
3689         } else {
3690           Info.FFDiag(E);
3691         }
3692         return CompleteObject();
3693       }
3694     }
3695 
3696     if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
3697       return CompleteObject();
3698   } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
3699     Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
3700     if (!Alloc) {
3701       Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
3702       return CompleteObject();
3703     }
3704     return CompleteObject(LVal.Base, &(*Alloc)->Value,
3705                           LVal.Base.getDynamicAllocType());
3706   } else {
3707     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3708 
3709     if (!Frame) {
3710       if (const MaterializeTemporaryExpr *MTE =
3711               dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
3712         assert(MTE->getStorageDuration() == SD_Static &&
3713                "should have a frame for a non-global materialized temporary");
3714 
3715         // Per C++1y [expr.const]p2:
3716         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3717         //   - a [...] glvalue of integral or enumeration type that refers to
3718         //     a non-volatile const object [...]
3719         //   [...]
3720         //   - a [...] glvalue of literal type that refers to a non-volatile
3721         //     object whose lifetime began within the evaluation of e.
3722         //
3723         // C++11 misses the 'began within the evaluation of e' check and
3724         // instead allows all temporaries, including things like:
3725         //   int &&r = 1;
3726         //   int x = ++r;
3727         //   constexpr int k = r;
3728         // Therefore we use the C++14 rules in C++11 too.
3729         //
3730         // Note that temporaries whose lifetimes began while evaluating a
3731         // variable's constructor are not usable while evaluating the
3732         // corresponding destructor, not even if they're of const-qualified
3733         // types.
3734         if (!(BaseType.isConstQualified() &&
3735               BaseType->isIntegralOrEnumerationType()) &&
3736             !lifetimeStartedInEvaluation(Info, LVal.Base)) {
3737           if (!IsAccess)
3738             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3739           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
3740           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3741           return CompleteObject();
3742         }
3743 
3744         BaseVal = MTE->getOrCreateValue(false);
3745         assert(BaseVal && "got reference to unevaluated temporary");
3746       } else {
3747         if (!IsAccess)
3748           return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3749         APValue Val;
3750         LVal.moveInto(Val);
3751         Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
3752             << AK
3753             << Val.getAsString(Info.Ctx,
3754                                Info.Ctx.getLValueReferenceType(LValType));
3755         NoteLValueLocation(Info, LVal.Base);
3756         return CompleteObject();
3757       }
3758     } else {
3759       BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
3760       assert(BaseVal && "missing value for temporary");
3761     }
3762   }
3763 
3764   // In C++14, we can't safely access any mutable state when we might be
3765   // evaluating after an unmodeled side effect.
3766   //
3767   // FIXME: Not all local state is mutable. Allow local constant subobjects
3768   // to be read here (but take care with 'mutable' fields).
3769   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3770        Info.EvalStatus.HasSideEffects) ||
3771       (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth))
3772     return CompleteObject();
3773 
3774   return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
3775 }
3776 
3777 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
3778 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3779 /// glvalue referred to by an entity of reference type.
3780 ///
3781 /// \param Info - Information about the ongoing evaluation.
3782 /// \param Conv - The expression for which we are performing the conversion.
3783 ///               Used for diagnostics.
3784 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3785 ///               case of a non-class type).
3786 /// \param LVal - The glvalue on which we are attempting to perform this action.
3787 /// \param RVal - The produced value will be placed here.
3788 /// \param WantObjectRepresentation - If true, we're looking for the object
3789 ///               representation rather than the value, and in particular,
3790 ///               there is no requirement that the result be fully initialized.
3791 static bool
3792 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
3793                                const LValue &LVal, APValue &RVal,
3794                                bool WantObjectRepresentation = false) {
3795   if (LVal.Designator.Invalid)
3796     return false;
3797 
3798   // Check for special cases where there is no existing APValue to look at.
3799   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3800 
3801   AccessKinds AK =
3802       WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
3803 
3804   if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
3805     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3806       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3807       // initializer until now for such expressions. Such an expression can't be
3808       // an ICE in C, so this only matters for fold.
3809       if (Type.isVolatileQualified()) {
3810         Info.FFDiag(Conv);
3811         return false;
3812       }
3813       APValue Lit;
3814       if (!Evaluate(Lit, Info, CLE->getInitializer()))
3815         return false;
3816       CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
3817       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
3818     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
3819       // Special-case character extraction so we don't have to construct an
3820       // APValue for the whole string.
3821       assert(LVal.Designator.Entries.size() <= 1 &&
3822              "Can only read characters from string literals");
3823       if (LVal.Designator.Entries.empty()) {
3824         // Fail for now for LValue to RValue conversion of an array.
3825         // (This shouldn't show up in C/C++, but it could be triggered by a
3826         // weird EvaluateAsRValue call from a tool.)
3827         Info.FFDiag(Conv);
3828         return false;
3829       }
3830       if (LVal.Designator.isOnePastTheEnd()) {
3831         if (Info.getLangOpts().CPlusPlus11)
3832           Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
3833         else
3834           Info.FFDiag(Conv);
3835         return false;
3836       }
3837       uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
3838       RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
3839       return true;
3840     }
3841   }
3842 
3843   CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
3844   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
3845 }
3846 
3847 /// Perform an assignment of Val to LVal. Takes ownership of Val.
3848 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
3849                              QualType LValType, APValue &Val) {
3850   if (LVal.Designator.Invalid)
3851     return false;
3852 
3853   if (!Info.getLangOpts().CPlusPlus14) {
3854     Info.FFDiag(E);
3855     return false;
3856   }
3857 
3858   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3859   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3860 }
3861 
3862 namespace {
3863 struct CompoundAssignSubobjectHandler {
3864   EvalInfo &Info;
3865   const Expr *E;
3866   QualType PromotedLHSType;
3867   BinaryOperatorKind Opcode;
3868   const APValue &RHS;
3869 
3870   static const AccessKinds AccessKind = AK_Assign;
3871 
3872   typedef bool result_type;
3873 
3874   bool checkConst(QualType QT) {
3875     // Assigning to a const object has undefined behavior.
3876     if (QT.isConstQualified()) {
3877       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3878       return false;
3879     }
3880     return true;
3881   }
3882 
3883   bool failed() { return false; }
3884   bool found(APValue &Subobj, QualType SubobjType) {
3885     switch (Subobj.getKind()) {
3886     case APValue::Int:
3887       return found(Subobj.getInt(), SubobjType);
3888     case APValue::Float:
3889       return found(Subobj.getFloat(), SubobjType);
3890     case APValue::ComplexInt:
3891     case APValue::ComplexFloat:
3892       // FIXME: Implement complex compound assignment.
3893       Info.FFDiag(E);
3894       return false;
3895     case APValue::LValue:
3896       return foundPointer(Subobj, SubobjType);
3897     default:
3898       // FIXME: can this happen?
3899       Info.FFDiag(E);
3900       return false;
3901     }
3902   }
3903   bool found(APSInt &Value, QualType SubobjType) {
3904     if (!checkConst(SubobjType))
3905       return false;
3906 
3907     if (!SubobjType->isIntegerType()) {
3908       // We don't support compound assignment on integer-cast-to-pointer
3909       // values.
3910       Info.FFDiag(E);
3911       return false;
3912     }
3913 
3914     if (RHS.isInt()) {
3915       APSInt LHS =
3916           HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
3917       if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3918         return false;
3919       Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3920       return true;
3921     } else if (RHS.isFloat()) {
3922       APFloat FValue(0.0);
3923       return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
3924                                   FValue) &&
3925              handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
3926              HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
3927                                   Value);
3928     }
3929 
3930     Info.FFDiag(E);
3931     return false;
3932   }
3933   bool found(APFloat &Value, QualType SubobjType) {
3934     return checkConst(SubobjType) &&
3935            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3936                                   Value) &&
3937            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3938            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
3939   }
3940   bool foundPointer(APValue &Subobj, QualType SubobjType) {
3941     if (!checkConst(SubobjType))
3942       return false;
3943 
3944     QualType PointeeType;
3945     if (const PointerType *PT = SubobjType->getAs<PointerType>())
3946       PointeeType = PT->getPointeeType();
3947 
3948     if (PointeeType.isNull() || !RHS.isInt() ||
3949         (Opcode != BO_Add && Opcode != BO_Sub)) {
3950       Info.FFDiag(E);
3951       return false;
3952     }
3953 
3954     APSInt Offset = RHS.getInt();
3955     if (Opcode == BO_Sub)
3956       negateAsSigned(Offset);
3957 
3958     LValue LVal;
3959     LVal.setFrom(Info.Ctx, Subobj);
3960     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3961       return false;
3962     LVal.moveInto(Subobj);
3963     return true;
3964   }
3965 };
3966 } // end anonymous namespace
3967 
3968 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3969 
3970 /// Perform a compound assignment of LVal <op>= RVal.
3971 static bool handleCompoundAssignment(
3972     EvalInfo &Info, const Expr *E,
3973     const LValue &LVal, QualType LValType, QualType PromotedLValType,
3974     BinaryOperatorKind Opcode, const APValue &RVal) {
3975   if (LVal.Designator.Invalid)
3976     return false;
3977 
3978   if (!Info.getLangOpts().CPlusPlus14) {
3979     Info.FFDiag(E);
3980     return false;
3981   }
3982 
3983   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3984   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3985                                              RVal };
3986   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3987 }
3988 
3989 namespace {
3990 struct IncDecSubobjectHandler {
3991   EvalInfo &Info;
3992   const UnaryOperator *E;
3993   AccessKinds AccessKind;
3994   APValue *Old;
3995 
3996   typedef bool result_type;
3997 
3998   bool checkConst(QualType QT) {
3999     // Assigning to a const object has undefined behavior.
4000     if (QT.isConstQualified()) {
4001       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4002       return false;
4003     }
4004     return true;
4005   }
4006 
4007   bool failed() { return false; }
4008   bool found(APValue &Subobj, QualType SubobjType) {
4009     // Stash the old value. Also clear Old, so we don't clobber it later
4010     // if we're post-incrementing a complex.
4011     if (Old) {
4012       *Old = Subobj;
4013       Old = nullptr;
4014     }
4015 
4016     switch (Subobj.getKind()) {
4017     case APValue::Int:
4018       return found(Subobj.getInt(), SubobjType);
4019     case APValue::Float:
4020       return found(Subobj.getFloat(), SubobjType);
4021     case APValue::ComplexInt:
4022       return found(Subobj.getComplexIntReal(),
4023                    SubobjType->castAs<ComplexType>()->getElementType()
4024                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4025     case APValue::ComplexFloat:
4026       return found(Subobj.getComplexFloatReal(),
4027                    SubobjType->castAs<ComplexType>()->getElementType()
4028                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4029     case APValue::LValue:
4030       return foundPointer(Subobj, SubobjType);
4031     default:
4032       // FIXME: can this happen?
4033       Info.FFDiag(E);
4034       return false;
4035     }
4036   }
4037   bool found(APSInt &Value, QualType SubobjType) {
4038     if (!checkConst(SubobjType))
4039       return false;
4040 
4041     if (!SubobjType->isIntegerType()) {
4042       // We don't support increment / decrement on integer-cast-to-pointer
4043       // values.
4044       Info.FFDiag(E);
4045       return false;
4046     }
4047 
4048     if (Old) *Old = APValue(Value);
4049 
4050     // bool arithmetic promotes to int, and the conversion back to bool
4051     // doesn't reduce mod 2^n, so special-case it.
4052     if (SubobjType->isBooleanType()) {
4053       if (AccessKind == AK_Increment)
4054         Value = 1;
4055       else
4056         Value = !Value;
4057       return true;
4058     }
4059 
4060     bool WasNegative = Value.isNegative();
4061     if (AccessKind == AK_Increment) {
4062       ++Value;
4063 
4064       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4065         APSInt ActualValue(Value, /*IsUnsigned*/true);
4066         return HandleOverflow(Info, E, ActualValue, SubobjType);
4067       }
4068     } else {
4069       --Value;
4070 
4071       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4072         unsigned BitWidth = Value.getBitWidth();
4073         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4074         ActualValue.setBit(BitWidth);
4075         return HandleOverflow(Info, E, ActualValue, SubobjType);
4076       }
4077     }
4078     return true;
4079   }
4080   bool found(APFloat &Value, QualType SubobjType) {
4081     if (!checkConst(SubobjType))
4082       return false;
4083 
4084     if (Old) *Old = APValue(Value);
4085 
4086     APFloat One(Value.getSemantics(), 1);
4087     if (AccessKind == AK_Increment)
4088       Value.add(One, APFloat::rmNearestTiesToEven);
4089     else
4090       Value.subtract(One, APFloat::rmNearestTiesToEven);
4091     return true;
4092   }
4093   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4094     if (!checkConst(SubobjType))
4095       return false;
4096 
4097     QualType PointeeType;
4098     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4099       PointeeType = PT->getPointeeType();
4100     else {
4101       Info.FFDiag(E);
4102       return false;
4103     }
4104 
4105     LValue LVal;
4106     LVal.setFrom(Info.Ctx, Subobj);
4107     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4108                                      AccessKind == AK_Increment ? 1 : -1))
4109       return false;
4110     LVal.moveInto(Subobj);
4111     return true;
4112   }
4113 };
4114 } // end anonymous namespace
4115 
4116 /// Perform an increment or decrement on LVal.
4117 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4118                          QualType LValType, bool IsIncrement, APValue *Old) {
4119   if (LVal.Designator.Invalid)
4120     return false;
4121 
4122   if (!Info.getLangOpts().CPlusPlus14) {
4123     Info.FFDiag(E);
4124     return false;
4125   }
4126 
4127   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4128   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4129   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4130   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4131 }
4132 
4133 /// Build an lvalue for the object argument of a member function call.
4134 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4135                                    LValue &This) {
4136   if (Object->getType()->isPointerType() && Object->isRValue())
4137     return EvaluatePointer(Object, This, Info);
4138 
4139   if (Object->isGLValue())
4140     return EvaluateLValue(Object, This, Info);
4141 
4142   if (Object->getType()->isLiteralType(Info.Ctx))
4143     return EvaluateTemporary(Object, This, Info);
4144 
4145   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4146   return false;
4147 }
4148 
4149 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
4150 /// lvalue referring to the result.
4151 ///
4152 /// \param Info - Information about the ongoing evaluation.
4153 /// \param LV - An lvalue referring to the base of the member pointer.
4154 /// \param RHS - The member pointer expression.
4155 /// \param IncludeMember - Specifies whether the member itself is included in
4156 ///        the resulting LValue subobject designator. This is not possible when
4157 ///        creating a bound member function.
4158 /// \return The field or method declaration to which the member pointer refers,
4159 ///         or 0 if evaluation fails.
4160 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4161                                                   QualType LVType,
4162                                                   LValue &LV,
4163                                                   const Expr *RHS,
4164                                                   bool IncludeMember = true) {
4165   MemberPtr MemPtr;
4166   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4167     return nullptr;
4168 
4169   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4170   // member value, the behavior is undefined.
4171   if (!MemPtr.getDecl()) {
4172     // FIXME: Specific diagnostic.
4173     Info.FFDiag(RHS);
4174     return nullptr;
4175   }
4176 
4177   if (MemPtr.isDerivedMember()) {
4178     // This is a member of some derived class. Truncate LV appropriately.
4179     // The end of the derived-to-base path for the base object must match the
4180     // derived-to-base path for the member pointer.
4181     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4182         LV.Designator.Entries.size()) {
4183       Info.FFDiag(RHS);
4184       return nullptr;
4185     }
4186     unsigned PathLengthToMember =
4187         LV.Designator.Entries.size() - MemPtr.Path.size();
4188     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4189       const CXXRecordDecl *LVDecl = getAsBaseClass(
4190           LV.Designator.Entries[PathLengthToMember + I]);
4191       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4192       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4193         Info.FFDiag(RHS);
4194         return nullptr;
4195       }
4196     }
4197 
4198     // Truncate the lvalue to the appropriate derived class.
4199     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4200                             PathLengthToMember))
4201       return nullptr;
4202   } else if (!MemPtr.Path.empty()) {
4203     // Extend the LValue path with the member pointer's path.
4204     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4205                                   MemPtr.Path.size() + IncludeMember);
4206 
4207     // Walk down to the appropriate base class.
4208     if (const PointerType *PT = LVType->getAs<PointerType>())
4209       LVType = PT->getPointeeType();
4210     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4211     assert(RD && "member pointer access on non-class-type expression");
4212     // The first class in the path is that of the lvalue.
4213     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4214       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4215       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4216         return nullptr;
4217       RD = Base;
4218     }
4219     // Finally cast to the class containing the member.
4220     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4221                                 MemPtr.getContainingRecord()))
4222       return nullptr;
4223   }
4224 
4225   // Add the member. Note that we cannot build bound member functions here.
4226   if (IncludeMember) {
4227     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4228       if (!HandleLValueMember(Info, RHS, LV, FD))
4229         return nullptr;
4230     } else if (const IndirectFieldDecl *IFD =
4231                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4232       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4233         return nullptr;
4234     } else {
4235       llvm_unreachable("can't construct reference to bound member function");
4236     }
4237   }
4238 
4239   return MemPtr.getDecl();
4240 }
4241 
4242 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4243                                                   const BinaryOperator *BO,
4244                                                   LValue &LV,
4245                                                   bool IncludeMember = true) {
4246   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4247 
4248   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4249     if (Info.noteFailure()) {
4250       MemberPtr MemPtr;
4251       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4252     }
4253     return nullptr;
4254   }
4255 
4256   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4257                                    BO->getRHS(), IncludeMember);
4258 }
4259 
4260 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4261 /// the provided lvalue, which currently refers to the base object.
4262 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4263                                     LValue &Result) {
4264   SubobjectDesignator &D = Result.Designator;
4265   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4266     return false;
4267 
4268   QualType TargetQT = E->getType();
4269   if (const PointerType *PT = TargetQT->getAs<PointerType>())
4270     TargetQT = PT->getPointeeType();
4271 
4272   // Check this cast lands within the final derived-to-base subobject path.
4273   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4274     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4275       << D.MostDerivedType << TargetQT;
4276     return false;
4277   }
4278 
4279   // Check the type of the final cast. We don't need to check the path,
4280   // since a cast can only be formed if the path is unique.
4281   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4282   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4283   const CXXRecordDecl *FinalType;
4284   if (NewEntriesSize == D.MostDerivedPathLength)
4285     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4286   else
4287     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4288   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4289     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4290       << D.MostDerivedType << TargetQT;
4291     return false;
4292   }
4293 
4294   // Truncate the lvalue to the appropriate derived class.
4295   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4296 }
4297 
4298 /// Get the value to use for a default-initialized object of type T.
4299 static APValue getDefaultInitValue(QualType T) {
4300   if (auto *RD = T->getAsCXXRecordDecl()) {
4301     if (RD->isUnion())
4302       return APValue((const FieldDecl*)nullptr);
4303 
4304     APValue Struct(APValue::UninitStruct(), RD->getNumBases(),
4305                    std::distance(RD->field_begin(), RD->field_end()));
4306 
4307     unsigned Index = 0;
4308     for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4309            End = RD->bases_end(); I != End; ++I, ++Index)
4310       Struct.getStructBase(Index) = getDefaultInitValue(I->getType());
4311 
4312     for (const auto *I : RD->fields()) {
4313       if (I->isUnnamedBitfield())
4314         continue;
4315       Struct.getStructField(I->getFieldIndex()) =
4316           getDefaultInitValue(I->getType());
4317     }
4318     return Struct;
4319   }
4320 
4321   if (auto *AT =
4322           dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4323     APValue Array(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4324     if (Array.hasArrayFiller())
4325       Array.getArrayFiller() = getDefaultInitValue(AT->getElementType());
4326     return Array;
4327   }
4328 
4329   return APValue::IndeterminateValue();
4330 }
4331 
4332 namespace {
4333 enum EvalStmtResult {
4334   /// Evaluation failed.
4335   ESR_Failed,
4336   /// Hit a 'return' statement.
4337   ESR_Returned,
4338   /// Evaluation succeeded.
4339   ESR_Succeeded,
4340   /// Hit a 'continue' statement.
4341   ESR_Continue,
4342   /// Hit a 'break' statement.
4343   ESR_Break,
4344   /// Still scanning for 'case' or 'default' statement.
4345   ESR_CaseNotFound
4346 };
4347 }
4348 
4349 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4350   // We don't need to evaluate the initializer for a static local.
4351   if (!VD->hasLocalStorage())
4352     return true;
4353 
4354   LValue Result;
4355   APValue &Val =
4356       Info.CurrentCall->createTemporary(VD, VD->getType(), true, Result);
4357 
4358   const Expr *InitE = VD->getInit();
4359   if (!InitE) {
4360     Val = getDefaultInitValue(VD->getType());
4361     return true;
4362   }
4363 
4364   if (InitE->isValueDependent())
4365     return false;
4366 
4367   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4368     // Wipe out any partially-computed value, to allow tracking that this
4369     // evaluation failed.
4370     Val = APValue();
4371     return false;
4372   }
4373 
4374   return true;
4375 }
4376 
4377 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4378   bool OK = true;
4379 
4380   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4381     OK &= EvaluateVarDecl(Info, VD);
4382 
4383   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4384     for (auto *BD : DD->bindings())
4385       if (auto *VD = BD->getHoldingVar())
4386         OK &= EvaluateDecl(Info, VD);
4387 
4388   return OK;
4389 }
4390 
4391 
4392 /// Evaluate a condition (either a variable declaration or an expression).
4393 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4394                          const Expr *Cond, bool &Result) {
4395   FullExpressionRAII Scope(Info);
4396   if (CondDecl && !EvaluateDecl(Info, CondDecl))
4397     return false;
4398   if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4399     return false;
4400   return Scope.destroy();
4401 }
4402 
4403 namespace {
4404 /// A location where the result (returned value) of evaluating a
4405 /// statement should be stored.
4406 struct StmtResult {
4407   /// The APValue that should be filled in with the returned value.
4408   APValue &Value;
4409   /// The location containing the result, if any (used to support RVO).
4410   const LValue *Slot;
4411 };
4412 
4413 struct TempVersionRAII {
4414   CallStackFrame &Frame;
4415 
4416   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4417     Frame.pushTempVersion();
4418   }
4419 
4420   ~TempVersionRAII() {
4421     Frame.popTempVersion();
4422   }
4423 };
4424 
4425 }
4426 
4427 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4428                                    const Stmt *S,
4429                                    const SwitchCase *SC = nullptr);
4430 
4431 /// Evaluate the body of a loop, and translate the result as appropriate.
4432 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4433                                        const Stmt *Body,
4434                                        const SwitchCase *Case = nullptr) {
4435   BlockScopeRAII Scope(Info);
4436 
4437   EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4438   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4439     ESR = ESR_Failed;
4440 
4441   switch (ESR) {
4442   case ESR_Break:
4443     return ESR_Succeeded;
4444   case ESR_Succeeded:
4445   case ESR_Continue:
4446     return ESR_Continue;
4447   case ESR_Failed:
4448   case ESR_Returned:
4449   case ESR_CaseNotFound:
4450     return ESR;
4451   }
4452   llvm_unreachable("Invalid EvalStmtResult!");
4453 }
4454 
4455 /// Evaluate a switch statement.
4456 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4457                                      const SwitchStmt *SS) {
4458   BlockScopeRAII Scope(Info);
4459 
4460   // Evaluate the switch condition.
4461   APSInt Value;
4462   {
4463     if (const Stmt *Init = SS->getInit()) {
4464       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4465       if (ESR != ESR_Succeeded) {
4466         if (ESR != ESR_Failed && !Scope.destroy())
4467           ESR = ESR_Failed;
4468         return ESR;
4469       }
4470     }
4471 
4472     FullExpressionRAII CondScope(Info);
4473     if (SS->getConditionVariable() &&
4474         !EvaluateDecl(Info, SS->getConditionVariable()))
4475       return ESR_Failed;
4476     if (!EvaluateInteger(SS->getCond(), Value, Info))
4477       return ESR_Failed;
4478     if (!CondScope.destroy())
4479       return ESR_Failed;
4480   }
4481 
4482   // Find the switch case corresponding to the value of the condition.
4483   // FIXME: Cache this lookup.
4484   const SwitchCase *Found = nullptr;
4485   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4486        SC = SC->getNextSwitchCase()) {
4487     if (isa<DefaultStmt>(SC)) {
4488       Found = SC;
4489       continue;
4490     }
4491 
4492     const CaseStmt *CS = cast<CaseStmt>(SC);
4493     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4494     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4495                               : LHS;
4496     if (LHS <= Value && Value <= RHS) {
4497       Found = SC;
4498       break;
4499     }
4500   }
4501 
4502   if (!Found)
4503     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4504 
4505   // Search the switch body for the switch case and evaluate it from there.
4506   EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
4507   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4508     return ESR_Failed;
4509 
4510   switch (ESR) {
4511   case ESR_Break:
4512     return ESR_Succeeded;
4513   case ESR_Succeeded:
4514   case ESR_Continue:
4515   case ESR_Failed:
4516   case ESR_Returned:
4517     return ESR;
4518   case ESR_CaseNotFound:
4519     // This can only happen if the switch case is nested within a statement
4520     // expression. We have no intention of supporting that.
4521     Info.FFDiag(Found->getBeginLoc(),
4522                 diag::note_constexpr_stmt_expr_unsupported);
4523     return ESR_Failed;
4524   }
4525   llvm_unreachable("Invalid EvalStmtResult!");
4526 }
4527 
4528 // Evaluate a statement.
4529 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4530                                    const Stmt *S, const SwitchCase *Case) {
4531   if (!Info.nextStep(S))
4532     return ESR_Failed;
4533 
4534   // If we're hunting down a 'case' or 'default' label, recurse through
4535   // substatements until we hit the label.
4536   if (Case) {
4537     switch (S->getStmtClass()) {
4538     case Stmt::CompoundStmtClass:
4539       // FIXME: Precompute which substatement of a compound statement we
4540       // would jump to, and go straight there rather than performing a
4541       // linear scan each time.
4542     case Stmt::LabelStmtClass:
4543     case Stmt::AttributedStmtClass:
4544     case Stmt::DoStmtClass:
4545       break;
4546 
4547     case Stmt::CaseStmtClass:
4548     case Stmt::DefaultStmtClass:
4549       if (Case == S)
4550         Case = nullptr;
4551       break;
4552 
4553     case Stmt::IfStmtClass: {
4554       // FIXME: Precompute which side of an 'if' we would jump to, and go
4555       // straight there rather than scanning both sides.
4556       const IfStmt *IS = cast<IfStmt>(S);
4557 
4558       // Wrap the evaluation in a block scope, in case it's a DeclStmt
4559       // preceded by our switch label.
4560       BlockScopeRAII Scope(Info);
4561 
4562       // Step into the init statement in case it brings an (uninitialized)
4563       // variable into scope.
4564       if (const Stmt *Init = IS->getInit()) {
4565         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
4566         if (ESR != ESR_CaseNotFound) {
4567           assert(ESR != ESR_Succeeded);
4568           return ESR;
4569         }
4570       }
4571 
4572       // Condition variable must be initialized if it exists.
4573       // FIXME: We can skip evaluating the body if there's a condition
4574       // variable, as there can't be any case labels within it.
4575       // (The same is true for 'for' statements.)
4576 
4577       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
4578       if (ESR == ESR_Failed)
4579         return ESR;
4580       if (ESR != ESR_CaseNotFound)
4581         return Scope.destroy() ? ESR : ESR_Failed;
4582       if (!IS->getElse())
4583         return ESR_CaseNotFound;
4584 
4585       ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
4586       if (ESR == ESR_Failed)
4587         return ESR;
4588       if (ESR != ESR_CaseNotFound)
4589         return Scope.destroy() ? ESR : ESR_Failed;
4590       return ESR_CaseNotFound;
4591     }
4592 
4593     case Stmt::WhileStmtClass: {
4594       EvalStmtResult ESR =
4595           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4596       if (ESR != ESR_Continue)
4597         return ESR;
4598       break;
4599     }
4600 
4601     case Stmt::ForStmtClass: {
4602       const ForStmt *FS = cast<ForStmt>(S);
4603       BlockScopeRAII Scope(Info);
4604 
4605       // Step into the init statement in case it brings an (uninitialized)
4606       // variable into scope.
4607       if (const Stmt *Init = FS->getInit()) {
4608         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
4609         if (ESR != ESR_CaseNotFound) {
4610           assert(ESR != ESR_Succeeded);
4611           return ESR;
4612         }
4613       }
4614 
4615       EvalStmtResult ESR =
4616           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4617       if (ESR != ESR_Continue)
4618         return ESR;
4619       if (FS->getInc()) {
4620         FullExpressionRAII IncScope(Info);
4621         if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
4622           return ESR_Failed;
4623       }
4624       break;
4625     }
4626 
4627     case Stmt::DeclStmtClass: {
4628       // Start the lifetime of any uninitialized variables we encounter. They
4629       // might be used by the selected branch of the switch.
4630       const DeclStmt *DS = cast<DeclStmt>(S);
4631       for (const auto *D : DS->decls()) {
4632         if (const auto *VD = dyn_cast<VarDecl>(D)) {
4633           if (VD->hasLocalStorage() && !VD->getInit())
4634             if (!EvaluateVarDecl(Info, VD))
4635               return ESR_Failed;
4636           // FIXME: If the variable has initialization that can't be jumped
4637           // over, bail out of any immediately-surrounding compound-statement
4638           // too. There can't be any case labels here.
4639         }
4640       }
4641       return ESR_CaseNotFound;
4642     }
4643 
4644     default:
4645       return ESR_CaseNotFound;
4646     }
4647   }
4648 
4649   switch (S->getStmtClass()) {
4650   default:
4651     if (const Expr *E = dyn_cast<Expr>(S)) {
4652       // Don't bother evaluating beyond an expression-statement which couldn't
4653       // be evaluated.
4654       // FIXME: Do we need the FullExpressionRAII object here?
4655       // VisitExprWithCleanups should create one when necessary.
4656       FullExpressionRAII Scope(Info);
4657       if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
4658         return ESR_Failed;
4659       return ESR_Succeeded;
4660     }
4661 
4662     Info.FFDiag(S->getBeginLoc());
4663     return ESR_Failed;
4664 
4665   case Stmt::NullStmtClass:
4666     return ESR_Succeeded;
4667 
4668   case Stmt::DeclStmtClass: {
4669     const DeclStmt *DS = cast<DeclStmt>(S);
4670     for (const auto *D : DS->decls()) {
4671       // Each declaration initialization is its own full-expression.
4672       FullExpressionRAII Scope(Info);
4673       if (!EvaluateDecl(Info, D) && !Info.noteFailure())
4674         return ESR_Failed;
4675       if (!Scope.destroy())
4676         return ESR_Failed;
4677     }
4678     return ESR_Succeeded;
4679   }
4680 
4681   case Stmt::ReturnStmtClass: {
4682     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
4683     FullExpressionRAII Scope(Info);
4684     if (RetExpr &&
4685         !(Result.Slot
4686               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4687               : Evaluate(Result.Value, Info, RetExpr)))
4688       return ESR_Failed;
4689     return Scope.destroy() ? ESR_Returned : ESR_Failed;
4690   }
4691 
4692   case Stmt::CompoundStmtClass: {
4693     BlockScopeRAII Scope(Info);
4694 
4695     const CompoundStmt *CS = cast<CompoundStmt>(S);
4696     for (const auto *BI : CS->body()) {
4697       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
4698       if (ESR == ESR_Succeeded)
4699         Case = nullptr;
4700       else if (ESR != ESR_CaseNotFound) {
4701         if (ESR != ESR_Failed && !Scope.destroy())
4702           return ESR_Failed;
4703         return ESR;
4704       }
4705     }
4706     if (Case)
4707       return ESR_CaseNotFound;
4708     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4709   }
4710 
4711   case Stmt::IfStmtClass: {
4712     const IfStmt *IS = cast<IfStmt>(S);
4713 
4714     // Evaluate the condition, as either a var decl or as an expression.
4715     BlockScopeRAII Scope(Info);
4716     if (const Stmt *Init = IS->getInit()) {
4717       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4718       if (ESR != ESR_Succeeded) {
4719         if (ESR != ESR_Failed && !Scope.destroy())
4720           return ESR_Failed;
4721         return ESR;
4722       }
4723     }
4724     bool Cond;
4725     if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
4726       return ESR_Failed;
4727 
4728     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4729       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4730       if (ESR != ESR_Succeeded) {
4731         if (ESR != ESR_Failed && !Scope.destroy())
4732           return ESR_Failed;
4733         return ESR;
4734       }
4735     }
4736     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4737   }
4738 
4739   case Stmt::WhileStmtClass: {
4740     const WhileStmt *WS = cast<WhileStmt>(S);
4741     while (true) {
4742       BlockScopeRAII Scope(Info);
4743       bool Continue;
4744       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4745                         Continue))
4746         return ESR_Failed;
4747       if (!Continue)
4748         break;
4749 
4750       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4751       if (ESR != ESR_Continue) {
4752         if (ESR != ESR_Failed && !Scope.destroy())
4753           return ESR_Failed;
4754         return ESR;
4755       }
4756       if (!Scope.destroy())
4757         return ESR_Failed;
4758     }
4759     return ESR_Succeeded;
4760   }
4761 
4762   case Stmt::DoStmtClass: {
4763     const DoStmt *DS = cast<DoStmt>(S);
4764     bool Continue;
4765     do {
4766       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
4767       if (ESR != ESR_Continue)
4768         return ESR;
4769       Case = nullptr;
4770 
4771       FullExpressionRAII CondScope(Info);
4772       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
4773           !CondScope.destroy())
4774         return ESR_Failed;
4775     } while (Continue);
4776     return ESR_Succeeded;
4777   }
4778 
4779   case Stmt::ForStmtClass: {
4780     const ForStmt *FS = cast<ForStmt>(S);
4781     BlockScopeRAII ForScope(Info);
4782     if (FS->getInit()) {
4783       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4784       if (ESR != ESR_Succeeded) {
4785         if (ESR != ESR_Failed && !ForScope.destroy())
4786           return ESR_Failed;
4787         return ESR;
4788       }
4789     }
4790     while (true) {
4791       BlockScopeRAII IterScope(Info);
4792       bool Continue = true;
4793       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4794                                          FS->getCond(), Continue))
4795         return ESR_Failed;
4796       if (!Continue)
4797         break;
4798 
4799       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4800       if (ESR != ESR_Continue) {
4801         if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
4802           return ESR_Failed;
4803         return ESR;
4804       }
4805 
4806       if (FS->getInc()) {
4807         FullExpressionRAII IncScope(Info);
4808         if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
4809           return ESR_Failed;
4810       }
4811 
4812       if (!IterScope.destroy())
4813         return ESR_Failed;
4814     }
4815     return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
4816   }
4817 
4818   case Stmt::CXXForRangeStmtClass: {
4819     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
4820     BlockScopeRAII Scope(Info);
4821 
4822     // Evaluate the init-statement if present.
4823     if (FS->getInit()) {
4824       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4825       if (ESR != ESR_Succeeded) {
4826         if (ESR != ESR_Failed && !Scope.destroy())
4827           return ESR_Failed;
4828         return ESR;
4829       }
4830     }
4831 
4832     // Initialize the __range variable.
4833     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4834     if (ESR != ESR_Succeeded) {
4835       if (ESR != ESR_Failed && !Scope.destroy())
4836         return ESR_Failed;
4837       return ESR;
4838     }
4839 
4840     // Create the __begin and __end iterators.
4841     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4842     if (ESR != ESR_Succeeded) {
4843       if (ESR != ESR_Failed && !Scope.destroy())
4844         return ESR_Failed;
4845       return ESR;
4846     }
4847     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
4848     if (ESR != ESR_Succeeded) {
4849       if (ESR != ESR_Failed && !Scope.destroy())
4850         return ESR_Failed;
4851       return ESR;
4852     }
4853 
4854     while (true) {
4855       // Condition: __begin != __end.
4856       {
4857         bool Continue = true;
4858         FullExpressionRAII CondExpr(Info);
4859         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4860           return ESR_Failed;
4861         if (!Continue)
4862           break;
4863       }
4864 
4865       // User's variable declaration, initialized by *__begin.
4866       BlockScopeRAII InnerScope(Info);
4867       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4868       if (ESR != ESR_Succeeded) {
4869         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
4870           return ESR_Failed;
4871         return ESR;
4872       }
4873 
4874       // Loop body.
4875       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4876       if (ESR != ESR_Continue) {
4877         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
4878           return ESR_Failed;
4879         return ESR;
4880       }
4881 
4882       // Increment: ++__begin
4883       if (!EvaluateIgnoredValue(Info, FS->getInc()))
4884         return ESR_Failed;
4885 
4886       if (!InnerScope.destroy())
4887         return ESR_Failed;
4888     }
4889 
4890     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4891   }
4892 
4893   case Stmt::SwitchStmtClass:
4894     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4895 
4896   case Stmt::ContinueStmtClass:
4897     return ESR_Continue;
4898 
4899   case Stmt::BreakStmtClass:
4900     return ESR_Break;
4901 
4902   case Stmt::LabelStmtClass:
4903     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4904 
4905   case Stmt::AttributedStmtClass:
4906     // As a general principle, C++11 attributes can be ignored without
4907     // any semantic impact.
4908     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4909                         Case);
4910 
4911   case Stmt::CaseStmtClass:
4912   case Stmt::DefaultStmtClass:
4913     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
4914   case Stmt::CXXTryStmtClass:
4915     // Evaluate try blocks by evaluating all sub statements.
4916     return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
4917   }
4918 }
4919 
4920 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4921 /// default constructor. If so, we'll fold it whether or not it's marked as
4922 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
4923 /// so we need special handling.
4924 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
4925                                            const CXXConstructorDecl *CD,
4926                                            bool IsValueInitialization) {
4927   if (!CD->isTrivial() || !CD->isDefaultConstructor())
4928     return false;
4929 
4930   // Value-initialization does not call a trivial default constructor, so such a
4931   // call is a core constant expression whether or not the constructor is
4932   // constexpr.
4933   if (!CD->isConstexpr() && !IsValueInitialization) {
4934     if (Info.getLangOpts().CPlusPlus11) {
4935       // FIXME: If DiagDecl is an implicitly-declared special member function,
4936       // we should be much more explicit about why it's not constexpr.
4937       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4938         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4939       Info.Note(CD->getLocation(), diag::note_declared_at);
4940     } else {
4941       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4942     }
4943   }
4944   return true;
4945 }
4946 
4947 /// CheckConstexprFunction - Check that a function can be called in a constant
4948 /// expression.
4949 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4950                                    const FunctionDecl *Declaration,
4951                                    const FunctionDecl *Definition,
4952                                    const Stmt *Body) {
4953   // Potential constant expressions can contain calls to declared, but not yet
4954   // defined, constexpr functions.
4955   if (Info.checkingPotentialConstantExpression() && !Definition &&
4956       Declaration->isConstexpr())
4957     return false;
4958 
4959   // Bail out if the function declaration itself is invalid.  We will
4960   // have produced a relevant diagnostic while parsing it, so just
4961   // note the problematic sub-expression.
4962   if (Declaration->isInvalidDecl()) {
4963     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4964     return false;
4965   }
4966 
4967   // DR1872: An instantiated virtual constexpr function can't be called in a
4968   // constant expression (prior to C++20). We can still constant-fold such a
4969   // call.
4970   if (!Info.Ctx.getLangOpts().CPlusPlus2a && isa<CXXMethodDecl>(Declaration) &&
4971       cast<CXXMethodDecl>(Declaration)->isVirtual())
4972     Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
4973 
4974   if (Definition && Definition->isInvalidDecl()) {
4975     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4976     return false;
4977   }
4978 
4979   // Can we evaluate this function call?
4980   if (Definition && Definition->isConstexpr() && Body)
4981     return true;
4982 
4983   if (Info.getLangOpts().CPlusPlus11) {
4984     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
4985 
4986     // If this function is not constexpr because it is an inherited
4987     // non-constexpr constructor, diagnose that directly.
4988     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4989     if (CD && CD->isInheritingConstructor()) {
4990       auto *Inherited = CD->getInheritedConstructor().getConstructor();
4991       if (!Inherited->isConstexpr())
4992         DiagDecl = CD = Inherited;
4993     }
4994 
4995     // FIXME: If DiagDecl is an implicitly-declared special member function
4996     // or an inheriting constructor, we should be much more explicit about why
4997     // it's not constexpr.
4998     if (CD && CD->isInheritingConstructor())
4999       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5000         << CD->getInheritedConstructor().getConstructor()->getParent();
5001     else
5002       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5003         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5004     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5005   } else {
5006     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5007   }
5008   return false;
5009 }
5010 
5011 namespace {
5012 struct CheckDynamicTypeHandler {
5013   AccessKinds AccessKind;
5014   typedef bool result_type;
5015   bool failed() { return false; }
5016   bool found(APValue &Subobj, QualType SubobjType) { return true; }
5017   bool found(APSInt &Value, QualType SubobjType) { return true; }
5018   bool found(APFloat &Value, QualType SubobjType) { return true; }
5019 };
5020 } // end anonymous namespace
5021 
5022 /// Check that we can access the notional vptr of an object / determine its
5023 /// dynamic type.
5024 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5025                              AccessKinds AK, bool Polymorphic) {
5026   if (This.Designator.Invalid)
5027     return false;
5028 
5029   CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5030 
5031   if (!Obj)
5032     return false;
5033 
5034   if (!Obj.Value) {
5035     // The object is not usable in constant expressions, so we can't inspect
5036     // its value to see if it's in-lifetime or what the active union members
5037     // are. We can still check for a one-past-the-end lvalue.
5038     if (This.Designator.isOnePastTheEnd() ||
5039         This.Designator.isMostDerivedAnUnsizedArray()) {
5040       Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5041                          ? diag::note_constexpr_access_past_end
5042                          : diag::note_constexpr_access_unsized_array)
5043           << AK;
5044       return false;
5045     } else if (Polymorphic) {
5046       // Conservatively refuse to perform a polymorphic operation if we would
5047       // not be able to read a notional 'vptr' value.
5048       APValue Val;
5049       This.moveInto(Val);
5050       QualType StarThisType =
5051           Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5052       Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5053           << AK << Val.getAsString(Info.Ctx, StarThisType);
5054       return false;
5055     }
5056     return true;
5057   }
5058 
5059   CheckDynamicTypeHandler Handler{AK};
5060   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5061 }
5062 
5063 /// Check that the pointee of the 'this' pointer in a member function call is
5064 /// either within its lifetime or in its period of construction or destruction.
5065 static bool
5066 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5067                                      const LValue &This,
5068                                      const CXXMethodDecl *NamedMember) {
5069   return checkDynamicType(
5070       Info, E, This,
5071       isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5072 }
5073 
5074 struct DynamicType {
5075   /// The dynamic class type of the object.
5076   const CXXRecordDecl *Type;
5077   /// The corresponding path length in the lvalue.
5078   unsigned PathLength;
5079 };
5080 
5081 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5082                                              unsigned PathLength) {
5083   assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5084       Designator.Entries.size() && "invalid path length");
5085   return (PathLength == Designator.MostDerivedPathLength)
5086              ? Designator.MostDerivedType->getAsCXXRecordDecl()
5087              : getAsBaseClass(Designator.Entries[PathLength - 1]);
5088 }
5089 
5090 /// Determine the dynamic type of an object.
5091 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
5092                                                 LValue &This, AccessKinds AK) {
5093   // If we don't have an lvalue denoting an object of class type, there is no
5094   // meaningful dynamic type. (We consider objects of non-class type to have no
5095   // dynamic type.)
5096   if (!checkDynamicType(Info, E, This, AK, true))
5097     return None;
5098 
5099   // Refuse to compute a dynamic type in the presence of virtual bases. This
5100   // shouldn't happen other than in constant-folding situations, since literal
5101   // types can't have virtual bases.
5102   //
5103   // Note that consumers of DynamicType assume that the type has no virtual
5104   // bases, and will need modifications if this restriction is relaxed.
5105   const CXXRecordDecl *Class =
5106       This.Designator.MostDerivedType->getAsCXXRecordDecl();
5107   if (!Class || Class->getNumVBases()) {
5108     Info.FFDiag(E);
5109     return None;
5110   }
5111 
5112   // FIXME: For very deep class hierarchies, it might be beneficial to use a
5113   // binary search here instead. But the overwhelmingly common case is that
5114   // we're not in the middle of a constructor, so it probably doesn't matter
5115   // in practice.
5116   ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5117   for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5118        PathLength <= Path.size(); ++PathLength) {
5119     switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5120                                       Path.slice(0, PathLength))) {
5121     case ConstructionPhase::Bases:
5122     case ConstructionPhase::DestroyingBases:
5123       // We're constructing or destroying a base class. This is not the dynamic
5124       // type.
5125       break;
5126 
5127     case ConstructionPhase::None:
5128     case ConstructionPhase::AfterBases:
5129     case ConstructionPhase::AfterFields:
5130     case ConstructionPhase::Destroying:
5131       // We've finished constructing the base classes and not yet started
5132       // destroying them again, so this is the dynamic type.
5133       return DynamicType{getBaseClassType(This.Designator, PathLength),
5134                          PathLength};
5135     }
5136   }
5137 
5138   // CWG issue 1517: we're constructing a base class of the object described by
5139   // 'This', so that object has not yet begun its period of construction and
5140   // any polymorphic operation on it results in undefined behavior.
5141   Info.FFDiag(E);
5142   return None;
5143 }
5144 
5145 /// Perform virtual dispatch.
5146 static const CXXMethodDecl *HandleVirtualDispatch(
5147     EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5148     llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5149   Optional<DynamicType> DynType = ComputeDynamicType(
5150       Info, E, This,
5151       isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5152   if (!DynType)
5153     return nullptr;
5154 
5155   // Find the final overrider. It must be declared in one of the classes on the
5156   // path from the dynamic type to the static type.
5157   // FIXME: If we ever allow literal types to have virtual base classes, that
5158   // won't be true.
5159   const CXXMethodDecl *Callee = Found;
5160   unsigned PathLength = DynType->PathLength;
5161   for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5162     const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5163     const CXXMethodDecl *Overrider =
5164         Found->getCorrespondingMethodDeclaredInClass(Class, false);
5165     if (Overrider) {
5166       Callee = Overrider;
5167       break;
5168     }
5169   }
5170 
5171   // C++2a [class.abstract]p6:
5172   //   the effect of making a virtual call to a pure virtual function [...] is
5173   //   undefined
5174   if (Callee->isPure()) {
5175     Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5176     Info.Note(Callee->getLocation(), diag::note_declared_at);
5177     return nullptr;
5178   }
5179 
5180   // If necessary, walk the rest of the path to determine the sequence of
5181   // covariant adjustment steps to apply.
5182   if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5183                                        Found->getReturnType())) {
5184     CovariantAdjustmentPath.push_back(Callee->getReturnType());
5185     for (unsigned CovariantPathLength = PathLength + 1;
5186          CovariantPathLength != This.Designator.Entries.size();
5187          ++CovariantPathLength) {
5188       const CXXRecordDecl *NextClass =
5189           getBaseClassType(This.Designator, CovariantPathLength);
5190       const CXXMethodDecl *Next =
5191           Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5192       if (Next && !Info.Ctx.hasSameUnqualifiedType(
5193                       Next->getReturnType(), CovariantAdjustmentPath.back()))
5194         CovariantAdjustmentPath.push_back(Next->getReturnType());
5195     }
5196     if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5197                                          CovariantAdjustmentPath.back()))
5198       CovariantAdjustmentPath.push_back(Found->getReturnType());
5199   }
5200 
5201   // Perform 'this' adjustment.
5202   if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5203     return nullptr;
5204 
5205   return Callee;
5206 }
5207 
5208 /// Perform the adjustment from a value returned by a virtual function to
5209 /// a value of the statically expected type, which may be a pointer or
5210 /// reference to a base class of the returned type.
5211 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5212                                             APValue &Result,
5213                                             ArrayRef<QualType> Path) {
5214   assert(Result.isLValue() &&
5215          "unexpected kind of APValue for covariant return");
5216   if (Result.isNullPointer())
5217     return true;
5218 
5219   LValue LVal;
5220   LVal.setFrom(Info.Ctx, Result);
5221 
5222   const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5223   for (unsigned I = 1; I != Path.size(); ++I) {
5224     const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5225     assert(OldClass && NewClass && "unexpected kind of covariant return");
5226     if (OldClass != NewClass &&
5227         !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5228       return false;
5229     OldClass = NewClass;
5230   }
5231 
5232   LVal.moveInto(Result);
5233   return true;
5234 }
5235 
5236 /// Determine whether \p Base, which is known to be a direct base class of
5237 /// \p Derived, is a public base class.
5238 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5239                               const CXXRecordDecl *Base) {
5240   for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5241     auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5242     if (BaseClass && declaresSameEntity(BaseClass, Base))
5243       return BaseSpec.getAccessSpecifier() == AS_public;
5244   }
5245   llvm_unreachable("Base is not a direct base of Derived");
5246 }
5247 
5248 /// Apply the given dynamic cast operation on the provided lvalue.
5249 ///
5250 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
5251 /// to find a suitable target subobject.
5252 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5253                               LValue &Ptr) {
5254   // We can't do anything with a non-symbolic pointer value.
5255   SubobjectDesignator &D = Ptr.Designator;
5256   if (D.Invalid)
5257     return false;
5258 
5259   // C++ [expr.dynamic.cast]p6:
5260   //   If v is a null pointer value, the result is a null pointer value.
5261   if (Ptr.isNullPointer() && !E->isGLValue())
5262     return true;
5263 
5264   // For all the other cases, we need the pointer to point to an object within
5265   // its lifetime / period of construction / destruction, and we need to know
5266   // its dynamic type.
5267   Optional<DynamicType> DynType =
5268       ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5269   if (!DynType)
5270     return false;
5271 
5272   // C++ [expr.dynamic.cast]p7:
5273   //   If T is "pointer to cv void", then the result is a pointer to the most
5274   //   derived object
5275   if (E->getType()->isVoidPointerType())
5276     return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5277 
5278   const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5279   assert(C && "dynamic_cast target is not void pointer nor class");
5280   CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5281 
5282   auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5283     // C++ [expr.dynamic.cast]p9:
5284     if (!E->isGLValue()) {
5285       //   The value of a failed cast to pointer type is the null pointer value
5286       //   of the required result type.
5287       Ptr.setNull(Info.Ctx, E->getType());
5288       return true;
5289     }
5290 
5291     //   A failed cast to reference type throws [...] std::bad_cast.
5292     unsigned DiagKind;
5293     if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5294                    DynType->Type->isDerivedFrom(C)))
5295       DiagKind = 0;
5296     else if (!Paths || Paths->begin() == Paths->end())
5297       DiagKind = 1;
5298     else if (Paths->isAmbiguous(CQT))
5299       DiagKind = 2;
5300     else {
5301       assert(Paths->front().Access != AS_public && "why did the cast fail?");
5302       DiagKind = 3;
5303     }
5304     Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5305         << DiagKind << Ptr.Designator.getType(Info.Ctx)
5306         << Info.Ctx.getRecordType(DynType->Type)
5307         << E->getType().getUnqualifiedType();
5308     return false;
5309   };
5310 
5311   // Runtime check, phase 1:
5312   //   Walk from the base subobject towards the derived object looking for the
5313   //   target type.
5314   for (int PathLength = Ptr.Designator.Entries.size();
5315        PathLength >= (int)DynType->PathLength; --PathLength) {
5316     const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5317     if (declaresSameEntity(Class, C))
5318       return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5319     // We can only walk across public inheritance edges.
5320     if (PathLength > (int)DynType->PathLength &&
5321         !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5322                            Class))
5323       return RuntimeCheckFailed(nullptr);
5324   }
5325 
5326   // Runtime check, phase 2:
5327   //   Search the dynamic type for an unambiguous public base of type C.
5328   CXXBasePaths Paths(/*FindAmbiguities=*/true,
5329                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
5330   if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5331       Paths.front().Access == AS_public) {
5332     // Downcast to the dynamic type...
5333     if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5334       return false;
5335     // ... then upcast to the chosen base class subobject.
5336     for (CXXBasePathElement &Elem : Paths.front())
5337       if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5338         return false;
5339     return true;
5340   }
5341 
5342   // Otherwise, the runtime check fails.
5343   return RuntimeCheckFailed(&Paths);
5344 }
5345 
5346 namespace {
5347 struct StartLifetimeOfUnionMemberHandler {
5348   EvalInfo &Info;
5349   const Expr *LHSExpr;
5350   const FieldDecl *Field;
5351   bool DuringInit;
5352 
5353   static const AccessKinds AccessKind = AK_Assign;
5354 
5355   typedef bool result_type;
5356   bool failed() { return false; }
5357   bool found(APValue &Subobj, QualType SubobjType) {
5358     // We are supposed to perform no initialization but begin the lifetime of
5359     // the object. We interpret that as meaning to do what default
5360     // initialization of the object would do if all constructors involved were
5361     // trivial:
5362     //  * All base, non-variant member, and array element subobjects' lifetimes
5363     //    begin
5364     //  * No variant members' lifetimes begin
5365     //  * All scalar subobjects whose lifetimes begin have indeterminate values
5366     assert(SubobjType->isUnionType());
5367     if (declaresSameEntity(Subobj.getUnionField(), Field)) {
5368       // This union member is already active. If it's also in-lifetime, there's
5369       // nothing to do.
5370       if (Subobj.getUnionValue().hasValue())
5371         return true;
5372     } else if (DuringInit) {
5373       // We're currently in the process of initializing a different union
5374       // member.  If we carried on, that initialization would attempt to
5375       // store to an inactive union member, resulting in undefined behavior.
5376       Info.FFDiag(LHSExpr,
5377                   diag::note_constexpr_union_member_change_during_init);
5378       return false;
5379     }
5380 
5381     Subobj.setUnion(Field, getDefaultInitValue(Field->getType()));
5382     return true;
5383   }
5384   bool found(APSInt &Value, QualType SubobjType) {
5385     llvm_unreachable("wrong value kind for union object");
5386   }
5387   bool found(APFloat &Value, QualType SubobjType) {
5388     llvm_unreachable("wrong value kind for union object");
5389   }
5390 };
5391 } // end anonymous namespace
5392 
5393 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5394 
5395 /// Handle a builtin simple-assignment or a call to a trivial assignment
5396 /// operator whose left-hand side might involve a union member access. If it
5397 /// does, implicitly start the lifetime of any accessed union elements per
5398 /// C++20 [class.union]5.
5399 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5400                                           const LValue &LHS) {
5401   if (LHS.InvalidBase || LHS.Designator.Invalid)
5402     return false;
5403 
5404   llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5405   // C++ [class.union]p5:
5406   //   define the set S(E) of subexpressions of E as follows:
5407   unsigned PathLength = LHS.Designator.Entries.size();
5408   for (const Expr *E = LHSExpr; E != nullptr;) {
5409     //   -- If E is of the form A.B, S(E) contains the elements of S(A)...
5410     if (auto *ME = dyn_cast<MemberExpr>(E)) {
5411       auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5412       // Note that we can't implicitly start the lifetime of a reference,
5413       // so we don't need to proceed any further if we reach one.
5414       if (!FD || FD->getType()->isReferenceType())
5415         break;
5416 
5417       //    ... and also contains A.B if B names a union member ...
5418       if (FD->getParent()->isUnion()) {
5419         //    ... of a non-class, non-array type, or of a class type with a
5420         //    trivial default constructor that is not deleted, or an array of
5421         //    such types.
5422         auto *RD =
5423             FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5424         if (!RD || RD->hasTrivialDefaultConstructor())
5425           UnionPathLengths.push_back({PathLength - 1, FD});
5426       }
5427 
5428       E = ME->getBase();
5429       --PathLength;
5430       assert(declaresSameEntity(FD,
5431                                 LHS.Designator.Entries[PathLength]
5432                                     .getAsBaseOrMember().getPointer()));
5433 
5434       //   -- If E is of the form A[B] and is interpreted as a built-in array
5435       //      subscripting operator, S(E) is [S(the array operand, if any)].
5436     } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5437       // Step over an ArrayToPointerDecay implicit cast.
5438       auto *Base = ASE->getBase()->IgnoreImplicit();
5439       if (!Base->getType()->isArrayType())
5440         break;
5441 
5442       E = Base;
5443       --PathLength;
5444 
5445     } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5446       // Step over a derived-to-base conversion.
5447       E = ICE->getSubExpr();
5448       if (ICE->getCastKind() == CK_NoOp)
5449         continue;
5450       if (ICE->getCastKind() != CK_DerivedToBase &&
5451           ICE->getCastKind() != CK_UncheckedDerivedToBase)
5452         break;
5453       // Walk path backwards as we walk up from the base to the derived class.
5454       for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
5455         --PathLength;
5456         (void)Elt;
5457         assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
5458                                   LHS.Designator.Entries[PathLength]
5459                                       .getAsBaseOrMember().getPointer()));
5460       }
5461 
5462     //   -- Otherwise, S(E) is empty.
5463     } else {
5464       break;
5465     }
5466   }
5467 
5468   // Common case: no unions' lifetimes are started.
5469   if (UnionPathLengths.empty())
5470     return true;
5471 
5472   //   if modification of X [would access an inactive union member], an object
5473   //   of the type of X is implicitly created
5474   CompleteObject Obj =
5475       findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
5476   if (!Obj)
5477     return false;
5478   for (std::pair<unsigned, const FieldDecl *> LengthAndField :
5479            llvm::reverse(UnionPathLengths)) {
5480     // Form a designator for the union object.
5481     SubobjectDesignator D = LHS.Designator;
5482     D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
5483 
5484     bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
5485                       ConstructionPhase::AfterBases;
5486     StartLifetimeOfUnionMemberHandler StartLifetime{
5487         Info, LHSExpr, LengthAndField.second, DuringInit};
5488     if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
5489       return false;
5490   }
5491 
5492   return true;
5493 }
5494 
5495 namespace {
5496 typedef SmallVector<APValue, 8> ArgVector;
5497 }
5498 
5499 /// EvaluateArgs - Evaluate the arguments to a function call.
5500 static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues,
5501                          EvalInfo &Info, const FunctionDecl *Callee) {
5502   bool Success = true;
5503   llvm::SmallBitVector ForbiddenNullArgs;
5504   if (Callee->hasAttr<NonNullAttr>()) {
5505     ForbiddenNullArgs.resize(Args.size());
5506     for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
5507       if (!Attr->args_size()) {
5508         ForbiddenNullArgs.set();
5509         break;
5510       } else
5511         for (auto Idx : Attr->args()) {
5512           unsigned ASTIdx = Idx.getASTIndex();
5513           if (ASTIdx >= Args.size())
5514             continue;
5515           ForbiddenNullArgs[ASTIdx] = 1;
5516         }
5517     }
5518   }
5519   // FIXME: This is the wrong evaluation order for an assignment operator
5520   // called via operator syntax.
5521   for (unsigned Idx = 0; Idx < Args.size(); Idx++) {
5522     if (!Evaluate(ArgValues[Idx], Info, Args[Idx])) {
5523       // If we're checking for a potential constant expression, evaluate all
5524       // initializers even if some of them fail.
5525       if (!Info.noteFailure())
5526         return false;
5527       Success = false;
5528     } else if (!ForbiddenNullArgs.empty() &&
5529                ForbiddenNullArgs[Idx] &&
5530                ArgValues[Idx].isLValue() &&
5531                ArgValues[Idx].isNullPointer()) {
5532       Info.CCEDiag(Args[Idx], diag::note_non_null_attribute_failed);
5533       if (!Info.noteFailure())
5534         return false;
5535       Success = false;
5536     }
5537   }
5538   return Success;
5539 }
5540 
5541 /// Evaluate a function call.
5542 static bool HandleFunctionCall(SourceLocation CallLoc,
5543                                const FunctionDecl *Callee, const LValue *This,
5544                                ArrayRef<const Expr*> Args, const Stmt *Body,
5545                                EvalInfo &Info, APValue &Result,
5546                                const LValue *ResultSlot) {
5547   ArgVector ArgValues(Args.size());
5548   if (!EvaluateArgs(Args, ArgValues, Info, Callee))
5549     return false;
5550 
5551   if (!Info.CheckCallLimit(CallLoc))
5552     return false;
5553 
5554   CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
5555 
5556   // For a trivial copy or move assignment, perform an APValue copy. This is
5557   // essential for unions, where the operations performed by the assignment
5558   // operator cannot be represented as statements.
5559   //
5560   // Skip this for non-union classes with no fields; in that case, the defaulted
5561   // copy/move does not actually read the object.
5562   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
5563   if (MD && MD->isDefaulted() &&
5564       (MD->getParent()->isUnion() ||
5565        (MD->isTrivial() &&
5566         isReadByLvalueToRvalueConversion(MD->getParent())))) {
5567     assert(This &&
5568            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
5569     LValue RHS;
5570     RHS.setFrom(Info.Ctx, ArgValues[0]);
5571     APValue RHSValue;
5572     if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), RHS,
5573                                         RHSValue, MD->getParent()->isUnion()))
5574       return false;
5575     if (Info.getLangOpts().CPlusPlus2a && MD->isTrivial() &&
5576         !HandleUnionActiveMemberChange(Info, Args[0], *This))
5577       return false;
5578     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
5579                           RHSValue))
5580       return false;
5581     This->moveInto(Result);
5582     return true;
5583   } else if (MD && isLambdaCallOperator(MD)) {
5584     // We're in a lambda; determine the lambda capture field maps unless we're
5585     // just constexpr checking a lambda's call operator. constexpr checking is
5586     // done before the captures have been added to the closure object (unless
5587     // we're inferring constexpr-ness), so we don't have access to them in this
5588     // case. But since we don't need the captures to constexpr check, we can
5589     // just ignore them.
5590     if (!Info.checkingPotentialConstantExpression())
5591       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
5592                                         Frame.LambdaThisCaptureField);
5593   }
5594 
5595   StmtResult Ret = {Result, ResultSlot};
5596   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
5597   if (ESR == ESR_Succeeded) {
5598     if (Callee->getReturnType()->isVoidType())
5599       return true;
5600     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
5601   }
5602   return ESR == ESR_Returned;
5603 }
5604 
5605 /// Evaluate a constructor call.
5606 static bool HandleConstructorCall(const Expr *E, const LValue &This,
5607                                   APValue *ArgValues,
5608                                   const CXXConstructorDecl *Definition,
5609                                   EvalInfo &Info, APValue &Result) {
5610   SourceLocation CallLoc = E->getExprLoc();
5611   if (!Info.CheckCallLimit(CallLoc))
5612     return false;
5613 
5614   const CXXRecordDecl *RD = Definition->getParent();
5615   if (RD->getNumVBases()) {
5616     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
5617     return false;
5618   }
5619 
5620   EvalInfo::EvaluatingConstructorRAII EvalObj(
5621       Info,
5622       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
5623       RD->getNumBases());
5624   CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
5625 
5626   // FIXME: Creating an APValue just to hold a nonexistent return value is
5627   // wasteful.
5628   APValue RetVal;
5629   StmtResult Ret = {RetVal, nullptr};
5630 
5631   // If it's a delegating constructor, delegate.
5632   if (Definition->isDelegatingConstructor()) {
5633     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
5634     {
5635       FullExpressionRAII InitScope(Info);
5636       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
5637           !InitScope.destroy())
5638         return false;
5639     }
5640     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
5641   }
5642 
5643   // For a trivial copy or move constructor, perform an APValue copy. This is
5644   // essential for unions (or classes with anonymous union members), where the
5645   // operations performed by the constructor cannot be represented by
5646   // ctor-initializers.
5647   //
5648   // Skip this for empty non-union classes; we should not perform an
5649   // lvalue-to-rvalue conversion on them because their copy constructor does not
5650   // actually read them.
5651   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
5652       (Definition->getParent()->isUnion() ||
5653        (Definition->isTrivial() &&
5654         isReadByLvalueToRvalueConversion(Definition->getParent())))) {
5655     LValue RHS;
5656     RHS.setFrom(Info.Ctx, ArgValues[0]);
5657     return handleLValueToRValueConversion(
5658         Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
5659         RHS, Result, Definition->getParent()->isUnion());
5660   }
5661 
5662   // Reserve space for the struct members.
5663   if (!Result.hasValue()) {
5664     if (!RD->isUnion())
5665       Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
5666                        std::distance(RD->field_begin(), RD->field_end()));
5667     else
5668       // A union starts with no active member.
5669       Result = APValue((const FieldDecl*)nullptr);
5670   }
5671 
5672   if (RD->isInvalidDecl()) return false;
5673   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5674 
5675   // A scope for temporaries lifetime-extended by reference members.
5676   BlockScopeRAII LifetimeExtendedScope(Info);
5677 
5678   bool Success = true;
5679   unsigned BasesSeen = 0;
5680 #ifndef NDEBUG
5681   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
5682 #endif
5683   CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
5684   auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
5685     // We might be initializing the same field again if this is an indirect
5686     // field initialization.
5687     if (FieldIt == RD->field_end() ||
5688         FieldIt->getFieldIndex() > FD->getFieldIndex()) {
5689       assert(Indirect && "fields out of order?");
5690       return;
5691     }
5692 
5693     // Default-initialize any fields with no explicit initializer.
5694     for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
5695       assert(FieldIt != RD->field_end() && "missing field?");
5696       if (!FieldIt->isUnnamedBitfield())
5697         Result.getStructField(FieldIt->getFieldIndex()) =
5698             getDefaultInitValue(FieldIt->getType());
5699     }
5700     ++FieldIt;
5701   };
5702   for (const auto *I : Definition->inits()) {
5703     LValue Subobject = This;
5704     LValue SubobjectParent = This;
5705     APValue *Value = &Result;
5706 
5707     // Determine the subobject to initialize.
5708     FieldDecl *FD = nullptr;
5709     if (I->isBaseInitializer()) {
5710       QualType BaseType(I->getBaseClass(), 0);
5711 #ifndef NDEBUG
5712       // Non-virtual base classes are initialized in the order in the class
5713       // definition. We have already checked for virtual base classes.
5714       assert(!BaseIt->isVirtual() && "virtual base for literal type");
5715       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
5716              "base class initializers not in expected order");
5717       ++BaseIt;
5718 #endif
5719       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
5720                                   BaseType->getAsCXXRecordDecl(), &Layout))
5721         return false;
5722       Value = &Result.getStructBase(BasesSeen++);
5723     } else if ((FD = I->getMember())) {
5724       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
5725         return false;
5726       if (RD->isUnion()) {
5727         Result = APValue(FD);
5728         Value = &Result.getUnionValue();
5729       } else {
5730         SkipToField(FD, false);
5731         Value = &Result.getStructField(FD->getFieldIndex());
5732       }
5733     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
5734       // Walk the indirect field decl's chain to find the object to initialize,
5735       // and make sure we've initialized every step along it.
5736       auto IndirectFieldChain = IFD->chain();
5737       for (auto *C : IndirectFieldChain) {
5738         FD = cast<FieldDecl>(C);
5739         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
5740         // Switch the union field if it differs. This happens if we had
5741         // preceding zero-initialization, and we're now initializing a union
5742         // subobject other than the first.
5743         // FIXME: In this case, the values of the other subobjects are
5744         // specified, since zero-initialization sets all padding bits to zero.
5745         if (!Value->hasValue() ||
5746             (Value->isUnion() && Value->getUnionField() != FD)) {
5747           if (CD->isUnion())
5748             *Value = APValue(FD);
5749           else
5750             // FIXME: This immediately starts the lifetime of all members of an
5751             // anonymous struct. It would be preferable to strictly start member
5752             // lifetime in initialization order.
5753             *Value = getDefaultInitValue(Info.Ctx.getRecordType(CD));
5754         }
5755         // Store Subobject as its parent before updating it for the last element
5756         // in the chain.
5757         if (C == IndirectFieldChain.back())
5758           SubobjectParent = Subobject;
5759         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
5760           return false;
5761         if (CD->isUnion())
5762           Value = &Value->getUnionValue();
5763         else {
5764           if (C == IndirectFieldChain.front() && !RD->isUnion())
5765             SkipToField(FD, true);
5766           Value = &Value->getStructField(FD->getFieldIndex());
5767         }
5768       }
5769     } else {
5770       llvm_unreachable("unknown base initializer kind");
5771     }
5772 
5773     // Need to override This for implicit field initializers as in this case
5774     // This refers to innermost anonymous struct/union containing initializer,
5775     // not to currently constructed class.
5776     const Expr *Init = I->getInit();
5777     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
5778                                   isa<CXXDefaultInitExpr>(Init));
5779     FullExpressionRAII InitScope(Info);
5780     if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
5781         (FD && FD->isBitField() &&
5782          !truncateBitfieldValue(Info, Init, *Value, FD))) {
5783       // If we're checking for a potential constant expression, evaluate all
5784       // initializers even if some of them fail.
5785       if (!Info.noteFailure())
5786         return false;
5787       Success = false;
5788     }
5789 
5790     // This is the point at which the dynamic type of the object becomes this
5791     // class type.
5792     if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
5793       EvalObj.finishedConstructingBases();
5794   }
5795 
5796   // Default-initialize any remaining fields.
5797   if (!RD->isUnion()) {
5798     for (; FieldIt != RD->field_end(); ++FieldIt) {
5799       if (!FieldIt->isUnnamedBitfield())
5800         Result.getStructField(FieldIt->getFieldIndex()) =
5801             getDefaultInitValue(FieldIt->getType());
5802     }
5803   }
5804 
5805   EvalObj.finishedConstructingFields();
5806 
5807   return Success &&
5808          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
5809          LifetimeExtendedScope.destroy();
5810 }
5811 
5812 static bool HandleConstructorCall(const Expr *E, const LValue &This,
5813                                   ArrayRef<const Expr*> Args,
5814                                   const CXXConstructorDecl *Definition,
5815                                   EvalInfo &Info, APValue &Result) {
5816   ArgVector ArgValues(Args.size());
5817   if (!EvaluateArgs(Args, ArgValues, Info, Definition))
5818     return false;
5819 
5820   return HandleConstructorCall(E, This, ArgValues.data(), Definition,
5821                                Info, Result);
5822 }
5823 
5824 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
5825                                   const LValue &This, APValue &Value,
5826                                   QualType T) {
5827   // Objects can only be destroyed while they're within their lifetimes.
5828   // FIXME: We have no representation for whether an object of type nullptr_t
5829   // is in its lifetime; it usually doesn't matter. Perhaps we should model it
5830   // as indeterminate instead?
5831   if (Value.isAbsent() && !T->isNullPtrType()) {
5832     APValue Printable;
5833     This.moveInto(Printable);
5834     Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
5835       << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
5836     return false;
5837   }
5838 
5839   // Invent an expression for location purposes.
5840   // FIXME: We shouldn't need to do this.
5841   OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue);
5842 
5843   // For arrays, destroy elements right-to-left.
5844   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
5845     uint64_t Size = CAT->getSize().getZExtValue();
5846     QualType ElemT = CAT->getElementType();
5847 
5848     LValue ElemLV = This;
5849     ElemLV.addArray(Info, &LocE, CAT);
5850     if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
5851       return false;
5852 
5853     // Ensure that we have actual array elements available to destroy; the
5854     // destructors might mutate the value, so we can't run them on the array
5855     // filler.
5856     if (Size && Size > Value.getArrayInitializedElts())
5857       expandArray(Value, Value.getArraySize() - 1);
5858 
5859     for (; Size != 0; --Size) {
5860       APValue &Elem = Value.getArrayInitializedElt(Size - 1);
5861       if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
5862           !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
5863         return false;
5864     }
5865 
5866     // End the lifetime of this array now.
5867     Value = APValue();
5868     return true;
5869   }
5870 
5871   const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
5872   if (!RD) {
5873     if (T.isDestructedType()) {
5874       Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
5875       return false;
5876     }
5877 
5878     Value = APValue();
5879     return true;
5880   }
5881 
5882   if (RD->getNumVBases()) {
5883     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
5884     return false;
5885   }
5886 
5887   const CXXDestructorDecl *DD = RD->getDestructor();
5888   if (!DD && !RD->hasTrivialDestructor()) {
5889     Info.FFDiag(CallLoc);
5890     return false;
5891   }
5892 
5893   if (!DD || DD->isTrivial() ||
5894       (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
5895     // A trivial destructor just ends the lifetime of the object. Check for
5896     // this case before checking for a body, because we might not bother
5897     // building a body for a trivial destructor. Note that it doesn't matter
5898     // whether the destructor is constexpr in this case; all trivial
5899     // destructors are constexpr.
5900     //
5901     // If an anonymous union would be destroyed, some enclosing destructor must
5902     // have been explicitly defined, and the anonymous union destruction should
5903     // have no effect.
5904     Value = APValue();
5905     return true;
5906   }
5907 
5908   if (!Info.CheckCallLimit(CallLoc))
5909     return false;
5910 
5911   const FunctionDecl *Definition = nullptr;
5912   const Stmt *Body = DD->getBody(Definition);
5913 
5914   if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
5915     return false;
5916 
5917   CallStackFrame Frame(Info, CallLoc, Definition, &This, nullptr);
5918 
5919   // We're now in the period of destruction of this object.
5920   unsigned BasesLeft = RD->getNumBases();
5921   EvalInfo::EvaluatingDestructorRAII EvalObj(
5922       Info,
5923       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
5924   if (!EvalObj.DidInsert) {
5925     // C++2a [class.dtor]p19:
5926     //   the behavior is undefined if the destructor is invoked for an object
5927     //   whose lifetime has ended
5928     // (Note that formally the lifetime ends when the period of destruction
5929     // begins, even though certain uses of the object remain valid until the
5930     // period of destruction ends.)
5931     Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
5932     return false;
5933   }
5934 
5935   // FIXME: Creating an APValue just to hold a nonexistent return value is
5936   // wasteful.
5937   APValue RetVal;
5938   StmtResult Ret = {RetVal, nullptr};
5939   if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
5940     return false;
5941 
5942   // A union destructor does not implicitly destroy its members.
5943   if (RD->isUnion())
5944     return true;
5945 
5946   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5947 
5948   // We don't have a good way to iterate fields in reverse, so collect all the
5949   // fields first and then walk them backwards.
5950   SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
5951   for (const FieldDecl *FD : llvm::reverse(Fields)) {
5952     if (FD->isUnnamedBitfield())
5953       continue;
5954 
5955     LValue Subobject = This;
5956     if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
5957       return false;
5958 
5959     APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
5960     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
5961                                FD->getType()))
5962       return false;
5963   }
5964 
5965   if (BasesLeft != 0)
5966     EvalObj.startedDestroyingBases();
5967 
5968   // Destroy base classes in reverse order.
5969   for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
5970     --BasesLeft;
5971 
5972     QualType BaseType = Base.getType();
5973     LValue Subobject = This;
5974     if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
5975                                 BaseType->getAsCXXRecordDecl(), &Layout))
5976       return false;
5977 
5978     APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
5979     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
5980                                BaseType))
5981       return false;
5982   }
5983   assert(BasesLeft == 0 && "NumBases was wrong?");
5984 
5985   // The period of destruction ends now. The object is gone.
5986   Value = APValue();
5987   return true;
5988 }
5989 
5990 namespace {
5991 struct DestroyObjectHandler {
5992   EvalInfo &Info;
5993   const Expr *E;
5994   const LValue &This;
5995   const AccessKinds AccessKind;
5996 
5997   typedef bool result_type;
5998   bool failed() { return false; }
5999   bool found(APValue &Subobj, QualType SubobjType) {
6000     return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
6001                                  SubobjType);
6002   }
6003   bool found(APSInt &Value, QualType SubobjType) {
6004     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6005     return false;
6006   }
6007   bool found(APFloat &Value, QualType SubobjType) {
6008     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6009     return false;
6010   }
6011 };
6012 }
6013 
6014 /// Perform a destructor or pseudo-destructor call on the given object, which
6015 /// might in general not be a complete object.
6016 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6017                               const LValue &This, QualType ThisType) {
6018   CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6019   DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6020   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6021 }
6022 
6023 /// Destroy and end the lifetime of the given complete object.
6024 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6025                               APValue::LValueBase LVBase, APValue &Value,
6026                               QualType T) {
6027   // If we've had an unmodeled side-effect, we can't rely on mutable state
6028   // (such as the object we're about to destroy) being correct.
6029   if (Info.EvalStatus.HasSideEffects)
6030     return false;
6031 
6032   LValue LV;
6033   LV.set({LVBase});
6034   return HandleDestructionImpl(Info, Loc, LV, Value, T);
6035 }
6036 
6037 /// Perform a call to 'perator new' or to `__builtin_operator_new'.
6038 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6039                                   LValue &Result) {
6040   if (Info.checkingPotentialConstantExpression() ||
6041       Info.SpeculativeEvaluationDepth)
6042     return false;
6043 
6044   // This is permitted only within a call to std::allocator<T>::allocate.
6045   auto Caller = Info.getStdAllocatorCaller("allocate");
6046   if (!Caller) {
6047     Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus2a
6048                                      ? diag::note_constexpr_new_untyped
6049                                      : diag::note_constexpr_new);
6050     return false;
6051   }
6052 
6053   QualType ElemType = Caller.ElemType;
6054   if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6055     Info.FFDiag(E->getExprLoc(),
6056                 diag::note_constexpr_new_not_complete_object_type)
6057         << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6058     return false;
6059   }
6060 
6061   APSInt ByteSize;
6062   if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6063     return false;
6064   bool IsNothrow = false;
6065   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6066     EvaluateIgnoredValue(Info, E->getArg(I));
6067     IsNothrow |= E->getType()->isNothrowT();
6068   }
6069 
6070   CharUnits ElemSize;
6071   if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6072     return false;
6073   APInt Size, Remainder;
6074   APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6075   APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6076   if (Remainder != 0) {
6077     // This likely indicates a bug in the implementation of 'std::allocator'.
6078     Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6079         << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6080     return false;
6081   }
6082 
6083   if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
6084     if (IsNothrow) {
6085       Result.setNull(Info.Ctx, E->getType());
6086       return true;
6087     }
6088 
6089     Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
6090     return false;
6091   }
6092 
6093   QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
6094                                                      ArrayType::Normal, 0);
6095   APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6096   *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6097   Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6098   return true;
6099 }
6100 
6101 static bool hasVirtualDestructor(QualType T) {
6102   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6103     if (CXXDestructorDecl *DD = RD->getDestructor())
6104       return DD->isVirtual();
6105   return false;
6106 }
6107 
6108 static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6109   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6110     if (CXXDestructorDecl *DD = RD->getDestructor())
6111       return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6112   return nullptr;
6113 }
6114 
6115 /// Check that the given object is a suitable pointer to a heap allocation that
6116 /// still exists and is of the right kind for the purpose of a deletion.
6117 ///
6118 /// On success, returns the heap allocation to deallocate. On failure, produces
6119 /// a diagnostic and returns None.
6120 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6121                                             const LValue &Pointer,
6122                                             DynAlloc::Kind DeallocKind) {
6123   auto PointerAsString = [&] {
6124     return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6125   };
6126 
6127   DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6128   if (!DA) {
6129     Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6130         << PointerAsString();
6131     if (Pointer.Base)
6132       NoteLValueLocation(Info, Pointer.Base);
6133     return None;
6134   }
6135 
6136   Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6137   if (!Alloc) {
6138     Info.FFDiag(E, diag::note_constexpr_double_delete);
6139     return None;
6140   }
6141 
6142   QualType AllocType = Pointer.Base.getDynamicAllocType();
6143   if (DeallocKind != (*Alloc)->getKind()) {
6144     Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6145         << DeallocKind << (*Alloc)->getKind() << AllocType;
6146     NoteLValueLocation(Info, Pointer.Base);
6147     return None;
6148   }
6149 
6150   bool Subobject = false;
6151   if (DeallocKind == DynAlloc::New) {
6152     Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6153                 Pointer.Designator.isOnePastTheEnd();
6154   } else {
6155     Subobject = Pointer.Designator.Entries.size() != 1 ||
6156                 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6157   }
6158   if (Subobject) {
6159     Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6160         << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6161     return None;
6162   }
6163 
6164   return Alloc;
6165 }
6166 
6167 // Perform a call to 'operator delete' or '__builtin_operator_delete'.
6168 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6169   if (Info.checkingPotentialConstantExpression() ||
6170       Info.SpeculativeEvaluationDepth)
6171     return false;
6172 
6173   // This is permitted only within a call to std::allocator<T>::deallocate.
6174   if (!Info.getStdAllocatorCaller("deallocate")) {
6175     Info.FFDiag(E->getExprLoc());
6176     return true;
6177   }
6178 
6179   LValue Pointer;
6180   if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6181     return false;
6182   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6183     EvaluateIgnoredValue(Info, E->getArg(I));
6184 
6185   if (Pointer.Designator.Invalid)
6186     return false;
6187 
6188   // Deleting a null pointer has no effect.
6189   if (Pointer.isNullPointer())
6190     return true;
6191 
6192   if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6193     return false;
6194 
6195   Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6196   return true;
6197 }
6198 
6199 //===----------------------------------------------------------------------===//
6200 // Generic Evaluation
6201 //===----------------------------------------------------------------------===//
6202 namespace {
6203 
6204 class BitCastBuffer {
6205   // FIXME: We're going to need bit-level granularity when we support
6206   // bit-fields.
6207   // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6208   // we don't support a host or target where that is the case. Still, we should
6209   // use a more generic type in case we ever do.
6210   SmallVector<Optional<unsigned char>, 32> Bytes;
6211 
6212   static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6213                 "Need at least 8 bit unsigned char");
6214 
6215   bool TargetIsLittleEndian;
6216 
6217 public:
6218   BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6219       : Bytes(Width.getQuantity()),
6220         TargetIsLittleEndian(TargetIsLittleEndian) {}
6221 
6222   LLVM_NODISCARD
6223   bool readObject(CharUnits Offset, CharUnits Width,
6224                   SmallVectorImpl<unsigned char> &Output) const {
6225     for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6226       // If a byte of an integer is uninitialized, then the whole integer is
6227       // uninitalized.
6228       if (!Bytes[I.getQuantity()])
6229         return false;
6230       Output.push_back(*Bytes[I.getQuantity()]);
6231     }
6232     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6233       std::reverse(Output.begin(), Output.end());
6234     return true;
6235   }
6236 
6237   void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6238     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6239       std::reverse(Input.begin(), Input.end());
6240 
6241     size_t Index = 0;
6242     for (unsigned char Byte : Input) {
6243       assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
6244       Bytes[Offset.getQuantity() + Index] = Byte;
6245       ++Index;
6246     }
6247   }
6248 
6249   size_t size() { return Bytes.size(); }
6250 };
6251 
6252 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6253 /// target would represent the value at runtime.
6254 class APValueToBufferConverter {
6255   EvalInfo &Info;
6256   BitCastBuffer Buffer;
6257   const CastExpr *BCE;
6258 
6259   APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6260                            const CastExpr *BCE)
6261       : Info(Info),
6262         Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6263         BCE(BCE) {}
6264 
6265   bool visit(const APValue &Val, QualType Ty) {
6266     return visit(Val, Ty, CharUnits::fromQuantity(0));
6267   }
6268 
6269   // Write out Val with type Ty into Buffer starting at Offset.
6270   bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6271     assert((size_t)Offset.getQuantity() <= Buffer.size());
6272 
6273     // As a special case, nullptr_t has an indeterminate value.
6274     if (Ty->isNullPtrType())
6275       return true;
6276 
6277     // Dig through Src to find the byte at SrcOffset.
6278     switch (Val.getKind()) {
6279     case APValue::Indeterminate:
6280     case APValue::None:
6281       return true;
6282 
6283     case APValue::Int:
6284       return visitInt(Val.getInt(), Ty, Offset);
6285     case APValue::Float:
6286       return visitFloat(Val.getFloat(), Ty, Offset);
6287     case APValue::Array:
6288       return visitArray(Val, Ty, Offset);
6289     case APValue::Struct:
6290       return visitRecord(Val, Ty, Offset);
6291 
6292     case APValue::ComplexInt:
6293     case APValue::ComplexFloat:
6294     case APValue::Vector:
6295     case APValue::FixedPoint:
6296       // FIXME: We should support these.
6297 
6298     case APValue::Union:
6299     case APValue::MemberPointer:
6300     case APValue::AddrLabelDiff: {
6301       Info.FFDiag(BCE->getBeginLoc(),
6302                   diag::note_constexpr_bit_cast_unsupported_type)
6303           << Ty;
6304       return false;
6305     }
6306 
6307     case APValue::LValue:
6308       llvm_unreachable("LValue subobject in bit_cast?");
6309     }
6310     llvm_unreachable("Unhandled APValue::ValueKind");
6311   }
6312 
6313   bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
6314     const RecordDecl *RD = Ty->getAsRecordDecl();
6315     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6316 
6317     // Visit the base classes.
6318     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6319       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6320         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6321         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6322 
6323         if (!visitRecord(Val.getStructBase(I), BS.getType(),
6324                          Layout.getBaseClassOffset(BaseDecl) + Offset))
6325           return false;
6326       }
6327     }
6328 
6329     // Visit the fields.
6330     unsigned FieldIdx = 0;
6331     for (FieldDecl *FD : RD->fields()) {
6332       if (FD->isBitField()) {
6333         Info.FFDiag(BCE->getBeginLoc(),
6334                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6335         return false;
6336       }
6337 
6338       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6339 
6340       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
6341              "only bit-fields can have sub-char alignment");
6342       CharUnits FieldOffset =
6343           Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
6344       QualType FieldTy = FD->getType();
6345       if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
6346         return false;
6347       ++FieldIdx;
6348     }
6349 
6350     return true;
6351   }
6352 
6353   bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
6354     const auto *CAT =
6355         dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
6356     if (!CAT)
6357       return false;
6358 
6359     CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
6360     unsigned NumInitializedElts = Val.getArrayInitializedElts();
6361     unsigned ArraySize = Val.getArraySize();
6362     // First, initialize the initialized elements.
6363     for (unsigned I = 0; I != NumInitializedElts; ++I) {
6364       const APValue &SubObj = Val.getArrayInitializedElt(I);
6365       if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
6366         return false;
6367     }
6368 
6369     // Next, initialize the rest of the array using the filler.
6370     if (Val.hasArrayFiller()) {
6371       const APValue &Filler = Val.getArrayFiller();
6372       for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
6373         if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
6374           return false;
6375       }
6376     }
6377 
6378     return true;
6379   }
6380 
6381   bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
6382     CharUnits Width = Info.Ctx.getTypeSizeInChars(Ty);
6383     SmallVector<unsigned char, 8> Bytes(Width.getQuantity());
6384     llvm::StoreIntToMemory(Val, &*Bytes.begin(), Width.getQuantity());
6385     Buffer.writeObject(Offset, Bytes);
6386     return true;
6387   }
6388 
6389   bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
6390     APSInt AsInt(Val.bitcastToAPInt());
6391     return visitInt(AsInt, Ty, Offset);
6392   }
6393 
6394 public:
6395   static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
6396                                          const CastExpr *BCE) {
6397     CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
6398     APValueToBufferConverter Converter(Info, DstSize, BCE);
6399     if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
6400       return None;
6401     return Converter.Buffer;
6402   }
6403 };
6404 
6405 /// Write an BitCastBuffer into an APValue.
6406 class BufferToAPValueConverter {
6407   EvalInfo &Info;
6408   const BitCastBuffer &Buffer;
6409   const CastExpr *BCE;
6410 
6411   BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
6412                            const CastExpr *BCE)
6413       : Info(Info), Buffer(Buffer), BCE(BCE) {}
6414 
6415   // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
6416   // with an invalid type, so anything left is a deficiency on our part (FIXME).
6417   // Ideally this will be unreachable.
6418   llvm::NoneType unsupportedType(QualType Ty) {
6419     Info.FFDiag(BCE->getBeginLoc(),
6420                 diag::note_constexpr_bit_cast_unsupported_type)
6421         << Ty;
6422     return None;
6423   }
6424 
6425   Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
6426                           const EnumType *EnumSugar = nullptr) {
6427     if (T->isNullPtrType()) {
6428       uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
6429       return APValue((Expr *)nullptr,
6430                      /*Offset=*/CharUnits::fromQuantity(NullValue),
6431                      APValue::NoLValuePath{}, /*IsNullPtr=*/true);
6432     }
6433 
6434     CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
6435     SmallVector<uint8_t, 8> Bytes;
6436     if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
6437       // If this is std::byte or unsigned char, then its okay to store an
6438       // indeterminate value.
6439       bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
6440       bool IsUChar =
6441           !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
6442                          T->isSpecificBuiltinType(BuiltinType::Char_U));
6443       if (!IsStdByte && !IsUChar) {
6444         QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
6445         Info.FFDiag(BCE->getExprLoc(),
6446                     diag::note_constexpr_bit_cast_indet_dest)
6447             << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
6448         return None;
6449       }
6450 
6451       return APValue::IndeterminateValue();
6452     }
6453 
6454     APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
6455     llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
6456 
6457     if (T->isIntegralOrEnumerationType()) {
6458       Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
6459       return APValue(Val);
6460     }
6461 
6462     if (T->isRealFloatingType()) {
6463       const llvm::fltSemantics &Semantics =
6464           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
6465       return APValue(APFloat(Semantics, Val));
6466     }
6467 
6468     return unsupportedType(QualType(T, 0));
6469   }
6470 
6471   Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
6472     const RecordDecl *RD = RTy->getAsRecordDecl();
6473     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6474 
6475     unsigned NumBases = 0;
6476     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6477       NumBases = CXXRD->getNumBases();
6478 
6479     APValue ResultVal(APValue::UninitStruct(), NumBases,
6480                       std::distance(RD->field_begin(), RD->field_end()));
6481 
6482     // Visit the base classes.
6483     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6484       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6485         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6486         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6487         if (BaseDecl->isEmpty() ||
6488             Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
6489           continue;
6490 
6491         Optional<APValue> SubObj = visitType(
6492             BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
6493         if (!SubObj)
6494           return None;
6495         ResultVal.getStructBase(I) = *SubObj;
6496       }
6497     }
6498 
6499     // Visit the fields.
6500     unsigned FieldIdx = 0;
6501     for (FieldDecl *FD : RD->fields()) {
6502       // FIXME: We don't currently support bit-fields. A lot of the logic for
6503       // this is in CodeGen, so we need to factor it around.
6504       if (FD->isBitField()) {
6505         Info.FFDiag(BCE->getBeginLoc(),
6506                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6507         return None;
6508       }
6509 
6510       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6511       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
6512 
6513       CharUnits FieldOffset =
6514           CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
6515           Offset;
6516       QualType FieldTy = FD->getType();
6517       Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
6518       if (!SubObj)
6519         return None;
6520       ResultVal.getStructField(FieldIdx) = *SubObj;
6521       ++FieldIdx;
6522     }
6523 
6524     return ResultVal;
6525   }
6526 
6527   Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
6528     QualType RepresentationType = Ty->getDecl()->getIntegerType();
6529     assert(!RepresentationType.isNull() &&
6530            "enum forward decl should be caught by Sema");
6531     const auto *AsBuiltin =
6532         RepresentationType.getCanonicalType()->castAs<BuiltinType>();
6533     // Recurse into the underlying type. Treat std::byte transparently as
6534     // unsigned char.
6535     return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
6536   }
6537 
6538   Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
6539     size_t Size = Ty->getSize().getLimitedValue();
6540     CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
6541 
6542     APValue ArrayValue(APValue::UninitArray(), Size, Size);
6543     for (size_t I = 0; I != Size; ++I) {
6544       Optional<APValue> ElementValue =
6545           visitType(Ty->getElementType(), Offset + I * ElementWidth);
6546       if (!ElementValue)
6547         return None;
6548       ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
6549     }
6550 
6551     return ArrayValue;
6552   }
6553 
6554   Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
6555     return unsupportedType(QualType(Ty, 0));
6556   }
6557 
6558   Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
6559     QualType Can = Ty.getCanonicalType();
6560 
6561     switch (Can->getTypeClass()) {
6562 #define TYPE(Class, Base)                                                      \
6563   case Type::Class:                                                            \
6564     return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
6565 #define ABSTRACT_TYPE(Class, Base)
6566 #define NON_CANONICAL_TYPE(Class, Base)                                        \
6567   case Type::Class:                                                            \
6568     llvm_unreachable("non-canonical type should be impossible!");
6569 #define DEPENDENT_TYPE(Class, Base)                                            \
6570   case Type::Class:                                                            \
6571     llvm_unreachable(                                                          \
6572         "dependent types aren't supported in the constant evaluator!");
6573 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)                            \
6574   case Type::Class:                                                            \
6575     llvm_unreachable("either dependent or not canonical!");
6576 #include "clang/AST/TypeNodes.inc"
6577     }
6578     llvm_unreachable("Unhandled Type::TypeClass");
6579   }
6580 
6581 public:
6582   // Pull out a full value of type DstType.
6583   static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
6584                                    const CastExpr *BCE) {
6585     BufferToAPValueConverter Converter(Info, Buffer, BCE);
6586     return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
6587   }
6588 };
6589 
6590 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
6591                                                  QualType Ty, EvalInfo *Info,
6592                                                  const ASTContext &Ctx,
6593                                                  bool CheckingDest) {
6594   Ty = Ty.getCanonicalType();
6595 
6596   auto diag = [&](int Reason) {
6597     if (Info)
6598       Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
6599           << CheckingDest << (Reason == 4) << Reason;
6600     return false;
6601   };
6602   auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
6603     if (Info)
6604       Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
6605           << NoteTy << Construct << Ty;
6606     return false;
6607   };
6608 
6609   if (Ty->isUnionType())
6610     return diag(0);
6611   if (Ty->isPointerType())
6612     return diag(1);
6613   if (Ty->isMemberPointerType())
6614     return diag(2);
6615   if (Ty.isVolatileQualified())
6616     return diag(3);
6617 
6618   if (RecordDecl *Record = Ty->getAsRecordDecl()) {
6619     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
6620       for (CXXBaseSpecifier &BS : CXXRD->bases())
6621         if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
6622                                                   CheckingDest))
6623           return note(1, BS.getType(), BS.getBeginLoc());
6624     }
6625     for (FieldDecl *FD : Record->fields()) {
6626       if (FD->getType()->isReferenceType())
6627         return diag(4);
6628       if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
6629                                                 CheckingDest))
6630         return note(0, FD->getType(), FD->getBeginLoc());
6631     }
6632   }
6633 
6634   if (Ty->isArrayType() &&
6635       !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
6636                                             Info, Ctx, CheckingDest))
6637     return false;
6638 
6639   return true;
6640 }
6641 
6642 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
6643                                              const ASTContext &Ctx,
6644                                              const CastExpr *BCE) {
6645   bool DestOK = checkBitCastConstexprEligibilityType(
6646       BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
6647   bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
6648                                 BCE->getBeginLoc(),
6649                                 BCE->getSubExpr()->getType(), Info, Ctx, false);
6650   return SourceOK;
6651 }
6652 
6653 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
6654                                         APValue &SourceValue,
6655                                         const CastExpr *BCE) {
6656   assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
6657          "no host or target supports non 8-bit chars");
6658   assert(SourceValue.isLValue() &&
6659          "LValueToRValueBitcast requires an lvalue operand!");
6660 
6661   if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
6662     return false;
6663 
6664   LValue SourceLValue;
6665   APValue SourceRValue;
6666   SourceLValue.setFrom(Info.Ctx, SourceValue);
6667   if (!handleLValueToRValueConversion(
6668           Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
6669           SourceRValue, /*WantObjectRepresentation=*/true))
6670     return false;
6671 
6672   // Read out SourceValue into a char buffer.
6673   Optional<BitCastBuffer> Buffer =
6674       APValueToBufferConverter::convert(Info, SourceRValue, BCE);
6675   if (!Buffer)
6676     return false;
6677 
6678   // Write out the buffer into a new APValue.
6679   Optional<APValue> MaybeDestValue =
6680       BufferToAPValueConverter::convert(Info, *Buffer, BCE);
6681   if (!MaybeDestValue)
6682     return false;
6683 
6684   DestValue = std::move(*MaybeDestValue);
6685   return true;
6686 }
6687 
6688 template <class Derived>
6689 class ExprEvaluatorBase
6690   : public ConstStmtVisitor<Derived, bool> {
6691 private:
6692   Derived &getDerived() { return static_cast<Derived&>(*this); }
6693   bool DerivedSuccess(const APValue &V, const Expr *E) {
6694     return getDerived().Success(V, E);
6695   }
6696   bool DerivedZeroInitialization(const Expr *E) {
6697     return getDerived().ZeroInitialization(E);
6698   }
6699 
6700   // Check whether a conditional operator with a non-constant condition is a
6701   // potential constant expression. If neither arm is a potential constant
6702   // expression, then the conditional operator is not either.
6703   template<typename ConditionalOperator>
6704   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
6705     assert(Info.checkingPotentialConstantExpression());
6706 
6707     // Speculatively evaluate both arms.
6708     SmallVector<PartialDiagnosticAt, 8> Diag;
6709     {
6710       SpeculativeEvaluationRAII Speculate(Info, &Diag);
6711       StmtVisitorTy::Visit(E->getFalseExpr());
6712       if (Diag.empty())
6713         return;
6714     }
6715 
6716     {
6717       SpeculativeEvaluationRAII Speculate(Info, &Diag);
6718       Diag.clear();
6719       StmtVisitorTy::Visit(E->getTrueExpr());
6720       if (Diag.empty())
6721         return;
6722     }
6723 
6724     Error(E, diag::note_constexpr_conditional_never_const);
6725   }
6726 
6727 
6728   template<typename ConditionalOperator>
6729   bool HandleConditionalOperator(const ConditionalOperator *E) {
6730     bool BoolResult;
6731     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
6732       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
6733         CheckPotentialConstantConditional(E);
6734         return false;
6735       }
6736       if (Info.noteFailure()) {
6737         StmtVisitorTy::Visit(E->getTrueExpr());
6738         StmtVisitorTy::Visit(E->getFalseExpr());
6739       }
6740       return false;
6741     }
6742 
6743     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
6744     return StmtVisitorTy::Visit(EvalExpr);
6745   }
6746 
6747 protected:
6748   EvalInfo &Info;
6749   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
6750   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
6751 
6752   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
6753     return Info.CCEDiag(E, D);
6754   }
6755 
6756   bool ZeroInitialization(const Expr *E) { return Error(E); }
6757 
6758 public:
6759   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
6760 
6761   EvalInfo &getEvalInfo() { return Info; }
6762 
6763   /// Report an evaluation error. This should only be called when an error is
6764   /// first discovered. When propagating an error, just return false.
6765   bool Error(const Expr *E, diag::kind D) {
6766     Info.FFDiag(E, D);
6767     return false;
6768   }
6769   bool Error(const Expr *E) {
6770     return Error(E, diag::note_invalid_subexpr_in_const_expr);
6771   }
6772 
6773   bool VisitStmt(const Stmt *) {
6774     llvm_unreachable("Expression evaluator should not be called on stmts");
6775   }
6776   bool VisitExpr(const Expr *E) {
6777     return Error(E);
6778   }
6779 
6780   bool VisitConstantExpr(const ConstantExpr *E) {
6781     if (E->hasAPValueResult())
6782       return DerivedSuccess(E->getAPValueResult(), E);
6783 
6784     return StmtVisitorTy::Visit(E->getSubExpr());
6785   }
6786 
6787   bool VisitParenExpr(const ParenExpr *E)
6788     { return StmtVisitorTy::Visit(E->getSubExpr()); }
6789   bool VisitUnaryExtension(const UnaryOperator *E)
6790     { return StmtVisitorTy::Visit(E->getSubExpr()); }
6791   bool VisitUnaryPlus(const UnaryOperator *E)
6792     { return StmtVisitorTy::Visit(E->getSubExpr()); }
6793   bool VisitChooseExpr(const ChooseExpr *E)
6794     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
6795   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
6796     { return StmtVisitorTy::Visit(E->getResultExpr()); }
6797   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
6798     { return StmtVisitorTy::Visit(E->getReplacement()); }
6799   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
6800     TempVersionRAII RAII(*Info.CurrentCall);
6801     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
6802     return StmtVisitorTy::Visit(E->getExpr());
6803   }
6804   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
6805     TempVersionRAII RAII(*Info.CurrentCall);
6806     // The initializer may not have been parsed yet, or might be erroneous.
6807     if (!E->getExpr())
6808       return Error(E);
6809     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
6810     return StmtVisitorTy::Visit(E->getExpr());
6811   }
6812 
6813   bool VisitExprWithCleanups(const ExprWithCleanups *E) {
6814     FullExpressionRAII Scope(Info);
6815     return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
6816   }
6817 
6818   // Temporaries are registered when created, so we don't care about
6819   // CXXBindTemporaryExpr.
6820   bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
6821     return StmtVisitorTy::Visit(E->getSubExpr());
6822   }
6823 
6824   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
6825     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
6826     return static_cast<Derived*>(this)->VisitCastExpr(E);
6827   }
6828   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
6829     if (!Info.Ctx.getLangOpts().CPlusPlus2a)
6830       CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
6831     return static_cast<Derived*>(this)->VisitCastExpr(E);
6832   }
6833   bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
6834     return static_cast<Derived*>(this)->VisitCastExpr(E);
6835   }
6836 
6837   bool VisitBinaryOperator(const BinaryOperator *E) {
6838     switch (E->getOpcode()) {
6839     default:
6840       return Error(E);
6841 
6842     case BO_Comma:
6843       VisitIgnoredValue(E->getLHS());
6844       return StmtVisitorTy::Visit(E->getRHS());
6845 
6846     case BO_PtrMemD:
6847     case BO_PtrMemI: {
6848       LValue Obj;
6849       if (!HandleMemberPointerAccess(Info, E, Obj))
6850         return false;
6851       APValue Result;
6852       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
6853         return false;
6854       return DerivedSuccess(Result, E);
6855     }
6856     }
6857   }
6858 
6859   bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
6860     return StmtVisitorTy::Visit(E->getSemanticForm());
6861   }
6862 
6863   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
6864     // Evaluate and cache the common expression. We treat it as a temporary,
6865     // even though it's not quite the same thing.
6866     LValue CommonLV;
6867     if (!Evaluate(Info.CurrentCall->createTemporary(
6868                       E->getOpaqueValue(),
6869                       getStorageType(Info.Ctx, E->getOpaqueValue()), false,
6870                       CommonLV),
6871                   Info, E->getCommon()))
6872       return false;
6873 
6874     return HandleConditionalOperator(E);
6875   }
6876 
6877   bool VisitConditionalOperator(const ConditionalOperator *E) {
6878     bool IsBcpCall = false;
6879     // If the condition (ignoring parens) is a __builtin_constant_p call,
6880     // the result is a constant expression if it can be folded without
6881     // side-effects. This is an important GNU extension. See GCC PR38377
6882     // for discussion.
6883     if (const CallExpr *CallCE =
6884           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
6885       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
6886         IsBcpCall = true;
6887 
6888     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
6889     // constant expression; we can't check whether it's potentially foldable.
6890     // FIXME: We should instead treat __builtin_constant_p as non-constant if
6891     // it would return 'false' in this mode.
6892     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
6893       return false;
6894 
6895     FoldConstant Fold(Info, IsBcpCall);
6896     if (!HandleConditionalOperator(E)) {
6897       Fold.keepDiagnostics();
6898       return false;
6899     }
6900 
6901     return true;
6902   }
6903 
6904   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
6905     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
6906       return DerivedSuccess(*Value, E);
6907 
6908     const Expr *Source = E->getSourceExpr();
6909     if (!Source)
6910       return Error(E);
6911     if (Source == E) { // sanity checking.
6912       assert(0 && "OpaqueValueExpr recursively refers to itself");
6913       return Error(E);
6914     }
6915     return StmtVisitorTy::Visit(Source);
6916   }
6917 
6918   bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
6919     for (const Expr *SemE : E->semantics()) {
6920       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
6921         // FIXME: We can't handle the case where an OpaqueValueExpr is also the
6922         // result expression: there could be two different LValues that would
6923         // refer to the same object in that case, and we can't model that.
6924         if (SemE == E->getResultExpr())
6925           return Error(E);
6926 
6927         // Unique OVEs get evaluated if and when we encounter them when
6928         // emitting the rest of the semantic form, rather than eagerly.
6929         if (OVE->isUnique())
6930           continue;
6931 
6932         LValue LV;
6933         if (!Evaluate(Info.CurrentCall->createTemporary(
6934                           OVE, getStorageType(Info.Ctx, OVE), false, LV),
6935                       Info, OVE->getSourceExpr()))
6936           return false;
6937       } else if (SemE == E->getResultExpr()) {
6938         if (!StmtVisitorTy::Visit(SemE))
6939           return false;
6940       } else {
6941         if (!EvaluateIgnoredValue(Info, SemE))
6942           return false;
6943       }
6944     }
6945     return true;
6946   }
6947 
6948   bool VisitCallExpr(const CallExpr *E) {
6949     APValue Result;
6950     if (!handleCallExpr(E, Result, nullptr))
6951       return false;
6952     return DerivedSuccess(Result, E);
6953   }
6954 
6955   bool handleCallExpr(const CallExpr *E, APValue &Result,
6956                      const LValue *ResultSlot) {
6957     const Expr *Callee = E->getCallee()->IgnoreParens();
6958     QualType CalleeType = Callee->getType();
6959 
6960     const FunctionDecl *FD = nullptr;
6961     LValue *This = nullptr, ThisVal;
6962     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
6963     bool HasQualifier = false;
6964 
6965     // Extract function decl and 'this' pointer from the callee.
6966     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
6967       const CXXMethodDecl *Member = nullptr;
6968       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
6969         // Explicit bound member calls, such as x.f() or p->g();
6970         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
6971           return false;
6972         Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
6973         if (!Member)
6974           return Error(Callee);
6975         This = &ThisVal;
6976         HasQualifier = ME->hasQualifier();
6977       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
6978         // Indirect bound member calls ('.*' or '->*').
6979         const ValueDecl *D =
6980             HandleMemberPointerAccess(Info, BE, ThisVal, false);
6981         if (!D)
6982           return false;
6983         Member = dyn_cast<CXXMethodDecl>(D);
6984         if (!Member)
6985           return Error(Callee);
6986         This = &ThisVal;
6987       } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
6988         if (!Info.getLangOpts().CPlusPlus2a)
6989           Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
6990         return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
6991                HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
6992       } else
6993         return Error(Callee);
6994       FD = Member;
6995     } else if (CalleeType->isFunctionPointerType()) {
6996       LValue Call;
6997       if (!EvaluatePointer(Callee, Call, Info))
6998         return false;
6999 
7000       if (!Call.getLValueOffset().isZero())
7001         return Error(Callee);
7002       FD = dyn_cast_or_null<FunctionDecl>(
7003                              Call.getLValueBase().dyn_cast<const ValueDecl*>());
7004       if (!FD)
7005         return Error(Callee);
7006       // Don't call function pointers which have been cast to some other type.
7007       // Per DR (no number yet), the caller and callee can differ in noexcept.
7008       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7009         CalleeType->getPointeeType(), FD->getType())) {
7010         return Error(E);
7011       }
7012 
7013       // Overloaded operator calls to member functions are represented as normal
7014       // calls with '*this' as the first argument.
7015       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7016       if (MD && !MD->isStatic()) {
7017         // FIXME: When selecting an implicit conversion for an overloaded
7018         // operator delete, we sometimes try to evaluate calls to conversion
7019         // operators without a 'this' parameter!
7020         if (Args.empty())
7021           return Error(E);
7022 
7023         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7024           return false;
7025         This = &ThisVal;
7026         Args = Args.slice(1);
7027       } else if (MD && MD->isLambdaStaticInvoker()) {
7028         // Map the static invoker for the lambda back to the call operator.
7029         // Conveniently, we don't have to slice out the 'this' argument (as is
7030         // being done for the non-static case), since a static member function
7031         // doesn't have an implicit argument passed in.
7032         const CXXRecordDecl *ClosureClass = MD->getParent();
7033         assert(
7034             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7035             "Number of captures must be zero for conversion to function-ptr");
7036 
7037         const CXXMethodDecl *LambdaCallOp =
7038             ClosureClass->getLambdaCallOperator();
7039 
7040         // Set 'FD', the function that will be called below, to the call
7041         // operator.  If the closure object represents a generic lambda, find
7042         // the corresponding specialization of the call operator.
7043 
7044         if (ClosureClass->isGenericLambda()) {
7045           assert(MD->isFunctionTemplateSpecialization() &&
7046                  "A generic lambda's static-invoker function must be a "
7047                  "template specialization");
7048           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7049           FunctionTemplateDecl *CallOpTemplate =
7050               LambdaCallOp->getDescribedFunctionTemplate();
7051           void *InsertPos = nullptr;
7052           FunctionDecl *CorrespondingCallOpSpecialization =
7053               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7054           assert(CorrespondingCallOpSpecialization &&
7055                  "We must always have a function call operator specialization "
7056                  "that corresponds to our static invoker specialization");
7057           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7058         } else
7059           FD = LambdaCallOp;
7060       } else if (FD->isReplaceableGlobalAllocationFunction()) {
7061         if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7062             FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7063           LValue Ptr;
7064           if (!HandleOperatorNewCall(Info, E, Ptr))
7065             return false;
7066           Ptr.moveInto(Result);
7067           return true;
7068         } else {
7069           return HandleOperatorDeleteCall(Info, E);
7070         }
7071       }
7072     } else
7073       return Error(E);
7074 
7075     SmallVector<QualType, 4> CovariantAdjustmentPath;
7076     if (This) {
7077       auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7078       if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
7079         // Perform virtual dispatch, if necessary.
7080         FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
7081                                    CovariantAdjustmentPath);
7082         if (!FD)
7083           return false;
7084       } else {
7085         // Check that the 'this' pointer points to an object of the right type.
7086         // FIXME: If this is an assignment operator call, we may need to change
7087         // the active union member before we check this.
7088         if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
7089           return false;
7090       }
7091     }
7092 
7093     // Destructor calls are different enough that they have their own codepath.
7094     if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
7095       assert(This && "no 'this' pointer for destructor call");
7096       return HandleDestruction(Info, E, *This,
7097                                Info.Ctx.getRecordType(DD->getParent()));
7098     }
7099 
7100     const FunctionDecl *Definition = nullptr;
7101     Stmt *Body = FD->getBody(Definition);
7102 
7103     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
7104         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
7105                             Result, ResultSlot))
7106       return false;
7107 
7108     if (!CovariantAdjustmentPath.empty() &&
7109         !HandleCovariantReturnAdjustment(Info, E, Result,
7110                                          CovariantAdjustmentPath))
7111       return false;
7112 
7113     return true;
7114   }
7115 
7116   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7117     return StmtVisitorTy::Visit(E->getInitializer());
7118   }
7119   bool VisitInitListExpr(const InitListExpr *E) {
7120     if (E->getNumInits() == 0)
7121       return DerivedZeroInitialization(E);
7122     if (E->getNumInits() == 1)
7123       return StmtVisitorTy::Visit(E->getInit(0));
7124     return Error(E);
7125   }
7126   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
7127     return DerivedZeroInitialization(E);
7128   }
7129   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
7130     return DerivedZeroInitialization(E);
7131   }
7132   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
7133     return DerivedZeroInitialization(E);
7134   }
7135 
7136   /// A member expression where the object is a prvalue is itself a prvalue.
7137   bool VisitMemberExpr(const MemberExpr *E) {
7138     assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
7139            "missing temporary materialization conversion");
7140     assert(!E->isArrow() && "missing call to bound member function?");
7141 
7142     APValue Val;
7143     if (!Evaluate(Val, Info, E->getBase()))
7144       return false;
7145 
7146     QualType BaseTy = E->getBase()->getType();
7147 
7148     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
7149     if (!FD) return Error(E);
7150     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
7151     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7152            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7153 
7154     // Note: there is no lvalue base here. But this case should only ever
7155     // happen in C or in C++98, where we cannot be evaluating a constexpr
7156     // constructor, which is the only case the base matters.
7157     CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
7158     SubobjectDesignator Designator(BaseTy);
7159     Designator.addDeclUnchecked(FD);
7160 
7161     APValue Result;
7162     return extractSubobject(Info, E, Obj, Designator, Result) &&
7163            DerivedSuccess(Result, E);
7164   }
7165 
7166   bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
7167     APValue Val;
7168     if (!Evaluate(Val, Info, E->getBase()))
7169       return false;
7170 
7171     if (Val.isVector()) {
7172       SmallVector<uint32_t, 4> Indices;
7173       E->getEncodedElementAccess(Indices);
7174       if (Indices.size() == 1) {
7175         // Return scalar.
7176         return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
7177       } else {
7178         // Construct new APValue vector.
7179         SmallVector<APValue, 4> Elts;
7180         for (unsigned I = 0; I < Indices.size(); ++I) {
7181           Elts.push_back(Val.getVectorElt(Indices[I]));
7182         }
7183         APValue VecResult(Elts.data(), Indices.size());
7184         return DerivedSuccess(VecResult, E);
7185       }
7186     }
7187 
7188     return false;
7189   }
7190 
7191   bool VisitCastExpr(const CastExpr *E) {
7192     switch (E->getCastKind()) {
7193     default:
7194       break;
7195 
7196     case CK_AtomicToNonAtomic: {
7197       APValue AtomicVal;
7198       // This does not need to be done in place even for class/array types:
7199       // atomic-to-non-atomic conversion implies copying the object
7200       // representation.
7201       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
7202         return false;
7203       return DerivedSuccess(AtomicVal, E);
7204     }
7205 
7206     case CK_NoOp:
7207     case CK_UserDefinedConversion:
7208       return StmtVisitorTy::Visit(E->getSubExpr());
7209 
7210     case CK_LValueToRValue: {
7211       LValue LVal;
7212       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
7213         return false;
7214       APValue RVal;
7215       // Note, we use the subexpression's type in order to retain cv-qualifiers.
7216       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7217                                           LVal, RVal))
7218         return false;
7219       return DerivedSuccess(RVal, E);
7220     }
7221     case CK_LValueToRValueBitCast: {
7222       APValue DestValue, SourceValue;
7223       if (!Evaluate(SourceValue, Info, E->getSubExpr()))
7224         return false;
7225       if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
7226         return false;
7227       return DerivedSuccess(DestValue, E);
7228     }
7229 
7230     case CK_AddressSpaceConversion: {
7231       APValue Value;
7232       if (!Evaluate(Value, Info, E->getSubExpr()))
7233         return false;
7234       return DerivedSuccess(Value, E);
7235     }
7236     }
7237 
7238     return Error(E);
7239   }
7240 
7241   bool VisitUnaryPostInc(const UnaryOperator *UO) {
7242     return VisitUnaryPostIncDec(UO);
7243   }
7244   bool VisitUnaryPostDec(const UnaryOperator *UO) {
7245     return VisitUnaryPostIncDec(UO);
7246   }
7247   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
7248     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7249       return Error(UO);
7250 
7251     LValue LVal;
7252     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
7253       return false;
7254     APValue RVal;
7255     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
7256                       UO->isIncrementOp(), &RVal))
7257       return false;
7258     return DerivedSuccess(RVal, UO);
7259   }
7260 
7261   bool VisitStmtExpr(const StmtExpr *E) {
7262     // We will have checked the full-expressions inside the statement expression
7263     // when they were completed, and don't need to check them again now.
7264     if (Info.checkingForUndefinedBehavior())
7265       return Error(E);
7266 
7267     const CompoundStmt *CS = E->getSubStmt();
7268     if (CS->body_empty())
7269       return true;
7270 
7271     BlockScopeRAII Scope(Info);
7272     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
7273                                            BE = CS->body_end();
7274          /**/; ++BI) {
7275       if (BI + 1 == BE) {
7276         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
7277         if (!FinalExpr) {
7278           Info.FFDiag((*BI)->getBeginLoc(),
7279                       diag::note_constexpr_stmt_expr_unsupported);
7280           return false;
7281         }
7282         return this->Visit(FinalExpr) && Scope.destroy();
7283       }
7284 
7285       APValue ReturnValue;
7286       StmtResult Result = { ReturnValue, nullptr };
7287       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
7288       if (ESR != ESR_Succeeded) {
7289         // FIXME: If the statement-expression terminated due to 'return',
7290         // 'break', or 'continue', it would be nice to propagate that to
7291         // the outer statement evaluation rather than bailing out.
7292         if (ESR != ESR_Failed)
7293           Info.FFDiag((*BI)->getBeginLoc(),
7294                       diag::note_constexpr_stmt_expr_unsupported);
7295         return false;
7296       }
7297     }
7298 
7299     llvm_unreachable("Return from function from the loop above.");
7300   }
7301 
7302   /// Visit a value which is evaluated, but whose value is ignored.
7303   void VisitIgnoredValue(const Expr *E) {
7304     EvaluateIgnoredValue(Info, E);
7305   }
7306 
7307   /// Potentially visit a MemberExpr's base expression.
7308   void VisitIgnoredBaseExpression(const Expr *E) {
7309     // While MSVC doesn't evaluate the base expression, it does diagnose the
7310     // presence of side-effecting behavior.
7311     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
7312       return;
7313     VisitIgnoredValue(E);
7314   }
7315 };
7316 
7317 } // namespace
7318 
7319 //===----------------------------------------------------------------------===//
7320 // Common base class for lvalue and temporary evaluation.
7321 //===----------------------------------------------------------------------===//
7322 namespace {
7323 template<class Derived>
7324 class LValueExprEvaluatorBase
7325   : public ExprEvaluatorBase<Derived> {
7326 protected:
7327   LValue &Result;
7328   bool InvalidBaseOK;
7329   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
7330   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
7331 
7332   bool Success(APValue::LValueBase B) {
7333     Result.set(B);
7334     return true;
7335   }
7336 
7337   bool evaluatePointer(const Expr *E, LValue &Result) {
7338     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
7339   }
7340 
7341 public:
7342   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
7343       : ExprEvaluatorBaseTy(Info), Result(Result),
7344         InvalidBaseOK(InvalidBaseOK) {}
7345 
7346   bool Success(const APValue &V, const Expr *E) {
7347     Result.setFrom(this->Info.Ctx, V);
7348     return true;
7349   }
7350 
7351   bool VisitMemberExpr(const MemberExpr *E) {
7352     // Handle non-static data members.
7353     QualType BaseTy;
7354     bool EvalOK;
7355     if (E->isArrow()) {
7356       EvalOK = evaluatePointer(E->getBase(), Result);
7357       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
7358     } else if (E->getBase()->isRValue()) {
7359       assert(E->getBase()->getType()->isRecordType());
7360       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
7361       BaseTy = E->getBase()->getType();
7362     } else {
7363       EvalOK = this->Visit(E->getBase());
7364       BaseTy = E->getBase()->getType();
7365     }
7366     if (!EvalOK) {
7367       if (!InvalidBaseOK)
7368         return false;
7369       Result.setInvalid(E);
7370       return true;
7371     }
7372 
7373     const ValueDecl *MD = E->getMemberDecl();
7374     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
7375       assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7376              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7377       (void)BaseTy;
7378       if (!HandleLValueMember(this->Info, E, Result, FD))
7379         return false;
7380     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
7381       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
7382         return false;
7383     } else
7384       return this->Error(E);
7385 
7386     if (MD->getType()->isReferenceType()) {
7387       APValue RefValue;
7388       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
7389                                           RefValue))
7390         return false;
7391       return Success(RefValue, E);
7392     }
7393     return true;
7394   }
7395 
7396   bool VisitBinaryOperator(const BinaryOperator *E) {
7397     switch (E->getOpcode()) {
7398     default:
7399       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7400 
7401     case BO_PtrMemD:
7402     case BO_PtrMemI:
7403       return HandleMemberPointerAccess(this->Info, E, Result);
7404     }
7405   }
7406 
7407   bool VisitCastExpr(const CastExpr *E) {
7408     switch (E->getCastKind()) {
7409     default:
7410       return ExprEvaluatorBaseTy::VisitCastExpr(E);
7411 
7412     case CK_DerivedToBase:
7413     case CK_UncheckedDerivedToBase:
7414       if (!this->Visit(E->getSubExpr()))
7415         return false;
7416 
7417       // Now figure out the necessary offset to add to the base LV to get from
7418       // the derived class to the base class.
7419       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
7420                                   Result);
7421     }
7422   }
7423 };
7424 }
7425 
7426 //===----------------------------------------------------------------------===//
7427 // LValue Evaluation
7428 //
7429 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
7430 // function designators (in C), decl references to void objects (in C), and
7431 // temporaries (if building with -Wno-address-of-temporary).
7432 //
7433 // LValue evaluation produces values comprising a base expression of one of the
7434 // following types:
7435 // - Declarations
7436 //  * VarDecl
7437 //  * FunctionDecl
7438 // - Literals
7439 //  * CompoundLiteralExpr in C (and in global scope in C++)
7440 //  * StringLiteral
7441 //  * PredefinedExpr
7442 //  * ObjCStringLiteralExpr
7443 //  * ObjCEncodeExpr
7444 //  * AddrLabelExpr
7445 //  * BlockExpr
7446 //  * CallExpr for a MakeStringConstant builtin
7447 // - typeid(T) expressions, as TypeInfoLValues
7448 // - Locals and temporaries
7449 //  * MaterializeTemporaryExpr
7450 //  * Any Expr, with a CallIndex indicating the function in which the temporary
7451 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
7452 //    from the AST (FIXME).
7453 //  * A MaterializeTemporaryExpr that has static storage duration, with no
7454 //    CallIndex, for a lifetime-extended temporary.
7455 //  * The ConstantExpr that is currently being evaluated during evaluation of an
7456 //    immediate invocation.
7457 // plus an offset in bytes.
7458 //===----------------------------------------------------------------------===//
7459 namespace {
7460 class LValueExprEvaluator
7461   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
7462 public:
7463   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
7464     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
7465 
7466   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
7467   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
7468 
7469   bool VisitDeclRefExpr(const DeclRefExpr *E);
7470   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
7471   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
7472   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
7473   bool VisitMemberExpr(const MemberExpr *E);
7474   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
7475   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
7476   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
7477   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
7478   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
7479   bool VisitUnaryDeref(const UnaryOperator *E);
7480   bool VisitUnaryReal(const UnaryOperator *E);
7481   bool VisitUnaryImag(const UnaryOperator *E);
7482   bool VisitUnaryPreInc(const UnaryOperator *UO) {
7483     return VisitUnaryPreIncDec(UO);
7484   }
7485   bool VisitUnaryPreDec(const UnaryOperator *UO) {
7486     return VisitUnaryPreIncDec(UO);
7487   }
7488   bool VisitBinAssign(const BinaryOperator *BO);
7489   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
7490 
7491   bool VisitCastExpr(const CastExpr *E) {
7492     switch (E->getCastKind()) {
7493     default:
7494       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
7495 
7496     case CK_LValueBitCast:
7497       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7498       if (!Visit(E->getSubExpr()))
7499         return false;
7500       Result.Designator.setInvalid();
7501       return true;
7502 
7503     case CK_BaseToDerived:
7504       if (!Visit(E->getSubExpr()))
7505         return false;
7506       return HandleBaseToDerivedCast(Info, E, Result);
7507 
7508     case CK_Dynamic:
7509       if (!Visit(E->getSubExpr()))
7510         return false;
7511       return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
7512     }
7513   }
7514 };
7515 } // end anonymous namespace
7516 
7517 /// Evaluate an expression as an lvalue. This can be legitimately called on
7518 /// expressions which are not glvalues, in three cases:
7519 ///  * function designators in C, and
7520 ///  * "extern void" objects
7521 ///  * @selector() expressions in Objective-C
7522 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
7523                            bool InvalidBaseOK) {
7524   assert(E->isGLValue() || E->getType()->isFunctionType() ||
7525          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
7526   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
7527 }
7528 
7529 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
7530   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
7531     return Success(FD);
7532   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
7533     return VisitVarDecl(E, VD);
7534   if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
7535     return Visit(BD->getBinding());
7536   return Error(E);
7537 }
7538 
7539 
7540 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
7541 
7542   // If we are within a lambda's call operator, check whether the 'VD' referred
7543   // to within 'E' actually represents a lambda-capture that maps to a
7544   // data-member/field within the closure object, and if so, evaluate to the
7545   // field or what the field refers to.
7546   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
7547       isa<DeclRefExpr>(E) &&
7548       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
7549     // We don't always have a complete capture-map when checking or inferring if
7550     // the function call operator meets the requirements of a constexpr function
7551     // - but we don't need to evaluate the captures to determine constexprness
7552     // (dcl.constexpr C++17).
7553     if (Info.checkingPotentialConstantExpression())
7554       return false;
7555 
7556     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
7557       // Start with 'Result' referring to the complete closure object...
7558       Result = *Info.CurrentCall->This;
7559       // ... then update it to refer to the field of the closure object
7560       // that represents the capture.
7561       if (!HandleLValueMember(Info, E, Result, FD))
7562         return false;
7563       // And if the field is of reference type, update 'Result' to refer to what
7564       // the field refers to.
7565       if (FD->getType()->isReferenceType()) {
7566         APValue RVal;
7567         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
7568                                             RVal))
7569           return false;
7570         Result.setFrom(Info.Ctx, RVal);
7571       }
7572       return true;
7573     }
7574   }
7575   CallStackFrame *Frame = nullptr;
7576   if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
7577     // Only if a local variable was declared in the function currently being
7578     // evaluated, do we expect to be able to find its value in the current
7579     // frame. (Otherwise it was likely declared in an enclosing context and
7580     // could either have a valid evaluatable value (for e.g. a constexpr
7581     // variable) or be ill-formed (and trigger an appropriate evaluation
7582     // diagnostic)).
7583     if (Info.CurrentCall->Callee &&
7584         Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
7585       Frame = Info.CurrentCall;
7586     }
7587   }
7588 
7589   if (!VD->getType()->isReferenceType()) {
7590     if (Frame) {
7591       Result.set({VD, Frame->Index,
7592                   Info.CurrentCall->getCurrentTemporaryVersion(VD)});
7593       return true;
7594     }
7595     return Success(VD);
7596   }
7597 
7598   APValue *V;
7599   if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
7600     return false;
7601   if (!V->hasValue()) {
7602     // FIXME: Is it possible for V to be indeterminate here? If so, we should
7603     // adjust the diagnostic to say that.
7604     if (!Info.checkingPotentialConstantExpression())
7605       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
7606     return false;
7607   }
7608   return Success(*V, E);
7609 }
7610 
7611 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
7612     const MaterializeTemporaryExpr *E) {
7613   // Walk through the expression to find the materialized temporary itself.
7614   SmallVector<const Expr *, 2> CommaLHSs;
7615   SmallVector<SubobjectAdjustment, 2> Adjustments;
7616   const Expr *Inner =
7617       E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
7618 
7619   // If we passed any comma operators, evaluate their LHSs.
7620   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
7621     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
7622       return false;
7623 
7624   // A materialized temporary with static storage duration can appear within the
7625   // result of a constant expression evaluation, so we need to preserve its
7626   // value for use outside this evaluation.
7627   APValue *Value;
7628   if (E->getStorageDuration() == SD_Static) {
7629     Value = E->getOrCreateValue(true);
7630     *Value = APValue();
7631     Result.set(E);
7632   } else {
7633     Value = &Info.CurrentCall->createTemporary(
7634         E, E->getType(), E->getStorageDuration() == SD_Automatic, Result);
7635   }
7636 
7637   QualType Type = Inner->getType();
7638 
7639   // Materialize the temporary itself.
7640   if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
7641     *Value = APValue();
7642     return false;
7643   }
7644 
7645   // Adjust our lvalue to refer to the desired subobject.
7646   for (unsigned I = Adjustments.size(); I != 0; /**/) {
7647     --I;
7648     switch (Adjustments[I].Kind) {
7649     case SubobjectAdjustment::DerivedToBaseAdjustment:
7650       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
7651                                 Type, Result))
7652         return false;
7653       Type = Adjustments[I].DerivedToBase.BasePath->getType();
7654       break;
7655 
7656     case SubobjectAdjustment::FieldAdjustment:
7657       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
7658         return false;
7659       Type = Adjustments[I].Field->getType();
7660       break;
7661 
7662     case SubobjectAdjustment::MemberPointerAdjustment:
7663       if (!HandleMemberPointerAccess(this->Info, Type, Result,
7664                                      Adjustments[I].Ptr.RHS))
7665         return false;
7666       Type = Adjustments[I].Ptr.MPT->getPointeeType();
7667       break;
7668     }
7669   }
7670 
7671   return true;
7672 }
7673 
7674 bool
7675 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7676   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
7677          "lvalue compound literal in c++?");
7678   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
7679   // only see this when folding in C, so there's no standard to follow here.
7680   return Success(E);
7681 }
7682 
7683 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
7684   TypeInfoLValue TypeInfo;
7685 
7686   if (!E->isPotentiallyEvaluated()) {
7687     if (E->isTypeOperand())
7688       TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
7689     else
7690       TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
7691   } else {
7692     if (!Info.Ctx.getLangOpts().CPlusPlus2a) {
7693       Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
7694         << E->getExprOperand()->getType()
7695         << E->getExprOperand()->getSourceRange();
7696     }
7697 
7698     if (!Visit(E->getExprOperand()))
7699       return false;
7700 
7701     Optional<DynamicType> DynType =
7702         ComputeDynamicType(Info, E, Result, AK_TypeId);
7703     if (!DynType)
7704       return false;
7705 
7706     TypeInfo =
7707         TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
7708   }
7709 
7710   return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
7711 }
7712 
7713 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
7714   return Success(E);
7715 }
7716 
7717 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
7718   // Handle static data members.
7719   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
7720     VisitIgnoredBaseExpression(E->getBase());
7721     return VisitVarDecl(E, VD);
7722   }
7723 
7724   // Handle static member functions.
7725   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
7726     if (MD->isStatic()) {
7727       VisitIgnoredBaseExpression(E->getBase());
7728       return Success(MD);
7729     }
7730   }
7731 
7732   // Handle non-static data members.
7733   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
7734 }
7735 
7736 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
7737   // FIXME: Deal with vectors as array subscript bases.
7738   if (E->getBase()->getType()->isVectorType())
7739     return Error(E);
7740 
7741   bool Success = true;
7742   if (!evaluatePointer(E->getBase(), Result)) {
7743     if (!Info.noteFailure())
7744       return false;
7745     Success = false;
7746   }
7747 
7748   APSInt Index;
7749   if (!EvaluateInteger(E->getIdx(), Index, Info))
7750     return false;
7751 
7752   return Success &&
7753          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
7754 }
7755 
7756 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
7757   return evaluatePointer(E->getSubExpr(), Result);
7758 }
7759 
7760 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7761   if (!Visit(E->getSubExpr()))
7762     return false;
7763   // __real is a no-op on scalar lvalues.
7764   if (E->getSubExpr()->getType()->isAnyComplexType())
7765     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
7766   return true;
7767 }
7768 
7769 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
7770   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
7771          "lvalue __imag__ on scalar?");
7772   if (!Visit(E->getSubExpr()))
7773     return false;
7774   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
7775   return true;
7776 }
7777 
7778 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
7779   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7780     return Error(UO);
7781 
7782   if (!this->Visit(UO->getSubExpr()))
7783     return false;
7784 
7785   return handleIncDec(
7786       this->Info, UO, Result, UO->getSubExpr()->getType(),
7787       UO->isIncrementOp(), nullptr);
7788 }
7789 
7790 bool LValueExprEvaluator::VisitCompoundAssignOperator(
7791     const CompoundAssignOperator *CAO) {
7792   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7793     return Error(CAO);
7794 
7795   APValue RHS;
7796 
7797   // The overall lvalue result is the result of evaluating the LHS.
7798   if (!this->Visit(CAO->getLHS())) {
7799     if (Info.noteFailure())
7800       Evaluate(RHS, this->Info, CAO->getRHS());
7801     return false;
7802   }
7803 
7804   if (!Evaluate(RHS, this->Info, CAO->getRHS()))
7805     return false;
7806 
7807   return handleCompoundAssignment(
7808       this->Info, CAO,
7809       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
7810       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
7811 }
7812 
7813 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
7814   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7815     return Error(E);
7816 
7817   APValue NewVal;
7818 
7819   if (!this->Visit(E->getLHS())) {
7820     if (Info.noteFailure())
7821       Evaluate(NewVal, this->Info, E->getRHS());
7822     return false;
7823   }
7824 
7825   if (!Evaluate(NewVal, this->Info, E->getRHS()))
7826     return false;
7827 
7828   if (Info.getLangOpts().CPlusPlus2a &&
7829       !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
7830     return false;
7831 
7832   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
7833                           NewVal);
7834 }
7835 
7836 //===----------------------------------------------------------------------===//
7837 // Pointer Evaluation
7838 //===----------------------------------------------------------------------===//
7839 
7840 /// Attempts to compute the number of bytes available at the pointer
7841 /// returned by a function with the alloc_size attribute. Returns true if we
7842 /// were successful. Places an unsigned number into `Result`.
7843 ///
7844 /// This expects the given CallExpr to be a call to a function with an
7845 /// alloc_size attribute.
7846 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
7847                                             const CallExpr *Call,
7848                                             llvm::APInt &Result) {
7849   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
7850 
7851   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
7852   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
7853   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
7854   if (Call->getNumArgs() <= SizeArgNo)
7855     return false;
7856 
7857   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
7858     Expr::EvalResult ExprResult;
7859     if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
7860       return false;
7861     Into = ExprResult.Val.getInt();
7862     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
7863       return false;
7864     Into = Into.zextOrSelf(BitsInSizeT);
7865     return true;
7866   };
7867 
7868   APSInt SizeOfElem;
7869   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
7870     return false;
7871 
7872   if (!AllocSize->getNumElemsParam().isValid()) {
7873     Result = std::move(SizeOfElem);
7874     return true;
7875   }
7876 
7877   APSInt NumberOfElems;
7878   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
7879   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
7880     return false;
7881 
7882   bool Overflow;
7883   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
7884   if (Overflow)
7885     return false;
7886 
7887   Result = std::move(BytesAvailable);
7888   return true;
7889 }
7890 
7891 /// Convenience function. LVal's base must be a call to an alloc_size
7892 /// function.
7893 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
7894                                             const LValue &LVal,
7895                                             llvm::APInt &Result) {
7896   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7897          "Can't get the size of a non alloc_size function");
7898   const auto *Base = LVal.getLValueBase().get<const Expr *>();
7899   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
7900   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
7901 }
7902 
7903 /// Attempts to evaluate the given LValueBase as the result of a call to
7904 /// a function with the alloc_size attribute. If it was possible to do so, this
7905 /// function will return true, make Result's Base point to said function call,
7906 /// and mark Result's Base as invalid.
7907 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
7908                                       LValue &Result) {
7909   if (Base.isNull())
7910     return false;
7911 
7912   // Because we do no form of static analysis, we only support const variables.
7913   //
7914   // Additionally, we can't support parameters, nor can we support static
7915   // variables (in the latter case, use-before-assign isn't UB; in the former,
7916   // we have no clue what they'll be assigned to).
7917   const auto *VD =
7918       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
7919   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
7920     return false;
7921 
7922   const Expr *Init = VD->getAnyInitializer();
7923   if (!Init)
7924     return false;
7925 
7926   const Expr *E = Init->IgnoreParens();
7927   if (!tryUnwrapAllocSizeCall(E))
7928     return false;
7929 
7930   // Store E instead of E unwrapped so that the type of the LValue's base is
7931   // what the user wanted.
7932   Result.setInvalid(E);
7933 
7934   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
7935   Result.addUnsizedArray(Info, E, Pointee);
7936   return true;
7937 }
7938 
7939 namespace {
7940 class PointerExprEvaluator
7941   : public ExprEvaluatorBase<PointerExprEvaluator> {
7942   LValue &Result;
7943   bool InvalidBaseOK;
7944 
7945   bool Success(const Expr *E) {
7946     Result.set(E);
7947     return true;
7948   }
7949 
7950   bool evaluateLValue(const Expr *E, LValue &Result) {
7951     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
7952   }
7953 
7954   bool evaluatePointer(const Expr *E, LValue &Result) {
7955     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
7956   }
7957 
7958   bool visitNonBuiltinCallExpr(const CallExpr *E);
7959 public:
7960 
7961   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
7962       : ExprEvaluatorBaseTy(info), Result(Result),
7963         InvalidBaseOK(InvalidBaseOK) {}
7964 
7965   bool Success(const APValue &V, const Expr *E) {
7966     Result.setFrom(Info.Ctx, V);
7967     return true;
7968   }
7969   bool ZeroInitialization(const Expr *E) {
7970     Result.setNull(Info.Ctx, E->getType());
7971     return true;
7972   }
7973 
7974   bool VisitBinaryOperator(const BinaryOperator *E);
7975   bool VisitCastExpr(const CastExpr* E);
7976   bool VisitUnaryAddrOf(const UnaryOperator *E);
7977   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
7978       { return Success(E); }
7979   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
7980     if (E->isExpressibleAsConstantInitializer())
7981       return Success(E);
7982     if (Info.noteFailure())
7983       EvaluateIgnoredValue(Info, E->getSubExpr());
7984     return Error(E);
7985   }
7986   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
7987       { return Success(E); }
7988   bool VisitCallExpr(const CallExpr *E);
7989   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
7990   bool VisitBlockExpr(const BlockExpr *E) {
7991     if (!E->getBlockDecl()->hasCaptures())
7992       return Success(E);
7993     return Error(E);
7994   }
7995   bool VisitCXXThisExpr(const CXXThisExpr *E) {
7996     // Can't look at 'this' when checking a potential constant expression.
7997     if (Info.checkingPotentialConstantExpression())
7998       return false;
7999     if (!Info.CurrentCall->This) {
8000       if (Info.getLangOpts().CPlusPlus11)
8001         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
8002       else
8003         Info.FFDiag(E);
8004       return false;
8005     }
8006     Result = *Info.CurrentCall->This;
8007     // If we are inside a lambda's call operator, the 'this' expression refers
8008     // to the enclosing '*this' object (either by value or reference) which is
8009     // either copied into the closure object's field that represents the '*this'
8010     // or refers to '*this'.
8011     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
8012       // Ensure we actually have captured 'this'. (an error will have
8013       // been previously reported if not).
8014       if (!Info.CurrentCall->LambdaThisCaptureField)
8015         return false;
8016 
8017       // Update 'Result' to refer to the data member/field of the closure object
8018       // that represents the '*this' capture.
8019       if (!HandleLValueMember(Info, E, Result,
8020                              Info.CurrentCall->LambdaThisCaptureField))
8021         return false;
8022       // If we captured '*this' by reference, replace the field with its referent.
8023       if (Info.CurrentCall->LambdaThisCaptureField->getType()
8024               ->isPointerType()) {
8025         APValue RVal;
8026         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
8027                                             RVal))
8028           return false;
8029 
8030         Result.setFrom(Info.Ctx, RVal);
8031       }
8032     }
8033     return true;
8034   }
8035 
8036   bool VisitCXXNewExpr(const CXXNewExpr *E);
8037 
8038   bool VisitSourceLocExpr(const SourceLocExpr *E) {
8039     assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
8040     APValue LValResult = E->EvaluateInContext(
8041         Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8042     Result.setFrom(Info.Ctx, LValResult);
8043     return true;
8044   }
8045 
8046   // FIXME: Missing: @protocol, @selector
8047 };
8048 } // end anonymous namespace
8049 
8050 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
8051                             bool InvalidBaseOK) {
8052   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
8053   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8054 }
8055 
8056 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8057   if (E->getOpcode() != BO_Add &&
8058       E->getOpcode() != BO_Sub)
8059     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8060 
8061   const Expr *PExp = E->getLHS();
8062   const Expr *IExp = E->getRHS();
8063   if (IExp->getType()->isPointerType())
8064     std::swap(PExp, IExp);
8065 
8066   bool EvalPtrOK = evaluatePointer(PExp, Result);
8067   if (!EvalPtrOK && !Info.noteFailure())
8068     return false;
8069 
8070   llvm::APSInt Offset;
8071   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
8072     return false;
8073 
8074   if (E->getOpcode() == BO_Sub)
8075     negateAsSigned(Offset);
8076 
8077   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
8078   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
8079 }
8080 
8081 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8082   return evaluateLValue(E->getSubExpr(), Result);
8083 }
8084 
8085 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8086   const Expr *SubExpr = E->getSubExpr();
8087 
8088   switch (E->getCastKind()) {
8089   default:
8090     break;
8091   case CK_BitCast:
8092   case CK_CPointerToObjCPointerCast:
8093   case CK_BlockPointerToObjCPointerCast:
8094   case CK_AnyPointerToBlockPointerCast:
8095   case CK_AddressSpaceConversion:
8096     if (!Visit(SubExpr))
8097       return false;
8098     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
8099     // permitted in constant expressions in C++11. Bitcasts from cv void* are
8100     // also static_casts, but we disallow them as a resolution to DR1312.
8101     if (!E->getType()->isVoidPointerType()) {
8102       if (!Result.InvalidBase && !Result.Designator.Invalid &&
8103           !Result.IsNullPtr &&
8104           Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
8105                                           E->getType()->getPointeeType()) &&
8106           Info.getStdAllocatorCaller("allocate")) {
8107         // Inside a call to std::allocator::allocate and friends, we permit
8108         // casting from void* back to cv1 T* for a pointer that points to a
8109         // cv2 T.
8110       } else {
8111         Result.Designator.setInvalid();
8112         if (SubExpr->getType()->isVoidPointerType())
8113           CCEDiag(E, diag::note_constexpr_invalid_cast)
8114             << 3 << SubExpr->getType();
8115         else
8116           CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8117       }
8118     }
8119     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
8120       ZeroInitialization(E);
8121     return true;
8122 
8123   case CK_DerivedToBase:
8124   case CK_UncheckedDerivedToBase:
8125     if (!evaluatePointer(E->getSubExpr(), Result))
8126       return false;
8127     if (!Result.Base && Result.Offset.isZero())
8128       return true;
8129 
8130     // Now figure out the necessary offset to add to the base LV to get from
8131     // the derived class to the base class.
8132     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
8133                                   castAs<PointerType>()->getPointeeType(),
8134                                 Result);
8135 
8136   case CK_BaseToDerived:
8137     if (!Visit(E->getSubExpr()))
8138       return false;
8139     if (!Result.Base && Result.Offset.isZero())
8140       return true;
8141     return HandleBaseToDerivedCast(Info, E, Result);
8142 
8143   case CK_Dynamic:
8144     if (!Visit(E->getSubExpr()))
8145       return false;
8146     return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8147 
8148   case CK_NullToPointer:
8149     VisitIgnoredValue(E->getSubExpr());
8150     return ZeroInitialization(E);
8151 
8152   case CK_IntegralToPointer: {
8153     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8154 
8155     APValue Value;
8156     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
8157       break;
8158 
8159     if (Value.isInt()) {
8160       unsigned Size = Info.Ctx.getTypeSize(E->getType());
8161       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
8162       Result.Base = (Expr*)nullptr;
8163       Result.InvalidBase = false;
8164       Result.Offset = CharUnits::fromQuantity(N);
8165       Result.Designator.setInvalid();
8166       Result.IsNullPtr = false;
8167       return true;
8168     } else {
8169       // Cast is of an lvalue, no need to change value.
8170       Result.setFrom(Info.Ctx, Value);
8171       return true;
8172     }
8173   }
8174 
8175   case CK_ArrayToPointerDecay: {
8176     if (SubExpr->isGLValue()) {
8177       if (!evaluateLValue(SubExpr, Result))
8178         return false;
8179     } else {
8180       APValue &Value = Info.CurrentCall->createTemporary(
8181           SubExpr, SubExpr->getType(), false, Result);
8182       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
8183         return false;
8184     }
8185     // The result is a pointer to the first element of the array.
8186     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
8187     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
8188       Result.addArray(Info, E, CAT);
8189     else
8190       Result.addUnsizedArray(Info, E, AT->getElementType());
8191     return true;
8192   }
8193 
8194   case CK_FunctionToPointerDecay:
8195     return evaluateLValue(SubExpr, Result);
8196 
8197   case CK_LValueToRValue: {
8198     LValue LVal;
8199     if (!evaluateLValue(E->getSubExpr(), LVal))
8200       return false;
8201 
8202     APValue RVal;
8203     // Note, we use the subexpression's type in order to retain cv-qualifiers.
8204     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8205                                         LVal, RVal))
8206       return InvalidBaseOK &&
8207              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
8208     return Success(RVal, E);
8209   }
8210   }
8211 
8212   return ExprEvaluatorBaseTy::VisitCastExpr(E);
8213 }
8214 
8215 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
8216                                 UnaryExprOrTypeTrait ExprKind) {
8217   // C++ [expr.alignof]p3:
8218   //     When alignof is applied to a reference type, the result is the
8219   //     alignment of the referenced type.
8220   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
8221     T = Ref->getPointeeType();
8222 
8223   if (T.getQualifiers().hasUnaligned())
8224     return CharUnits::One();
8225 
8226   const bool AlignOfReturnsPreferred =
8227       Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
8228 
8229   // __alignof is defined to return the preferred alignment.
8230   // Before 8, clang returned the preferred alignment for alignof and _Alignof
8231   // as well.
8232   if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
8233     return Info.Ctx.toCharUnitsFromBits(
8234       Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
8235   // alignof and _Alignof are defined to return the ABI alignment.
8236   else if (ExprKind == UETT_AlignOf)
8237     return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
8238   else
8239     llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
8240 }
8241 
8242 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
8243                                 UnaryExprOrTypeTrait ExprKind) {
8244   E = E->IgnoreParens();
8245 
8246   // The kinds of expressions that we have special-case logic here for
8247   // should be kept up to date with the special checks for those
8248   // expressions in Sema.
8249 
8250   // alignof decl is always accepted, even if it doesn't make sense: we default
8251   // to 1 in those cases.
8252   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8253     return Info.Ctx.getDeclAlign(DRE->getDecl(),
8254                                  /*RefAsPointee*/true);
8255 
8256   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
8257     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
8258                                  /*RefAsPointee*/true);
8259 
8260   return GetAlignOfType(Info, E->getType(), ExprKind);
8261 }
8262 
8263 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
8264   if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
8265     return Info.Ctx.getDeclAlign(VD);
8266   if (const auto *E = Value.Base.dyn_cast<const Expr *>())
8267     return GetAlignOfExpr(Info, E, UETT_AlignOf);
8268   return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
8269 }
8270 
8271 /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
8272 /// __builtin_is_aligned and __builtin_assume_aligned.
8273 static bool getAlignmentArgument(const Expr *E, QualType ForType,
8274                                  EvalInfo &Info, APSInt &Alignment) {
8275   if (!EvaluateInteger(E, Alignment, Info))
8276     return false;
8277   if (Alignment < 0 || !Alignment.isPowerOf2()) {
8278     Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
8279     return false;
8280   }
8281   unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
8282   APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
8283   if (APSInt::compareValues(Alignment, MaxValue) > 0) {
8284     Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
8285         << MaxValue << ForType << Alignment;
8286     return false;
8287   }
8288   // Ensure both alignment and source value have the same bit width so that we
8289   // don't assert when computing the resulting value.
8290   APSInt ExtAlignment =
8291       APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
8292   assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
8293          "Alignment should not be changed by ext/trunc");
8294   Alignment = ExtAlignment;
8295   assert(Alignment.getBitWidth() == SrcWidth);
8296   return true;
8297 }
8298 
8299 // To be clear: this happily visits unsupported builtins. Better name welcomed.
8300 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
8301   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
8302     return true;
8303 
8304   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
8305     return false;
8306 
8307   Result.setInvalid(E);
8308   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
8309   Result.addUnsizedArray(Info, E, PointeeTy);
8310   return true;
8311 }
8312 
8313 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
8314   if (IsStringLiteralCall(E))
8315     return Success(E);
8316 
8317   if (unsigned BuiltinOp = E->getBuiltinCallee())
8318     return VisitBuiltinCallExpr(E, BuiltinOp);
8319 
8320   return visitNonBuiltinCallExpr(E);
8321 }
8322 
8323 // Determine if T is a character type for which we guarantee that
8324 // sizeof(T) == 1.
8325 static bool isOneByteCharacterType(QualType T) {
8326   return T->isCharType() || T->isChar8Type();
8327 }
8328 
8329 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8330                                                 unsigned BuiltinOp) {
8331   switch (BuiltinOp) {
8332   case Builtin::BI__builtin_addressof:
8333     return evaluateLValue(E->getArg(0), Result);
8334   case Builtin::BI__builtin_assume_aligned: {
8335     // We need to be very careful here because: if the pointer does not have the
8336     // asserted alignment, then the behavior is undefined, and undefined
8337     // behavior is non-constant.
8338     if (!evaluatePointer(E->getArg(0), Result))
8339       return false;
8340 
8341     LValue OffsetResult(Result);
8342     APSInt Alignment;
8343     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
8344                               Alignment))
8345       return false;
8346     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
8347 
8348     if (E->getNumArgs() > 2) {
8349       APSInt Offset;
8350       if (!EvaluateInteger(E->getArg(2), Offset, Info))
8351         return false;
8352 
8353       int64_t AdditionalOffset = -Offset.getZExtValue();
8354       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
8355     }
8356 
8357     // If there is a base object, then it must have the correct alignment.
8358     if (OffsetResult.Base) {
8359       CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
8360 
8361       if (BaseAlignment < Align) {
8362         Result.Designator.setInvalid();
8363         // FIXME: Add support to Diagnostic for long / long long.
8364         CCEDiag(E->getArg(0),
8365                 diag::note_constexpr_baa_insufficient_alignment) << 0
8366           << (unsigned)BaseAlignment.getQuantity()
8367           << (unsigned)Align.getQuantity();
8368         return false;
8369       }
8370     }
8371 
8372     // The offset must also have the correct alignment.
8373     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
8374       Result.Designator.setInvalid();
8375 
8376       (OffsetResult.Base
8377            ? CCEDiag(E->getArg(0),
8378                      diag::note_constexpr_baa_insufficient_alignment) << 1
8379            : CCEDiag(E->getArg(0),
8380                      diag::note_constexpr_baa_value_insufficient_alignment))
8381         << (int)OffsetResult.Offset.getQuantity()
8382         << (unsigned)Align.getQuantity();
8383       return false;
8384     }
8385 
8386     return true;
8387   }
8388   case Builtin::BI__builtin_align_up:
8389   case Builtin::BI__builtin_align_down: {
8390     if (!evaluatePointer(E->getArg(0), Result))
8391       return false;
8392     APSInt Alignment;
8393     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
8394                               Alignment))
8395       return false;
8396     CharUnits BaseAlignment = getBaseAlignment(Info, Result);
8397     CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
8398     // For align_up/align_down, we can return the same value if the alignment
8399     // is known to be greater or equal to the requested value.
8400     if (PtrAlign.getQuantity() >= Alignment)
8401       return true;
8402 
8403     // The alignment could be greater than the minimum at run-time, so we cannot
8404     // infer much about the resulting pointer value. One case is possible:
8405     // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
8406     // can infer the correct index if the requested alignment is smaller than
8407     // the base alignment so we can perform the computation on the offset.
8408     if (BaseAlignment.getQuantity() >= Alignment) {
8409       assert(Alignment.getBitWidth() <= 64 &&
8410              "Cannot handle > 64-bit address-space");
8411       uint64_t Alignment64 = Alignment.getZExtValue();
8412       CharUnits NewOffset = CharUnits::fromQuantity(
8413           BuiltinOp == Builtin::BI__builtin_align_down
8414               ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
8415               : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
8416       Result.adjustOffset(NewOffset - Result.Offset);
8417       // TODO: diagnose out-of-bounds values/only allow for arrays?
8418       return true;
8419     }
8420     // Otherwise, we cannot constant-evaluate the result.
8421     Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
8422         << Alignment;
8423     return false;
8424   }
8425   case Builtin::BI__builtin_operator_new:
8426     return HandleOperatorNewCall(Info, E, Result);
8427   case Builtin::BI__builtin_launder:
8428     return evaluatePointer(E->getArg(0), Result);
8429   case Builtin::BIstrchr:
8430   case Builtin::BIwcschr:
8431   case Builtin::BImemchr:
8432   case Builtin::BIwmemchr:
8433     if (Info.getLangOpts().CPlusPlus11)
8434       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8435         << /*isConstexpr*/0 << /*isConstructor*/0
8436         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
8437     else
8438       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
8439     LLVM_FALLTHROUGH;
8440   case Builtin::BI__builtin_strchr:
8441   case Builtin::BI__builtin_wcschr:
8442   case Builtin::BI__builtin_memchr:
8443   case Builtin::BI__builtin_char_memchr:
8444   case Builtin::BI__builtin_wmemchr: {
8445     if (!Visit(E->getArg(0)))
8446       return false;
8447     APSInt Desired;
8448     if (!EvaluateInteger(E->getArg(1), Desired, Info))
8449       return false;
8450     uint64_t MaxLength = uint64_t(-1);
8451     if (BuiltinOp != Builtin::BIstrchr &&
8452         BuiltinOp != Builtin::BIwcschr &&
8453         BuiltinOp != Builtin::BI__builtin_strchr &&
8454         BuiltinOp != Builtin::BI__builtin_wcschr) {
8455       APSInt N;
8456       if (!EvaluateInteger(E->getArg(2), N, Info))
8457         return false;
8458       MaxLength = N.getExtValue();
8459     }
8460     // We cannot find the value if there are no candidates to match against.
8461     if (MaxLength == 0u)
8462       return ZeroInitialization(E);
8463     if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
8464         Result.Designator.Invalid)
8465       return false;
8466     QualType CharTy = Result.Designator.getType(Info.Ctx);
8467     bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
8468                      BuiltinOp == Builtin::BI__builtin_memchr;
8469     assert(IsRawByte ||
8470            Info.Ctx.hasSameUnqualifiedType(
8471                CharTy, E->getArg(0)->getType()->getPointeeType()));
8472     // Pointers to const void may point to objects of incomplete type.
8473     if (IsRawByte && CharTy->isIncompleteType()) {
8474       Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
8475       return false;
8476     }
8477     // Give up on byte-oriented matching against multibyte elements.
8478     // FIXME: We can compare the bytes in the correct order.
8479     if (IsRawByte && !isOneByteCharacterType(CharTy)) {
8480       Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
8481           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
8482           << CharTy;
8483       return false;
8484     }
8485     // Figure out what value we're actually looking for (after converting to
8486     // the corresponding unsigned type if necessary).
8487     uint64_t DesiredVal;
8488     bool StopAtNull = false;
8489     switch (BuiltinOp) {
8490     case Builtin::BIstrchr:
8491     case Builtin::BI__builtin_strchr:
8492       // strchr compares directly to the passed integer, and therefore
8493       // always fails if given an int that is not a char.
8494       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
8495                                                   E->getArg(1)->getType(),
8496                                                   Desired),
8497                                Desired))
8498         return ZeroInitialization(E);
8499       StopAtNull = true;
8500       LLVM_FALLTHROUGH;
8501     case Builtin::BImemchr:
8502     case Builtin::BI__builtin_memchr:
8503     case Builtin::BI__builtin_char_memchr:
8504       // memchr compares by converting both sides to unsigned char. That's also
8505       // correct for strchr if we get this far (to cope with plain char being
8506       // unsigned in the strchr case).
8507       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
8508       break;
8509 
8510     case Builtin::BIwcschr:
8511     case Builtin::BI__builtin_wcschr:
8512       StopAtNull = true;
8513       LLVM_FALLTHROUGH;
8514     case Builtin::BIwmemchr:
8515     case Builtin::BI__builtin_wmemchr:
8516       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
8517       DesiredVal = Desired.getZExtValue();
8518       break;
8519     }
8520 
8521     for (; MaxLength; --MaxLength) {
8522       APValue Char;
8523       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
8524           !Char.isInt())
8525         return false;
8526       if (Char.getInt().getZExtValue() == DesiredVal)
8527         return true;
8528       if (StopAtNull && !Char.getInt())
8529         break;
8530       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
8531         return false;
8532     }
8533     // Not found: return nullptr.
8534     return ZeroInitialization(E);
8535   }
8536 
8537   case Builtin::BImemcpy:
8538   case Builtin::BImemmove:
8539   case Builtin::BIwmemcpy:
8540   case Builtin::BIwmemmove:
8541     if (Info.getLangOpts().CPlusPlus11)
8542       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8543         << /*isConstexpr*/0 << /*isConstructor*/0
8544         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
8545     else
8546       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
8547     LLVM_FALLTHROUGH;
8548   case Builtin::BI__builtin_memcpy:
8549   case Builtin::BI__builtin_memmove:
8550   case Builtin::BI__builtin_wmemcpy:
8551   case Builtin::BI__builtin_wmemmove: {
8552     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
8553                  BuiltinOp == Builtin::BIwmemmove ||
8554                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
8555                  BuiltinOp == Builtin::BI__builtin_wmemmove;
8556     bool Move = BuiltinOp == Builtin::BImemmove ||
8557                 BuiltinOp == Builtin::BIwmemmove ||
8558                 BuiltinOp == Builtin::BI__builtin_memmove ||
8559                 BuiltinOp == Builtin::BI__builtin_wmemmove;
8560 
8561     // The result of mem* is the first argument.
8562     if (!Visit(E->getArg(0)))
8563       return false;
8564     LValue Dest = Result;
8565 
8566     LValue Src;
8567     if (!EvaluatePointer(E->getArg(1), Src, Info))
8568       return false;
8569 
8570     APSInt N;
8571     if (!EvaluateInteger(E->getArg(2), N, Info))
8572       return false;
8573     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
8574 
8575     // If the size is zero, we treat this as always being a valid no-op.
8576     // (Even if one of the src and dest pointers is null.)
8577     if (!N)
8578       return true;
8579 
8580     // Otherwise, if either of the operands is null, we can't proceed. Don't
8581     // try to determine the type of the copied objects, because there aren't
8582     // any.
8583     if (!Src.Base || !Dest.Base) {
8584       APValue Val;
8585       (!Src.Base ? Src : Dest).moveInto(Val);
8586       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
8587           << Move << WChar << !!Src.Base
8588           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
8589       return false;
8590     }
8591     if (Src.Designator.Invalid || Dest.Designator.Invalid)
8592       return false;
8593 
8594     // We require that Src and Dest are both pointers to arrays of
8595     // trivially-copyable type. (For the wide version, the designator will be
8596     // invalid if the designated object is not a wchar_t.)
8597     QualType T = Dest.Designator.getType(Info.Ctx);
8598     QualType SrcT = Src.Designator.getType(Info.Ctx);
8599     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
8600       // FIXME: Consider using our bit_cast implementation to support this.
8601       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
8602       return false;
8603     }
8604     if (T->isIncompleteType()) {
8605       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
8606       return false;
8607     }
8608     if (!T.isTriviallyCopyableType(Info.Ctx)) {
8609       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
8610       return false;
8611     }
8612 
8613     // Figure out how many T's we're copying.
8614     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
8615     if (!WChar) {
8616       uint64_t Remainder;
8617       llvm::APInt OrigN = N;
8618       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
8619       if (Remainder) {
8620         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
8621             << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
8622             << (unsigned)TSize;
8623         return false;
8624       }
8625     }
8626 
8627     // Check that the copying will remain within the arrays, just so that we
8628     // can give a more meaningful diagnostic. This implicitly also checks that
8629     // N fits into 64 bits.
8630     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
8631     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
8632     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
8633       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
8634           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
8635           << N.toString(10, /*Signed*/false);
8636       return false;
8637     }
8638     uint64_t NElems = N.getZExtValue();
8639     uint64_t NBytes = NElems * TSize;
8640 
8641     // Check for overlap.
8642     int Direction = 1;
8643     if (HasSameBase(Src, Dest)) {
8644       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
8645       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
8646       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
8647         // Dest is inside the source region.
8648         if (!Move) {
8649           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
8650           return false;
8651         }
8652         // For memmove and friends, copy backwards.
8653         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
8654             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
8655           return false;
8656         Direction = -1;
8657       } else if (!Move && SrcOffset >= DestOffset &&
8658                  SrcOffset - DestOffset < NBytes) {
8659         // Src is inside the destination region for memcpy: invalid.
8660         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
8661         return false;
8662       }
8663     }
8664 
8665     while (true) {
8666       APValue Val;
8667       // FIXME: Set WantObjectRepresentation to true if we're copying a
8668       // char-like type?
8669       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
8670           !handleAssignment(Info, E, Dest, T, Val))
8671         return false;
8672       // Do not iterate past the last element; if we're copying backwards, that
8673       // might take us off the start of the array.
8674       if (--NElems == 0)
8675         return true;
8676       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
8677           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
8678         return false;
8679     }
8680   }
8681 
8682   default:
8683     break;
8684   }
8685 
8686   return visitNonBuiltinCallExpr(E);
8687 }
8688 
8689 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
8690                                      APValue &Result, const InitListExpr *ILE,
8691                                      QualType AllocType);
8692 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
8693                                           APValue &Result,
8694                                           const CXXConstructExpr *CCE,
8695                                           QualType AllocType);
8696 
8697 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
8698   if (!Info.getLangOpts().CPlusPlus2a)
8699     Info.CCEDiag(E, diag::note_constexpr_new);
8700 
8701   // We cannot speculatively evaluate a delete expression.
8702   if (Info.SpeculativeEvaluationDepth)
8703     return false;
8704 
8705   FunctionDecl *OperatorNew = E->getOperatorNew();
8706 
8707   bool IsNothrow = false;
8708   bool IsPlacement = false;
8709   if (OperatorNew->isReservedGlobalPlacementOperator() &&
8710       Info.CurrentCall->isStdFunction() && !E->isArray()) {
8711     // FIXME Support array placement new.
8712     assert(E->getNumPlacementArgs() == 1);
8713     if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
8714       return false;
8715     if (Result.Designator.Invalid)
8716       return false;
8717     IsPlacement = true;
8718   } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
8719     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
8720         << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
8721     return false;
8722   } else if (E->getNumPlacementArgs()) {
8723     // The only new-placement list we support is of the form (std::nothrow).
8724     //
8725     // FIXME: There is no restriction on this, but it's not clear that any
8726     // other form makes any sense. We get here for cases such as:
8727     //
8728     //   new (std::align_val_t{N}) X(int)
8729     //
8730     // (which should presumably be valid only if N is a multiple of
8731     // alignof(int), and in any case can't be deallocated unless N is
8732     // alignof(X) and X has new-extended alignment).
8733     if (E->getNumPlacementArgs() != 1 ||
8734         !E->getPlacementArg(0)->getType()->isNothrowT())
8735       return Error(E, diag::note_constexpr_new_placement);
8736 
8737     LValue Nothrow;
8738     if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
8739       return false;
8740     IsNothrow = true;
8741   }
8742 
8743   const Expr *Init = E->getInitializer();
8744   const InitListExpr *ResizedArrayILE = nullptr;
8745   const CXXConstructExpr *ResizedArrayCCE = nullptr;
8746 
8747   QualType AllocType = E->getAllocatedType();
8748   if (Optional<const Expr*> ArraySize = E->getArraySize()) {
8749     const Expr *Stripped = *ArraySize;
8750     for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
8751          Stripped = ICE->getSubExpr())
8752       if (ICE->getCastKind() != CK_NoOp &&
8753           ICE->getCastKind() != CK_IntegralCast)
8754         break;
8755 
8756     llvm::APSInt ArrayBound;
8757     if (!EvaluateInteger(Stripped, ArrayBound, Info))
8758       return false;
8759 
8760     // C++ [expr.new]p9:
8761     //   The expression is erroneous if:
8762     //   -- [...] its value before converting to size_t [or] applying the
8763     //      second standard conversion sequence is less than zero
8764     if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
8765       if (IsNothrow)
8766         return ZeroInitialization(E);
8767 
8768       Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
8769           << ArrayBound << (*ArraySize)->getSourceRange();
8770       return false;
8771     }
8772 
8773     //   -- its value is such that the size of the allocated object would
8774     //      exceed the implementation-defined limit
8775     if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
8776                                                 ArrayBound) >
8777         ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
8778       if (IsNothrow)
8779         return ZeroInitialization(E);
8780 
8781       Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
8782         << ArrayBound << (*ArraySize)->getSourceRange();
8783       return false;
8784     }
8785 
8786     //   -- the new-initializer is a braced-init-list and the number of
8787     //      array elements for which initializers are provided [...]
8788     //      exceeds the number of elements to initialize
8789     if (Init && !isa<CXXConstructExpr>(Init)) {
8790       auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
8791       assert(CAT && "unexpected type for array initializer");
8792 
8793       unsigned Bits =
8794           std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
8795       llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits);
8796       llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits);
8797       if (InitBound.ugt(AllocBound)) {
8798         if (IsNothrow)
8799           return ZeroInitialization(E);
8800 
8801         Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
8802             << AllocBound.toString(10, /*Signed=*/false)
8803             << InitBound.toString(10, /*Signed=*/false)
8804             << (*ArraySize)->getSourceRange();
8805         return false;
8806       }
8807 
8808       // If the sizes differ, we must have an initializer list, and we need
8809       // special handling for this case when we initialize.
8810       if (InitBound != AllocBound)
8811         ResizedArrayILE = cast<InitListExpr>(Init);
8812     } else if (Init) {
8813       ResizedArrayCCE = cast<CXXConstructExpr>(Init);
8814     }
8815 
8816     AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
8817                                               ArrayType::Normal, 0);
8818   } else {
8819     assert(!AllocType->isArrayType() &&
8820            "array allocation with non-array new");
8821   }
8822 
8823   APValue *Val;
8824   if (IsPlacement) {
8825     AccessKinds AK = AK_Construct;
8826     struct FindObjectHandler {
8827       EvalInfo &Info;
8828       const Expr *E;
8829       QualType AllocType;
8830       const AccessKinds AccessKind;
8831       APValue *Value;
8832 
8833       typedef bool result_type;
8834       bool failed() { return false; }
8835       bool found(APValue &Subobj, QualType SubobjType) {
8836         // FIXME: Reject the cases where [basic.life]p8 would not permit the
8837         // old name of the object to be used to name the new object.
8838         if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
8839           Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
8840             SubobjType << AllocType;
8841           return false;
8842         }
8843         Value = &Subobj;
8844         return true;
8845       }
8846       bool found(APSInt &Value, QualType SubobjType) {
8847         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
8848         return false;
8849       }
8850       bool found(APFloat &Value, QualType SubobjType) {
8851         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
8852         return false;
8853       }
8854     } Handler = {Info, E, AllocType, AK, nullptr};
8855 
8856     CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
8857     if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
8858       return false;
8859 
8860     Val = Handler.Value;
8861 
8862     // [basic.life]p1:
8863     //   The lifetime of an object o of type T ends when [...] the storage
8864     //   which the object occupies is [...] reused by an object that is not
8865     //   nested within o (6.6.2).
8866     *Val = APValue();
8867   } else {
8868     // Perform the allocation and obtain a pointer to the resulting object.
8869     Val = Info.createHeapAlloc(E, AllocType, Result);
8870     if (!Val)
8871       return false;
8872   }
8873 
8874   if (ResizedArrayILE) {
8875     if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
8876                                   AllocType))
8877       return false;
8878   } else if (ResizedArrayCCE) {
8879     if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
8880                                        AllocType))
8881       return false;
8882   } else if (Init) {
8883     if (!EvaluateInPlace(*Val, Info, Result, Init))
8884       return false;
8885   } else {
8886     *Val = getDefaultInitValue(AllocType);
8887   }
8888 
8889   // Array new returns a pointer to the first element, not a pointer to the
8890   // array.
8891   if (auto *AT = AllocType->getAsArrayTypeUnsafe())
8892     Result.addArray(Info, E, cast<ConstantArrayType>(AT));
8893 
8894   return true;
8895 }
8896 //===----------------------------------------------------------------------===//
8897 // Member Pointer Evaluation
8898 //===----------------------------------------------------------------------===//
8899 
8900 namespace {
8901 class MemberPointerExprEvaluator
8902   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
8903   MemberPtr &Result;
8904 
8905   bool Success(const ValueDecl *D) {
8906     Result = MemberPtr(D);
8907     return true;
8908   }
8909 public:
8910 
8911   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
8912     : ExprEvaluatorBaseTy(Info), Result(Result) {}
8913 
8914   bool Success(const APValue &V, const Expr *E) {
8915     Result.setFrom(V);
8916     return true;
8917   }
8918   bool ZeroInitialization(const Expr *E) {
8919     return Success((const ValueDecl*)nullptr);
8920   }
8921 
8922   bool VisitCastExpr(const CastExpr *E);
8923   bool VisitUnaryAddrOf(const UnaryOperator *E);
8924 };
8925 } // end anonymous namespace
8926 
8927 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
8928                                   EvalInfo &Info) {
8929   assert(E->isRValue() && E->getType()->isMemberPointerType());
8930   return MemberPointerExprEvaluator(Info, Result).Visit(E);
8931 }
8932 
8933 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8934   switch (E->getCastKind()) {
8935   default:
8936     return ExprEvaluatorBaseTy::VisitCastExpr(E);
8937 
8938   case CK_NullToMemberPointer:
8939     VisitIgnoredValue(E->getSubExpr());
8940     return ZeroInitialization(E);
8941 
8942   case CK_BaseToDerivedMemberPointer: {
8943     if (!Visit(E->getSubExpr()))
8944       return false;
8945     if (E->path_empty())
8946       return true;
8947     // Base-to-derived member pointer casts store the path in derived-to-base
8948     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
8949     // the wrong end of the derived->base arc, so stagger the path by one class.
8950     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
8951     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
8952          PathI != PathE; ++PathI) {
8953       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
8954       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
8955       if (!Result.castToDerived(Derived))
8956         return Error(E);
8957     }
8958     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
8959     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
8960       return Error(E);
8961     return true;
8962   }
8963 
8964   case CK_DerivedToBaseMemberPointer:
8965     if (!Visit(E->getSubExpr()))
8966       return false;
8967     for (CastExpr::path_const_iterator PathI = E->path_begin(),
8968          PathE = E->path_end(); PathI != PathE; ++PathI) {
8969       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
8970       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
8971       if (!Result.castToBase(Base))
8972         return Error(E);
8973     }
8974     return true;
8975   }
8976 }
8977 
8978 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8979   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
8980   // member can be formed.
8981   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
8982 }
8983 
8984 //===----------------------------------------------------------------------===//
8985 // Record Evaluation
8986 //===----------------------------------------------------------------------===//
8987 
8988 namespace {
8989   class RecordExprEvaluator
8990   : public ExprEvaluatorBase<RecordExprEvaluator> {
8991     const LValue &This;
8992     APValue &Result;
8993   public:
8994 
8995     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
8996       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
8997 
8998     bool Success(const APValue &V, const Expr *E) {
8999       Result = V;
9000       return true;
9001     }
9002     bool ZeroInitialization(const Expr *E) {
9003       return ZeroInitialization(E, E->getType());
9004     }
9005     bool ZeroInitialization(const Expr *E, QualType T);
9006 
9007     bool VisitCallExpr(const CallExpr *E) {
9008       return handleCallExpr(E, Result, &This);
9009     }
9010     bool VisitCastExpr(const CastExpr *E);
9011     bool VisitInitListExpr(const InitListExpr *E);
9012     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9013       return VisitCXXConstructExpr(E, E->getType());
9014     }
9015     bool VisitLambdaExpr(const LambdaExpr *E);
9016     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
9017     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
9018     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
9019     bool VisitBinCmp(const BinaryOperator *E);
9020   };
9021 }
9022 
9023 /// Perform zero-initialization on an object of non-union class type.
9024 /// C++11 [dcl.init]p5:
9025 ///  To zero-initialize an object or reference of type T means:
9026 ///    [...]
9027 ///    -- if T is a (possibly cv-qualified) non-union class type,
9028 ///       each non-static data member and each base-class subobject is
9029 ///       zero-initialized
9030 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
9031                                           const RecordDecl *RD,
9032                                           const LValue &This, APValue &Result) {
9033   assert(!RD->isUnion() && "Expected non-union class type");
9034   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
9035   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
9036                    std::distance(RD->field_begin(), RD->field_end()));
9037 
9038   if (RD->isInvalidDecl()) return false;
9039   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9040 
9041   if (CD) {
9042     unsigned Index = 0;
9043     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
9044            End = CD->bases_end(); I != End; ++I, ++Index) {
9045       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
9046       LValue Subobject = This;
9047       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
9048         return false;
9049       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
9050                                          Result.getStructBase(Index)))
9051         return false;
9052     }
9053   }
9054 
9055   for (const auto *I : RD->fields()) {
9056     // -- if T is a reference type, no initialization is performed.
9057     if (I->getType()->isReferenceType())
9058       continue;
9059 
9060     LValue Subobject = This;
9061     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
9062       return false;
9063 
9064     ImplicitValueInitExpr VIE(I->getType());
9065     if (!EvaluateInPlace(
9066           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
9067       return false;
9068   }
9069 
9070   return true;
9071 }
9072 
9073 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
9074   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
9075   if (RD->isInvalidDecl()) return false;
9076   if (RD->isUnion()) {
9077     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
9078     // object's first non-static named data member is zero-initialized
9079     RecordDecl::field_iterator I = RD->field_begin();
9080     if (I == RD->field_end()) {
9081       Result = APValue((const FieldDecl*)nullptr);
9082       return true;
9083     }
9084 
9085     LValue Subobject = This;
9086     if (!HandleLValueMember(Info, E, Subobject, *I))
9087       return false;
9088     Result = APValue(*I);
9089     ImplicitValueInitExpr VIE(I->getType());
9090     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
9091   }
9092 
9093   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
9094     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
9095     return false;
9096   }
9097 
9098   return HandleClassZeroInitialization(Info, E, RD, This, Result);
9099 }
9100 
9101 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
9102   switch (E->getCastKind()) {
9103   default:
9104     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9105 
9106   case CK_ConstructorConversion:
9107     return Visit(E->getSubExpr());
9108 
9109   case CK_DerivedToBase:
9110   case CK_UncheckedDerivedToBase: {
9111     APValue DerivedObject;
9112     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
9113       return false;
9114     if (!DerivedObject.isStruct())
9115       return Error(E->getSubExpr());
9116 
9117     // Derived-to-base rvalue conversion: just slice off the derived part.
9118     APValue *Value = &DerivedObject;
9119     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
9120     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9121          PathE = E->path_end(); PathI != PathE; ++PathI) {
9122       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
9123       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9124       Value = &Value->getStructBase(getBaseIndex(RD, Base));
9125       RD = Base;
9126     }
9127     Result = *Value;
9128     return true;
9129   }
9130   }
9131 }
9132 
9133 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9134   if (E->isTransparent())
9135     return Visit(E->getInit(0));
9136 
9137   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
9138   if (RD->isInvalidDecl()) return false;
9139   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9140   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
9141 
9142   EvalInfo::EvaluatingConstructorRAII EvalObj(
9143       Info,
9144       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
9145       CXXRD && CXXRD->getNumBases());
9146 
9147   if (RD->isUnion()) {
9148     const FieldDecl *Field = E->getInitializedFieldInUnion();
9149     Result = APValue(Field);
9150     if (!Field)
9151       return true;
9152 
9153     // If the initializer list for a union does not contain any elements, the
9154     // first element of the union is value-initialized.
9155     // FIXME: The element should be initialized from an initializer list.
9156     //        Is this difference ever observable for initializer lists which
9157     //        we don't build?
9158     ImplicitValueInitExpr VIE(Field->getType());
9159     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
9160 
9161     LValue Subobject = This;
9162     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
9163       return false;
9164 
9165     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9166     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9167                                   isa<CXXDefaultInitExpr>(InitExpr));
9168 
9169     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
9170   }
9171 
9172   if (!Result.hasValue())
9173     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
9174                      std::distance(RD->field_begin(), RD->field_end()));
9175   unsigned ElementNo = 0;
9176   bool Success = true;
9177 
9178   // Initialize base classes.
9179   if (CXXRD && CXXRD->getNumBases()) {
9180     for (const auto &Base : CXXRD->bases()) {
9181       assert(ElementNo < E->getNumInits() && "missing init for base class");
9182       const Expr *Init = E->getInit(ElementNo);
9183 
9184       LValue Subobject = This;
9185       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
9186         return false;
9187 
9188       APValue &FieldVal = Result.getStructBase(ElementNo);
9189       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
9190         if (!Info.noteFailure())
9191           return false;
9192         Success = false;
9193       }
9194       ++ElementNo;
9195     }
9196 
9197     EvalObj.finishedConstructingBases();
9198   }
9199 
9200   // Initialize members.
9201   for (const auto *Field : RD->fields()) {
9202     // Anonymous bit-fields are not considered members of the class for
9203     // purposes of aggregate initialization.
9204     if (Field->isUnnamedBitfield())
9205       continue;
9206 
9207     LValue Subobject = This;
9208 
9209     bool HaveInit = ElementNo < E->getNumInits();
9210 
9211     // FIXME: Diagnostics here should point to the end of the initializer
9212     // list, not the start.
9213     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
9214                             Subobject, Field, &Layout))
9215       return false;
9216 
9217     // Perform an implicit value-initialization for members beyond the end of
9218     // the initializer list.
9219     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
9220     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
9221 
9222     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9223     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9224                                   isa<CXXDefaultInitExpr>(Init));
9225 
9226     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9227     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
9228         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
9229                                                        FieldVal, Field))) {
9230       if (!Info.noteFailure())
9231         return false;
9232       Success = false;
9233     }
9234   }
9235 
9236   EvalObj.finishedConstructingFields();
9237 
9238   return Success;
9239 }
9240 
9241 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
9242                                                 QualType T) {
9243   // Note that E's type is not necessarily the type of our class here; we might
9244   // be initializing an array element instead.
9245   const CXXConstructorDecl *FD = E->getConstructor();
9246   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
9247 
9248   bool ZeroInit = E->requiresZeroInitialization();
9249   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
9250     // If we've already performed zero-initialization, we're already done.
9251     if (Result.hasValue())
9252       return true;
9253 
9254     if (ZeroInit)
9255       return ZeroInitialization(E, T);
9256 
9257     Result = getDefaultInitValue(T);
9258     return true;
9259   }
9260 
9261   const FunctionDecl *Definition = nullptr;
9262   auto Body = FD->getBody(Definition);
9263 
9264   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9265     return false;
9266 
9267   // Avoid materializing a temporary for an elidable copy/move constructor.
9268   if (E->isElidable() && !ZeroInit)
9269     if (const MaterializeTemporaryExpr *ME
9270           = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
9271       return Visit(ME->getSubExpr());
9272 
9273   if (ZeroInit && !ZeroInitialization(E, T))
9274     return false;
9275 
9276   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
9277   return HandleConstructorCall(E, This, Args,
9278                                cast<CXXConstructorDecl>(Definition), Info,
9279                                Result);
9280 }
9281 
9282 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
9283     const CXXInheritedCtorInitExpr *E) {
9284   if (!Info.CurrentCall) {
9285     assert(Info.checkingPotentialConstantExpression());
9286     return false;
9287   }
9288 
9289   const CXXConstructorDecl *FD = E->getConstructor();
9290   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
9291     return false;
9292 
9293   const FunctionDecl *Definition = nullptr;
9294   auto Body = FD->getBody(Definition);
9295 
9296   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9297     return false;
9298 
9299   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
9300                                cast<CXXConstructorDecl>(Definition), Info,
9301                                Result);
9302 }
9303 
9304 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
9305     const CXXStdInitializerListExpr *E) {
9306   const ConstantArrayType *ArrayType =
9307       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
9308 
9309   LValue Array;
9310   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
9311     return false;
9312 
9313   // Get a pointer to the first element of the array.
9314   Array.addArray(Info, E, ArrayType);
9315 
9316   // FIXME: Perform the checks on the field types in SemaInit.
9317   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
9318   RecordDecl::field_iterator Field = Record->field_begin();
9319   if (Field == Record->field_end())
9320     return Error(E);
9321 
9322   // Start pointer.
9323   if (!Field->getType()->isPointerType() ||
9324       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
9325                             ArrayType->getElementType()))
9326     return Error(E);
9327 
9328   // FIXME: What if the initializer_list type has base classes, etc?
9329   Result = APValue(APValue::UninitStruct(), 0, 2);
9330   Array.moveInto(Result.getStructField(0));
9331 
9332   if (++Field == Record->field_end())
9333     return Error(E);
9334 
9335   if (Field->getType()->isPointerType() &&
9336       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
9337                            ArrayType->getElementType())) {
9338     // End pointer.
9339     if (!HandleLValueArrayAdjustment(Info, E, Array,
9340                                      ArrayType->getElementType(),
9341                                      ArrayType->getSize().getZExtValue()))
9342       return false;
9343     Array.moveInto(Result.getStructField(1));
9344   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
9345     // Length.
9346     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
9347   else
9348     return Error(E);
9349 
9350   if (++Field != Record->field_end())
9351     return Error(E);
9352 
9353   return true;
9354 }
9355 
9356 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
9357   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
9358   if (ClosureClass->isInvalidDecl())
9359     return false;
9360 
9361   const size_t NumFields =
9362       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
9363 
9364   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
9365                                             E->capture_init_end()) &&
9366          "The number of lambda capture initializers should equal the number of "
9367          "fields within the closure type");
9368 
9369   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
9370   // Iterate through all the lambda's closure object's fields and initialize
9371   // them.
9372   auto *CaptureInitIt = E->capture_init_begin();
9373   const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
9374   bool Success = true;
9375   for (const auto *Field : ClosureClass->fields()) {
9376     assert(CaptureInitIt != E->capture_init_end());
9377     // Get the initializer for this field
9378     Expr *const CurFieldInit = *CaptureInitIt++;
9379 
9380     // If there is no initializer, either this is a VLA or an error has
9381     // occurred.
9382     if (!CurFieldInit)
9383       return Error(E);
9384 
9385     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9386     if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
9387       if (!Info.keepEvaluatingAfterFailure())
9388         return false;
9389       Success = false;
9390     }
9391     ++CaptureIt;
9392   }
9393   return Success;
9394 }
9395 
9396 static bool EvaluateRecord(const Expr *E, const LValue &This,
9397                            APValue &Result, EvalInfo &Info) {
9398   assert(E->isRValue() && E->getType()->isRecordType() &&
9399          "can't evaluate expression as a record rvalue");
9400   return RecordExprEvaluator(Info, This, Result).Visit(E);
9401 }
9402 
9403 //===----------------------------------------------------------------------===//
9404 // Temporary Evaluation
9405 //
9406 // Temporaries are represented in the AST as rvalues, but generally behave like
9407 // lvalues. The full-object of which the temporary is a subobject is implicitly
9408 // materialized so that a reference can bind to it.
9409 //===----------------------------------------------------------------------===//
9410 namespace {
9411 class TemporaryExprEvaluator
9412   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
9413 public:
9414   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
9415     LValueExprEvaluatorBaseTy(Info, Result, false) {}
9416 
9417   /// Visit an expression which constructs the value of this temporary.
9418   bool VisitConstructExpr(const Expr *E) {
9419     APValue &Value =
9420         Info.CurrentCall->createTemporary(E, E->getType(), false, Result);
9421     return EvaluateInPlace(Value, Info, Result, E);
9422   }
9423 
9424   bool VisitCastExpr(const CastExpr *E) {
9425     switch (E->getCastKind()) {
9426     default:
9427       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
9428 
9429     case CK_ConstructorConversion:
9430       return VisitConstructExpr(E->getSubExpr());
9431     }
9432   }
9433   bool VisitInitListExpr(const InitListExpr *E) {
9434     return VisitConstructExpr(E);
9435   }
9436   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9437     return VisitConstructExpr(E);
9438   }
9439   bool VisitCallExpr(const CallExpr *E) {
9440     return VisitConstructExpr(E);
9441   }
9442   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
9443     return VisitConstructExpr(E);
9444   }
9445   bool VisitLambdaExpr(const LambdaExpr *E) {
9446     return VisitConstructExpr(E);
9447   }
9448 };
9449 } // end anonymous namespace
9450 
9451 /// Evaluate an expression of record type as a temporary.
9452 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
9453   assert(E->isRValue() && E->getType()->isRecordType());
9454   return TemporaryExprEvaluator(Info, Result).Visit(E);
9455 }
9456 
9457 //===----------------------------------------------------------------------===//
9458 // Vector Evaluation
9459 //===----------------------------------------------------------------------===//
9460 
9461 namespace {
9462   class VectorExprEvaluator
9463   : public ExprEvaluatorBase<VectorExprEvaluator> {
9464     APValue &Result;
9465   public:
9466 
9467     VectorExprEvaluator(EvalInfo &info, APValue &Result)
9468       : ExprEvaluatorBaseTy(info), Result(Result) {}
9469 
9470     bool Success(ArrayRef<APValue> V, const Expr *E) {
9471       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
9472       // FIXME: remove this APValue copy.
9473       Result = APValue(V.data(), V.size());
9474       return true;
9475     }
9476     bool Success(const APValue &V, const Expr *E) {
9477       assert(V.isVector());
9478       Result = V;
9479       return true;
9480     }
9481     bool ZeroInitialization(const Expr *E);
9482 
9483     bool VisitUnaryReal(const UnaryOperator *E)
9484       { return Visit(E->getSubExpr()); }
9485     bool VisitCastExpr(const CastExpr* E);
9486     bool VisitInitListExpr(const InitListExpr *E);
9487     bool VisitUnaryImag(const UnaryOperator *E);
9488     // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
9489     //                 binary comparisons, binary and/or/xor,
9490     //                 conditional operator (for GNU conditional select),
9491     //                 shufflevector, ExtVectorElementExpr
9492   };
9493 } // end anonymous namespace
9494 
9495 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
9496   assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
9497   return VectorExprEvaluator(Info, Result).Visit(E);
9498 }
9499 
9500 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
9501   const VectorType *VTy = E->getType()->castAs<VectorType>();
9502   unsigned NElts = VTy->getNumElements();
9503 
9504   const Expr *SE = E->getSubExpr();
9505   QualType SETy = SE->getType();
9506 
9507   switch (E->getCastKind()) {
9508   case CK_VectorSplat: {
9509     APValue Val = APValue();
9510     if (SETy->isIntegerType()) {
9511       APSInt IntResult;
9512       if (!EvaluateInteger(SE, IntResult, Info))
9513         return false;
9514       Val = APValue(std::move(IntResult));
9515     } else if (SETy->isRealFloatingType()) {
9516       APFloat FloatResult(0.0);
9517       if (!EvaluateFloat(SE, FloatResult, Info))
9518         return false;
9519       Val = APValue(std::move(FloatResult));
9520     } else {
9521       return Error(E);
9522     }
9523 
9524     // Splat and create vector APValue.
9525     SmallVector<APValue, 4> Elts(NElts, Val);
9526     return Success(Elts, E);
9527   }
9528   case CK_BitCast: {
9529     // Evaluate the operand into an APInt we can extract from.
9530     llvm::APInt SValInt;
9531     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
9532       return false;
9533     // Extract the elements
9534     QualType EltTy = VTy->getElementType();
9535     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
9536     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
9537     SmallVector<APValue, 4> Elts;
9538     if (EltTy->isRealFloatingType()) {
9539       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
9540       unsigned FloatEltSize = EltSize;
9541       if (&Sem == &APFloat::x87DoubleExtended())
9542         FloatEltSize = 80;
9543       for (unsigned i = 0; i < NElts; i++) {
9544         llvm::APInt Elt;
9545         if (BigEndian)
9546           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
9547         else
9548           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
9549         Elts.push_back(APValue(APFloat(Sem, Elt)));
9550       }
9551     } else if (EltTy->isIntegerType()) {
9552       for (unsigned i = 0; i < NElts; i++) {
9553         llvm::APInt Elt;
9554         if (BigEndian)
9555           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
9556         else
9557           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
9558         Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
9559       }
9560     } else {
9561       return Error(E);
9562     }
9563     return Success(Elts, E);
9564   }
9565   default:
9566     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9567   }
9568 }
9569 
9570 bool
9571 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9572   const VectorType *VT = E->getType()->castAs<VectorType>();
9573   unsigned NumInits = E->getNumInits();
9574   unsigned NumElements = VT->getNumElements();
9575 
9576   QualType EltTy = VT->getElementType();
9577   SmallVector<APValue, 4> Elements;
9578 
9579   // The number of initializers can be less than the number of
9580   // vector elements. For OpenCL, this can be due to nested vector
9581   // initialization. For GCC compatibility, missing trailing elements
9582   // should be initialized with zeroes.
9583   unsigned CountInits = 0, CountElts = 0;
9584   while (CountElts < NumElements) {
9585     // Handle nested vector initialization.
9586     if (CountInits < NumInits
9587         && E->getInit(CountInits)->getType()->isVectorType()) {
9588       APValue v;
9589       if (!EvaluateVector(E->getInit(CountInits), v, Info))
9590         return Error(E);
9591       unsigned vlen = v.getVectorLength();
9592       for (unsigned j = 0; j < vlen; j++)
9593         Elements.push_back(v.getVectorElt(j));
9594       CountElts += vlen;
9595     } else if (EltTy->isIntegerType()) {
9596       llvm::APSInt sInt(32);
9597       if (CountInits < NumInits) {
9598         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
9599           return false;
9600       } else // trailing integer zero.
9601         sInt = Info.Ctx.MakeIntValue(0, EltTy);
9602       Elements.push_back(APValue(sInt));
9603       CountElts++;
9604     } else {
9605       llvm::APFloat f(0.0);
9606       if (CountInits < NumInits) {
9607         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
9608           return false;
9609       } else // trailing float zero.
9610         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
9611       Elements.push_back(APValue(f));
9612       CountElts++;
9613     }
9614     CountInits++;
9615   }
9616   return Success(Elements, E);
9617 }
9618 
9619 bool
9620 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
9621   const auto *VT = E->getType()->castAs<VectorType>();
9622   QualType EltTy = VT->getElementType();
9623   APValue ZeroElement;
9624   if (EltTy->isIntegerType())
9625     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
9626   else
9627     ZeroElement =
9628         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
9629 
9630   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
9631   return Success(Elements, E);
9632 }
9633 
9634 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9635   VisitIgnoredValue(E->getSubExpr());
9636   return ZeroInitialization(E);
9637 }
9638 
9639 //===----------------------------------------------------------------------===//
9640 // Array Evaluation
9641 //===----------------------------------------------------------------------===//
9642 
9643 namespace {
9644   class ArrayExprEvaluator
9645   : public ExprEvaluatorBase<ArrayExprEvaluator> {
9646     const LValue &This;
9647     APValue &Result;
9648   public:
9649 
9650     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
9651       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
9652 
9653     bool Success(const APValue &V, const Expr *E) {
9654       assert(V.isArray() && "expected array");
9655       Result = V;
9656       return true;
9657     }
9658 
9659     bool ZeroInitialization(const Expr *E) {
9660       const ConstantArrayType *CAT =
9661           Info.Ctx.getAsConstantArrayType(E->getType());
9662       if (!CAT)
9663         return Error(E);
9664 
9665       Result = APValue(APValue::UninitArray(), 0,
9666                        CAT->getSize().getZExtValue());
9667       if (!Result.hasArrayFiller()) return true;
9668 
9669       // Zero-initialize all elements.
9670       LValue Subobject = This;
9671       Subobject.addArray(Info, E, CAT);
9672       ImplicitValueInitExpr VIE(CAT->getElementType());
9673       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
9674     }
9675 
9676     bool VisitCallExpr(const CallExpr *E) {
9677       return handleCallExpr(E, Result, &This);
9678     }
9679     bool VisitInitListExpr(const InitListExpr *E,
9680                            QualType AllocType = QualType());
9681     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
9682     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
9683     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
9684                                const LValue &Subobject,
9685                                APValue *Value, QualType Type);
9686     bool VisitStringLiteral(const StringLiteral *E,
9687                             QualType AllocType = QualType()) {
9688       expandStringLiteral(Info, E, Result, AllocType);
9689       return true;
9690     }
9691   };
9692 } // end anonymous namespace
9693 
9694 static bool EvaluateArray(const Expr *E, const LValue &This,
9695                           APValue &Result, EvalInfo &Info) {
9696   assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
9697   return ArrayExprEvaluator(Info, This, Result).Visit(E);
9698 }
9699 
9700 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9701                                      APValue &Result, const InitListExpr *ILE,
9702                                      QualType AllocType) {
9703   assert(ILE->isRValue() && ILE->getType()->isArrayType() &&
9704          "not an array rvalue");
9705   return ArrayExprEvaluator(Info, This, Result)
9706       .VisitInitListExpr(ILE, AllocType);
9707 }
9708 
9709 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
9710                                           APValue &Result,
9711                                           const CXXConstructExpr *CCE,
9712                                           QualType AllocType) {
9713   assert(CCE->isRValue() && CCE->getType()->isArrayType() &&
9714          "not an array rvalue");
9715   return ArrayExprEvaluator(Info, This, Result)
9716       .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
9717 }
9718 
9719 // Return true iff the given array filler may depend on the element index.
9720 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
9721   // For now, just whitelist non-class value-initialization and initialization
9722   // lists comprised of them.
9723   if (isa<ImplicitValueInitExpr>(FillerExpr))
9724     return false;
9725   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
9726     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
9727       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
9728         return true;
9729     }
9730     return false;
9731   }
9732   return true;
9733 }
9734 
9735 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
9736                                            QualType AllocType) {
9737   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
9738       AllocType.isNull() ? E->getType() : AllocType);
9739   if (!CAT)
9740     return Error(E);
9741 
9742   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
9743   // an appropriately-typed string literal enclosed in braces.
9744   if (E->isStringLiteralInit()) {
9745     auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens());
9746     // FIXME: Support ObjCEncodeExpr here once we support it in
9747     // ArrayExprEvaluator generally.
9748     if (!SL)
9749       return Error(E);
9750     return VisitStringLiteral(SL, AllocType);
9751   }
9752 
9753   bool Success = true;
9754 
9755   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
9756          "zero-initialized array shouldn't have any initialized elts");
9757   APValue Filler;
9758   if (Result.isArray() && Result.hasArrayFiller())
9759     Filler = Result.getArrayFiller();
9760 
9761   unsigned NumEltsToInit = E->getNumInits();
9762   unsigned NumElts = CAT->getSize().getZExtValue();
9763   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
9764 
9765   // If the initializer might depend on the array index, run it for each
9766   // array element.
9767   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
9768     NumEltsToInit = NumElts;
9769 
9770   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
9771                           << NumEltsToInit << ".\n");
9772 
9773   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
9774 
9775   // If the array was previously zero-initialized, preserve the
9776   // zero-initialized values.
9777   if (Filler.hasValue()) {
9778     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
9779       Result.getArrayInitializedElt(I) = Filler;
9780     if (Result.hasArrayFiller())
9781       Result.getArrayFiller() = Filler;
9782   }
9783 
9784   LValue Subobject = This;
9785   Subobject.addArray(Info, E, CAT);
9786   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
9787     const Expr *Init =
9788         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
9789     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
9790                          Info, Subobject, Init) ||
9791         !HandleLValueArrayAdjustment(Info, Init, Subobject,
9792                                      CAT->getElementType(), 1)) {
9793       if (!Info.noteFailure())
9794         return false;
9795       Success = false;
9796     }
9797   }
9798 
9799   if (!Result.hasArrayFiller())
9800     return Success;
9801 
9802   // If we get here, we have a trivial filler, which we can just evaluate
9803   // once and splat over the rest of the array elements.
9804   assert(FillerExpr && "no array filler for incomplete init list");
9805   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
9806                          FillerExpr) && Success;
9807 }
9808 
9809 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
9810   LValue CommonLV;
9811   if (E->getCommonExpr() &&
9812       !Evaluate(Info.CurrentCall->createTemporary(
9813                     E->getCommonExpr(),
9814                     getStorageType(Info.Ctx, E->getCommonExpr()), false,
9815                     CommonLV),
9816                 Info, E->getCommonExpr()->getSourceExpr()))
9817     return false;
9818 
9819   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
9820 
9821   uint64_t Elements = CAT->getSize().getZExtValue();
9822   Result = APValue(APValue::UninitArray(), Elements, Elements);
9823 
9824   LValue Subobject = This;
9825   Subobject.addArray(Info, E, CAT);
9826 
9827   bool Success = true;
9828   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
9829     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
9830                          Info, Subobject, E->getSubExpr()) ||
9831         !HandleLValueArrayAdjustment(Info, E, Subobject,
9832                                      CAT->getElementType(), 1)) {
9833       if (!Info.noteFailure())
9834         return false;
9835       Success = false;
9836     }
9837   }
9838 
9839   return Success;
9840 }
9841 
9842 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
9843   return VisitCXXConstructExpr(E, This, &Result, E->getType());
9844 }
9845 
9846 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
9847                                                const LValue &Subobject,
9848                                                APValue *Value,
9849                                                QualType Type) {
9850   bool HadZeroInit = Value->hasValue();
9851 
9852   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
9853     unsigned N = CAT->getSize().getZExtValue();
9854 
9855     // Preserve the array filler if we had prior zero-initialization.
9856     APValue Filler =
9857       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
9858                                              : APValue();
9859 
9860     *Value = APValue(APValue::UninitArray(), N, N);
9861 
9862     if (HadZeroInit)
9863       for (unsigned I = 0; I != N; ++I)
9864         Value->getArrayInitializedElt(I) = Filler;
9865 
9866     // Initialize the elements.
9867     LValue ArrayElt = Subobject;
9868     ArrayElt.addArray(Info, E, CAT);
9869     for (unsigned I = 0; I != N; ++I)
9870       if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
9871                                  CAT->getElementType()) ||
9872           !HandleLValueArrayAdjustment(Info, E, ArrayElt,
9873                                        CAT->getElementType(), 1))
9874         return false;
9875 
9876     return true;
9877   }
9878 
9879   if (!Type->isRecordType())
9880     return Error(E);
9881 
9882   return RecordExprEvaluator(Info, Subobject, *Value)
9883              .VisitCXXConstructExpr(E, Type);
9884 }
9885 
9886 //===----------------------------------------------------------------------===//
9887 // Integer Evaluation
9888 //
9889 // As a GNU extension, we support casting pointers to sufficiently-wide integer
9890 // types and back in constant folding. Integer values are thus represented
9891 // either as an integer-valued APValue, or as an lvalue-valued APValue.
9892 //===----------------------------------------------------------------------===//
9893 
9894 namespace {
9895 class IntExprEvaluator
9896         : public ExprEvaluatorBase<IntExprEvaluator> {
9897   APValue &Result;
9898 public:
9899   IntExprEvaluator(EvalInfo &info, APValue &result)
9900       : ExprEvaluatorBaseTy(info), Result(result) {}
9901 
9902   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
9903     assert(E->getType()->isIntegralOrEnumerationType() &&
9904            "Invalid evaluation result.");
9905     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
9906            "Invalid evaluation result.");
9907     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
9908            "Invalid evaluation result.");
9909     Result = APValue(SI);
9910     return true;
9911   }
9912   bool Success(const llvm::APSInt &SI, const Expr *E) {
9913     return Success(SI, E, Result);
9914   }
9915 
9916   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
9917     assert(E->getType()->isIntegralOrEnumerationType() &&
9918            "Invalid evaluation result.");
9919     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
9920            "Invalid evaluation result.");
9921     Result = APValue(APSInt(I));
9922     Result.getInt().setIsUnsigned(
9923                             E->getType()->isUnsignedIntegerOrEnumerationType());
9924     return true;
9925   }
9926   bool Success(const llvm::APInt &I, const Expr *E) {
9927     return Success(I, E, Result);
9928   }
9929 
9930   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
9931     assert(E->getType()->isIntegralOrEnumerationType() &&
9932            "Invalid evaluation result.");
9933     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
9934     return true;
9935   }
9936   bool Success(uint64_t Value, const Expr *E) {
9937     return Success(Value, E, Result);
9938   }
9939 
9940   bool Success(CharUnits Size, const Expr *E) {
9941     return Success(Size.getQuantity(), E);
9942   }
9943 
9944   bool Success(const APValue &V, const Expr *E) {
9945     if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
9946       Result = V;
9947       return true;
9948     }
9949     return Success(V.getInt(), E);
9950   }
9951 
9952   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
9953 
9954   //===--------------------------------------------------------------------===//
9955   //                            Visitor Methods
9956   //===--------------------------------------------------------------------===//
9957 
9958   bool VisitConstantExpr(const ConstantExpr *E);
9959 
9960   bool VisitIntegerLiteral(const IntegerLiteral *E) {
9961     return Success(E->getValue(), E);
9962   }
9963   bool VisitCharacterLiteral(const CharacterLiteral *E) {
9964     return Success(E->getValue(), E);
9965   }
9966 
9967   bool CheckReferencedDecl(const Expr *E, const Decl *D);
9968   bool VisitDeclRefExpr(const DeclRefExpr *E) {
9969     if (CheckReferencedDecl(E, E->getDecl()))
9970       return true;
9971 
9972     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
9973   }
9974   bool VisitMemberExpr(const MemberExpr *E) {
9975     if (CheckReferencedDecl(E, E->getMemberDecl())) {
9976       VisitIgnoredBaseExpression(E->getBase());
9977       return true;
9978     }
9979 
9980     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
9981   }
9982 
9983   bool VisitCallExpr(const CallExpr *E);
9984   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
9985   bool VisitBinaryOperator(const BinaryOperator *E);
9986   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
9987   bool VisitUnaryOperator(const UnaryOperator *E);
9988 
9989   bool VisitCastExpr(const CastExpr* E);
9990   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
9991 
9992   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
9993     return Success(E->getValue(), E);
9994   }
9995 
9996   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
9997     return Success(E->getValue(), E);
9998   }
9999 
10000   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
10001     if (Info.ArrayInitIndex == uint64_t(-1)) {
10002       // We were asked to evaluate this subexpression independent of the
10003       // enclosing ArrayInitLoopExpr. We can't do that.
10004       Info.FFDiag(E);
10005       return false;
10006     }
10007     return Success(Info.ArrayInitIndex, E);
10008   }
10009 
10010   // Note, GNU defines __null as an integer, not a pointer.
10011   bool VisitGNUNullExpr(const GNUNullExpr *E) {
10012     return ZeroInitialization(E);
10013   }
10014 
10015   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
10016     return Success(E->getValue(), E);
10017   }
10018 
10019   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
10020     return Success(E->getValue(), E);
10021   }
10022 
10023   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
10024     return Success(E->getValue(), E);
10025   }
10026 
10027   bool VisitUnaryReal(const UnaryOperator *E);
10028   bool VisitUnaryImag(const UnaryOperator *E);
10029 
10030   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
10031   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
10032   bool VisitSourceLocExpr(const SourceLocExpr *E);
10033   bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
10034   bool VisitRequiresExpr(const RequiresExpr *E);
10035   // FIXME: Missing: array subscript of vector, member of vector
10036 };
10037 
10038 class FixedPointExprEvaluator
10039     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
10040   APValue &Result;
10041 
10042  public:
10043   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
10044       : ExprEvaluatorBaseTy(info), Result(result) {}
10045 
10046   bool Success(const llvm::APInt &I, const Expr *E) {
10047     return Success(
10048         APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10049   }
10050 
10051   bool Success(uint64_t Value, const Expr *E) {
10052     return Success(
10053         APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10054   }
10055 
10056   bool Success(const APValue &V, const Expr *E) {
10057     return Success(V.getFixedPoint(), E);
10058   }
10059 
10060   bool Success(const APFixedPoint &V, const Expr *E) {
10061     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
10062     assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10063            "Invalid evaluation result.");
10064     Result = APValue(V);
10065     return true;
10066   }
10067 
10068   //===--------------------------------------------------------------------===//
10069   //                            Visitor Methods
10070   //===--------------------------------------------------------------------===//
10071 
10072   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
10073     return Success(E->getValue(), E);
10074   }
10075 
10076   bool VisitCastExpr(const CastExpr *E);
10077   bool VisitUnaryOperator(const UnaryOperator *E);
10078   bool VisitBinaryOperator(const BinaryOperator *E);
10079 };
10080 } // end anonymous namespace
10081 
10082 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
10083 /// produce either the integer value or a pointer.
10084 ///
10085 /// GCC has a heinous extension which folds casts between pointer types and
10086 /// pointer-sized integral types. We support this by allowing the evaluation of
10087 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
10088 /// Some simple arithmetic on such values is supported (they are treated much
10089 /// like char*).
10090 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
10091                                     EvalInfo &Info) {
10092   assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
10093   return IntExprEvaluator(Info, Result).Visit(E);
10094 }
10095 
10096 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
10097   APValue Val;
10098   if (!EvaluateIntegerOrLValue(E, Val, Info))
10099     return false;
10100   if (!Val.isInt()) {
10101     // FIXME: It would be better to produce the diagnostic for casting
10102     //        a pointer to an integer.
10103     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10104     return false;
10105   }
10106   Result = Val.getInt();
10107   return true;
10108 }
10109 
10110 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
10111   APValue Evaluated = E->EvaluateInContext(
10112       Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
10113   return Success(Evaluated, E);
10114 }
10115 
10116 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
10117                                EvalInfo &Info) {
10118   if (E->getType()->isFixedPointType()) {
10119     APValue Val;
10120     if (!FixedPointExprEvaluator(Info, Val).Visit(E))
10121       return false;
10122     if (!Val.isFixedPoint())
10123       return false;
10124 
10125     Result = Val.getFixedPoint();
10126     return true;
10127   }
10128   return false;
10129 }
10130 
10131 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
10132                                         EvalInfo &Info) {
10133   if (E->getType()->isIntegerType()) {
10134     auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
10135     APSInt Val;
10136     if (!EvaluateInteger(E, Val, Info))
10137       return false;
10138     Result = APFixedPoint(Val, FXSema);
10139     return true;
10140   } else if (E->getType()->isFixedPointType()) {
10141     return EvaluateFixedPoint(E, Result, Info);
10142   }
10143   return false;
10144 }
10145 
10146 /// Check whether the given declaration can be directly converted to an integral
10147 /// rvalue. If not, no diagnostic is produced; there are other things we can
10148 /// try.
10149 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
10150   // Enums are integer constant exprs.
10151   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
10152     // Check for signedness/width mismatches between E type and ECD value.
10153     bool SameSign = (ECD->getInitVal().isSigned()
10154                      == E->getType()->isSignedIntegerOrEnumerationType());
10155     bool SameWidth = (ECD->getInitVal().getBitWidth()
10156                       == Info.Ctx.getIntWidth(E->getType()));
10157     if (SameSign && SameWidth)
10158       return Success(ECD->getInitVal(), E);
10159     else {
10160       // Get rid of mismatch (otherwise Success assertions will fail)
10161       // by computing a new value matching the type of E.
10162       llvm::APSInt Val = ECD->getInitVal();
10163       if (!SameSign)
10164         Val.setIsSigned(!ECD->getInitVal().isSigned());
10165       if (!SameWidth)
10166         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
10167       return Success(Val, E);
10168     }
10169   }
10170   return false;
10171 }
10172 
10173 /// Values returned by __builtin_classify_type, chosen to match the values
10174 /// produced by GCC's builtin.
10175 enum class GCCTypeClass {
10176   None = -1,
10177   Void = 0,
10178   Integer = 1,
10179   // GCC reserves 2 for character types, but instead classifies them as
10180   // integers.
10181   Enum = 3,
10182   Bool = 4,
10183   Pointer = 5,
10184   // GCC reserves 6 for references, but appears to never use it (because
10185   // expressions never have reference type, presumably).
10186   PointerToDataMember = 7,
10187   RealFloat = 8,
10188   Complex = 9,
10189   // GCC reserves 10 for functions, but does not use it since GCC version 6 due
10190   // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
10191   // GCC claims to reserve 11 for pointers to member functions, but *actually*
10192   // uses 12 for that purpose, same as for a class or struct. Maybe it
10193   // internally implements a pointer to member as a struct?  Who knows.
10194   PointerToMemberFunction = 12, // Not a bug, see above.
10195   ClassOrStruct = 12,
10196   Union = 13,
10197   // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
10198   // decay to pointer. (Prior to version 6 it was only used in C++ mode).
10199   // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
10200   // literals.
10201 };
10202 
10203 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
10204 /// as GCC.
10205 static GCCTypeClass
10206 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
10207   assert(!T->isDependentType() && "unexpected dependent type");
10208 
10209   QualType CanTy = T.getCanonicalType();
10210   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
10211 
10212   switch (CanTy->getTypeClass()) {
10213 #define TYPE(ID, BASE)
10214 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
10215 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
10216 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
10217 #include "clang/AST/TypeNodes.inc"
10218   case Type::Auto:
10219   case Type::DeducedTemplateSpecialization:
10220       llvm_unreachable("unexpected non-canonical or dependent type");
10221 
10222   case Type::Builtin:
10223     switch (BT->getKind()) {
10224 #define BUILTIN_TYPE(ID, SINGLETON_ID)
10225 #define SIGNED_TYPE(ID, SINGLETON_ID) \
10226     case BuiltinType::ID: return GCCTypeClass::Integer;
10227 #define FLOATING_TYPE(ID, SINGLETON_ID) \
10228     case BuiltinType::ID: return GCCTypeClass::RealFloat;
10229 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
10230     case BuiltinType::ID: break;
10231 #include "clang/AST/BuiltinTypes.def"
10232     case BuiltinType::Void:
10233       return GCCTypeClass::Void;
10234 
10235     case BuiltinType::Bool:
10236       return GCCTypeClass::Bool;
10237 
10238     case BuiltinType::Char_U:
10239     case BuiltinType::UChar:
10240     case BuiltinType::WChar_U:
10241     case BuiltinType::Char8:
10242     case BuiltinType::Char16:
10243     case BuiltinType::Char32:
10244     case BuiltinType::UShort:
10245     case BuiltinType::UInt:
10246     case BuiltinType::ULong:
10247     case BuiltinType::ULongLong:
10248     case BuiltinType::UInt128:
10249       return GCCTypeClass::Integer;
10250 
10251     case BuiltinType::UShortAccum:
10252     case BuiltinType::UAccum:
10253     case BuiltinType::ULongAccum:
10254     case BuiltinType::UShortFract:
10255     case BuiltinType::UFract:
10256     case BuiltinType::ULongFract:
10257     case BuiltinType::SatUShortAccum:
10258     case BuiltinType::SatUAccum:
10259     case BuiltinType::SatULongAccum:
10260     case BuiltinType::SatUShortFract:
10261     case BuiltinType::SatUFract:
10262     case BuiltinType::SatULongFract:
10263       return GCCTypeClass::None;
10264 
10265     case BuiltinType::NullPtr:
10266 
10267     case BuiltinType::ObjCId:
10268     case BuiltinType::ObjCClass:
10269     case BuiltinType::ObjCSel:
10270 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
10271     case BuiltinType::Id:
10272 #include "clang/Basic/OpenCLImageTypes.def"
10273 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
10274     case BuiltinType::Id:
10275 #include "clang/Basic/OpenCLExtensionTypes.def"
10276     case BuiltinType::OCLSampler:
10277     case BuiltinType::OCLEvent:
10278     case BuiltinType::OCLClkEvent:
10279     case BuiltinType::OCLQueue:
10280     case BuiltinType::OCLReserveID:
10281 #define SVE_TYPE(Name, Id, SingletonId) \
10282     case BuiltinType::Id:
10283 #include "clang/Basic/AArch64SVEACLETypes.def"
10284       return GCCTypeClass::None;
10285 
10286     case BuiltinType::Dependent:
10287       llvm_unreachable("unexpected dependent type");
10288     };
10289     llvm_unreachable("unexpected placeholder type");
10290 
10291   case Type::Enum:
10292     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
10293 
10294   case Type::Pointer:
10295   case Type::ConstantArray:
10296   case Type::VariableArray:
10297   case Type::IncompleteArray:
10298   case Type::FunctionNoProto:
10299   case Type::FunctionProto:
10300     return GCCTypeClass::Pointer;
10301 
10302   case Type::MemberPointer:
10303     return CanTy->isMemberDataPointerType()
10304                ? GCCTypeClass::PointerToDataMember
10305                : GCCTypeClass::PointerToMemberFunction;
10306 
10307   case Type::Complex:
10308     return GCCTypeClass::Complex;
10309 
10310   case Type::Record:
10311     return CanTy->isUnionType() ? GCCTypeClass::Union
10312                                 : GCCTypeClass::ClassOrStruct;
10313 
10314   case Type::Atomic:
10315     // GCC classifies _Atomic T the same as T.
10316     return EvaluateBuiltinClassifyType(
10317         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
10318 
10319   case Type::BlockPointer:
10320   case Type::Vector:
10321   case Type::ExtVector:
10322   case Type::ObjCObject:
10323   case Type::ObjCInterface:
10324   case Type::ObjCObjectPointer:
10325   case Type::Pipe:
10326     // GCC classifies vectors as None. We follow its lead and classify all
10327     // other types that don't fit into the regular classification the same way.
10328     return GCCTypeClass::None;
10329 
10330   case Type::LValueReference:
10331   case Type::RValueReference:
10332     llvm_unreachable("invalid type for expression");
10333   }
10334 
10335   llvm_unreachable("unexpected type class");
10336 }
10337 
10338 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
10339 /// as GCC.
10340 static GCCTypeClass
10341 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
10342   // If no argument was supplied, default to None. This isn't
10343   // ideal, however it is what gcc does.
10344   if (E->getNumArgs() == 0)
10345     return GCCTypeClass::None;
10346 
10347   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
10348   // being an ICE, but still folds it to a constant using the type of the first
10349   // argument.
10350   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
10351 }
10352 
10353 /// EvaluateBuiltinConstantPForLValue - Determine the result of
10354 /// __builtin_constant_p when applied to the given pointer.
10355 ///
10356 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
10357 /// or it points to the first character of a string literal.
10358 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
10359   APValue::LValueBase Base = LV.getLValueBase();
10360   if (Base.isNull()) {
10361     // A null base is acceptable.
10362     return true;
10363   } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
10364     if (!isa<StringLiteral>(E))
10365       return false;
10366     return LV.getLValueOffset().isZero();
10367   } else if (Base.is<TypeInfoLValue>()) {
10368     // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
10369     // evaluate to true.
10370     return true;
10371   } else {
10372     // Any other base is not constant enough for GCC.
10373     return false;
10374   }
10375 }
10376 
10377 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
10378 /// GCC as we can manage.
10379 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
10380   // This evaluation is not permitted to have side-effects, so evaluate it in
10381   // a speculative evaluation context.
10382   SpeculativeEvaluationRAII SpeculativeEval(Info);
10383 
10384   // Constant-folding is always enabled for the operand of __builtin_constant_p
10385   // (even when the enclosing evaluation context otherwise requires a strict
10386   // language-specific constant expression).
10387   FoldConstant Fold(Info, true);
10388 
10389   QualType ArgType = Arg->getType();
10390 
10391   // __builtin_constant_p always has one operand. The rules which gcc follows
10392   // are not precisely documented, but are as follows:
10393   //
10394   //  - If the operand is of integral, floating, complex or enumeration type,
10395   //    and can be folded to a known value of that type, it returns 1.
10396   //  - If the operand can be folded to a pointer to the first character
10397   //    of a string literal (or such a pointer cast to an integral type)
10398   //    or to a null pointer or an integer cast to a pointer, it returns 1.
10399   //
10400   // Otherwise, it returns 0.
10401   //
10402   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
10403   // its support for this did not work prior to GCC 9 and is not yet well
10404   // understood.
10405   if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
10406       ArgType->isAnyComplexType() || ArgType->isPointerType() ||
10407       ArgType->isNullPtrType()) {
10408     APValue V;
10409     if (!::EvaluateAsRValue(Info, Arg, V)) {
10410       Fold.keepDiagnostics();
10411       return false;
10412     }
10413 
10414     // For a pointer (possibly cast to integer), there are special rules.
10415     if (V.getKind() == APValue::LValue)
10416       return EvaluateBuiltinConstantPForLValue(V);
10417 
10418     // Otherwise, any constant value is good enough.
10419     return V.hasValue();
10420   }
10421 
10422   // Anything else isn't considered to be sufficiently constant.
10423   return false;
10424 }
10425 
10426 /// Retrieves the "underlying object type" of the given expression,
10427 /// as used by __builtin_object_size.
10428 static QualType getObjectType(APValue::LValueBase B) {
10429   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
10430     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
10431       return VD->getType();
10432   } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
10433     if (isa<CompoundLiteralExpr>(E))
10434       return E->getType();
10435   } else if (B.is<TypeInfoLValue>()) {
10436     return B.getTypeInfoType();
10437   } else if (B.is<DynamicAllocLValue>()) {
10438     return B.getDynamicAllocType();
10439   }
10440 
10441   return QualType();
10442 }
10443 
10444 /// A more selective version of E->IgnoreParenCasts for
10445 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
10446 /// to change the type of E.
10447 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
10448 ///
10449 /// Always returns an RValue with a pointer representation.
10450 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
10451   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
10452 
10453   auto *NoParens = E->IgnoreParens();
10454   auto *Cast = dyn_cast<CastExpr>(NoParens);
10455   if (Cast == nullptr)
10456     return NoParens;
10457 
10458   // We only conservatively allow a few kinds of casts, because this code is
10459   // inherently a simple solution that seeks to support the common case.
10460   auto CastKind = Cast->getCastKind();
10461   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
10462       CastKind != CK_AddressSpaceConversion)
10463     return NoParens;
10464 
10465   auto *SubExpr = Cast->getSubExpr();
10466   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
10467     return NoParens;
10468   return ignorePointerCastsAndParens(SubExpr);
10469 }
10470 
10471 /// Checks to see if the given LValue's Designator is at the end of the LValue's
10472 /// record layout. e.g.
10473 ///   struct { struct { int a, b; } fst, snd; } obj;
10474 ///   obj.fst   // no
10475 ///   obj.snd   // yes
10476 ///   obj.fst.a // no
10477 ///   obj.fst.b // no
10478 ///   obj.snd.a // no
10479 ///   obj.snd.b // yes
10480 ///
10481 /// Please note: this function is specialized for how __builtin_object_size
10482 /// views "objects".
10483 ///
10484 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
10485 /// correct result, it will always return true.
10486 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
10487   assert(!LVal.Designator.Invalid);
10488 
10489   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
10490     const RecordDecl *Parent = FD->getParent();
10491     Invalid = Parent->isInvalidDecl();
10492     if (Invalid || Parent->isUnion())
10493       return true;
10494     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
10495     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
10496   };
10497 
10498   auto &Base = LVal.getLValueBase();
10499   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
10500     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
10501       bool Invalid;
10502       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
10503         return Invalid;
10504     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
10505       for (auto *FD : IFD->chain()) {
10506         bool Invalid;
10507         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
10508           return Invalid;
10509       }
10510     }
10511   }
10512 
10513   unsigned I = 0;
10514   QualType BaseType = getType(Base);
10515   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
10516     // If we don't know the array bound, conservatively assume we're looking at
10517     // the final array element.
10518     ++I;
10519     if (BaseType->isIncompleteArrayType())
10520       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
10521     else
10522       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
10523   }
10524 
10525   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
10526     const auto &Entry = LVal.Designator.Entries[I];
10527     if (BaseType->isArrayType()) {
10528       // Because __builtin_object_size treats arrays as objects, we can ignore
10529       // the index iff this is the last array in the Designator.
10530       if (I + 1 == E)
10531         return true;
10532       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
10533       uint64_t Index = Entry.getAsArrayIndex();
10534       if (Index + 1 != CAT->getSize())
10535         return false;
10536       BaseType = CAT->getElementType();
10537     } else if (BaseType->isAnyComplexType()) {
10538       const auto *CT = BaseType->castAs<ComplexType>();
10539       uint64_t Index = Entry.getAsArrayIndex();
10540       if (Index != 1)
10541         return false;
10542       BaseType = CT->getElementType();
10543     } else if (auto *FD = getAsField(Entry)) {
10544       bool Invalid;
10545       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
10546         return Invalid;
10547       BaseType = FD->getType();
10548     } else {
10549       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
10550       return false;
10551     }
10552   }
10553   return true;
10554 }
10555 
10556 /// Tests to see if the LValue has a user-specified designator (that isn't
10557 /// necessarily valid). Note that this always returns 'true' if the LValue has
10558 /// an unsized array as its first designator entry, because there's currently no
10559 /// way to tell if the user typed *foo or foo[0].
10560 static bool refersToCompleteObject(const LValue &LVal) {
10561   if (LVal.Designator.Invalid)
10562     return false;
10563 
10564   if (!LVal.Designator.Entries.empty())
10565     return LVal.Designator.isMostDerivedAnUnsizedArray();
10566 
10567   if (!LVal.InvalidBase)
10568     return true;
10569 
10570   // If `E` is a MemberExpr, then the first part of the designator is hiding in
10571   // the LValueBase.
10572   const auto *E = LVal.Base.dyn_cast<const Expr *>();
10573   return !E || !isa<MemberExpr>(E);
10574 }
10575 
10576 /// Attempts to detect a user writing into a piece of memory that's impossible
10577 /// to figure out the size of by just using types.
10578 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
10579   const SubobjectDesignator &Designator = LVal.Designator;
10580   // Notes:
10581   // - Users can only write off of the end when we have an invalid base. Invalid
10582   //   bases imply we don't know where the memory came from.
10583   // - We used to be a bit more aggressive here; we'd only be conservative if
10584   //   the array at the end was flexible, or if it had 0 or 1 elements. This
10585   //   broke some common standard library extensions (PR30346), but was
10586   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
10587   //   with some sort of whitelist. OTOH, it seems that GCC is always
10588   //   conservative with the last element in structs (if it's an array), so our
10589   //   current behavior is more compatible than a whitelisting approach would
10590   //   be.
10591   return LVal.InvalidBase &&
10592          Designator.Entries.size() == Designator.MostDerivedPathLength &&
10593          Designator.MostDerivedIsArrayElement &&
10594          isDesignatorAtObjectEnd(Ctx, LVal);
10595 }
10596 
10597 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
10598 /// Fails if the conversion would cause loss of precision.
10599 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
10600                                             CharUnits &Result) {
10601   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
10602   if (Int.ugt(CharUnitsMax))
10603     return false;
10604   Result = CharUnits::fromQuantity(Int.getZExtValue());
10605   return true;
10606 }
10607 
10608 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
10609 /// determine how many bytes exist from the beginning of the object to either
10610 /// the end of the current subobject, or the end of the object itself, depending
10611 /// on what the LValue looks like + the value of Type.
10612 ///
10613 /// If this returns false, the value of Result is undefined.
10614 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
10615                                unsigned Type, const LValue &LVal,
10616                                CharUnits &EndOffset) {
10617   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
10618 
10619   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
10620     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
10621       return false;
10622     return HandleSizeof(Info, ExprLoc, Ty, Result);
10623   };
10624 
10625   // We want to evaluate the size of the entire object. This is a valid fallback
10626   // for when Type=1 and the designator is invalid, because we're asked for an
10627   // upper-bound.
10628   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
10629     // Type=3 wants a lower bound, so we can't fall back to this.
10630     if (Type == 3 && !DetermineForCompleteObject)
10631       return false;
10632 
10633     llvm::APInt APEndOffset;
10634     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
10635         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
10636       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
10637 
10638     if (LVal.InvalidBase)
10639       return false;
10640 
10641     QualType BaseTy = getObjectType(LVal.getLValueBase());
10642     return CheckedHandleSizeof(BaseTy, EndOffset);
10643   }
10644 
10645   // We want to evaluate the size of a subobject.
10646   const SubobjectDesignator &Designator = LVal.Designator;
10647 
10648   // The following is a moderately common idiom in C:
10649   //
10650   // struct Foo { int a; char c[1]; };
10651   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
10652   // strcpy(&F->c[0], Bar);
10653   //
10654   // In order to not break too much legacy code, we need to support it.
10655   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
10656     // If we can resolve this to an alloc_size call, we can hand that back,
10657     // because we know for certain how many bytes there are to write to.
10658     llvm::APInt APEndOffset;
10659     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
10660         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
10661       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
10662 
10663     // If we cannot determine the size of the initial allocation, then we can't
10664     // given an accurate upper-bound. However, we are still able to give
10665     // conservative lower-bounds for Type=3.
10666     if (Type == 1)
10667       return false;
10668   }
10669 
10670   CharUnits BytesPerElem;
10671   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
10672     return false;
10673 
10674   // According to the GCC documentation, we want the size of the subobject
10675   // denoted by the pointer. But that's not quite right -- what we actually
10676   // want is the size of the immediately-enclosing array, if there is one.
10677   int64_t ElemsRemaining;
10678   if (Designator.MostDerivedIsArrayElement &&
10679       Designator.Entries.size() == Designator.MostDerivedPathLength) {
10680     uint64_t ArraySize = Designator.getMostDerivedArraySize();
10681     uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
10682     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
10683   } else {
10684     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
10685   }
10686 
10687   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
10688   return true;
10689 }
10690 
10691 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
10692 /// returns true and stores the result in @p Size.
10693 ///
10694 /// If @p WasError is non-null, this will report whether the failure to evaluate
10695 /// is to be treated as an Error in IntExprEvaluator.
10696 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
10697                                          EvalInfo &Info, uint64_t &Size) {
10698   // Determine the denoted object.
10699   LValue LVal;
10700   {
10701     // The operand of __builtin_object_size is never evaluated for side-effects.
10702     // If there are any, but we can determine the pointed-to object anyway, then
10703     // ignore the side-effects.
10704     SpeculativeEvaluationRAII SpeculativeEval(Info);
10705     IgnoreSideEffectsRAII Fold(Info);
10706 
10707     if (E->isGLValue()) {
10708       // It's possible for us to be given GLValues if we're called via
10709       // Expr::tryEvaluateObjectSize.
10710       APValue RVal;
10711       if (!EvaluateAsRValue(Info, E, RVal))
10712         return false;
10713       LVal.setFrom(Info.Ctx, RVal);
10714     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
10715                                 /*InvalidBaseOK=*/true))
10716       return false;
10717   }
10718 
10719   // If we point to before the start of the object, there are no accessible
10720   // bytes.
10721   if (LVal.getLValueOffset().isNegative()) {
10722     Size = 0;
10723     return true;
10724   }
10725 
10726   CharUnits EndOffset;
10727   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
10728     return false;
10729 
10730   // If we've fallen outside of the end offset, just pretend there's nothing to
10731   // write to/read from.
10732   if (EndOffset <= LVal.getLValueOffset())
10733     Size = 0;
10734   else
10735     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
10736   return true;
10737 }
10738 
10739 bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
10740   llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
10741   if (E->getResultAPValueKind() != APValue::None)
10742     return Success(E->getAPValueResult(), E);
10743   return ExprEvaluatorBaseTy::VisitConstantExpr(E);
10744 }
10745 
10746 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
10747   if (unsigned BuiltinOp = E->getBuiltinCallee())
10748     return VisitBuiltinCallExpr(E, BuiltinOp);
10749 
10750   return ExprEvaluatorBaseTy::VisitCallExpr(E);
10751 }
10752 
10753 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
10754                                      APValue &Val, APSInt &Alignment) {
10755   QualType SrcTy = E->getArg(0)->getType();
10756   if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
10757     return false;
10758   // Even though we are evaluating integer expressions we could get a pointer
10759   // argument for the __builtin_is_aligned() case.
10760   if (SrcTy->isPointerType()) {
10761     LValue Ptr;
10762     if (!EvaluatePointer(E->getArg(0), Ptr, Info))
10763       return false;
10764     Ptr.moveInto(Val);
10765   } else if (!SrcTy->isIntegralOrEnumerationType()) {
10766     Info.FFDiag(E->getArg(0));
10767     return false;
10768   } else {
10769     APSInt SrcInt;
10770     if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
10771       return false;
10772     assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
10773            "Bit widths must be the same");
10774     Val = APValue(SrcInt);
10775   }
10776   assert(Val.hasValue());
10777   return true;
10778 }
10779 
10780 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
10781                                             unsigned BuiltinOp) {
10782   switch (BuiltinOp) {
10783   default:
10784     return ExprEvaluatorBaseTy::VisitCallExpr(E);
10785 
10786   case Builtin::BI__builtin_dynamic_object_size:
10787   case Builtin::BI__builtin_object_size: {
10788     // The type was checked when we built the expression.
10789     unsigned Type =
10790         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
10791     assert(Type <= 3 && "unexpected type");
10792 
10793     uint64_t Size;
10794     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
10795       return Success(Size, E);
10796 
10797     if (E->getArg(0)->HasSideEffects(Info.Ctx))
10798       return Success((Type & 2) ? 0 : -1, E);
10799 
10800     // Expression had no side effects, but we couldn't statically determine the
10801     // size of the referenced object.
10802     switch (Info.EvalMode) {
10803     case EvalInfo::EM_ConstantExpression:
10804     case EvalInfo::EM_ConstantFold:
10805     case EvalInfo::EM_IgnoreSideEffects:
10806       // Leave it to IR generation.
10807       return Error(E);
10808     case EvalInfo::EM_ConstantExpressionUnevaluated:
10809       // Reduce it to a constant now.
10810       return Success((Type & 2) ? 0 : -1, E);
10811     }
10812 
10813     llvm_unreachable("unexpected EvalMode");
10814   }
10815 
10816   case Builtin::BI__builtin_os_log_format_buffer_size: {
10817     analyze_os_log::OSLogBufferLayout Layout;
10818     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
10819     return Success(Layout.size().getQuantity(), E);
10820   }
10821 
10822   case Builtin::BI__builtin_is_aligned: {
10823     APValue Src;
10824     APSInt Alignment;
10825     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
10826       return false;
10827     if (Src.isLValue()) {
10828       // If we evaluated a pointer, check the minimum known alignment.
10829       LValue Ptr;
10830       Ptr.setFrom(Info.Ctx, Src);
10831       CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
10832       CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
10833       // We can return true if the known alignment at the computed offset is
10834       // greater than the requested alignment.
10835       assert(PtrAlign.isPowerOfTwo());
10836       assert(Alignment.isPowerOf2());
10837       if (PtrAlign.getQuantity() >= Alignment)
10838         return Success(1, E);
10839       // If the alignment is not known to be sufficient, some cases could still
10840       // be aligned at run time. However, if the requested alignment is less or
10841       // equal to the base alignment and the offset is not aligned, we know that
10842       // the run-time value can never be aligned.
10843       if (BaseAlignment.getQuantity() >= Alignment &&
10844           PtrAlign.getQuantity() < Alignment)
10845         return Success(0, E);
10846       // Otherwise we can't infer whether the value is sufficiently aligned.
10847       // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
10848       //  in cases where we can't fully evaluate the pointer.
10849       Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
10850           << Alignment;
10851       return false;
10852     }
10853     assert(Src.isInt());
10854     return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
10855   }
10856   case Builtin::BI__builtin_align_up: {
10857     APValue Src;
10858     APSInt Alignment;
10859     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
10860       return false;
10861     if (!Src.isInt())
10862       return Error(E);
10863     APSInt AlignedVal =
10864         APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
10865                Src.getInt().isUnsigned());
10866     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
10867     return Success(AlignedVal, E);
10868   }
10869   case Builtin::BI__builtin_align_down: {
10870     APValue Src;
10871     APSInt Alignment;
10872     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
10873       return false;
10874     if (!Src.isInt())
10875       return Error(E);
10876     APSInt AlignedVal =
10877         APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
10878     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
10879     return Success(AlignedVal, E);
10880   }
10881 
10882   case Builtin::BI__builtin_bswap16:
10883   case Builtin::BI__builtin_bswap32:
10884   case Builtin::BI__builtin_bswap64: {
10885     APSInt Val;
10886     if (!EvaluateInteger(E->getArg(0), Val, Info))
10887       return false;
10888 
10889     return Success(Val.byteSwap(), E);
10890   }
10891 
10892   case Builtin::BI__builtin_classify_type:
10893     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
10894 
10895   case Builtin::BI__builtin_clrsb:
10896   case Builtin::BI__builtin_clrsbl:
10897   case Builtin::BI__builtin_clrsbll: {
10898     APSInt Val;
10899     if (!EvaluateInteger(E->getArg(0), Val, Info))
10900       return false;
10901 
10902     return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
10903   }
10904 
10905   case Builtin::BI__builtin_clz:
10906   case Builtin::BI__builtin_clzl:
10907   case Builtin::BI__builtin_clzll:
10908   case Builtin::BI__builtin_clzs: {
10909     APSInt Val;
10910     if (!EvaluateInteger(E->getArg(0), Val, Info))
10911       return false;
10912     if (!Val)
10913       return Error(E);
10914 
10915     return Success(Val.countLeadingZeros(), E);
10916   }
10917 
10918   case Builtin::BI__builtin_constant_p: {
10919     const Expr *Arg = E->getArg(0);
10920     if (EvaluateBuiltinConstantP(Info, Arg))
10921       return Success(true, E);
10922     if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
10923       // Outside a constant context, eagerly evaluate to false in the presence
10924       // of side-effects in order to avoid -Wunsequenced false-positives in
10925       // a branch on __builtin_constant_p(expr).
10926       return Success(false, E);
10927     }
10928     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10929     return false;
10930   }
10931 
10932   case Builtin::BI__builtin_is_constant_evaluated: {
10933     const auto *Callee = Info.CurrentCall->getCallee();
10934     if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
10935         (Info.CallStackDepth == 1 ||
10936          (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
10937           Callee->getIdentifier() &&
10938           Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
10939       // FIXME: Find a better way to avoid duplicated diagnostics.
10940       if (Info.EvalStatus.Diag)
10941         Info.report((Info.CallStackDepth == 1) ? E->getExprLoc()
10942                                                : Info.CurrentCall->CallLoc,
10943                     diag::warn_is_constant_evaluated_always_true_constexpr)
10944             << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
10945                                          : "std::is_constant_evaluated");
10946     }
10947 
10948     return Success(Info.InConstantContext, E);
10949   }
10950 
10951   case Builtin::BI__builtin_ctz:
10952   case Builtin::BI__builtin_ctzl:
10953   case Builtin::BI__builtin_ctzll:
10954   case Builtin::BI__builtin_ctzs: {
10955     APSInt Val;
10956     if (!EvaluateInteger(E->getArg(0), Val, Info))
10957       return false;
10958     if (!Val)
10959       return Error(E);
10960 
10961     return Success(Val.countTrailingZeros(), E);
10962   }
10963 
10964   case Builtin::BI__builtin_eh_return_data_regno: {
10965     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
10966     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
10967     return Success(Operand, E);
10968   }
10969 
10970   case Builtin::BI__builtin_expect:
10971     return Visit(E->getArg(0));
10972 
10973   case Builtin::BI__builtin_ffs:
10974   case Builtin::BI__builtin_ffsl:
10975   case Builtin::BI__builtin_ffsll: {
10976     APSInt Val;
10977     if (!EvaluateInteger(E->getArg(0), Val, Info))
10978       return false;
10979 
10980     unsigned N = Val.countTrailingZeros();
10981     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
10982   }
10983 
10984   case Builtin::BI__builtin_fpclassify: {
10985     APFloat Val(0.0);
10986     if (!EvaluateFloat(E->getArg(5), Val, Info))
10987       return false;
10988     unsigned Arg;
10989     switch (Val.getCategory()) {
10990     case APFloat::fcNaN: Arg = 0; break;
10991     case APFloat::fcInfinity: Arg = 1; break;
10992     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
10993     case APFloat::fcZero: Arg = 4; break;
10994     }
10995     return Visit(E->getArg(Arg));
10996   }
10997 
10998   case Builtin::BI__builtin_isinf_sign: {
10999     APFloat Val(0.0);
11000     return EvaluateFloat(E->getArg(0), Val, Info) &&
11001            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
11002   }
11003 
11004   case Builtin::BI__builtin_isinf: {
11005     APFloat Val(0.0);
11006     return EvaluateFloat(E->getArg(0), Val, Info) &&
11007            Success(Val.isInfinity() ? 1 : 0, E);
11008   }
11009 
11010   case Builtin::BI__builtin_isfinite: {
11011     APFloat Val(0.0);
11012     return EvaluateFloat(E->getArg(0), Val, Info) &&
11013            Success(Val.isFinite() ? 1 : 0, E);
11014   }
11015 
11016   case Builtin::BI__builtin_isnan: {
11017     APFloat Val(0.0);
11018     return EvaluateFloat(E->getArg(0), Val, Info) &&
11019            Success(Val.isNaN() ? 1 : 0, E);
11020   }
11021 
11022   case Builtin::BI__builtin_isnormal: {
11023     APFloat Val(0.0);
11024     return EvaluateFloat(E->getArg(0), Val, Info) &&
11025            Success(Val.isNormal() ? 1 : 0, E);
11026   }
11027 
11028   case Builtin::BI__builtin_parity:
11029   case Builtin::BI__builtin_parityl:
11030   case Builtin::BI__builtin_parityll: {
11031     APSInt Val;
11032     if (!EvaluateInteger(E->getArg(0), Val, Info))
11033       return false;
11034 
11035     return Success(Val.countPopulation() % 2, E);
11036   }
11037 
11038   case Builtin::BI__builtin_popcount:
11039   case Builtin::BI__builtin_popcountl:
11040   case Builtin::BI__builtin_popcountll: {
11041     APSInt Val;
11042     if (!EvaluateInteger(E->getArg(0), Val, Info))
11043       return false;
11044 
11045     return Success(Val.countPopulation(), E);
11046   }
11047 
11048   case Builtin::BIstrlen:
11049   case Builtin::BIwcslen:
11050     // A call to strlen is not a constant expression.
11051     if (Info.getLangOpts().CPlusPlus11)
11052       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11053         << /*isConstexpr*/0 << /*isConstructor*/0
11054         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11055     else
11056       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11057     LLVM_FALLTHROUGH;
11058   case Builtin::BI__builtin_strlen:
11059   case Builtin::BI__builtin_wcslen: {
11060     // As an extension, we support __builtin_strlen() as a constant expression,
11061     // and support folding strlen() to a constant.
11062     LValue String;
11063     if (!EvaluatePointer(E->getArg(0), String, Info))
11064       return false;
11065 
11066     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
11067 
11068     // Fast path: if it's a string literal, search the string value.
11069     if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
11070             String.getLValueBase().dyn_cast<const Expr *>())) {
11071       // The string literal may have embedded null characters. Find the first
11072       // one and truncate there.
11073       StringRef Str = S->getBytes();
11074       int64_t Off = String.Offset.getQuantity();
11075       if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
11076           S->getCharByteWidth() == 1 &&
11077           // FIXME: Add fast-path for wchar_t too.
11078           Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
11079         Str = Str.substr(Off);
11080 
11081         StringRef::size_type Pos = Str.find(0);
11082         if (Pos != StringRef::npos)
11083           Str = Str.substr(0, Pos);
11084 
11085         return Success(Str.size(), E);
11086       }
11087 
11088       // Fall through to slow path to issue appropriate diagnostic.
11089     }
11090 
11091     // Slow path: scan the bytes of the string looking for the terminating 0.
11092     for (uint64_t Strlen = 0; /**/; ++Strlen) {
11093       APValue Char;
11094       if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
11095           !Char.isInt())
11096         return false;
11097       if (!Char.getInt())
11098         return Success(Strlen, E);
11099       if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
11100         return false;
11101     }
11102   }
11103 
11104   case Builtin::BIstrcmp:
11105   case Builtin::BIwcscmp:
11106   case Builtin::BIstrncmp:
11107   case Builtin::BIwcsncmp:
11108   case Builtin::BImemcmp:
11109   case Builtin::BIbcmp:
11110   case Builtin::BIwmemcmp:
11111     // A call to strlen is not a constant expression.
11112     if (Info.getLangOpts().CPlusPlus11)
11113       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11114         << /*isConstexpr*/0 << /*isConstructor*/0
11115         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11116     else
11117       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11118     LLVM_FALLTHROUGH;
11119   case Builtin::BI__builtin_strcmp:
11120   case Builtin::BI__builtin_wcscmp:
11121   case Builtin::BI__builtin_strncmp:
11122   case Builtin::BI__builtin_wcsncmp:
11123   case Builtin::BI__builtin_memcmp:
11124   case Builtin::BI__builtin_bcmp:
11125   case Builtin::BI__builtin_wmemcmp: {
11126     LValue String1, String2;
11127     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
11128         !EvaluatePointer(E->getArg(1), String2, Info))
11129       return false;
11130 
11131     uint64_t MaxLength = uint64_t(-1);
11132     if (BuiltinOp != Builtin::BIstrcmp &&
11133         BuiltinOp != Builtin::BIwcscmp &&
11134         BuiltinOp != Builtin::BI__builtin_strcmp &&
11135         BuiltinOp != Builtin::BI__builtin_wcscmp) {
11136       APSInt N;
11137       if (!EvaluateInteger(E->getArg(2), N, Info))
11138         return false;
11139       MaxLength = N.getExtValue();
11140     }
11141 
11142     // Empty substrings compare equal by definition.
11143     if (MaxLength == 0u)
11144       return Success(0, E);
11145 
11146     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11147         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11148         String1.Designator.Invalid || String2.Designator.Invalid)
11149       return false;
11150 
11151     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
11152     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
11153 
11154     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
11155                      BuiltinOp == Builtin::BIbcmp ||
11156                      BuiltinOp == Builtin::BI__builtin_memcmp ||
11157                      BuiltinOp == Builtin::BI__builtin_bcmp;
11158 
11159     assert(IsRawByte ||
11160            (Info.Ctx.hasSameUnqualifiedType(
11161                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
11162             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
11163 
11164     // For memcmp, allow comparing any arrays of '[[un]signed] char' or
11165     // 'char8_t', but no other types.
11166     if (IsRawByte &&
11167         !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
11168       // FIXME: Consider using our bit_cast implementation to support this.
11169       Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
11170           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
11171           << CharTy1 << CharTy2;
11172       return false;
11173     }
11174 
11175     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
11176       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
11177              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
11178              Char1.isInt() && Char2.isInt();
11179     };
11180     const auto &AdvanceElems = [&] {
11181       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
11182              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
11183     };
11184 
11185     bool StopAtNull =
11186         (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
11187          BuiltinOp != Builtin::BIwmemcmp &&
11188          BuiltinOp != Builtin::BI__builtin_memcmp &&
11189          BuiltinOp != Builtin::BI__builtin_bcmp &&
11190          BuiltinOp != Builtin::BI__builtin_wmemcmp);
11191     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
11192                   BuiltinOp == Builtin::BIwcsncmp ||
11193                   BuiltinOp == Builtin::BIwmemcmp ||
11194                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
11195                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
11196                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
11197 
11198     for (; MaxLength; --MaxLength) {
11199       APValue Char1, Char2;
11200       if (!ReadCurElems(Char1, Char2))
11201         return false;
11202       if (Char1.getInt().ne(Char2.getInt())) {
11203         if (IsWide) // wmemcmp compares with wchar_t signedness.
11204           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
11205         // memcmp always compares unsigned chars.
11206         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
11207       }
11208       if (StopAtNull && !Char1.getInt())
11209         return Success(0, E);
11210       assert(!(StopAtNull && !Char2.getInt()));
11211       if (!AdvanceElems())
11212         return false;
11213     }
11214     // We hit the strncmp / memcmp limit.
11215     return Success(0, E);
11216   }
11217 
11218   case Builtin::BI__atomic_always_lock_free:
11219   case Builtin::BI__atomic_is_lock_free:
11220   case Builtin::BI__c11_atomic_is_lock_free: {
11221     APSInt SizeVal;
11222     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
11223       return false;
11224 
11225     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
11226     // of two less than the maximum inline atomic width, we know it is
11227     // lock-free.  If the size isn't a power of two, or greater than the
11228     // maximum alignment where we promote atomics, we know it is not lock-free
11229     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
11230     // the answer can only be determined at runtime; for example, 16-byte
11231     // atomics have lock-free implementations on some, but not all,
11232     // x86-64 processors.
11233 
11234     // Check power-of-two.
11235     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
11236     if (Size.isPowerOfTwo()) {
11237       // Check against inlining width.
11238       unsigned InlineWidthBits =
11239           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
11240       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
11241         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
11242             Size == CharUnits::One() ||
11243             E->getArg(1)->isNullPointerConstant(Info.Ctx,
11244                                                 Expr::NPC_NeverValueDependent))
11245           // OK, we will inline appropriately-aligned operations of this size,
11246           // and _Atomic(T) is appropriately-aligned.
11247           return Success(1, E);
11248 
11249         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
11250           castAs<PointerType>()->getPointeeType();
11251         if (!PointeeType->isIncompleteType() &&
11252             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
11253           // OK, we will inline operations on this object.
11254           return Success(1, E);
11255         }
11256       }
11257     }
11258 
11259     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
11260         Success(0, E) : Error(E);
11261   }
11262   case Builtin::BIomp_is_initial_device:
11263     // We can decide statically which value the runtime would return if called.
11264     return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
11265   case Builtin::BI__builtin_add_overflow:
11266   case Builtin::BI__builtin_sub_overflow:
11267   case Builtin::BI__builtin_mul_overflow:
11268   case Builtin::BI__builtin_sadd_overflow:
11269   case Builtin::BI__builtin_uadd_overflow:
11270   case Builtin::BI__builtin_uaddl_overflow:
11271   case Builtin::BI__builtin_uaddll_overflow:
11272   case Builtin::BI__builtin_usub_overflow:
11273   case Builtin::BI__builtin_usubl_overflow:
11274   case Builtin::BI__builtin_usubll_overflow:
11275   case Builtin::BI__builtin_umul_overflow:
11276   case Builtin::BI__builtin_umull_overflow:
11277   case Builtin::BI__builtin_umulll_overflow:
11278   case Builtin::BI__builtin_saddl_overflow:
11279   case Builtin::BI__builtin_saddll_overflow:
11280   case Builtin::BI__builtin_ssub_overflow:
11281   case Builtin::BI__builtin_ssubl_overflow:
11282   case Builtin::BI__builtin_ssubll_overflow:
11283   case Builtin::BI__builtin_smul_overflow:
11284   case Builtin::BI__builtin_smull_overflow:
11285   case Builtin::BI__builtin_smulll_overflow: {
11286     LValue ResultLValue;
11287     APSInt LHS, RHS;
11288 
11289     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
11290     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
11291         !EvaluateInteger(E->getArg(1), RHS, Info) ||
11292         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
11293       return false;
11294 
11295     APSInt Result;
11296     bool DidOverflow = false;
11297 
11298     // If the types don't have to match, enlarge all 3 to the largest of them.
11299     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
11300         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
11301         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
11302       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
11303                       ResultType->isSignedIntegerOrEnumerationType();
11304       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
11305                       ResultType->isSignedIntegerOrEnumerationType();
11306       uint64_t LHSSize = LHS.getBitWidth();
11307       uint64_t RHSSize = RHS.getBitWidth();
11308       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
11309       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
11310 
11311       // Add an additional bit if the signedness isn't uniformly agreed to. We
11312       // could do this ONLY if there is a signed and an unsigned that both have
11313       // MaxBits, but the code to check that is pretty nasty.  The issue will be
11314       // caught in the shrink-to-result later anyway.
11315       if (IsSigned && !AllSigned)
11316         ++MaxBits;
11317 
11318       LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
11319       RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
11320       Result = APSInt(MaxBits, !IsSigned);
11321     }
11322 
11323     // Find largest int.
11324     switch (BuiltinOp) {
11325     default:
11326       llvm_unreachable("Invalid value for BuiltinOp");
11327     case Builtin::BI__builtin_add_overflow:
11328     case Builtin::BI__builtin_sadd_overflow:
11329     case Builtin::BI__builtin_saddl_overflow:
11330     case Builtin::BI__builtin_saddll_overflow:
11331     case Builtin::BI__builtin_uadd_overflow:
11332     case Builtin::BI__builtin_uaddl_overflow:
11333     case Builtin::BI__builtin_uaddll_overflow:
11334       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
11335                               : LHS.uadd_ov(RHS, DidOverflow);
11336       break;
11337     case Builtin::BI__builtin_sub_overflow:
11338     case Builtin::BI__builtin_ssub_overflow:
11339     case Builtin::BI__builtin_ssubl_overflow:
11340     case Builtin::BI__builtin_ssubll_overflow:
11341     case Builtin::BI__builtin_usub_overflow:
11342     case Builtin::BI__builtin_usubl_overflow:
11343     case Builtin::BI__builtin_usubll_overflow:
11344       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
11345                               : LHS.usub_ov(RHS, DidOverflow);
11346       break;
11347     case Builtin::BI__builtin_mul_overflow:
11348     case Builtin::BI__builtin_smul_overflow:
11349     case Builtin::BI__builtin_smull_overflow:
11350     case Builtin::BI__builtin_smulll_overflow:
11351     case Builtin::BI__builtin_umul_overflow:
11352     case Builtin::BI__builtin_umull_overflow:
11353     case Builtin::BI__builtin_umulll_overflow:
11354       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
11355                               : LHS.umul_ov(RHS, DidOverflow);
11356       break;
11357     }
11358 
11359     // In the case where multiple sizes are allowed, truncate and see if
11360     // the values are the same.
11361     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
11362         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
11363         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
11364       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
11365       // since it will give us the behavior of a TruncOrSelf in the case where
11366       // its parameter <= its size.  We previously set Result to be at least the
11367       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
11368       // will work exactly like TruncOrSelf.
11369       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
11370       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
11371 
11372       if (!APSInt::isSameValue(Temp, Result))
11373         DidOverflow = true;
11374       Result = Temp;
11375     }
11376 
11377     APValue APV{Result};
11378     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
11379       return false;
11380     return Success(DidOverflow, E);
11381   }
11382   }
11383 }
11384 
11385 /// Determine whether this is a pointer past the end of the complete
11386 /// object referred to by the lvalue.
11387 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
11388                                             const LValue &LV) {
11389   // A null pointer can be viewed as being "past the end" but we don't
11390   // choose to look at it that way here.
11391   if (!LV.getLValueBase())
11392     return false;
11393 
11394   // If the designator is valid and refers to a subobject, we're not pointing
11395   // past the end.
11396   if (!LV.getLValueDesignator().Invalid &&
11397       !LV.getLValueDesignator().isOnePastTheEnd())
11398     return false;
11399 
11400   // A pointer to an incomplete type might be past-the-end if the type's size is
11401   // zero.  We cannot tell because the type is incomplete.
11402   QualType Ty = getType(LV.getLValueBase());
11403   if (Ty->isIncompleteType())
11404     return true;
11405 
11406   // We're a past-the-end pointer if we point to the byte after the object,
11407   // no matter what our type or path is.
11408   auto Size = Ctx.getTypeSizeInChars(Ty);
11409   return LV.getLValueOffset() == Size;
11410 }
11411 
11412 namespace {
11413 
11414 /// Data recursive integer evaluator of certain binary operators.
11415 ///
11416 /// We use a data recursive algorithm for binary operators so that we are able
11417 /// to handle extreme cases of chained binary operators without causing stack
11418 /// overflow.
11419 class DataRecursiveIntBinOpEvaluator {
11420   struct EvalResult {
11421     APValue Val;
11422     bool Failed;
11423 
11424     EvalResult() : Failed(false) { }
11425 
11426     void swap(EvalResult &RHS) {
11427       Val.swap(RHS.Val);
11428       Failed = RHS.Failed;
11429       RHS.Failed = false;
11430     }
11431   };
11432 
11433   struct Job {
11434     const Expr *E;
11435     EvalResult LHSResult; // meaningful only for binary operator expression.
11436     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
11437 
11438     Job() = default;
11439     Job(Job &&) = default;
11440 
11441     void startSpeculativeEval(EvalInfo &Info) {
11442       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
11443     }
11444 
11445   private:
11446     SpeculativeEvaluationRAII SpecEvalRAII;
11447   };
11448 
11449   SmallVector<Job, 16> Queue;
11450 
11451   IntExprEvaluator &IntEval;
11452   EvalInfo &Info;
11453   APValue &FinalResult;
11454 
11455 public:
11456   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
11457     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
11458 
11459   /// True if \param E is a binary operator that we are going to handle
11460   /// data recursively.
11461   /// We handle binary operators that are comma, logical, or that have operands
11462   /// with integral or enumeration type.
11463   static bool shouldEnqueue(const BinaryOperator *E) {
11464     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
11465            (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
11466             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
11467             E->getRHS()->getType()->isIntegralOrEnumerationType());
11468   }
11469 
11470   bool Traverse(const BinaryOperator *E) {
11471     enqueue(E);
11472     EvalResult PrevResult;
11473     while (!Queue.empty())
11474       process(PrevResult);
11475 
11476     if (PrevResult.Failed) return false;
11477 
11478     FinalResult.swap(PrevResult.Val);
11479     return true;
11480   }
11481 
11482 private:
11483   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
11484     return IntEval.Success(Value, E, Result);
11485   }
11486   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
11487     return IntEval.Success(Value, E, Result);
11488   }
11489   bool Error(const Expr *E) {
11490     return IntEval.Error(E);
11491   }
11492   bool Error(const Expr *E, diag::kind D) {
11493     return IntEval.Error(E, D);
11494   }
11495 
11496   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
11497     return Info.CCEDiag(E, D);
11498   }
11499 
11500   // Returns true if visiting the RHS is necessary, false otherwise.
11501   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
11502                          bool &SuppressRHSDiags);
11503 
11504   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
11505                   const BinaryOperator *E, APValue &Result);
11506 
11507   void EvaluateExpr(const Expr *E, EvalResult &Result) {
11508     Result.Failed = !Evaluate(Result.Val, Info, E);
11509     if (Result.Failed)
11510       Result.Val = APValue();
11511   }
11512 
11513   void process(EvalResult &Result);
11514 
11515   void enqueue(const Expr *E) {
11516     E = E->IgnoreParens();
11517     Queue.resize(Queue.size()+1);
11518     Queue.back().E = E;
11519     Queue.back().Kind = Job::AnyExprKind;
11520   }
11521 };
11522 
11523 }
11524 
11525 bool DataRecursiveIntBinOpEvaluator::
11526        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
11527                          bool &SuppressRHSDiags) {
11528   if (E->getOpcode() == BO_Comma) {
11529     // Ignore LHS but note if we could not evaluate it.
11530     if (LHSResult.Failed)
11531       return Info.noteSideEffect();
11532     return true;
11533   }
11534 
11535   if (E->isLogicalOp()) {
11536     bool LHSAsBool;
11537     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
11538       // We were able to evaluate the LHS, see if we can get away with not
11539       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
11540       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
11541         Success(LHSAsBool, E, LHSResult.Val);
11542         return false; // Ignore RHS
11543       }
11544     } else {
11545       LHSResult.Failed = true;
11546 
11547       // Since we weren't able to evaluate the left hand side, it
11548       // might have had side effects.
11549       if (!Info.noteSideEffect())
11550         return false;
11551 
11552       // We can't evaluate the LHS; however, sometimes the result
11553       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
11554       // Don't ignore RHS and suppress diagnostics from this arm.
11555       SuppressRHSDiags = true;
11556     }
11557 
11558     return true;
11559   }
11560 
11561   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
11562          E->getRHS()->getType()->isIntegralOrEnumerationType());
11563 
11564   if (LHSResult.Failed && !Info.noteFailure())
11565     return false; // Ignore RHS;
11566 
11567   return true;
11568 }
11569 
11570 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
11571                                     bool IsSub) {
11572   // Compute the new offset in the appropriate width, wrapping at 64 bits.
11573   // FIXME: When compiling for a 32-bit target, we should use 32-bit
11574   // offsets.
11575   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
11576   CharUnits &Offset = LVal.getLValueOffset();
11577   uint64_t Offset64 = Offset.getQuantity();
11578   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
11579   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
11580                                          : Offset64 + Index64);
11581 }
11582 
11583 bool DataRecursiveIntBinOpEvaluator::
11584        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
11585                   const BinaryOperator *E, APValue &Result) {
11586   if (E->getOpcode() == BO_Comma) {
11587     if (RHSResult.Failed)
11588       return false;
11589     Result = RHSResult.Val;
11590     return true;
11591   }
11592 
11593   if (E->isLogicalOp()) {
11594     bool lhsResult, rhsResult;
11595     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
11596     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
11597 
11598     if (LHSIsOK) {
11599       if (RHSIsOK) {
11600         if (E->getOpcode() == BO_LOr)
11601           return Success(lhsResult || rhsResult, E, Result);
11602         else
11603           return Success(lhsResult && rhsResult, E, Result);
11604       }
11605     } else {
11606       if (RHSIsOK) {
11607         // We can't evaluate the LHS; however, sometimes the result
11608         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
11609         if (rhsResult == (E->getOpcode() == BO_LOr))
11610           return Success(rhsResult, E, Result);
11611       }
11612     }
11613 
11614     return false;
11615   }
11616 
11617   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
11618          E->getRHS()->getType()->isIntegralOrEnumerationType());
11619 
11620   if (LHSResult.Failed || RHSResult.Failed)
11621     return false;
11622 
11623   const APValue &LHSVal = LHSResult.Val;
11624   const APValue &RHSVal = RHSResult.Val;
11625 
11626   // Handle cases like (unsigned long)&a + 4.
11627   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
11628     Result = LHSVal;
11629     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
11630     return true;
11631   }
11632 
11633   // Handle cases like 4 + (unsigned long)&a
11634   if (E->getOpcode() == BO_Add &&
11635       RHSVal.isLValue() && LHSVal.isInt()) {
11636     Result = RHSVal;
11637     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
11638     return true;
11639   }
11640 
11641   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
11642     // Handle (intptr_t)&&A - (intptr_t)&&B.
11643     if (!LHSVal.getLValueOffset().isZero() ||
11644         !RHSVal.getLValueOffset().isZero())
11645       return false;
11646     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
11647     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
11648     if (!LHSExpr || !RHSExpr)
11649       return false;
11650     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
11651     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
11652     if (!LHSAddrExpr || !RHSAddrExpr)
11653       return false;
11654     // Make sure both labels come from the same function.
11655     if (LHSAddrExpr->getLabel()->getDeclContext() !=
11656         RHSAddrExpr->getLabel()->getDeclContext())
11657       return false;
11658     Result = APValue(LHSAddrExpr, RHSAddrExpr);
11659     return true;
11660   }
11661 
11662   // All the remaining cases expect both operands to be an integer
11663   if (!LHSVal.isInt() || !RHSVal.isInt())
11664     return Error(E);
11665 
11666   // Set up the width and signedness manually, in case it can't be deduced
11667   // from the operation we're performing.
11668   // FIXME: Don't do this in the cases where we can deduce it.
11669   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
11670                E->getType()->isUnsignedIntegerOrEnumerationType());
11671   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
11672                          RHSVal.getInt(), Value))
11673     return false;
11674   return Success(Value, E, Result);
11675 }
11676 
11677 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
11678   Job &job = Queue.back();
11679 
11680   switch (job.Kind) {
11681     case Job::AnyExprKind: {
11682       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
11683         if (shouldEnqueue(Bop)) {
11684           job.Kind = Job::BinOpKind;
11685           enqueue(Bop->getLHS());
11686           return;
11687         }
11688       }
11689 
11690       EvaluateExpr(job.E, Result);
11691       Queue.pop_back();
11692       return;
11693     }
11694 
11695     case Job::BinOpKind: {
11696       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
11697       bool SuppressRHSDiags = false;
11698       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
11699         Queue.pop_back();
11700         return;
11701       }
11702       if (SuppressRHSDiags)
11703         job.startSpeculativeEval(Info);
11704       job.LHSResult.swap(Result);
11705       job.Kind = Job::BinOpVisitedLHSKind;
11706       enqueue(Bop->getRHS());
11707       return;
11708     }
11709 
11710     case Job::BinOpVisitedLHSKind: {
11711       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
11712       EvalResult RHS;
11713       RHS.swap(Result);
11714       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
11715       Queue.pop_back();
11716       return;
11717     }
11718   }
11719 
11720   llvm_unreachable("Invalid Job::Kind!");
11721 }
11722 
11723 namespace {
11724 /// Used when we determine that we should fail, but can keep evaluating prior to
11725 /// noting that we had a failure.
11726 class DelayedNoteFailureRAII {
11727   EvalInfo &Info;
11728   bool NoteFailure;
11729 
11730 public:
11731   DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
11732       : Info(Info), NoteFailure(NoteFailure) {}
11733   ~DelayedNoteFailureRAII() {
11734     if (NoteFailure) {
11735       bool ContinueAfterFailure = Info.noteFailure();
11736       (void)ContinueAfterFailure;
11737       assert(ContinueAfterFailure &&
11738              "Shouldn't have kept evaluating on failure.");
11739     }
11740   }
11741 };
11742 
11743 enum class CmpResult {
11744   Unequal,
11745   Less,
11746   Equal,
11747   Greater,
11748   Unordered,
11749 };
11750 }
11751 
11752 template <class SuccessCB, class AfterCB>
11753 static bool
11754 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
11755                                  SuccessCB &&Success, AfterCB &&DoAfter) {
11756   assert(E->isComparisonOp() && "expected comparison operator");
11757   assert((E->getOpcode() == BO_Cmp ||
11758           E->getType()->isIntegralOrEnumerationType()) &&
11759          "unsupported binary expression evaluation");
11760   auto Error = [&](const Expr *E) {
11761     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11762     return false;
11763   };
11764 
11765   bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
11766   bool IsEquality = E->isEqualityOp();
11767 
11768   QualType LHSTy = E->getLHS()->getType();
11769   QualType RHSTy = E->getRHS()->getType();
11770 
11771   if (LHSTy->isIntegralOrEnumerationType() &&
11772       RHSTy->isIntegralOrEnumerationType()) {
11773     APSInt LHS, RHS;
11774     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
11775     if (!LHSOK && !Info.noteFailure())
11776       return false;
11777     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
11778       return false;
11779     if (LHS < RHS)
11780       return Success(CmpResult::Less, E);
11781     if (LHS > RHS)
11782       return Success(CmpResult::Greater, E);
11783     return Success(CmpResult::Equal, E);
11784   }
11785 
11786   if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
11787     APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
11788     APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
11789 
11790     bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
11791     if (!LHSOK && !Info.noteFailure())
11792       return false;
11793     if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
11794       return false;
11795     if (LHSFX < RHSFX)
11796       return Success(CmpResult::Less, E);
11797     if (LHSFX > RHSFX)
11798       return Success(CmpResult::Greater, E);
11799     return Success(CmpResult::Equal, E);
11800   }
11801 
11802   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
11803     ComplexValue LHS, RHS;
11804     bool LHSOK;
11805     if (E->isAssignmentOp()) {
11806       LValue LV;
11807       EvaluateLValue(E->getLHS(), LV, Info);
11808       LHSOK = false;
11809     } else if (LHSTy->isRealFloatingType()) {
11810       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
11811       if (LHSOK) {
11812         LHS.makeComplexFloat();
11813         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
11814       }
11815     } else {
11816       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
11817     }
11818     if (!LHSOK && !Info.noteFailure())
11819       return false;
11820 
11821     if (E->getRHS()->getType()->isRealFloatingType()) {
11822       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
11823         return false;
11824       RHS.makeComplexFloat();
11825       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
11826     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
11827       return false;
11828 
11829     if (LHS.isComplexFloat()) {
11830       APFloat::cmpResult CR_r =
11831         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
11832       APFloat::cmpResult CR_i =
11833         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
11834       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
11835       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
11836     } else {
11837       assert(IsEquality && "invalid complex comparison");
11838       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
11839                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
11840       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
11841     }
11842   }
11843 
11844   if (LHSTy->isRealFloatingType() &&
11845       RHSTy->isRealFloatingType()) {
11846     APFloat RHS(0.0), LHS(0.0);
11847 
11848     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
11849     if (!LHSOK && !Info.noteFailure())
11850       return false;
11851 
11852     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
11853       return false;
11854 
11855     assert(E->isComparisonOp() && "Invalid binary operator!");
11856     auto GetCmpRes = [&]() {
11857       switch (LHS.compare(RHS)) {
11858       case APFloat::cmpEqual:
11859         return CmpResult::Equal;
11860       case APFloat::cmpLessThan:
11861         return CmpResult::Less;
11862       case APFloat::cmpGreaterThan:
11863         return CmpResult::Greater;
11864       case APFloat::cmpUnordered:
11865         return CmpResult::Unordered;
11866       }
11867       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
11868     };
11869     return Success(GetCmpRes(), E);
11870   }
11871 
11872   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
11873     LValue LHSValue, RHSValue;
11874 
11875     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
11876     if (!LHSOK && !Info.noteFailure())
11877       return false;
11878 
11879     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
11880       return false;
11881 
11882     // Reject differing bases from the normal codepath; we special-case
11883     // comparisons to null.
11884     if (!HasSameBase(LHSValue, RHSValue)) {
11885       // Inequalities and subtractions between unrelated pointers have
11886       // unspecified or undefined behavior.
11887       if (!IsEquality) {
11888         Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified);
11889         return false;
11890       }
11891       // A constant address may compare equal to the address of a symbol.
11892       // The one exception is that address of an object cannot compare equal
11893       // to a null pointer constant.
11894       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
11895           (!RHSValue.Base && !RHSValue.Offset.isZero()))
11896         return Error(E);
11897       // It's implementation-defined whether distinct literals will have
11898       // distinct addresses. In clang, the result of such a comparison is
11899       // unspecified, so it is not a constant expression. However, we do know
11900       // that the address of a literal will be non-null.
11901       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
11902           LHSValue.Base && RHSValue.Base)
11903         return Error(E);
11904       // We can't tell whether weak symbols will end up pointing to the same
11905       // object.
11906       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
11907         return Error(E);
11908       // We can't compare the address of the start of one object with the
11909       // past-the-end address of another object, per C++ DR1652.
11910       if ((LHSValue.Base && LHSValue.Offset.isZero() &&
11911            isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
11912           (RHSValue.Base && RHSValue.Offset.isZero() &&
11913            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
11914         return Error(E);
11915       // We can't tell whether an object is at the same address as another
11916       // zero sized object.
11917       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
11918           (LHSValue.Base && isZeroSized(RHSValue)))
11919         return Error(E);
11920       return Success(CmpResult::Unequal, E);
11921     }
11922 
11923     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
11924     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
11925 
11926     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
11927     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
11928 
11929     // C++11 [expr.rel]p3:
11930     //   Pointers to void (after pointer conversions) can be compared, with a
11931     //   result defined as follows: If both pointers represent the same
11932     //   address or are both the null pointer value, the result is true if the
11933     //   operator is <= or >= and false otherwise; otherwise the result is
11934     //   unspecified.
11935     // We interpret this as applying to pointers to *cv* void.
11936     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
11937       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
11938 
11939     // C++11 [expr.rel]p2:
11940     // - If two pointers point to non-static data members of the same object,
11941     //   or to subobjects or array elements fo such members, recursively, the
11942     //   pointer to the later declared member compares greater provided the
11943     //   two members have the same access control and provided their class is
11944     //   not a union.
11945     //   [...]
11946     // - Otherwise pointer comparisons are unspecified.
11947     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
11948       bool WasArrayIndex;
11949       unsigned Mismatch = FindDesignatorMismatch(
11950           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
11951       // At the point where the designators diverge, the comparison has a
11952       // specified value if:
11953       //  - we are comparing array indices
11954       //  - we are comparing fields of a union, or fields with the same access
11955       // Otherwise, the result is unspecified and thus the comparison is not a
11956       // constant expression.
11957       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
11958           Mismatch < RHSDesignator.Entries.size()) {
11959         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
11960         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
11961         if (!LF && !RF)
11962           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
11963         else if (!LF)
11964           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
11965               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
11966               << RF->getParent() << RF;
11967         else if (!RF)
11968           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
11969               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
11970               << LF->getParent() << LF;
11971         else if (!LF->getParent()->isUnion() &&
11972                  LF->getAccess() != RF->getAccess())
11973           Info.CCEDiag(E,
11974                        diag::note_constexpr_pointer_comparison_differing_access)
11975               << LF << LF->getAccess() << RF << RF->getAccess()
11976               << LF->getParent();
11977       }
11978     }
11979 
11980     // The comparison here must be unsigned, and performed with the same
11981     // width as the pointer.
11982     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
11983     uint64_t CompareLHS = LHSOffset.getQuantity();
11984     uint64_t CompareRHS = RHSOffset.getQuantity();
11985     assert(PtrSize <= 64 && "Unexpected pointer width");
11986     uint64_t Mask = ~0ULL >> (64 - PtrSize);
11987     CompareLHS &= Mask;
11988     CompareRHS &= Mask;
11989 
11990     // If there is a base and this is a relational operator, we can only
11991     // compare pointers within the object in question; otherwise, the result
11992     // depends on where the object is located in memory.
11993     if (!LHSValue.Base.isNull() && IsRelational) {
11994       QualType BaseTy = getType(LHSValue.Base);
11995       if (BaseTy->isIncompleteType())
11996         return Error(E);
11997       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
11998       uint64_t OffsetLimit = Size.getQuantity();
11999       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
12000         return Error(E);
12001     }
12002 
12003     if (CompareLHS < CompareRHS)
12004       return Success(CmpResult::Less, E);
12005     if (CompareLHS > CompareRHS)
12006       return Success(CmpResult::Greater, E);
12007     return Success(CmpResult::Equal, E);
12008   }
12009 
12010   if (LHSTy->isMemberPointerType()) {
12011     assert(IsEquality && "unexpected member pointer operation");
12012     assert(RHSTy->isMemberPointerType() && "invalid comparison");
12013 
12014     MemberPtr LHSValue, RHSValue;
12015 
12016     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
12017     if (!LHSOK && !Info.noteFailure())
12018       return false;
12019 
12020     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12021       return false;
12022 
12023     // C++11 [expr.eq]p2:
12024     //   If both operands are null, they compare equal. Otherwise if only one is
12025     //   null, they compare unequal.
12026     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
12027       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
12028       return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12029     }
12030 
12031     //   Otherwise if either is a pointer to a virtual member function, the
12032     //   result is unspecified.
12033     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
12034       if (MD->isVirtual())
12035         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12036     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
12037       if (MD->isVirtual())
12038         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12039 
12040     //   Otherwise they compare equal if and only if they would refer to the
12041     //   same member of the same most derived object or the same subobject if
12042     //   they were dereferenced with a hypothetical object of the associated
12043     //   class type.
12044     bool Equal = LHSValue == RHSValue;
12045     return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12046   }
12047 
12048   if (LHSTy->isNullPtrType()) {
12049     assert(E->isComparisonOp() && "unexpected nullptr operation");
12050     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
12051     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
12052     // are compared, the result is true of the operator is <=, >= or ==, and
12053     // false otherwise.
12054     return Success(CmpResult::Equal, E);
12055   }
12056 
12057   return DoAfter();
12058 }
12059 
12060 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
12061   if (!CheckLiteralType(Info, E))
12062     return false;
12063 
12064   auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12065     ComparisonCategoryResult CCR;
12066     switch (CR) {
12067     case CmpResult::Unequal:
12068       llvm_unreachable("should never produce Unequal for three-way comparison");
12069     case CmpResult::Less:
12070       CCR = ComparisonCategoryResult::Less;
12071       break;
12072     case CmpResult::Equal:
12073       CCR = ComparisonCategoryResult::Equal;
12074       break;
12075     case CmpResult::Greater:
12076       CCR = ComparisonCategoryResult::Greater;
12077       break;
12078     case CmpResult::Unordered:
12079       CCR = ComparisonCategoryResult::Unordered;
12080       break;
12081     }
12082     // Evaluation succeeded. Lookup the information for the comparison category
12083     // type and fetch the VarDecl for the result.
12084     const ComparisonCategoryInfo &CmpInfo =
12085         Info.Ctx.CompCategories.getInfoForType(E->getType());
12086     const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
12087     // Check and evaluate the result as a constant expression.
12088     LValue LV;
12089     LV.set(VD);
12090     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
12091       return false;
12092     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
12093   };
12094   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12095     return ExprEvaluatorBaseTy::VisitBinCmp(E);
12096   });
12097 }
12098 
12099 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12100   // We don't call noteFailure immediately because the assignment happens after
12101   // we evaluate LHS and RHS.
12102   if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
12103     return Error(E);
12104 
12105   DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
12106   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
12107     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
12108 
12109   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
12110           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
12111          "DataRecursiveIntBinOpEvaluator should have handled integral types");
12112 
12113   if (E->isComparisonOp()) {
12114     // Evaluate builtin binary comparisons by evaluating them as three-way
12115     // comparisons and then translating the result.
12116     auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12117       assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
12118              "should only produce Unequal for equality comparisons");
12119       bool IsEqual   = CR == CmpResult::Equal,
12120            IsLess    = CR == CmpResult::Less,
12121            IsGreater = CR == CmpResult::Greater;
12122       auto Op = E->getOpcode();
12123       switch (Op) {
12124       default:
12125         llvm_unreachable("unsupported binary operator");
12126       case BO_EQ:
12127       case BO_NE:
12128         return Success(IsEqual == (Op == BO_EQ), E);
12129       case BO_LT:
12130         return Success(IsLess, E);
12131       case BO_GT:
12132         return Success(IsGreater, E);
12133       case BO_LE:
12134         return Success(IsEqual || IsLess, E);
12135       case BO_GE:
12136         return Success(IsEqual || IsGreater, E);
12137       }
12138     };
12139     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12140       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12141     });
12142   }
12143 
12144   QualType LHSTy = E->getLHS()->getType();
12145   QualType RHSTy = E->getRHS()->getType();
12146 
12147   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
12148       E->getOpcode() == BO_Sub) {
12149     LValue LHSValue, RHSValue;
12150 
12151     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12152     if (!LHSOK && !Info.noteFailure())
12153       return false;
12154 
12155     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12156       return false;
12157 
12158     // Reject differing bases from the normal codepath; we special-case
12159     // comparisons to null.
12160     if (!HasSameBase(LHSValue, RHSValue)) {
12161       // Handle &&A - &&B.
12162       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
12163         return Error(E);
12164       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
12165       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
12166       if (!LHSExpr || !RHSExpr)
12167         return Error(E);
12168       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12169       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12170       if (!LHSAddrExpr || !RHSAddrExpr)
12171         return Error(E);
12172       // Make sure both labels come from the same function.
12173       if (LHSAddrExpr->getLabel()->getDeclContext() !=
12174           RHSAddrExpr->getLabel()->getDeclContext())
12175         return Error(E);
12176       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
12177     }
12178     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12179     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12180 
12181     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12182     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12183 
12184     // C++11 [expr.add]p6:
12185     //   Unless both pointers point to elements of the same array object, or
12186     //   one past the last element of the array object, the behavior is
12187     //   undefined.
12188     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
12189         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
12190                                 RHSDesignator))
12191       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
12192 
12193     QualType Type = E->getLHS()->getType();
12194     QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
12195 
12196     CharUnits ElementSize;
12197     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
12198       return false;
12199 
12200     // As an extension, a type may have zero size (empty struct or union in
12201     // C, array of zero length). Pointer subtraction in such cases has
12202     // undefined behavior, so is not constant.
12203     if (ElementSize.isZero()) {
12204       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
12205           << ElementType;
12206       return false;
12207     }
12208 
12209     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
12210     // and produce incorrect results when it overflows. Such behavior
12211     // appears to be non-conforming, but is common, so perhaps we should
12212     // assume the standard intended for such cases to be undefined behavior
12213     // and check for them.
12214 
12215     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
12216     // overflow in the final conversion to ptrdiff_t.
12217     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
12218     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
12219     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
12220                     false);
12221     APSInt TrueResult = (LHS - RHS) / ElemSize;
12222     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
12223 
12224     if (Result.extend(65) != TrueResult &&
12225         !HandleOverflow(Info, E, TrueResult, E->getType()))
12226       return false;
12227     return Success(Result, E);
12228   }
12229 
12230   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12231 }
12232 
12233 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
12234 /// a result as the expression's type.
12235 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
12236                                     const UnaryExprOrTypeTraitExpr *E) {
12237   switch(E->getKind()) {
12238   case UETT_PreferredAlignOf:
12239   case UETT_AlignOf: {
12240     if (E->isArgumentType())
12241       return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
12242                      E);
12243     else
12244       return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
12245                      E);
12246   }
12247 
12248   case UETT_VecStep: {
12249     QualType Ty = E->getTypeOfArgument();
12250 
12251     if (Ty->isVectorType()) {
12252       unsigned n = Ty->castAs<VectorType>()->getNumElements();
12253 
12254       // The vec_step built-in functions that take a 3-component
12255       // vector return 4. (OpenCL 1.1 spec 6.11.12)
12256       if (n == 3)
12257         n = 4;
12258 
12259       return Success(n, E);
12260     } else
12261       return Success(1, E);
12262   }
12263 
12264   case UETT_SizeOf: {
12265     QualType SrcTy = E->getTypeOfArgument();
12266     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
12267     //   the result is the size of the referenced type."
12268     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
12269       SrcTy = Ref->getPointeeType();
12270 
12271     CharUnits Sizeof;
12272     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
12273       return false;
12274     return Success(Sizeof, E);
12275   }
12276   case UETT_OpenMPRequiredSimdAlign:
12277     assert(E->isArgumentType());
12278     return Success(
12279         Info.Ctx.toCharUnitsFromBits(
12280                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
12281             .getQuantity(),
12282         E);
12283   }
12284 
12285   llvm_unreachable("unknown expr/type trait");
12286 }
12287 
12288 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
12289   CharUnits Result;
12290   unsigned n = OOE->getNumComponents();
12291   if (n == 0)
12292     return Error(OOE);
12293   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
12294   for (unsigned i = 0; i != n; ++i) {
12295     OffsetOfNode ON = OOE->getComponent(i);
12296     switch (ON.getKind()) {
12297     case OffsetOfNode::Array: {
12298       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
12299       APSInt IdxResult;
12300       if (!EvaluateInteger(Idx, IdxResult, Info))
12301         return false;
12302       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
12303       if (!AT)
12304         return Error(OOE);
12305       CurrentType = AT->getElementType();
12306       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
12307       Result += IdxResult.getSExtValue() * ElementSize;
12308       break;
12309     }
12310 
12311     case OffsetOfNode::Field: {
12312       FieldDecl *MemberDecl = ON.getField();
12313       const RecordType *RT = CurrentType->getAs<RecordType>();
12314       if (!RT)
12315         return Error(OOE);
12316       RecordDecl *RD = RT->getDecl();
12317       if (RD->isInvalidDecl()) return false;
12318       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
12319       unsigned i = MemberDecl->getFieldIndex();
12320       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
12321       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
12322       CurrentType = MemberDecl->getType().getNonReferenceType();
12323       break;
12324     }
12325 
12326     case OffsetOfNode::Identifier:
12327       llvm_unreachable("dependent __builtin_offsetof");
12328 
12329     case OffsetOfNode::Base: {
12330       CXXBaseSpecifier *BaseSpec = ON.getBase();
12331       if (BaseSpec->isVirtual())
12332         return Error(OOE);
12333 
12334       // Find the layout of the class whose base we are looking into.
12335       const RecordType *RT = CurrentType->getAs<RecordType>();
12336       if (!RT)
12337         return Error(OOE);
12338       RecordDecl *RD = RT->getDecl();
12339       if (RD->isInvalidDecl()) return false;
12340       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
12341 
12342       // Find the base class itself.
12343       CurrentType = BaseSpec->getType();
12344       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
12345       if (!BaseRT)
12346         return Error(OOE);
12347 
12348       // Add the offset to the base.
12349       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
12350       break;
12351     }
12352     }
12353   }
12354   return Success(Result, OOE);
12355 }
12356 
12357 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12358   switch (E->getOpcode()) {
12359   default:
12360     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
12361     // See C99 6.6p3.
12362     return Error(E);
12363   case UO_Extension:
12364     // FIXME: Should extension allow i-c-e extension expressions in its scope?
12365     // If so, we could clear the diagnostic ID.
12366     return Visit(E->getSubExpr());
12367   case UO_Plus:
12368     // The result is just the value.
12369     return Visit(E->getSubExpr());
12370   case UO_Minus: {
12371     if (!Visit(E->getSubExpr()))
12372       return false;
12373     if (!Result.isInt()) return Error(E);
12374     const APSInt &Value = Result.getInt();
12375     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
12376         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
12377                         E->getType()))
12378       return false;
12379     return Success(-Value, E);
12380   }
12381   case UO_Not: {
12382     if (!Visit(E->getSubExpr()))
12383       return false;
12384     if (!Result.isInt()) return Error(E);
12385     return Success(~Result.getInt(), E);
12386   }
12387   case UO_LNot: {
12388     bool bres;
12389     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
12390       return false;
12391     return Success(!bres, E);
12392   }
12393   }
12394 }
12395 
12396 /// HandleCast - This is used to evaluate implicit or explicit casts where the
12397 /// result type is integer.
12398 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
12399   const Expr *SubExpr = E->getSubExpr();
12400   QualType DestType = E->getType();
12401   QualType SrcType = SubExpr->getType();
12402 
12403   switch (E->getCastKind()) {
12404   case CK_BaseToDerived:
12405   case CK_DerivedToBase:
12406   case CK_UncheckedDerivedToBase:
12407   case CK_Dynamic:
12408   case CK_ToUnion:
12409   case CK_ArrayToPointerDecay:
12410   case CK_FunctionToPointerDecay:
12411   case CK_NullToPointer:
12412   case CK_NullToMemberPointer:
12413   case CK_BaseToDerivedMemberPointer:
12414   case CK_DerivedToBaseMemberPointer:
12415   case CK_ReinterpretMemberPointer:
12416   case CK_ConstructorConversion:
12417   case CK_IntegralToPointer:
12418   case CK_ToVoid:
12419   case CK_VectorSplat:
12420   case CK_IntegralToFloating:
12421   case CK_FloatingCast:
12422   case CK_CPointerToObjCPointerCast:
12423   case CK_BlockPointerToObjCPointerCast:
12424   case CK_AnyPointerToBlockPointerCast:
12425   case CK_ObjCObjectLValueCast:
12426   case CK_FloatingRealToComplex:
12427   case CK_FloatingComplexToReal:
12428   case CK_FloatingComplexCast:
12429   case CK_FloatingComplexToIntegralComplex:
12430   case CK_IntegralRealToComplex:
12431   case CK_IntegralComplexCast:
12432   case CK_IntegralComplexToFloatingComplex:
12433   case CK_BuiltinFnToFnPtr:
12434   case CK_ZeroToOCLOpaqueType:
12435   case CK_NonAtomicToAtomic:
12436   case CK_AddressSpaceConversion:
12437   case CK_IntToOCLSampler:
12438   case CK_FixedPointCast:
12439   case CK_IntegralToFixedPoint:
12440     llvm_unreachable("invalid cast kind for integral value");
12441 
12442   case CK_BitCast:
12443   case CK_Dependent:
12444   case CK_LValueBitCast:
12445   case CK_ARCProduceObject:
12446   case CK_ARCConsumeObject:
12447   case CK_ARCReclaimReturnedObject:
12448   case CK_ARCExtendBlockObject:
12449   case CK_CopyAndAutoreleaseBlockObject:
12450     return Error(E);
12451 
12452   case CK_UserDefinedConversion:
12453   case CK_LValueToRValue:
12454   case CK_AtomicToNonAtomic:
12455   case CK_NoOp:
12456   case CK_LValueToRValueBitCast:
12457     return ExprEvaluatorBaseTy::VisitCastExpr(E);
12458 
12459   case CK_MemberPointerToBoolean:
12460   case CK_PointerToBoolean:
12461   case CK_IntegralToBoolean:
12462   case CK_FloatingToBoolean:
12463   case CK_BooleanToSignedIntegral:
12464   case CK_FloatingComplexToBoolean:
12465   case CK_IntegralComplexToBoolean: {
12466     bool BoolResult;
12467     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
12468       return false;
12469     uint64_t IntResult = BoolResult;
12470     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
12471       IntResult = (uint64_t)-1;
12472     return Success(IntResult, E);
12473   }
12474 
12475   case CK_FixedPointToIntegral: {
12476     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
12477     if (!EvaluateFixedPoint(SubExpr, Src, Info))
12478       return false;
12479     bool Overflowed;
12480     llvm::APSInt Result = Src.convertToInt(
12481         Info.Ctx.getIntWidth(DestType),
12482         DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
12483     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
12484       return false;
12485     return Success(Result, E);
12486   }
12487 
12488   case CK_FixedPointToBoolean: {
12489     // Unsigned padding does not affect this.
12490     APValue Val;
12491     if (!Evaluate(Val, Info, SubExpr))
12492       return false;
12493     return Success(Val.getFixedPoint().getBoolValue(), E);
12494   }
12495 
12496   case CK_IntegralCast: {
12497     if (!Visit(SubExpr))
12498       return false;
12499 
12500     if (!Result.isInt()) {
12501       // Allow casts of address-of-label differences if they are no-ops
12502       // or narrowing.  (The narrowing case isn't actually guaranteed to
12503       // be constant-evaluatable except in some narrow cases which are hard
12504       // to detect here.  We let it through on the assumption the user knows
12505       // what they are doing.)
12506       if (Result.isAddrLabelDiff())
12507         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
12508       // Only allow casts of lvalues if they are lossless.
12509       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
12510     }
12511 
12512     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
12513                                       Result.getInt()), E);
12514   }
12515 
12516   case CK_PointerToIntegral: {
12517     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
12518 
12519     LValue LV;
12520     if (!EvaluatePointer(SubExpr, LV, Info))
12521       return false;
12522 
12523     if (LV.getLValueBase()) {
12524       // Only allow based lvalue casts if they are lossless.
12525       // FIXME: Allow a larger integer size than the pointer size, and allow
12526       // narrowing back down to pointer width in subsequent integral casts.
12527       // FIXME: Check integer type's active bits, not its type size.
12528       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
12529         return Error(E);
12530 
12531       LV.Designator.setInvalid();
12532       LV.moveInto(Result);
12533       return true;
12534     }
12535 
12536     APSInt AsInt;
12537     APValue V;
12538     LV.moveInto(V);
12539     if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
12540       llvm_unreachable("Can't cast this!");
12541 
12542     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
12543   }
12544 
12545   case CK_IntegralComplexToReal: {
12546     ComplexValue C;
12547     if (!EvaluateComplex(SubExpr, C, Info))
12548       return false;
12549     return Success(C.getComplexIntReal(), E);
12550   }
12551 
12552   case CK_FloatingToIntegral: {
12553     APFloat F(0.0);
12554     if (!EvaluateFloat(SubExpr, F, Info))
12555       return false;
12556 
12557     APSInt Value;
12558     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
12559       return false;
12560     return Success(Value, E);
12561   }
12562   }
12563 
12564   llvm_unreachable("unknown cast resulting in integral value");
12565 }
12566 
12567 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
12568   if (E->getSubExpr()->getType()->isAnyComplexType()) {
12569     ComplexValue LV;
12570     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
12571       return false;
12572     if (!LV.isComplexInt())
12573       return Error(E);
12574     return Success(LV.getComplexIntReal(), E);
12575   }
12576 
12577   return Visit(E->getSubExpr());
12578 }
12579 
12580 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
12581   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
12582     ComplexValue LV;
12583     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
12584       return false;
12585     if (!LV.isComplexInt())
12586       return Error(E);
12587     return Success(LV.getComplexIntImag(), E);
12588   }
12589 
12590   VisitIgnoredValue(E->getSubExpr());
12591   return Success(0, E);
12592 }
12593 
12594 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
12595   return Success(E->getPackLength(), E);
12596 }
12597 
12598 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
12599   return Success(E->getValue(), E);
12600 }
12601 
12602 bool IntExprEvaluator::VisitConceptSpecializationExpr(
12603        const ConceptSpecializationExpr *E) {
12604   return Success(E->isSatisfied(), E);
12605 }
12606 
12607 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
12608   return Success(E->isSatisfied(), E);
12609 }
12610 
12611 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12612   switch (E->getOpcode()) {
12613     default:
12614       // Invalid unary operators
12615       return Error(E);
12616     case UO_Plus:
12617       // The result is just the value.
12618       return Visit(E->getSubExpr());
12619     case UO_Minus: {
12620       if (!Visit(E->getSubExpr())) return false;
12621       if (!Result.isFixedPoint())
12622         return Error(E);
12623       bool Overflowed;
12624       APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
12625       if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
12626         return false;
12627       return Success(Negated, E);
12628     }
12629     case UO_LNot: {
12630       bool bres;
12631       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
12632         return false;
12633       return Success(!bres, E);
12634     }
12635   }
12636 }
12637 
12638 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
12639   const Expr *SubExpr = E->getSubExpr();
12640   QualType DestType = E->getType();
12641   assert(DestType->isFixedPointType() &&
12642          "Expected destination type to be a fixed point type");
12643   auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
12644 
12645   switch (E->getCastKind()) {
12646   case CK_FixedPointCast: {
12647     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
12648     if (!EvaluateFixedPoint(SubExpr, Src, Info))
12649       return false;
12650     bool Overflowed;
12651     APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
12652     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
12653       return false;
12654     return Success(Result, E);
12655   }
12656   case CK_IntegralToFixedPoint: {
12657     APSInt Src;
12658     if (!EvaluateInteger(SubExpr, Src, Info))
12659       return false;
12660 
12661     bool Overflowed;
12662     APFixedPoint IntResult = APFixedPoint::getFromIntValue(
12663         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
12664 
12665     if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType))
12666       return false;
12667 
12668     return Success(IntResult, E);
12669   }
12670   case CK_NoOp:
12671   case CK_LValueToRValue:
12672     return ExprEvaluatorBaseTy::VisitCastExpr(E);
12673   default:
12674     return Error(E);
12675   }
12676 }
12677 
12678 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12679   const Expr *LHS = E->getLHS();
12680   const Expr *RHS = E->getRHS();
12681   FixedPointSemantics ResultFXSema =
12682       Info.Ctx.getFixedPointSemantics(E->getType());
12683 
12684   APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
12685   if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
12686     return false;
12687   APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
12688   if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
12689     return false;
12690 
12691   switch (E->getOpcode()) {
12692   case BO_Add: {
12693     bool AddOverflow, ConversionOverflow;
12694     APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow)
12695                               .convert(ResultFXSema, &ConversionOverflow);
12696     if ((AddOverflow || ConversionOverflow) &&
12697         !HandleOverflow(Info, E, Result, E->getType()))
12698       return false;
12699     return Success(Result, E);
12700   }
12701   default:
12702     return false;
12703   }
12704   llvm_unreachable("Should've exited before this");
12705 }
12706 
12707 //===----------------------------------------------------------------------===//
12708 // Float Evaluation
12709 //===----------------------------------------------------------------------===//
12710 
12711 namespace {
12712 class FloatExprEvaluator
12713   : public ExprEvaluatorBase<FloatExprEvaluator> {
12714   APFloat &Result;
12715 public:
12716   FloatExprEvaluator(EvalInfo &info, APFloat &result)
12717     : ExprEvaluatorBaseTy(info), Result(result) {}
12718 
12719   bool Success(const APValue &V, const Expr *e) {
12720     Result = V.getFloat();
12721     return true;
12722   }
12723 
12724   bool ZeroInitialization(const Expr *E) {
12725     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
12726     return true;
12727   }
12728 
12729   bool VisitCallExpr(const CallExpr *E);
12730 
12731   bool VisitUnaryOperator(const UnaryOperator *E);
12732   bool VisitBinaryOperator(const BinaryOperator *E);
12733   bool VisitFloatingLiteral(const FloatingLiteral *E);
12734   bool VisitCastExpr(const CastExpr *E);
12735 
12736   bool VisitUnaryReal(const UnaryOperator *E);
12737   bool VisitUnaryImag(const UnaryOperator *E);
12738 
12739   // FIXME: Missing: array subscript of vector, member of vector
12740 };
12741 } // end anonymous namespace
12742 
12743 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
12744   assert(E->isRValue() && E->getType()->isRealFloatingType());
12745   return FloatExprEvaluator(Info, Result).Visit(E);
12746 }
12747 
12748 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
12749                                   QualType ResultTy,
12750                                   const Expr *Arg,
12751                                   bool SNaN,
12752                                   llvm::APFloat &Result) {
12753   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
12754   if (!S) return false;
12755 
12756   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
12757 
12758   llvm::APInt fill;
12759 
12760   // Treat empty strings as if they were zero.
12761   if (S->getString().empty())
12762     fill = llvm::APInt(32, 0);
12763   else if (S->getString().getAsInteger(0, fill))
12764     return false;
12765 
12766   if (Context.getTargetInfo().isNan2008()) {
12767     if (SNaN)
12768       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
12769     else
12770       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
12771   } else {
12772     // Prior to IEEE 754-2008, architectures were allowed to choose whether
12773     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
12774     // a different encoding to what became a standard in 2008, and for pre-
12775     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
12776     // sNaN. This is now known as "legacy NaN" encoding.
12777     if (SNaN)
12778       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
12779     else
12780       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
12781   }
12782 
12783   return true;
12784 }
12785 
12786 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
12787   switch (E->getBuiltinCallee()) {
12788   default:
12789     return ExprEvaluatorBaseTy::VisitCallExpr(E);
12790 
12791   case Builtin::BI__builtin_huge_val:
12792   case Builtin::BI__builtin_huge_valf:
12793   case Builtin::BI__builtin_huge_vall:
12794   case Builtin::BI__builtin_huge_valf128:
12795   case Builtin::BI__builtin_inf:
12796   case Builtin::BI__builtin_inff:
12797   case Builtin::BI__builtin_infl:
12798   case Builtin::BI__builtin_inff128: {
12799     const llvm::fltSemantics &Sem =
12800       Info.Ctx.getFloatTypeSemantics(E->getType());
12801     Result = llvm::APFloat::getInf(Sem);
12802     return true;
12803   }
12804 
12805   case Builtin::BI__builtin_nans:
12806   case Builtin::BI__builtin_nansf:
12807   case Builtin::BI__builtin_nansl:
12808   case Builtin::BI__builtin_nansf128:
12809     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
12810                                true, Result))
12811       return Error(E);
12812     return true;
12813 
12814   case Builtin::BI__builtin_nan:
12815   case Builtin::BI__builtin_nanf:
12816   case Builtin::BI__builtin_nanl:
12817   case Builtin::BI__builtin_nanf128:
12818     // If this is __builtin_nan() turn this into a nan, otherwise we
12819     // can't constant fold it.
12820     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
12821                                false, Result))
12822       return Error(E);
12823     return true;
12824 
12825   case Builtin::BI__builtin_fabs:
12826   case Builtin::BI__builtin_fabsf:
12827   case Builtin::BI__builtin_fabsl:
12828   case Builtin::BI__builtin_fabsf128:
12829     if (!EvaluateFloat(E->getArg(0), Result, Info))
12830       return false;
12831 
12832     if (Result.isNegative())
12833       Result.changeSign();
12834     return true;
12835 
12836   // FIXME: Builtin::BI__builtin_powi
12837   // FIXME: Builtin::BI__builtin_powif
12838   // FIXME: Builtin::BI__builtin_powil
12839 
12840   case Builtin::BI__builtin_copysign:
12841   case Builtin::BI__builtin_copysignf:
12842   case Builtin::BI__builtin_copysignl:
12843   case Builtin::BI__builtin_copysignf128: {
12844     APFloat RHS(0.);
12845     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
12846         !EvaluateFloat(E->getArg(1), RHS, Info))
12847       return false;
12848     Result.copySign(RHS);
12849     return true;
12850   }
12851   }
12852 }
12853 
12854 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
12855   if (E->getSubExpr()->getType()->isAnyComplexType()) {
12856     ComplexValue CV;
12857     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
12858       return false;
12859     Result = CV.FloatReal;
12860     return true;
12861   }
12862 
12863   return Visit(E->getSubExpr());
12864 }
12865 
12866 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
12867   if (E->getSubExpr()->getType()->isAnyComplexType()) {
12868     ComplexValue CV;
12869     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
12870       return false;
12871     Result = CV.FloatImag;
12872     return true;
12873   }
12874 
12875   VisitIgnoredValue(E->getSubExpr());
12876   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
12877   Result = llvm::APFloat::getZero(Sem);
12878   return true;
12879 }
12880 
12881 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12882   switch (E->getOpcode()) {
12883   default: return Error(E);
12884   case UO_Plus:
12885     return EvaluateFloat(E->getSubExpr(), Result, Info);
12886   case UO_Minus:
12887     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
12888       return false;
12889     Result.changeSign();
12890     return true;
12891   }
12892 }
12893 
12894 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12895   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
12896     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12897 
12898   APFloat RHS(0.0);
12899   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
12900   if (!LHSOK && !Info.noteFailure())
12901     return false;
12902   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
12903          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
12904 }
12905 
12906 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
12907   Result = E->getValue();
12908   return true;
12909 }
12910 
12911 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
12912   const Expr* SubExpr = E->getSubExpr();
12913 
12914   switch (E->getCastKind()) {
12915   default:
12916     return ExprEvaluatorBaseTy::VisitCastExpr(E);
12917 
12918   case CK_IntegralToFloating: {
12919     APSInt IntResult;
12920     return EvaluateInteger(SubExpr, IntResult, Info) &&
12921            HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
12922                                 E->getType(), Result);
12923   }
12924 
12925   case CK_FloatingCast: {
12926     if (!Visit(SubExpr))
12927       return false;
12928     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
12929                                   Result);
12930   }
12931 
12932   case CK_FloatingComplexToReal: {
12933     ComplexValue V;
12934     if (!EvaluateComplex(SubExpr, V, Info))
12935       return false;
12936     Result = V.getComplexFloatReal();
12937     return true;
12938   }
12939   }
12940 }
12941 
12942 //===----------------------------------------------------------------------===//
12943 // Complex Evaluation (for float and integer)
12944 //===----------------------------------------------------------------------===//
12945 
12946 namespace {
12947 class ComplexExprEvaluator
12948   : public ExprEvaluatorBase<ComplexExprEvaluator> {
12949   ComplexValue &Result;
12950 
12951 public:
12952   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
12953     : ExprEvaluatorBaseTy(info), Result(Result) {}
12954 
12955   bool Success(const APValue &V, const Expr *e) {
12956     Result.setFrom(V);
12957     return true;
12958   }
12959 
12960   bool ZeroInitialization(const Expr *E);
12961 
12962   //===--------------------------------------------------------------------===//
12963   //                            Visitor Methods
12964   //===--------------------------------------------------------------------===//
12965 
12966   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
12967   bool VisitCastExpr(const CastExpr *E);
12968   bool VisitBinaryOperator(const BinaryOperator *E);
12969   bool VisitUnaryOperator(const UnaryOperator *E);
12970   bool VisitInitListExpr(const InitListExpr *E);
12971 };
12972 } // end anonymous namespace
12973 
12974 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
12975                             EvalInfo &Info) {
12976   assert(E->isRValue() && E->getType()->isAnyComplexType());
12977   return ComplexExprEvaluator(Info, Result).Visit(E);
12978 }
12979 
12980 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
12981   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
12982   if (ElemTy->isRealFloatingType()) {
12983     Result.makeComplexFloat();
12984     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
12985     Result.FloatReal = Zero;
12986     Result.FloatImag = Zero;
12987   } else {
12988     Result.makeComplexInt();
12989     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
12990     Result.IntReal = Zero;
12991     Result.IntImag = Zero;
12992   }
12993   return true;
12994 }
12995 
12996 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
12997   const Expr* SubExpr = E->getSubExpr();
12998 
12999   if (SubExpr->getType()->isRealFloatingType()) {
13000     Result.makeComplexFloat();
13001     APFloat &Imag = Result.FloatImag;
13002     if (!EvaluateFloat(SubExpr, Imag, Info))
13003       return false;
13004 
13005     Result.FloatReal = APFloat(Imag.getSemantics());
13006     return true;
13007   } else {
13008     assert(SubExpr->getType()->isIntegerType() &&
13009            "Unexpected imaginary literal.");
13010 
13011     Result.makeComplexInt();
13012     APSInt &Imag = Result.IntImag;
13013     if (!EvaluateInteger(SubExpr, Imag, Info))
13014       return false;
13015 
13016     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
13017     return true;
13018   }
13019 }
13020 
13021 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
13022 
13023   switch (E->getCastKind()) {
13024   case CK_BitCast:
13025   case CK_BaseToDerived:
13026   case CK_DerivedToBase:
13027   case CK_UncheckedDerivedToBase:
13028   case CK_Dynamic:
13029   case CK_ToUnion:
13030   case CK_ArrayToPointerDecay:
13031   case CK_FunctionToPointerDecay:
13032   case CK_NullToPointer:
13033   case CK_NullToMemberPointer:
13034   case CK_BaseToDerivedMemberPointer:
13035   case CK_DerivedToBaseMemberPointer:
13036   case CK_MemberPointerToBoolean:
13037   case CK_ReinterpretMemberPointer:
13038   case CK_ConstructorConversion:
13039   case CK_IntegralToPointer:
13040   case CK_PointerToIntegral:
13041   case CK_PointerToBoolean:
13042   case CK_ToVoid:
13043   case CK_VectorSplat:
13044   case CK_IntegralCast:
13045   case CK_BooleanToSignedIntegral:
13046   case CK_IntegralToBoolean:
13047   case CK_IntegralToFloating:
13048   case CK_FloatingToIntegral:
13049   case CK_FloatingToBoolean:
13050   case CK_FloatingCast:
13051   case CK_CPointerToObjCPointerCast:
13052   case CK_BlockPointerToObjCPointerCast:
13053   case CK_AnyPointerToBlockPointerCast:
13054   case CK_ObjCObjectLValueCast:
13055   case CK_FloatingComplexToReal:
13056   case CK_FloatingComplexToBoolean:
13057   case CK_IntegralComplexToReal:
13058   case CK_IntegralComplexToBoolean:
13059   case CK_ARCProduceObject:
13060   case CK_ARCConsumeObject:
13061   case CK_ARCReclaimReturnedObject:
13062   case CK_ARCExtendBlockObject:
13063   case CK_CopyAndAutoreleaseBlockObject:
13064   case CK_BuiltinFnToFnPtr:
13065   case CK_ZeroToOCLOpaqueType:
13066   case CK_NonAtomicToAtomic:
13067   case CK_AddressSpaceConversion:
13068   case CK_IntToOCLSampler:
13069   case CK_FixedPointCast:
13070   case CK_FixedPointToBoolean:
13071   case CK_FixedPointToIntegral:
13072   case CK_IntegralToFixedPoint:
13073     llvm_unreachable("invalid cast kind for complex value");
13074 
13075   case CK_LValueToRValue:
13076   case CK_AtomicToNonAtomic:
13077   case CK_NoOp:
13078   case CK_LValueToRValueBitCast:
13079     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13080 
13081   case CK_Dependent:
13082   case CK_LValueBitCast:
13083   case CK_UserDefinedConversion:
13084     return Error(E);
13085 
13086   case CK_FloatingRealToComplex: {
13087     APFloat &Real = Result.FloatReal;
13088     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
13089       return false;
13090 
13091     Result.makeComplexFloat();
13092     Result.FloatImag = APFloat(Real.getSemantics());
13093     return true;
13094   }
13095 
13096   case CK_FloatingComplexCast: {
13097     if (!Visit(E->getSubExpr()))
13098       return false;
13099 
13100     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13101     QualType From
13102       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13103 
13104     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
13105            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
13106   }
13107 
13108   case CK_FloatingComplexToIntegralComplex: {
13109     if (!Visit(E->getSubExpr()))
13110       return false;
13111 
13112     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13113     QualType From
13114       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13115     Result.makeComplexInt();
13116     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
13117                                 To, Result.IntReal) &&
13118            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
13119                                 To, Result.IntImag);
13120   }
13121 
13122   case CK_IntegralRealToComplex: {
13123     APSInt &Real = Result.IntReal;
13124     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
13125       return false;
13126 
13127     Result.makeComplexInt();
13128     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
13129     return true;
13130   }
13131 
13132   case CK_IntegralComplexCast: {
13133     if (!Visit(E->getSubExpr()))
13134       return false;
13135 
13136     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13137     QualType From
13138       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13139 
13140     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
13141     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
13142     return true;
13143   }
13144 
13145   case CK_IntegralComplexToFloatingComplex: {
13146     if (!Visit(E->getSubExpr()))
13147       return false;
13148 
13149     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13150     QualType From
13151       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13152     Result.makeComplexFloat();
13153     return HandleIntToFloatCast(Info, E, From, Result.IntReal,
13154                                 To, Result.FloatReal) &&
13155            HandleIntToFloatCast(Info, E, From, Result.IntImag,
13156                                 To, Result.FloatImag);
13157   }
13158   }
13159 
13160   llvm_unreachable("unknown cast resulting in complex value");
13161 }
13162 
13163 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13164   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13165     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13166 
13167   // Track whether the LHS or RHS is real at the type system level. When this is
13168   // the case we can simplify our evaluation strategy.
13169   bool LHSReal = false, RHSReal = false;
13170 
13171   bool LHSOK;
13172   if (E->getLHS()->getType()->isRealFloatingType()) {
13173     LHSReal = true;
13174     APFloat &Real = Result.FloatReal;
13175     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
13176     if (LHSOK) {
13177       Result.makeComplexFloat();
13178       Result.FloatImag = APFloat(Real.getSemantics());
13179     }
13180   } else {
13181     LHSOK = Visit(E->getLHS());
13182   }
13183   if (!LHSOK && !Info.noteFailure())
13184     return false;
13185 
13186   ComplexValue RHS;
13187   if (E->getRHS()->getType()->isRealFloatingType()) {
13188     RHSReal = true;
13189     APFloat &Real = RHS.FloatReal;
13190     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
13191       return false;
13192     RHS.makeComplexFloat();
13193     RHS.FloatImag = APFloat(Real.getSemantics());
13194   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
13195     return false;
13196 
13197   assert(!(LHSReal && RHSReal) &&
13198          "Cannot have both operands of a complex operation be real.");
13199   switch (E->getOpcode()) {
13200   default: return Error(E);
13201   case BO_Add:
13202     if (Result.isComplexFloat()) {
13203       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
13204                                        APFloat::rmNearestTiesToEven);
13205       if (LHSReal)
13206         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
13207       else if (!RHSReal)
13208         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
13209                                          APFloat::rmNearestTiesToEven);
13210     } else {
13211       Result.getComplexIntReal() += RHS.getComplexIntReal();
13212       Result.getComplexIntImag() += RHS.getComplexIntImag();
13213     }
13214     break;
13215   case BO_Sub:
13216     if (Result.isComplexFloat()) {
13217       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
13218                                             APFloat::rmNearestTiesToEven);
13219       if (LHSReal) {
13220         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
13221         Result.getComplexFloatImag().changeSign();
13222       } else if (!RHSReal) {
13223         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
13224                                               APFloat::rmNearestTiesToEven);
13225       }
13226     } else {
13227       Result.getComplexIntReal() -= RHS.getComplexIntReal();
13228       Result.getComplexIntImag() -= RHS.getComplexIntImag();
13229     }
13230     break;
13231   case BO_Mul:
13232     if (Result.isComplexFloat()) {
13233       // This is an implementation of complex multiplication according to the
13234       // constraints laid out in C11 Annex G. The implementation uses the
13235       // following naming scheme:
13236       //   (a + ib) * (c + id)
13237       ComplexValue LHS = Result;
13238       APFloat &A = LHS.getComplexFloatReal();
13239       APFloat &B = LHS.getComplexFloatImag();
13240       APFloat &C = RHS.getComplexFloatReal();
13241       APFloat &D = RHS.getComplexFloatImag();
13242       APFloat &ResR = Result.getComplexFloatReal();
13243       APFloat &ResI = Result.getComplexFloatImag();
13244       if (LHSReal) {
13245         assert(!RHSReal && "Cannot have two real operands for a complex op!");
13246         ResR = A * C;
13247         ResI = A * D;
13248       } else if (RHSReal) {
13249         ResR = C * A;
13250         ResI = C * B;
13251       } else {
13252         // In the fully general case, we need to handle NaNs and infinities
13253         // robustly.
13254         APFloat AC = A * C;
13255         APFloat BD = B * D;
13256         APFloat AD = A * D;
13257         APFloat BC = B * C;
13258         ResR = AC - BD;
13259         ResI = AD + BC;
13260         if (ResR.isNaN() && ResI.isNaN()) {
13261           bool Recalc = false;
13262           if (A.isInfinity() || B.isInfinity()) {
13263             A = APFloat::copySign(
13264                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
13265             B = APFloat::copySign(
13266                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
13267             if (C.isNaN())
13268               C = APFloat::copySign(APFloat(C.getSemantics()), C);
13269             if (D.isNaN())
13270               D = APFloat::copySign(APFloat(D.getSemantics()), D);
13271             Recalc = true;
13272           }
13273           if (C.isInfinity() || D.isInfinity()) {
13274             C = APFloat::copySign(
13275                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
13276             D = APFloat::copySign(
13277                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
13278             if (A.isNaN())
13279               A = APFloat::copySign(APFloat(A.getSemantics()), A);
13280             if (B.isNaN())
13281               B = APFloat::copySign(APFloat(B.getSemantics()), B);
13282             Recalc = true;
13283           }
13284           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
13285                           AD.isInfinity() || BC.isInfinity())) {
13286             if (A.isNaN())
13287               A = APFloat::copySign(APFloat(A.getSemantics()), A);
13288             if (B.isNaN())
13289               B = APFloat::copySign(APFloat(B.getSemantics()), B);
13290             if (C.isNaN())
13291               C = APFloat::copySign(APFloat(C.getSemantics()), C);
13292             if (D.isNaN())
13293               D = APFloat::copySign(APFloat(D.getSemantics()), D);
13294             Recalc = true;
13295           }
13296           if (Recalc) {
13297             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
13298             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
13299           }
13300         }
13301       }
13302     } else {
13303       ComplexValue LHS = Result;
13304       Result.getComplexIntReal() =
13305         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
13306          LHS.getComplexIntImag() * RHS.getComplexIntImag());
13307       Result.getComplexIntImag() =
13308         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
13309          LHS.getComplexIntImag() * RHS.getComplexIntReal());
13310     }
13311     break;
13312   case BO_Div:
13313     if (Result.isComplexFloat()) {
13314       // This is an implementation of complex division according to the
13315       // constraints laid out in C11 Annex G. The implementation uses the
13316       // following naming scheme:
13317       //   (a + ib) / (c + id)
13318       ComplexValue LHS = Result;
13319       APFloat &A = LHS.getComplexFloatReal();
13320       APFloat &B = LHS.getComplexFloatImag();
13321       APFloat &C = RHS.getComplexFloatReal();
13322       APFloat &D = RHS.getComplexFloatImag();
13323       APFloat &ResR = Result.getComplexFloatReal();
13324       APFloat &ResI = Result.getComplexFloatImag();
13325       if (RHSReal) {
13326         ResR = A / C;
13327         ResI = B / C;
13328       } else {
13329         if (LHSReal) {
13330           // No real optimizations we can do here, stub out with zero.
13331           B = APFloat::getZero(A.getSemantics());
13332         }
13333         int DenomLogB = 0;
13334         APFloat MaxCD = maxnum(abs(C), abs(D));
13335         if (MaxCD.isFinite()) {
13336           DenomLogB = ilogb(MaxCD);
13337           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
13338           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
13339         }
13340         APFloat Denom = C * C + D * D;
13341         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
13342                       APFloat::rmNearestTiesToEven);
13343         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
13344                       APFloat::rmNearestTiesToEven);
13345         if (ResR.isNaN() && ResI.isNaN()) {
13346           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
13347             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
13348             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
13349           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
13350                      D.isFinite()) {
13351             A = APFloat::copySign(
13352                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
13353             B = APFloat::copySign(
13354                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
13355             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
13356             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
13357           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
13358             C = APFloat::copySign(
13359                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
13360             D = APFloat::copySign(
13361                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
13362             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
13363             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
13364           }
13365         }
13366       }
13367     } else {
13368       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
13369         return Error(E, diag::note_expr_divide_by_zero);
13370 
13371       ComplexValue LHS = Result;
13372       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
13373         RHS.getComplexIntImag() * RHS.getComplexIntImag();
13374       Result.getComplexIntReal() =
13375         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
13376          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
13377       Result.getComplexIntImag() =
13378         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
13379          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
13380     }
13381     break;
13382   }
13383 
13384   return true;
13385 }
13386 
13387 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13388   // Get the operand value into 'Result'.
13389   if (!Visit(E->getSubExpr()))
13390     return false;
13391 
13392   switch (E->getOpcode()) {
13393   default:
13394     return Error(E);
13395   case UO_Extension:
13396     return true;
13397   case UO_Plus:
13398     // The result is always just the subexpr.
13399     return true;
13400   case UO_Minus:
13401     if (Result.isComplexFloat()) {
13402       Result.getComplexFloatReal().changeSign();
13403       Result.getComplexFloatImag().changeSign();
13404     }
13405     else {
13406       Result.getComplexIntReal() = -Result.getComplexIntReal();
13407       Result.getComplexIntImag() = -Result.getComplexIntImag();
13408     }
13409     return true;
13410   case UO_Not:
13411     if (Result.isComplexFloat())
13412       Result.getComplexFloatImag().changeSign();
13413     else
13414       Result.getComplexIntImag() = -Result.getComplexIntImag();
13415     return true;
13416   }
13417 }
13418 
13419 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
13420   if (E->getNumInits() == 2) {
13421     if (E->getType()->isComplexType()) {
13422       Result.makeComplexFloat();
13423       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
13424         return false;
13425       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
13426         return false;
13427     } else {
13428       Result.makeComplexInt();
13429       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
13430         return false;
13431       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
13432         return false;
13433     }
13434     return true;
13435   }
13436   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
13437 }
13438 
13439 //===----------------------------------------------------------------------===//
13440 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
13441 // implicit conversion.
13442 //===----------------------------------------------------------------------===//
13443 
13444 namespace {
13445 class AtomicExprEvaluator :
13446     public ExprEvaluatorBase<AtomicExprEvaluator> {
13447   const LValue *This;
13448   APValue &Result;
13449 public:
13450   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
13451       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
13452 
13453   bool Success(const APValue &V, const Expr *E) {
13454     Result = V;
13455     return true;
13456   }
13457 
13458   bool ZeroInitialization(const Expr *E) {
13459     ImplicitValueInitExpr VIE(
13460         E->getType()->castAs<AtomicType>()->getValueType());
13461     // For atomic-qualified class (and array) types in C++, initialize the
13462     // _Atomic-wrapped subobject directly, in-place.
13463     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
13464                 : Evaluate(Result, Info, &VIE);
13465   }
13466 
13467   bool VisitCastExpr(const CastExpr *E) {
13468     switch (E->getCastKind()) {
13469     default:
13470       return ExprEvaluatorBaseTy::VisitCastExpr(E);
13471     case CK_NonAtomicToAtomic:
13472       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
13473                   : Evaluate(Result, Info, E->getSubExpr());
13474     }
13475   }
13476 };
13477 } // end anonymous namespace
13478 
13479 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
13480                            EvalInfo &Info) {
13481   assert(E->isRValue() && E->getType()->isAtomicType());
13482   return AtomicExprEvaluator(Info, This, Result).Visit(E);
13483 }
13484 
13485 //===----------------------------------------------------------------------===//
13486 // Void expression evaluation, primarily for a cast to void on the LHS of a
13487 // comma operator
13488 //===----------------------------------------------------------------------===//
13489 
13490 namespace {
13491 class VoidExprEvaluator
13492   : public ExprEvaluatorBase<VoidExprEvaluator> {
13493 public:
13494   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
13495 
13496   bool Success(const APValue &V, const Expr *e) { return true; }
13497 
13498   bool ZeroInitialization(const Expr *E) { return true; }
13499 
13500   bool VisitCastExpr(const CastExpr *E) {
13501     switch (E->getCastKind()) {
13502     default:
13503       return ExprEvaluatorBaseTy::VisitCastExpr(E);
13504     case CK_ToVoid:
13505       VisitIgnoredValue(E->getSubExpr());
13506       return true;
13507     }
13508   }
13509 
13510   bool VisitCallExpr(const CallExpr *E) {
13511     switch (E->getBuiltinCallee()) {
13512     case Builtin::BI__assume:
13513     case Builtin::BI__builtin_assume:
13514       // The argument is not evaluated!
13515       return true;
13516 
13517     case Builtin::BI__builtin_operator_delete:
13518       return HandleOperatorDeleteCall(Info, E);
13519 
13520     default:
13521       break;
13522     }
13523 
13524     return ExprEvaluatorBaseTy::VisitCallExpr(E);
13525   }
13526 
13527   bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
13528 };
13529 } // end anonymous namespace
13530 
13531 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
13532   // We cannot speculatively evaluate a delete expression.
13533   if (Info.SpeculativeEvaluationDepth)
13534     return false;
13535 
13536   FunctionDecl *OperatorDelete = E->getOperatorDelete();
13537   if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
13538     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
13539         << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
13540     return false;
13541   }
13542 
13543   const Expr *Arg = E->getArgument();
13544 
13545   LValue Pointer;
13546   if (!EvaluatePointer(Arg, Pointer, Info))
13547     return false;
13548   if (Pointer.Designator.Invalid)
13549     return false;
13550 
13551   // Deleting a null pointer has no effect.
13552   if (Pointer.isNullPointer()) {
13553     // This is the only case where we need to produce an extension warning:
13554     // the only other way we can succeed is if we find a dynamic allocation,
13555     // and we will have warned when we allocated it in that case.
13556     if (!Info.getLangOpts().CPlusPlus2a)
13557       Info.CCEDiag(E, diag::note_constexpr_new);
13558     return true;
13559   }
13560 
13561   Optional<DynAlloc *> Alloc = CheckDeleteKind(
13562       Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
13563   if (!Alloc)
13564     return false;
13565   QualType AllocType = Pointer.Base.getDynamicAllocType();
13566 
13567   // For the non-array case, the designator must be empty if the static type
13568   // does not have a virtual destructor.
13569   if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
13570       !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
13571     Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
13572         << Arg->getType()->getPointeeType() << AllocType;
13573     return false;
13574   }
13575 
13576   // For a class type with a virtual destructor, the selected operator delete
13577   // is the one looked up when building the destructor.
13578   if (!E->isArrayForm() && !E->isGlobalDelete()) {
13579     const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
13580     if (VirtualDelete &&
13581         !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
13582       Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
13583           << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
13584       return false;
13585     }
13586   }
13587 
13588   if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
13589                          (*Alloc)->Value, AllocType))
13590     return false;
13591 
13592   if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
13593     // The element was already erased. This means the destructor call also
13594     // deleted the object.
13595     // FIXME: This probably results in undefined behavior before we get this
13596     // far, and should be diagnosed elsewhere first.
13597     Info.FFDiag(E, diag::note_constexpr_double_delete);
13598     return false;
13599   }
13600 
13601   return true;
13602 }
13603 
13604 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
13605   assert(E->isRValue() && E->getType()->isVoidType());
13606   return VoidExprEvaluator(Info).Visit(E);
13607 }
13608 
13609 //===----------------------------------------------------------------------===//
13610 // Top level Expr::EvaluateAsRValue method.
13611 //===----------------------------------------------------------------------===//
13612 
13613 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
13614   // In C, function designators are not lvalues, but we evaluate them as if they
13615   // are.
13616   QualType T = E->getType();
13617   if (E->isGLValue() || T->isFunctionType()) {
13618     LValue LV;
13619     if (!EvaluateLValue(E, LV, Info))
13620       return false;
13621     LV.moveInto(Result);
13622   } else if (T->isVectorType()) {
13623     if (!EvaluateVector(E, Result, Info))
13624       return false;
13625   } else if (T->isIntegralOrEnumerationType()) {
13626     if (!IntExprEvaluator(Info, Result).Visit(E))
13627       return false;
13628   } else if (T->hasPointerRepresentation()) {
13629     LValue LV;
13630     if (!EvaluatePointer(E, LV, Info))
13631       return false;
13632     LV.moveInto(Result);
13633   } else if (T->isRealFloatingType()) {
13634     llvm::APFloat F(0.0);
13635     if (!EvaluateFloat(E, F, Info))
13636       return false;
13637     Result = APValue(F);
13638   } else if (T->isAnyComplexType()) {
13639     ComplexValue C;
13640     if (!EvaluateComplex(E, C, Info))
13641       return false;
13642     C.moveInto(Result);
13643   } else if (T->isFixedPointType()) {
13644     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
13645   } else if (T->isMemberPointerType()) {
13646     MemberPtr P;
13647     if (!EvaluateMemberPointer(E, P, Info))
13648       return false;
13649     P.moveInto(Result);
13650     return true;
13651   } else if (T->isArrayType()) {
13652     LValue LV;
13653     APValue &Value =
13654         Info.CurrentCall->createTemporary(E, T, false, LV);
13655     if (!EvaluateArray(E, LV, Value, Info))
13656       return false;
13657     Result = Value;
13658   } else if (T->isRecordType()) {
13659     LValue LV;
13660     APValue &Value = Info.CurrentCall->createTemporary(E, T, false, LV);
13661     if (!EvaluateRecord(E, LV, Value, Info))
13662       return false;
13663     Result = Value;
13664   } else if (T->isVoidType()) {
13665     if (!Info.getLangOpts().CPlusPlus11)
13666       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
13667         << E->getType();
13668     if (!EvaluateVoid(E, Info))
13669       return false;
13670   } else if (T->isAtomicType()) {
13671     QualType Unqual = T.getAtomicUnqualifiedType();
13672     if (Unqual->isArrayType() || Unqual->isRecordType()) {
13673       LValue LV;
13674       APValue &Value = Info.CurrentCall->createTemporary(E, Unqual, false, LV);
13675       if (!EvaluateAtomic(E, &LV, Value, Info))
13676         return false;
13677     } else {
13678       if (!EvaluateAtomic(E, nullptr, Result, Info))
13679         return false;
13680     }
13681   } else if (Info.getLangOpts().CPlusPlus11) {
13682     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
13683     return false;
13684   } else {
13685     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
13686     return false;
13687   }
13688 
13689   return true;
13690 }
13691 
13692 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
13693 /// cases, the in-place evaluation is essential, since later initializers for
13694 /// an object can indirectly refer to subobjects which were initialized earlier.
13695 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
13696                             const Expr *E, bool AllowNonLiteralTypes) {
13697   assert(!E->isValueDependent());
13698 
13699   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
13700     return false;
13701 
13702   if (E->isRValue()) {
13703     // Evaluate arrays and record types in-place, so that later initializers can
13704     // refer to earlier-initialized members of the object.
13705     QualType T = E->getType();
13706     if (T->isArrayType())
13707       return EvaluateArray(E, This, Result, Info);
13708     else if (T->isRecordType())
13709       return EvaluateRecord(E, This, Result, Info);
13710     else if (T->isAtomicType()) {
13711       QualType Unqual = T.getAtomicUnqualifiedType();
13712       if (Unqual->isArrayType() || Unqual->isRecordType())
13713         return EvaluateAtomic(E, &This, Result, Info);
13714     }
13715   }
13716 
13717   // For any other type, in-place evaluation is unimportant.
13718   return Evaluate(Result, Info, E);
13719 }
13720 
13721 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
13722 /// lvalue-to-rvalue cast if it is an lvalue.
13723 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
13724   if (Info.EnableNewConstInterp) {
13725     if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
13726       return false;
13727   } else {
13728     if (E->getType().isNull())
13729       return false;
13730 
13731     if (!CheckLiteralType(Info, E))
13732       return false;
13733 
13734     if (!::Evaluate(Result, Info, E))
13735       return false;
13736 
13737     if (E->isGLValue()) {
13738       LValue LV;
13739       LV.setFrom(Info.Ctx, Result);
13740       if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
13741         return false;
13742     }
13743   }
13744 
13745   // Check this core constant expression is a constant expression.
13746   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result) &&
13747          CheckMemoryLeaks(Info);
13748 }
13749 
13750 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
13751                                  const ASTContext &Ctx, bool &IsConst) {
13752   // Fast-path evaluations of integer literals, since we sometimes see files
13753   // containing vast quantities of these.
13754   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
13755     Result.Val = APValue(APSInt(L->getValue(),
13756                                 L->getType()->isUnsignedIntegerType()));
13757     IsConst = true;
13758     return true;
13759   }
13760 
13761   // This case should be rare, but we need to check it before we check on
13762   // the type below.
13763   if (Exp->getType().isNull()) {
13764     IsConst = false;
13765     return true;
13766   }
13767 
13768   // FIXME: Evaluating values of large array and record types can cause
13769   // performance problems. Only do so in C++11 for now.
13770   if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
13771                           Exp->getType()->isRecordType()) &&
13772       !Ctx.getLangOpts().CPlusPlus11) {
13773     IsConst = false;
13774     return true;
13775   }
13776   return false;
13777 }
13778 
13779 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
13780                                       Expr::SideEffectsKind SEK) {
13781   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
13782          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
13783 }
13784 
13785 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
13786                              const ASTContext &Ctx, EvalInfo &Info) {
13787   bool IsConst;
13788   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
13789     return IsConst;
13790 
13791   return EvaluateAsRValue(Info, E, Result.Val);
13792 }
13793 
13794 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
13795                           const ASTContext &Ctx,
13796                           Expr::SideEffectsKind AllowSideEffects,
13797                           EvalInfo &Info) {
13798   if (!E->getType()->isIntegralOrEnumerationType())
13799     return false;
13800 
13801   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
13802       !ExprResult.Val.isInt() ||
13803       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
13804     return false;
13805 
13806   return true;
13807 }
13808 
13809 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
13810                                  const ASTContext &Ctx,
13811                                  Expr::SideEffectsKind AllowSideEffects,
13812                                  EvalInfo &Info) {
13813   if (!E->getType()->isFixedPointType())
13814     return false;
13815 
13816   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
13817     return false;
13818 
13819   if (!ExprResult.Val.isFixedPoint() ||
13820       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
13821     return false;
13822 
13823   return true;
13824 }
13825 
13826 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
13827 /// any crazy technique (that has nothing to do with language standards) that
13828 /// we want to.  If this function returns true, it returns the folded constant
13829 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
13830 /// will be applied to the result.
13831 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
13832                             bool InConstantContext) const {
13833   assert(!isValueDependent() &&
13834          "Expression evaluator can't be called on a dependent expression.");
13835   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
13836   Info.InConstantContext = InConstantContext;
13837   return ::EvaluateAsRValue(this, Result, Ctx, Info);
13838 }
13839 
13840 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
13841                                       bool InConstantContext) const {
13842   assert(!isValueDependent() &&
13843          "Expression evaluator can't be called on a dependent expression.");
13844   EvalResult Scratch;
13845   return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
13846          HandleConversionToBool(Scratch.Val, Result);
13847 }
13848 
13849 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
13850                          SideEffectsKind AllowSideEffects,
13851                          bool InConstantContext) const {
13852   assert(!isValueDependent() &&
13853          "Expression evaluator can't be called on a dependent expression.");
13854   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
13855   Info.InConstantContext = InConstantContext;
13856   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
13857 }
13858 
13859 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
13860                                 SideEffectsKind AllowSideEffects,
13861                                 bool InConstantContext) const {
13862   assert(!isValueDependent() &&
13863          "Expression evaluator can't be called on a dependent expression.");
13864   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
13865   Info.InConstantContext = InConstantContext;
13866   return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
13867 }
13868 
13869 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
13870                            SideEffectsKind AllowSideEffects,
13871                            bool InConstantContext) const {
13872   assert(!isValueDependent() &&
13873          "Expression evaluator can't be called on a dependent expression.");
13874 
13875   if (!getType()->isRealFloatingType())
13876     return false;
13877 
13878   EvalResult ExprResult;
13879   if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
13880       !ExprResult.Val.isFloat() ||
13881       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
13882     return false;
13883 
13884   Result = ExprResult.Val.getFloat();
13885   return true;
13886 }
13887 
13888 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
13889                             bool InConstantContext) const {
13890   assert(!isValueDependent() &&
13891          "Expression evaluator can't be called on a dependent expression.");
13892 
13893   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
13894   Info.InConstantContext = InConstantContext;
13895   LValue LV;
13896   CheckedTemporaries CheckedTemps;
13897   if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
13898       Result.HasSideEffects ||
13899       !CheckLValueConstantExpression(Info, getExprLoc(),
13900                                      Ctx.getLValueReferenceType(getType()), LV,
13901                                      Expr::EvaluateForCodeGen, CheckedTemps))
13902     return false;
13903 
13904   LV.moveInto(Result.Val);
13905   return true;
13906 }
13907 
13908 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
13909                                   const ASTContext &Ctx, bool InPlace) const {
13910   assert(!isValueDependent() &&
13911          "Expression evaluator can't be called on a dependent expression.");
13912 
13913   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
13914   EvalInfo Info(Ctx, Result, EM);
13915   Info.InConstantContext = true;
13916 
13917   if (InPlace) {
13918     Info.setEvaluatingDecl(this, Result.Val);
13919     LValue LVal;
13920     LVal.set(this);
13921     if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
13922         Result.HasSideEffects)
13923       return false;
13924   } else if (!::Evaluate(Result.Val, Info, this) || Result.HasSideEffects)
13925     return false;
13926 
13927   if (!Info.discardCleanups())
13928     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
13929 
13930   return CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
13931                                  Result.Val, Usage) &&
13932          CheckMemoryLeaks(Info);
13933 }
13934 
13935 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
13936                                  const VarDecl *VD,
13937                             SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
13938   assert(!isValueDependent() &&
13939          "Expression evaluator can't be called on a dependent expression.");
13940 
13941   // FIXME: Evaluating initializers for large array and record types can cause
13942   // performance problems. Only do so in C++11 for now.
13943   if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
13944       !Ctx.getLangOpts().CPlusPlus11)
13945     return false;
13946 
13947   Expr::EvalStatus EStatus;
13948   EStatus.Diag = &Notes;
13949 
13950   EvalInfo Info(Ctx, EStatus, VD->isConstexpr()
13951                                       ? EvalInfo::EM_ConstantExpression
13952                                       : EvalInfo::EM_ConstantFold);
13953   Info.setEvaluatingDecl(VD, Value);
13954   Info.InConstantContext = true;
13955 
13956   SourceLocation DeclLoc = VD->getLocation();
13957   QualType DeclTy = VD->getType();
13958 
13959   if (Info.EnableNewConstInterp) {
13960     auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
13961     if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
13962       return false;
13963   } else {
13964     LValue LVal;
13965     LVal.set(VD);
13966 
13967     if (!EvaluateInPlace(Value, Info, LVal, this,
13968                          /*AllowNonLiteralTypes=*/true) ||
13969         EStatus.HasSideEffects)
13970       return false;
13971 
13972     // At this point, any lifetime-extended temporaries are completely
13973     // initialized.
13974     Info.performLifetimeExtension();
13975 
13976     if (!Info.discardCleanups())
13977       llvm_unreachable("Unhandled cleanup; missing full expression marker?");
13978   }
13979   return CheckConstantExpression(Info, DeclLoc, DeclTy, Value) &&
13980          CheckMemoryLeaks(Info);
13981 }
13982 
13983 bool VarDecl::evaluateDestruction(
13984     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
13985   Expr::EvalStatus EStatus;
13986   EStatus.Diag = &Notes;
13987 
13988   // Make a copy of the value for the destructor to mutate, if we know it.
13989   // Otherwise, treat the value as default-initialized; if the destructor works
13990   // anyway, then the destruction is constant (and must be essentially empty).
13991   APValue DestroyedValue =
13992       (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
13993           ? *getEvaluatedValue()
13994           : getDefaultInitValue(getType());
13995 
13996   EvalInfo Info(getASTContext(), EStatus, EvalInfo::EM_ConstantExpression);
13997   Info.setEvaluatingDecl(this, DestroyedValue,
13998                          EvalInfo::EvaluatingDeclKind::Dtor);
13999   Info.InConstantContext = true;
14000 
14001   SourceLocation DeclLoc = getLocation();
14002   QualType DeclTy = getType();
14003 
14004   LValue LVal;
14005   LVal.set(this);
14006 
14007   if (!HandleDestruction(Info, DeclLoc, LVal.Base, DestroyedValue, DeclTy) ||
14008       EStatus.HasSideEffects)
14009     return false;
14010 
14011   if (!Info.discardCleanups())
14012     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14013 
14014   ensureEvaluatedStmt()->HasConstantDestruction = true;
14015   return true;
14016 }
14017 
14018 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
14019 /// constant folded, but discard the result.
14020 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
14021   assert(!isValueDependent() &&
14022          "Expression evaluator can't be called on a dependent expression.");
14023 
14024   EvalResult Result;
14025   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
14026          !hasUnacceptableSideEffect(Result, SEK);
14027 }
14028 
14029 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
14030                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
14031   assert(!isValueDependent() &&
14032          "Expression evaluator can't be called on a dependent expression.");
14033 
14034   EvalResult EVResult;
14035   EVResult.Diag = Diag;
14036   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14037   Info.InConstantContext = true;
14038 
14039   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
14040   (void)Result;
14041   assert(Result && "Could not evaluate expression");
14042   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
14043 
14044   return EVResult.Val.getInt();
14045 }
14046 
14047 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
14048     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
14049   assert(!isValueDependent() &&
14050          "Expression evaluator can't be called on a dependent expression.");
14051 
14052   EvalResult EVResult;
14053   EVResult.Diag = Diag;
14054   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14055   Info.InConstantContext = true;
14056   Info.CheckingForUndefinedBehavior = true;
14057 
14058   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
14059   (void)Result;
14060   assert(Result && "Could not evaluate expression");
14061   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
14062 
14063   return EVResult.Val.getInt();
14064 }
14065 
14066 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
14067   assert(!isValueDependent() &&
14068          "Expression evaluator can't be called on a dependent expression.");
14069 
14070   bool IsConst;
14071   EvalResult EVResult;
14072   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
14073     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14074     Info.CheckingForUndefinedBehavior = true;
14075     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
14076   }
14077 }
14078 
14079 bool Expr::EvalResult::isGlobalLValue() const {
14080   assert(Val.isLValue());
14081   return IsGlobalLValue(Val.getLValueBase());
14082 }
14083 
14084 
14085 /// isIntegerConstantExpr - this recursive routine will test if an expression is
14086 /// an integer constant expression.
14087 
14088 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
14089 /// comma, etc
14090 
14091 // CheckICE - This function does the fundamental ICE checking: the returned
14092 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
14093 // and a (possibly null) SourceLocation indicating the location of the problem.
14094 //
14095 // Note that to reduce code duplication, this helper does no evaluation
14096 // itself; the caller checks whether the expression is evaluatable, and
14097 // in the rare cases where CheckICE actually cares about the evaluated
14098 // value, it calls into Evaluate.
14099 
14100 namespace {
14101 
14102 enum ICEKind {
14103   /// This expression is an ICE.
14104   IK_ICE,
14105   /// This expression is not an ICE, but if it isn't evaluated, it's
14106   /// a legal subexpression for an ICE. This return value is used to handle
14107   /// the comma operator in C99 mode, and non-constant subexpressions.
14108   IK_ICEIfUnevaluated,
14109   /// This expression is not an ICE, and is not a legal subexpression for one.
14110   IK_NotICE
14111 };
14112 
14113 struct ICEDiag {
14114   ICEKind Kind;
14115   SourceLocation Loc;
14116 
14117   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
14118 };
14119 
14120 }
14121 
14122 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
14123 
14124 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
14125 
14126 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
14127   Expr::EvalResult EVResult;
14128   Expr::EvalStatus Status;
14129   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
14130 
14131   Info.InConstantContext = true;
14132   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
14133       !EVResult.Val.isInt())
14134     return ICEDiag(IK_NotICE, E->getBeginLoc());
14135 
14136   return NoDiag();
14137 }
14138 
14139 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
14140   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
14141   if (!E->getType()->isIntegralOrEnumerationType())
14142     return ICEDiag(IK_NotICE, E->getBeginLoc());
14143 
14144   switch (E->getStmtClass()) {
14145 #define ABSTRACT_STMT(Node)
14146 #define STMT(Node, Base) case Expr::Node##Class:
14147 #define EXPR(Node, Base)
14148 #include "clang/AST/StmtNodes.inc"
14149   case Expr::PredefinedExprClass:
14150   case Expr::FloatingLiteralClass:
14151   case Expr::ImaginaryLiteralClass:
14152   case Expr::StringLiteralClass:
14153   case Expr::ArraySubscriptExprClass:
14154   case Expr::OMPArraySectionExprClass:
14155   case Expr::OMPArrayShapingExprClass:
14156   case Expr::OMPIteratorExprClass:
14157   case Expr::MemberExprClass:
14158   case Expr::CompoundAssignOperatorClass:
14159   case Expr::CompoundLiteralExprClass:
14160   case Expr::ExtVectorElementExprClass:
14161   case Expr::DesignatedInitExprClass:
14162   case Expr::ArrayInitLoopExprClass:
14163   case Expr::ArrayInitIndexExprClass:
14164   case Expr::NoInitExprClass:
14165   case Expr::DesignatedInitUpdateExprClass:
14166   case Expr::ImplicitValueInitExprClass:
14167   case Expr::ParenListExprClass:
14168   case Expr::VAArgExprClass:
14169   case Expr::AddrLabelExprClass:
14170   case Expr::StmtExprClass:
14171   case Expr::CXXMemberCallExprClass:
14172   case Expr::CUDAKernelCallExprClass:
14173   case Expr::CXXDynamicCastExprClass:
14174   case Expr::CXXTypeidExprClass:
14175   case Expr::CXXUuidofExprClass:
14176   case Expr::MSPropertyRefExprClass:
14177   case Expr::MSPropertySubscriptExprClass:
14178   case Expr::CXXNullPtrLiteralExprClass:
14179   case Expr::UserDefinedLiteralClass:
14180   case Expr::CXXThisExprClass:
14181   case Expr::CXXThrowExprClass:
14182   case Expr::CXXNewExprClass:
14183   case Expr::CXXDeleteExprClass:
14184   case Expr::CXXPseudoDestructorExprClass:
14185   case Expr::UnresolvedLookupExprClass:
14186   case Expr::TypoExprClass:
14187   case Expr::RecoveryExprClass:
14188   case Expr::DependentScopeDeclRefExprClass:
14189   case Expr::CXXConstructExprClass:
14190   case Expr::CXXInheritedCtorInitExprClass:
14191   case Expr::CXXStdInitializerListExprClass:
14192   case Expr::CXXBindTemporaryExprClass:
14193   case Expr::ExprWithCleanupsClass:
14194   case Expr::CXXTemporaryObjectExprClass:
14195   case Expr::CXXUnresolvedConstructExprClass:
14196   case Expr::CXXDependentScopeMemberExprClass:
14197   case Expr::UnresolvedMemberExprClass:
14198   case Expr::ObjCStringLiteralClass:
14199   case Expr::ObjCBoxedExprClass:
14200   case Expr::ObjCArrayLiteralClass:
14201   case Expr::ObjCDictionaryLiteralClass:
14202   case Expr::ObjCEncodeExprClass:
14203   case Expr::ObjCMessageExprClass:
14204   case Expr::ObjCSelectorExprClass:
14205   case Expr::ObjCProtocolExprClass:
14206   case Expr::ObjCIvarRefExprClass:
14207   case Expr::ObjCPropertyRefExprClass:
14208   case Expr::ObjCSubscriptRefExprClass:
14209   case Expr::ObjCIsaExprClass:
14210   case Expr::ObjCAvailabilityCheckExprClass:
14211   case Expr::ShuffleVectorExprClass:
14212   case Expr::ConvertVectorExprClass:
14213   case Expr::BlockExprClass:
14214   case Expr::NoStmtClass:
14215   case Expr::OpaqueValueExprClass:
14216   case Expr::PackExpansionExprClass:
14217   case Expr::SubstNonTypeTemplateParmPackExprClass:
14218   case Expr::FunctionParmPackExprClass:
14219   case Expr::AsTypeExprClass:
14220   case Expr::ObjCIndirectCopyRestoreExprClass:
14221   case Expr::MaterializeTemporaryExprClass:
14222   case Expr::PseudoObjectExprClass:
14223   case Expr::AtomicExprClass:
14224   case Expr::LambdaExprClass:
14225   case Expr::CXXFoldExprClass:
14226   case Expr::CoawaitExprClass:
14227   case Expr::DependentCoawaitExprClass:
14228   case Expr::CoyieldExprClass:
14229     return ICEDiag(IK_NotICE, E->getBeginLoc());
14230 
14231   case Expr::InitListExprClass: {
14232     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
14233     // form "T x = { a };" is equivalent to "T x = a;".
14234     // Unless we're initializing a reference, T is a scalar as it is known to be
14235     // of integral or enumeration type.
14236     if (E->isRValue())
14237       if (cast<InitListExpr>(E)->getNumInits() == 1)
14238         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
14239     return ICEDiag(IK_NotICE, E->getBeginLoc());
14240   }
14241 
14242   case Expr::SizeOfPackExprClass:
14243   case Expr::GNUNullExprClass:
14244   case Expr::SourceLocExprClass:
14245     return NoDiag();
14246 
14247   case Expr::SubstNonTypeTemplateParmExprClass:
14248     return
14249       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
14250 
14251   case Expr::ConstantExprClass:
14252     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
14253 
14254   case Expr::ParenExprClass:
14255     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
14256   case Expr::GenericSelectionExprClass:
14257     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
14258   case Expr::IntegerLiteralClass:
14259   case Expr::FixedPointLiteralClass:
14260   case Expr::CharacterLiteralClass:
14261   case Expr::ObjCBoolLiteralExprClass:
14262   case Expr::CXXBoolLiteralExprClass:
14263   case Expr::CXXScalarValueInitExprClass:
14264   case Expr::TypeTraitExprClass:
14265   case Expr::ConceptSpecializationExprClass:
14266   case Expr::RequiresExprClass:
14267   case Expr::ArrayTypeTraitExprClass:
14268   case Expr::ExpressionTraitExprClass:
14269   case Expr::CXXNoexceptExprClass:
14270     return NoDiag();
14271   case Expr::CallExprClass:
14272   case Expr::CXXOperatorCallExprClass: {
14273     // C99 6.6/3 allows function calls within unevaluated subexpressions of
14274     // constant expressions, but they can never be ICEs because an ICE cannot
14275     // contain an operand of (pointer to) function type.
14276     const CallExpr *CE = cast<CallExpr>(E);
14277     if (CE->getBuiltinCallee())
14278       return CheckEvalInICE(E, Ctx);
14279     return ICEDiag(IK_NotICE, E->getBeginLoc());
14280   }
14281   case Expr::CXXRewrittenBinaryOperatorClass:
14282     return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
14283                     Ctx);
14284   case Expr::DeclRefExprClass: {
14285     if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
14286       return NoDiag();
14287     const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
14288     if (Ctx.getLangOpts().CPlusPlus &&
14289         D && IsConstNonVolatile(D->getType())) {
14290       // Parameter variables are never constants.  Without this check,
14291       // getAnyInitializer() can find a default argument, which leads
14292       // to chaos.
14293       if (isa<ParmVarDecl>(D))
14294         return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
14295 
14296       // C++ 7.1.5.1p2
14297       //   A variable of non-volatile const-qualified integral or enumeration
14298       //   type initialized by an ICE can be used in ICEs.
14299       if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
14300         if (!Dcl->getType()->isIntegralOrEnumerationType())
14301           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
14302 
14303         const VarDecl *VD;
14304         // Look for a declaration of this variable that has an initializer, and
14305         // check whether it is an ICE.
14306         if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
14307           return NoDiag();
14308         else
14309           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
14310       }
14311     }
14312     return ICEDiag(IK_NotICE, E->getBeginLoc());
14313   }
14314   case Expr::UnaryOperatorClass: {
14315     const UnaryOperator *Exp = cast<UnaryOperator>(E);
14316     switch (Exp->getOpcode()) {
14317     case UO_PostInc:
14318     case UO_PostDec:
14319     case UO_PreInc:
14320     case UO_PreDec:
14321     case UO_AddrOf:
14322     case UO_Deref:
14323     case UO_Coawait:
14324       // C99 6.6/3 allows increment and decrement within unevaluated
14325       // subexpressions of constant expressions, but they can never be ICEs
14326       // because an ICE cannot contain an lvalue operand.
14327       return ICEDiag(IK_NotICE, E->getBeginLoc());
14328     case UO_Extension:
14329     case UO_LNot:
14330     case UO_Plus:
14331     case UO_Minus:
14332     case UO_Not:
14333     case UO_Real:
14334     case UO_Imag:
14335       return CheckICE(Exp->getSubExpr(), Ctx);
14336     }
14337     llvm_unreachable("invalid unary operator class");
14338   }
14339   case Expr::OffsetOfExprClass: {
14340     // Note that per C99, offsetof must be an ICE. And AFAIK, using
14341     // EvaluateAsRValue matches the proposed gcc behavior for cases like
14342     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
14343     // compliance: we should warn earlier for offsetof expressions with
14344     // array subscripts that aren't ICEs, and if the array subscripts
14345     // are ICEs, the value of the offsetof must be an integer constant.
14346     return CheckEvalInICE(E, Ctx);
14347   }
14348   case Expr::UnaryExprOrTypeTraitExprClass: {
14349     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
14350     if ((Exp->getKind() ==  UETT_SizeOf) &&
14351         Exp->getTypeOfArgument()->isVariableArrayType())
14352       return ICEDiag(IK_NotICE, E->getBeginLoc());
14353     return NoDiag();
14354   }
14355   case Expr::BinaryOperatorClass: {
14356     const BinaryOperator *Exp = cast<BinaryOperator>(E);
14357     switch (Exp->getOpcode()) {
14358     case BO_PtrMemD:
14359     case BO_PtrMemI:
14360     case BO_Assign:
14361     case BO_MulAssign:
14362     case BO_DivAssign:
14363     case BO_RemAssign:
14364     case BO_AddAssign:
14365     case BO_SubAssign:
14366     case BO_ShlAssign:
14367     case BO_ShrAssign:
14368     case BO_AndAssign:
14369     case BO_XorAssign:
14370     case BO_OrAssign:
14371       // C99 6.6/3 allows assignments within unevaluated subexpressions of
14372       // constant expressions, but they can never be ICEs because an ICE cannot
14373       // contain an lvalue operand.
14374       return ICEDiag(IK_NotICE, E->getBeginLoc());
14375 
14376     case BO_Mul:
14377     case BO_Div:
14378     case BO_Rem:
14379     case BO_Add:
14380     case BO_Sub:
14381     case BO_Shl:
14382     case BO_Shr:
14383     case BO_LT:
14384     case BO_GT:
14385     case BO_LE:
14386     case BO_GE:
14387     case BO_EQ:
14388     case BO_NE:
14389     case BO_And:
14390     case BO_Xor:
14391     case BO_Or:
14392     case BO_Comma:
14393     case BO_Cmp: {
14394       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
14395       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
14396       if (Exp->getOpcode() == BO_Div ||
14397           Exp->getOpcode() == BO_Rem) {
14398         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
14399         // we don't evaluate one.
14400         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
14401           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
14402           if (REval == 0)
14403             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
14404           if (REval.isSigned() && REval.isAllOnesValue()) {
14405             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
14406             if (LEval.isMinSignedValue())
14407               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
14408           }
14409         }
14410       }
14411       if (Exp->getOpcode() == BO_Comma) {
14412         if (Ctx.getLangOpts().C99) {
14413           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
14414           // if it isn't evaluated.
14415           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
14416             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
14417         } else {
14418           // In both C89 and C++, commas in ICEs are illegal.
14419           return ICEDiag(IK_NotICE, E->getBeginLoc());
14420         }
14421       }
14422       return Worst(LHSResult, RHSResult);
14423     }
14424     case BO_LAnd:
14425     case BO_LOr: {
14426       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
14427       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
14428       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
14429         // Rare case where the RHS has a comma "side-effect"; we need
14430         // to actually check the condition to see whether the side
14431         // with the comma is evaluated.
14432         if ((Exp->getOpcode() == BO_LAnd) !=
14433             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
14434           return RHSResult;
14435         return NoDiag();
14436       }
14437 
14438       return Worst(LHSResult, RHSResult);
14439     }
14440     }
14441     llvm_unreachable("invalid binary operator kind");
14442   }
14443   case Expr::ImplicitCastExprClass:
14444   case Expr::CStyleCastExprClass:
14445   case Expr::CXXFunctionalCastExprClass:
14446   case Expr::CXXStaticCastExprClass:
14447   case Expr::CXXReinterpretCastExprClass:
14448   case Expr::CXXConstCastExprClass:
14449   case Expr::ObjCBridgedCastExprClass: {
14450     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
14451     if (isa<ExplicitCastExpr>(E)) {
14452       if (const FloatingLiteral *FL
14453             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
14454         unsigned DestWidth = Ctx.getIntWidth(E->getType());
14455         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
14456         APSInt IgnoredVal(DestWidth, !DestSigned);
14457         bool Ignored;
14458         // If the value does not fit in the destination type, the behavior is
14459         // undefined, so we are not required to treat it as a constant
14460         // expression.
14461         if (FL->getValue().convertToInteger(IgnoredVal,
14462                                             llvm::APFloat::rmTowardZero,
14463                                             &Ignored) & APFloat::opInvalidOp)
14464           return ICEDiag(IK_NotICE, E->getBeginLoc());
14465         return NoDiag();
14466       }
14467     }
14468     switch (cast<CastExpr>(E)->getCastKind()) {
14469     case CK_LValueToRValue:
14470     case CK_AtomicToNonAtomic:
14471     case CK_NonAtomicToAtomic:
14472     case CK_NoOp:
14473     case CK_IntegralToBoolean:
14474     case CK_IntegralCast:
14475       return CheckICE(SubExpr, Ctx);
14476     default:
14477       return ICEDiag(IK_NotICE, E->getBeginLoc());
14478     }
14479   }
14480   case Expr::BinaryConditionalOperatorClass: {
14481     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
14482     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
14483     if (CommonResult.Kind == IK_NotICE) return CommonResult;
14484     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
14485     if (FalseResult.Kind == IK_NotICE) return FalseResult;
14486     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
14487     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
14488         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
14489     return FalseResult;
14490   }
14491   case Expr::ConditionalOperatorClass: {
14492     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
14493     // If the condition (ignoring parens) is a __builtin_constant_p call,
14494     // then only the true side is actually considered in an integer constant
14495     // expression, and it is fully evaluated.  This is an important GNU
14496     // extension.  See GCC PR38377 for discussion.
14497     if (const CallExpr *CallCE
14498         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
14499       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
14500         return CheckEvalInICE(E, Ctx);
14501     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
14502     if (CondResult.Kind == IK_NotICE)
14503       return CondResult;
14504 
14505     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
14506     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
14507 
14508     if (TrueResult.Kind == IK_NotICE)
14509       return TrueResult;
14510     if (FalseResult.Kind == IK_NotICE)
14511       return FalseResult;
14512     if (CondResult.Kind == IK_ICEIfUnevaluated)
14513       return CondResult;
14514     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
14515       return NoDiag();
14516     // Rare case where the diagnostics depend on which side is evaluated
14517     // Note that if we get here, CondResult is 0, and at least one of
14518     // TrueResult and FalseResult is non-zero.
14519     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
14520       return FalseResult;
14521     return TrueResult;
14522   }
14523   case Expr::CXXDefaultArgExprClass:
14524     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
14525   case Expr::CXXDefaultInitExprClass:
14526     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
14527   case Expr::ChooseExprClass: {
14528     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
14529   }
14530   case Expr::BuiltinBitCastExprClass: {
14531     if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
14532       return ICEDiag(IK_NotICE, E->getBeginLoc());
14533     return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
14534   }
14535   }
14536 
14537   llvm_unreachable("Invalid StmtClass!");
14538 }
14539 
14540 /// Evaluate an expression as a C++11 integral constant expression.
14541 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
14542                                                     const Expr *E,
14543                                                     llvm::APSInt *Value,
14544                                                     SourceLocation *Loc) {
14545   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
14546     if (Loc) *Loc = E->getExprLoc();
14547     return false;
14548   }
14549 
14550   APValue Result;
14551   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
14552     return false;
14553 
14554   if (!Result.isInt()) {
14555     if (Loc) *Loc = E->getExprLoc();
14556     return false;
14557   }
14558 
14559   if (Value) *Value = Result.getInt();
14560   return true;
14561 }
14562 
14563 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
14564                                  SourceLocation *Loc) const {
14565   assert(!isValueDependent() &&
14566          "Expression evaluator can't be called on a dependent expression.");
14567 
14568   if (Ctx.getLangOpts().CPlusPlus11)
14569     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
14570 
14571   ICEDiag D = CheckICE(this, Ctx);
14572   if (D.Kind != IK_ICE) {
14573     if (Loc) *Loc = D.Loc;
14574     return false;
14575   }
14576   return true;
14577 }
14578 
14579 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
14580                                  SourceLocation *Loc, bool isEvaluated) const {
14581   assert(!isValueDependent() &&
14582          "Expression evaluator can't be called on a dependent expression.");
14583 
14584   if (Ctx.getLangOpts().CPlusPlus11)
14585     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
14586 
14587   if (!isIntegerConstantExpr(Ctx, Loc))
14588     return false;
14589 
14590   // The only possible side-effects here are due to UB discovered in the
14591   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
14592   // required to treat the expression as an ICE, so we produce the folded
14593   // value.
14594   EvalResult ExprResult;
14595   Expr::EvalStatus Status;
14596   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
14597   Info.InConstantContext = true;
14598 
14599   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
14600     llvm_unreachable("ICE cannot be evaluated!");
14601 
14602   Value = ExprResult.Val.getInt();
14603   return true;
14604 }
14605 
14606 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
14607   assert(!isValueDependent() &&
14608          "Expression evaluator can't be called on a dependent expression.");
14609 
14610   return CheckICE(this, Ctx).Kind == IK_ICE;
14611 }
14612 
14613 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
14614                                SourceLocation *Loc) const {
14615   assert(!isValueDependent() &&
14616          "Expression evaluator can't be called on a dependent expression.");
14617 
14618   // We support this checking in C++98 mode in order to diagnose compatibility
14619   // issues.
14620   assert(Ctx.getLangOpts().CPlusPlus);
14621 
14622   // Build evaluation settings.
14623   Expr::EvalStatus Status;
14624   SmallVector<PartialDiagnosticAt, 8> Diags;
14625   Status.Diag = &Diags;
14626   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
14627 
14628   APValue Scratch;
14629   bool IsConstExpr =
14630       ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
14631       // FIXME: We don't produce a diagnostic for this, but the callers that
14632       // call us on arbitrary full-expressions should generally not care.
14633       Info.discardCleanups() && !Status.HasSideEffects;
14634 
14635   if (!Diags.empty()) {
14636     IsConstExpr = false;
14637     if (Loc) *Loc = Diags[0].first;
14638   } else if (!IsConstExpr) {
14639     // FIXME: This shouldn't happen.
14640     if (Loc) *Loc = getExprLoc();
14641   }
14642 
14643   return IsConstExpr;
14644 }
14645 
14646 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
14647                                     const FunctionDecl *Callee,
14648                                     ArrayRef<const Expr*> Args,
14649                                     const Expr *This) const {
14650   assert(!isValueDependent() &&
14651          "Expression evaluator can't be called on a dependent expression.");
14652 
14653   Expr::EvalStatus Status;
14654   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
14655   Info.InConstantContext = true;
14656 
14657   LValue ThisVal;
14658   const LValue *ThisPtr = nullptr;
14659   if (This) {
14660 #ifndef NDEBUG
14661     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
14662     assert(MD && "Don't provide `this` for non-methods.");
14663     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
14664 #endif
14665     if (!This->isValueDependent() &&
14666         EvaluateObjectArgument(Info, This, ThisVal) &&
14667         !Info.EvalStatus.HasSideEffects)
14668       ThisPtr = &ThisVal;
14669 
14670     // Ignore any side-effects from a failed evaluation. This is safe because
14671     // they can't interfere with any other argument evaluation.
14672     Info.EvalStatus.HasSideEffects = false;
14673   }
14674 
14675   ArgVector ArgValues(Args.size());
14676   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
14677        I != E; ++I) {
14678     if ((*I)->isValueDependent() ||
14679         !Evaluate(ArgValues[I - Args.begin()], Info, *I) ||
14680         Info.EvalStatus.HasSideEffects)
14681       // If evaluation fails, throw away the argument entirely.
14682       ArgValues[I - Args.begin()] = APValue();
14683 
14684     // Ignore any side-effects from a failed evaluation. This is safe because
14685     // they can't interfere with any other argument evaluation.
14686     Info.EvalStatus.HasSideEffects = false;
14687   }
14688 
14689   // Parameter cleanups happen in the caller and are not part of this
14690   // evaluation.
14691   Info.discardCleanups();
14692   Info.EvalStatus.HasSideEffects = false;
14693 
14694   // Build fake call to Callee.
14695   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
14696                        ArgValues.data());
14697   // FIXME: Missing ExprWithCleanups in enable_if conditions?
14698   FullExpressionRAII Scope(Info);
14699   return Evaluate(Value, Info, this) && Scope.destroy() &&
14700          !Info.EvalStatus.HasSideEffects;
14701 }
14702 
14703 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
14704                                    SmallVectorImpl<
14705                                      PartialDiagnosticAt> &Diags) {
14706   // FIXME: It would be useful to check constexpr function templates, but at the
14707   // moment the constant expression evaluator cannot cope with the non-rigorous
14708   // ASTs which we build for dependent expressions.
14709   if (FD->isDependentContext())
14710     return true;
14711 
14712   Expr::EvalStatus Status;
14713   Status.Diag = &Diags;
14714 
14715   EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
14716   Info.InConstantContext = true;
14717   Info.CheckingPotentialConstantExpression = true;
14718 
14719   // The constexpr VM attempts to compile all methods to bytecode here.
14720   if (Info.EnableNewConstInterp) {
14721     Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
14722     return Diags.empty();
14723   }
14724 
14725   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
14726   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
14727 
14728   // Fabricate an arbitrary expression on the stack and pretend that it
14729   // is a temporary being used as the 'this' pointer.
14730   LValue This;
14731   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
14732   This.set({&VIE, Info.CurrentCall->Index});
14733 
14734   ArrayRef<const Expr*> Args;
14735 
14736   APValue Scratch;
14737   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
14738     // Evaluate the call as a constant initializer, to allow the construction
14739     // of objects of non-literal types.
14740     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
14741     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
14742   } else {
14743     SourceLocation Loc = FD->getLocation();
14744     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
14745                        Args, FD->getBody(), Info, Scratch, nullptr);
14746   }
14747 
14748   return Diags.empty();
14749 }
14750 
14751 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
14752                                               const FunctionDecl *FD,
14753                                               SmallVectorImpl<
14754                                                 PartialDiagnosticAt> &Diags) {
14755   assert(!E->isValueDependent() &&
14756          "Expression evaluator can't be called on a dependent expression.");
14757 
14758   Expr::EvalStatus Status;
14759   Status.Diag = &Diags;
14760 
14761   EvalInfo Info(FD->getASTContext(), Status,
14762                 EvalInfo::EM_ConstantExpressionUnevaluated);
14763   Info.InConstantContext = true;
14764   Info.CheckingPotentialConstantExpression = true;
14765 
14766   // Fabricate a call stack frame to give the arguments a plausible cover story.
14767   ArrayRef<const Expr*> Args;
14768   ArgVector ArgValues(0);
14769   bool Success = EvaluateArgs(Args, ArgValues, Info, FD);
14770   (void)Success;
14771   assert(Success &&
14772          "Failed to set up arguments for potential constant evaluation");
14773   CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
14774 
14775   APValue ResultScratch;
14776   Evaluate(ResultScratch, Info, E);
14777   return Diags.empty();
14778 }
14779 
14780 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
14781                                  unsigned Type) const {
14782   if (!getType()->isPointerType())
14783     return false;
14784 
14785   Expr::EvalStatus Status;
14786   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
14787   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
14788 }
14789