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/TargetInfo.h"
54 #include "llvm/ADT/APFixedPoint.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::APFixedPoint;
67 using llvm::APInt;
68 using llvm::APSInt;
69 using llvm::APFloat;
70 using llvm::FixedPointSemantics;
71 using llvm::Optional;
72 
73 namespace {
74   struct LValue;
75   class CallStackFrame;
76   class EvalInfo;
77 
78   using SourceLocExprScopeGuard =
79       CurrentSourceLocExprScope::SourceLocExprScopeGuard;
80 
81   static QualType getType(APValue::LValueBase B) {
82     if (!B) return QualType();
83     if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
84       // FIXME: It's unclear where we're supposed to take the type from, and
85       // this actually matters for arrays of unknown bound. Eg:
86       //
87       // extern int arr[]; void f() { extern int arr[3]; };
88       // constexpr int *p = &arr[1]; // valid?
89       //
90       // For now, we take the array bound from the most recent declaration.
91       for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
92            Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
93         QualType T = Redecl->getType();
94         if (!T->isIncompleteArrayType())
95           return T;
96       }
97       return D->getType();
98     }
99 
100     if (B.is<TypeInfoLValue>())
101       return B.getTypeInfoType();
102 
103     if (B.is<DynamicAllocLValue>())
104       return B.getDynamicAllocType();
105 
106     const Expr *Base = B.get<const Expr*>();
107 
108     // For a materialized temporary, the type of the temporary we materialized
109     // may not be the type of the expression.
110     if (const MaterializeTemporaryExpr *MTE =
111             dyn_cast<MaterializeTemporaryExpr>(Base)) {
112       SmallVector<const Expr *, 2> CommaLHSs;
113       SmallVector<SubobjectAdjustment, 2> Adjustments;
114       const Expr *Temp = MTE->getSubExpr();
115       const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
116                                                                Adjustments);
117       // Keep any cv-qualifiers from the reference if we generated a temporary
118       // for it directly. Otherwise use the type after adjustment.
119       if (!Adjustments.empty())
120         return Inner->getType();
121     }
122 
123     return Base->getType();
124   }
125 
126   /// Get an LValue path entry, which is known to not be an array index, as a
127   /// field declaration.
128   static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
129     return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
130   }
131   /// Get an LValue path entry, which is known to not be an array index, as a
132   /// base class declaration.
133   static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
134     return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
135   }
136   /// Determine whether this LValue path entry for a base class names a virtual
137   /// base class.
138   static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
139     return E.getAsBaseOrMember().getInt();
140   }
141 
142   /// Given an expression, determine the type used to store the result of
143   /// evaluating that expression.
144   static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
145     if (E->isRValue())
146       return E->getType();
147     return Ctx.getLValueReferenceType(E->getType());
148   }
149 
150   /// Given a CallExpr, try to get the alloc_size attribute. May return null.
151   static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
152     const FunctionDecl *Callee = CE->getDirectCallee();
153     return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
154   }
155 
156   /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
157   /// This will look through a single cast.
158   ///
159   /// Returns null if we couldn't unwrap a function with alloc_size.
160   static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
161     if (!E->getType()->isPointerType())
162       return nullptr;
163 
164     E = E->IgnoreParens();
165     // If we're doing a variable assignment from e.g. malloc(N), there will
166     // probably be a cast of some kind. In exotic cases, we might also see a
167     // top-level ExprWithCleanups. Ignore them either way.
168     if (const auto *FE = dyn_cast<FullExpr>(E))
169       E = FE->getSubExpr()->IgnoreParens();
170 
171     if (const auto *Cast = dyn_cast<CastExpr>(E))
172       E = Cast->getSubExpr()->IgnoreParens();
173 
174     if (const auto *CE = dyn_cast<CallExpr>(E))
175       return getAllocSizeAttr(CE) ? CE : nullptr;
176     return nullptr;
177   }
178 
179   /// Determines whether or not the given Base contains a call to a function
180   /// with the alloc_size attribute.
181   static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
182     const auto *E = Base.dyn_cast<const Expr *>();
183     return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
184   }
185 
186   /// The bound to claim that an array of unknown bound has.
187   /// The value in MostDerivedArraySize is undefined in this case. So, set it
188   /// to an arbitrary value that's likely to loudly break things if it's used.
189   static const uint64_t AssumedSizeForUnsizedArray =
190       std::numeric_limits<uint64_t>::max() / 2;
191 
192   /// Determines if an LValue with the given LValueBase will have an unsized
193   /// array in its designator.
194   /// Find the path length and type of the most-derived subobject in the given
195   /// path, and find the size of the containing array, if any.
196   static unsigned
197   findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
198                            ArrayRef<APValue::LValuePathEntry> Path,
199                            uint64_t &ArraySize, QualType &Type, bool &IsArray,
200                            bool &FirstEntryIsUnsizedArray) {
201     // This only accepts LValueBases from APValues, and APValues don't support
202     // arrays that lack size info.
203     assert(!isBaseAnAllocSizeCall(Base) &&
204            "Unsized arrays shouldn't appear here");
205     unsigned MostDerivedLength = 0;
206     Type = getType(Base);
207 
208     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
209       if (Type->isArrayType()) {
210         const ArrayType *AT = Ctx.getAsArrayType(Type);
211         Type = AT->getElementType();
212         MostDerivedLength = I + 1;
213         IsArray = true;
214 
215         if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
216           ArraySize = CAT->getSize().getZExtValue();
217         } else {
218           assert(I == 0 && "unexpected unsized array designator");
219           FirstEntryIsUnsizedArray = true;
220           ArraySize = AssumedSizeForUnsizedArray;
221         }
222       } else if (Type->isAnyComplexType()) {
223         const ComplexType *CT = Type->castAs<ComplexType>();
224         Type = CT->getElementType();
225         ArraySize = 2;
226         MostDerivedLength = I + 1;
227         IsArray = true;
228       } else if (const FieldDecl *FD = getAsField(Path[I])) {
229         Type = FD->getType();
230         ArraySize = 0;
231         MostDerivedLength = I + 1;
232         IsArray = false;
233       } else {
234         // Path[I] describes a base class.
235         ArraySize = 0;
236         IsArray = false;
237       }
238     }
239     return MostDerivedLength;
240   }
241 
242   /// A path from a glvalue to a subobject of that glvalue.
243   struct SubobjectDesignator {
244     /// True if the subobject was named in a manner not supported by C++11. Such
245     /// lvalues can still be folded, but they are not core constant expressions
246     /// and we cannot perform lvalue-to-rvalue conversions on them.
247     unsigned Invalid : 1;
248 
249     /// Is this a pointer one past the end of an object?
250     unsigned IsOnePastTheEnd : 1;
251 
252     /// Indicator of whether the first entry is an unsized array.
253     unsigned FirstEntryIsAnUnsizedArray : 1;
254 
255     /// Indicator of whether the most-derived object is an array element.
256     unsigned MostDerivedIsArrayElement : 1;
257 
258     /// The length of the path to the most-derived object of which this is a
259     /// subobject.
260     unsigned MostDerivedPathLength : 28;
261 
262     /// The size of the array of which the most-derived object is an element.
263     /// This will always be 0 if the most-derived object is not an array
264     /// element. 0 is not an indicator of whether or not the most-derived object
265     /// is an array, however, because 0-length arrays are allowed.
266     ///
267     /// If the current array is an unsized array, the value of this is
268     /// undefined.
269     uint64_t MostDerivedArraySize;
270 
271     /// The type of the most derived object referred to by this address.
272     QualType MostDerivedType;
273 
274     typedef APValue::LValuePathEntry PathEntry;
275 
276     /// The entries on the path from the glvalue to the designated subobject.
277     SmallVector<PathEntry, 8> Entries;
278 
279     SubobjectDesignator() : Invalid(true) {}
280 
281     explicit SubobjectDesignator(QualType T)
282         : Invalid(false), IsOnePastTheEnd(false),
283           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
284           MostDerivedPathLength(0), MostDerivedArraySize(0),
285           MostDerivedType(T) {}
286 
287     SubobjectDesignator(ASTContext &Ctx, const APValue &V)
288         : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
289           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
290           MostDerivedPathLength(0), MostDerivedArraySize(0) {
291       assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
292       if (!Invalid) {
293         IsOnePastTheEnd = V.isLValueOnePastTheEnd();
294         ArrayRef<PathEntry> VEntries = V.getLValuePath();
295         Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
296         if (V.getLValueBase()) {
297           bool IsArray = false;
298           bool FirstIsUnsizedArray = false;
299           MostDerivedPathLength = findMostDerivedSubobject(
300               Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
301               MostDerivedType, IsArray, FirstIsUnsizedArray);
302           MostDerivedIsArrayElement = IsArray;
303           FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
304         }
305       }
306     }
307 
308     void truncate(ASTContext &Ctx, APValue::LValueBase Base,
309                   unsigned NewLength) {
310       if (Invalid)
311         return;
312 
313       assert(Base && "cannot truncate path for null pointer");
314       assert(NewLength <= Entries.size() && "not a truncation");
315 
316       if (NewLength == Entries.size())
317         return;
318       Entries.resize(NewLength);
319 
320       bool IsArray = false;
321       bool FirstIsUnsizedArray = false;
322       MostDerivedPathLength = findMostDerivedSubobject(
323           Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
324           FirstIsUnsizedArray);
325       MostDerivedIsArrayElement = IsArray;
326       FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
327     }
328 
329     void setInvalid() {
330       Invalid = true;
331       Entries.clear();
332     }
333 
334     /// Determine whether the most derived subobject is an array without a
335     /// known bound.
336     bool isMostDerivedAnUnsizedArray() const {
337       assert(!Invalid && "Calling this makes no sense on invalid designators");
338       return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
339     }
340 
341     /// Determine what the most derived array's size is. Results in an assertion
342     /// failure if the most derived array lacks a size.
343     uint64_t getMostDerivedArraySize() const {
344       assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
345       return MostDerivedArraySize;
346     }
347 
348     /// Determine whether this is a one-past-the-end pointer.
349     bool isOnePastTheEnd() const {
350       assert(!Invalid);
351       if (IsOnePastTheEnd)
352         return true;
353       if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
354           Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
355               MostDerivedArraySize)
356         return true;
357       return false;
358     }
359 
360     /// Get the range of valid index adjustments in the form
361     ///   {maximum value that can be subtracted from this pointer,
362     ///    maximum value that can be added to this pointer}
363     std::pair<uint64_t, uint64_t> validIndexAdjustments() {
364       if (Invalid || isMostDerivedAnUnsizedArray())
365         return {0, 0};
366 
367       // [expr.add]p4: For the purposes of these operators, a pointer to a
368       // nonarray object behaves the same as a pointer to the first element of
369       // an array of length one with the type of the object as its element type.
370       bool IsArray = MostDerivedPathLength == Entries.size() &&
371                      MostDerivedIsArrayElement;
372       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
373                                     : (uint64_t)IsOnePastTheEnd;
374       uint64_t ArraySize =
375           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
376       return {ArrayIndex, ArraySize - ArrayIndex};
377     }
378 
379     /// Check that this refers to a valid subobject.
380     bool isValidSubobject() const {
381       if (Invalid)
382         return false;
383       return !isOnePastTheEnd();
384     }
385     /// Check that this refers to a valid subobject, and if not, produce a
386     /// relevant diagnostic and set the designator as invalid.
387     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
388 
389     /// Get the type of the designated object.
390     QualType getType(ASTContext &Ctx) const {
391       assert(!Invalid && "invalid designator has no subobject type");
392       return MostDerivedPathLength == Entries.size()
393                  ? MostDerivedType
394                  : Ctx.getRecordType(getAsBaseClass(Entries.back()));
395     }
396 
397     /// Update this designator to refer to the first element within this array.
398     void addArrayUnchecked(const ConstantArrayType *CAT) {
399       Entries.push_back(PathEntry::ArrayIndex(0));
400 
401       // This is a most-derived object.
402       MostDerivedType = CAT->getElementType();
403       MostDerivedIsArrayElement = true;
404       MostDerivedArraySize = CAT->getSize().getZExtValue();
405       MostDerivedPathLength = Entries.size();
406     }
407     /// Update this designator to refer to the first element within the array of
408     /// elements of type T. This is an array of unknown size.
409     void addUnsizedArrayUnchecked(QualType ElemTy) {
410       Entries.push_back(PathEntry::ArrayIndex(0));
411 
412       MostDerivedType = ElemTy;
413       MostDerivedIsArrayElement = true;
414       // The value in MostDerivedArraySize is undefined in this case. So, set it
415       // to an arbitrary value that's likely to loudly break things if it's
416       // used.
417       MostDerivedArraySize = AssumedSizeForUnsizedArray;
418       MostDerivedPathLength = Entries.size();
419     }
420     /// Update this designator to refer to the given base or member of this
421     /// object.
422     void addDeclUnchecked(const Decl *D, bool Virtual = false) {
423       Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
424 
425       // If this isn't a base class, it's a new most-derived object.
426       if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
427         MostDerivedType = FD->getType();
428         MostDerivedIsArrayElement = false;
429         MostDerivedArraySize = 0;
430         MostDerivedPathLength = Entries.size();
431       }
432     }
433     /// Update this designator to refer to the given complex component.
434     void addComplexUnchecked(QualType EltTy, bool Imag) {
435       Entries.push_back(PathEntry::ArrayIndex(Imag));
436 
437       // This is technically a most-derived object, though in practice this
438       // is unlikely to matter.
439       MostDerivedType = EltTy;
440       MostDerivedIsArrayElement = true;
441       MostDerivedArraySize = 2;
442       MostDerivedPathLength = Entries.size();
443     }
444     void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
445     void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
446                                    const APSInt &N);
447     /// Add N to the address of this subobject.
448     void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
449       if (Invalid || !N) return;
450       uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
451       if (isMostDerivedAnUnsizedArray()) {
452         diagnoseUnsizedArrayPointerArithmetic(Info, E);
453         // Can't verify -- trust that the user is doing the right thing (or if
454         // not, trust that the caller will catch the bad behavior).
455         // FIXME: Should we reject if this overflows, at least?
456         Entries.back() = PathEntry::ArrayIndex(
457             Entries.back().getAsArrayIndex() + TruncatedN);
458         return;
459       }
460 
461       // [expr.add]p4: For the purposes of these operators, a pointer to a
462       // nonarray object behaves the same as a pointer to the first element of
463       // an array of length one with the type of the object as its element type.
464       bool IsArray = MostDerivedPathLength == Entries.size() &&
465                      MostDerivedIsArrayElement;
466       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
467                                     : (uint64_t)IsOnePastTheEnd;
468       uint64_t ArraySize =
469           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
470 
471       if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
472         // Calculate the actual index in a wide enough type, so we can include
473         // it in the note.
474         N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
475         (llvm::APInt&)N += ArrayIndex;
476         assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
477         diagnosePointerArithmetic(Info, E, N);
478         setInvalid();
479         return;
480       }
481 
482       ArrayIndex += TruncatedN;
483       assert(ArrayIndex <= ArraySize &&
484              "bounds check succeeded for out-of-bounds index");
485 
486       if (IsArray)
487         Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
488       else
489         IsOnePastTheEnd = (ArrayIndex != 0);
490     }
491   };
492 
493   /// A scope at the end of which an object can need to be destroyed.
494   enum class ScopeKind {
495     Block,
496     FullExpression,
497     Call
498   };
499 
500   /// A reference to a particular call and its arguments.
501   struct CallRef {
502     CallRef() : OrigCallee(), CallIndex(0), Version() {}
503     CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
504         : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
505 
506     explicit operator bool() const { return OrigCallee; }
507 
508     /// Get the parameter that the caller initialized, corresponding to the
509     /// given parameter in the callee.
510     const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
511       return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
512                         : PVD;
513     }
514 
515     /// The callee at the point where the arguments were evaluated. This might
516     /// be different from the actual callee (a different redeclaration, or a
517     /// virtual override), but this function's parameters are the ones that
518     /// appear in the parameter map.
519     const FunctionDecl *OrigCallee;
520     /// The call index of the frame that holds the argument values.
521     unsigned CallIndex;
522     /// The version of the parameters corresponding to this call.
523     unsigned Version;
524   };
525 
526   /// A stack frame in the constexpr call stack.
527   class CallStackFrame : public interp::Frame {
528   public:
529     EvalInfo &Info;
530 
531     /// Parent - The caller of this stack frame.
532     CallStackFrame *Caller;
533 
534     /// Callee - The function which was called.
535     const FunctionDecl *Callee;
536 
537     /// This - The binding for the this pointer in this call, if any.
538     const LValue *This;
539 
540     /// Information on how to find the arguments to this call. Our arguments
541     /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
542     /// key and this value as the version.
543     CallRef Arguments;
544 
545     /// Source location information about the default argument or default
546     /// initializer expression we're evaluating, if any.
547     CurrentSourceLocExprScope CurSourceLocExprScope;
548 
549     // Note that we intentionally use std::map here so that references to
550     // values are stable.
551     typedef std::pair<const void *, unsigned> MapKeyTy;
552     typedef std::map<MapKeyTy, APValue> MapTy;
553     /// Temporaries - Temporary lvalues materialized within this stack frame.
554     MapTy Temporaries;
555 
556     /// CallLoc - The location of the call expression for this call.
557     SourceLocation CallLoc;
558 
559     /// Index - The call index of this call.
560     unsigned Index;
561 
562     /// The stack of integers for tracking version numbers for temporaries.
563     SmallVector<unsigned, 2> TempVersionStack = {1};
564     unsigned CurTempVersion = TempVersionStack.back();
565 
566     unsigned getTempVersion() const { return TempVersionStack.back(); }
567 
568     void pushTempVersion() {
569       TempVersionStack.push_back(++CurTempVersion);
570     }
571 
572     void popTempVersion() {
573       TempVersionStack.pop_back();
574     }
575 
576     CallRef createCall(const FunctionDecl *Callee) {
577       return {Callee, Index, ++CurTempVersion};
578     }
579 
580     // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
581     // on the overall stack usage of deeply-recursing constexpr evaluations.
582     // (We should cache this map rather than recomputing it repeatedly.)
583     // But let's try this and see how it goes; we can look into caching the map
584     // as a later change.
585 
586     /// LambdaCaptureFields - Mapping from captured variables/this to
587     /// corresponding data members in the closure class.
588     llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
589     FieldDecl *LambdaThisCaptureField;
590 
591     CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
592                    const FunctionDecl *Callee, const LValue *This,
593                    CallRef Arguments);
594     ~CallStackFrame();
595 
596     // Return the temporary for Key whose version number is Version.
597     APValue *getTemporary(const void *Key, unsigned Version) {
598       MapKeyTy KV(Key, Version);
599       auto LB = Temporaries.lower_bound(KV);
600       if (LB != Temporaries.end() && LB->first == KV)
601         return &LB->second;
602       // Pair (Key,Version) wasn't found in the map. Check that no elements
603       // in the map have 'Key' as their key.
604       assert((LB == Temporaries.end() || LB->first.first != Key) &&
605              (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
606              "Element with key 'Key' found in map");
607       return nullptr;
608     }
609 
610     // Return the current temporary for Key in the map.
611     APValue *getCurrentTemporary(const void *Key) {
612       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
613       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
614         return &std::prev(UB)->second;
615       return nullptr;
616     }
617 
618     // Return the version number of the current temporary for Key.
619     unsigned getCurrentTemporaryVersion(const void *Key) const {
620       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
621       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
622         return std::prev(UB)->first.second;
623       return 0;
624     }
625 
626     /// Allocate storage for an object of type T in this stack frame.
627     /// Populates LV with a handle to the created object. Key identifies
628     /// the temporary within the stack frame, and must not be reused without
629     /// bumping the temporary version number.
630     template<typename KeyT>
631     APValue &createTemporary(const KeyT *Key, QualType T,
632                              ScopeKind Scope, LValue &LV);
633 
634     /// Allocate storage for a parameter of a function call made in this frame.
635     APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
636 
637     void describe(llvm::raw_ostream &OS) override;
638 
639     Frame *getCaller() const override { return Caller; }
640     SourceLocation getCallLocation() const override { return CallLoc; }
641     const FunctionDecl *getCallee() const override { return Callee; }
642 
643     bool isStdFunction() const {
644       for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
645         if (DC->isStdNamespace())
646           return true;
647       return false;
648     }
649 
650   private:
651     APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
652                          ScopeKind Scope);
653   };
654 
655   /// Temporarily override 'this'.
656   class ThisOverrideRAII {
657   public:
658     ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
659         : Frame(Frame), OldThis(Frame.This) {
660       if (Enable)
661         Frame.This = NewThis;
662     }
663     ~ThisOverrideRAII() {
664       Frame.This = OldThis;
665     }
666   private:
667     CallStackFrame &Frame;
668     const LValue *OldThis;
669   };
670 }
671 
672 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
673                               const LValue &This, QualType ThisType);
674 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
675                               APValue::LValueBase LVBase, APValue &Value,
676                               QualType T);
677 
678 namespace {
679   /// A cleanup, and a flag indicating whether it is lifetime-extended.
680   class Cleanup {
681     llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
682     APValue::LValueBase Base;
683     QualType T;
684 
685   public:
686     Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
687             ScopeKind Scope)
688         : Value(Val, Scope), Base(Base), T(T) {}
689 
690     /// Determine whether this cleanup should be performed at the end of the
691     /// given kind of scope.
692     bool isDestroyedAtEndOf(ScopeKind K) const {
693       return (int)Value.getInt() >= (int)K;
694     }
695     bool endLifetime(EvalInfo &Info, bool RunDestructors) {
696       if (RunDestructors) {
697         SourceLocation Loc;
698         if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
699           Loc = VD->getLocation();
700         else if (const Expr *E = Base.dyn_cast<const Expr*>())
701           Loc = E->getExprLoc();
702         return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
703       }
704       *Value.getPointer() = APValue();
705       return true;
706     }
707 
708     bool hasSideEffect() {
709       return T.isDestructedType();
710     }
711   };
712 
713   /// A reference to an object whose construction we are currently evaluating.
714   struct ObjectUnderConstruction {
715     APValue::LValueBase Base;
716     ArrayRef<APValue::LValuePathEntry> Path;
717     friend bool operator==(const ObjectUnderConstruction &LHS,
718                            const ObjectUnderConstruction &RHS) {
719       return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
720     }
721     friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
722       return llvm::hash_combine(Obj.Base, Obj.Path);
723     }
724   };
725   enum class ConstructionPhase {
726     None,
727     Bases,
728     AfterBases,
729     AfterFields,
730     Destroying,
731     DestroyingBases
732   };
733 }
734 
735 namespace llvm {
736 template<> struct DenseMapInfo<ObjectUnderConstruction> {
737   using Base = DenseMapInfo<APValue::LValueBase>;
738   static ObjectUnderConstruction getEmptyKey() {
739     return {Base::getEmptyKey(), {}}; }
740   static ObjectUnderConstruction getTombstoneKey() {
741     return {Base::getTombstoneKey(), {}};
742   }
743   static unsigned getHashValue(const ObjectUnderConstruction &Object) {
744     return hash_value(Object);
745   }
746   static bool isEqual(const ObjectUnderConstruction &LHS,
747                       const ObjectUnderConstruction &RHS) {
748     return LHS == RHS;
749   }
750 };
751 }
752 
753 namespace {
754   /// A dynamically-allocated heap object.
755   struct DynAlloc {
756     /// The value of this heap-allocated object.
757     APValue Value;
758     /// The allocating expression; used for diagnostics. Either a CXXNewExpr
759     /// or a CallExpr (the latter is for direct calls to operator new inside
760     /// std::allocator<T>::allocate).
761     const Expr *AllocExpr = nullptr;
762 
763     enum Kind {
764       New,
765       ArrayNew,
766       StdAllocator
767     };
768 
769     /// Get the kind of the allocation. This must match between allocation
770     /// and deallocation.
771     Kind getKind() const {
772       if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
773         return NE->isArray() ? ArrayNew : New;
774       assert(isa<CallExpr>(AllocExpr));
775       return StdAllocator;
776     }
777   };
778 
779   struct DynAllocOrder {
780     bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
781       return L.getIndex() < R.getIndex();
782     }
783   };
784 
785   /// EvalInfo - This is a private struct used by the evaluator to capture
786   /// information about a subexpression as it is folded.  It retains information
787   /// about the AST context, but also maintains information about the folded
788   /// expression.
789   ///
790   /// If an expression could be evaluated, it is still possible it is not a C
791   /// "integer constant expression" or constant expression.  If not, this struct
792   /// captures information about how and why not.
793   ///
794   /// One bit of information passed *into* the request for constant folding
795   /// indicates whether the subexpression is "evaluated" or not according to C
796   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
797   /// evaluate the expression regardless of what the RHS is, but C only allows
798   /// certain things in certain situations.
799   class EvalInfo : public interp::State {
800   public:
801     ASTContext &Ctx;
802 
803     /// EvalStatus - Contains information about the evaluation.
804     Expr::EvalStatus &EvalStatus;
805 
806     /// CurrentCall - The top of the constexpr call stack.
807     CallStackFrame *CurrentCall;
808 
809     /// CallStackDepth - The number of calls in the call stack right now.
810     unsigned CallStackDepth;
811 
812     /// NextCallIndex - The next call index to assign.
813     unsigned NextCallIndex;
814 
815     /// StepsLeft - The remaining number of evaluation steps we're permitted
816     /// to perform. This is essentially a limit for the number of statements
817     /// we will evaluate.
818     unsigned StepsLeft;
819 
820     /// Enable the experimental new constant interpreter. If an expression is
821     /// not supported by the interpreter, an error is triggered.
822     bool EnableNewConstInterp;
823 
824     /// BottomFrame - The frame in which evaluation started. This must be
825     /// initialized after CurrentCall and CallStackDepth.
826     CallStackFrame BottomFrame;
827 
828     /// A stack of values whose lifetimes end at the end of some surrounding
829     /// evaluation frame.
830     llvm::SmallVector<Cleanup, 16> CleanupStack;
831 
832     /// EvaluatingDecl - This is the declaration whose initializer is being
833     /// evaluated, if any.
834     APValue::LValueBase EvaluatingDecl;
835 
836     enum class EvaluatingDeclKind {
837       None,
838       /// We're evaluating the construction of EvaluatingDecl.
839       Ctor,
840       /// We're evaluating the destruction of EvaluatingDecl.
841       Dtor,
842     };
843     EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
844 
845     /// EvaluatingDeclValue - This is the value being constructed for the
846     /// declaration whose initializer is being evaluated, if any.
847     APValue *EvaluatingDeclValue;
848 
849     /// Set of objects that are currently being constructed.
850     llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
851         ObjectsUnderConstruction;
852 
853     /// Current heap allocations, along with the location where each was
854     /// allocated. We use std::map here because we need stable addresses
855     /// for the stored APValues.
856     std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
857 
858     /// The number of heap allocations performed so far in this evaluation.
859     unsigned NumHeapAllocs = 0;
860 
861     struct EvaluatingConstructorRAII {
862       EvalInfo &EI;
863       ObjectUnderConstruction Object;
864       bool DidInsert;
865       EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
866                                 bool HasBases)
867           : EI(EI), Object(Object) {
868         DidInsert =
869             EI.ObjectsUnderConstruction
870                 .insert({Object, HasBases ? ConstructionPhase::Bases
871                                           : ConstructionPhase::AfterBases})
872                 .second;
873       }
874       void finishedConstructingBases() {
875         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
876       }
877       void finishedConstructingFields() {
878         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
879       }
880       ~EvaluatingConstructorRAII() {
881         if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
882       }
883     };
884 
885     struct EvaluatingDestructorRAII {
886       EvalInfo &EI;
887       ObjectUnderConstruction Object;
888       bool DidInsert;
889       EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
890           : EI(EI), Object(Object) {
891         DidInsert = EI.ObjectsUnderConstruction
892                         .insert({Object, ConstructionPhase::Destroying})
893                         .second;
894       }
895       void startedDestroyingBases() {
896         EI.ObjectsUnderConstruction[Object] =
897             ConstructionPhase::DestroyingBases;
898       }
899       ~EvaluatingDestructorRAII() {
900         if (DidInsert)
901           EI.ObjectsUnderConstruction.erase(Object);
902       }
903     };
904 
905     ConstructionPhase
906     isEvaluatingCtorDtor(APValue::LValueBase Base,
907                          ArrayRef<APValue::LValuePathEntry> Path) {
908       return ObjectsUnderConstruction.lookup({Base, Path});
909     }
910 
911     /// If we're currently speculatively evaluating, the outermost call stack
912     /// depth at which we can mutate state, otherwise 0.
913     unsigned SpeculativeEvaluationDepth = 0;
914 
915     /// The current array initialization index, if we're performing array
916     /// initialization.
917     uint64_t ArrayInitIndex = -1;
918 
919     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
920     /// notes attached to it will also be stored, otherwise they will not be.
921     bool HasActiveDiagnostic;
922 
923     /// Have we emitted a diagnostic explaining why we couldn't constant
924     /// fold (not just why it's not strictly a constant expression)?
925     bool HasFoldFailureDiagnostic;
926 
927     /// Whether or not we're in a context where the front end requires a
928     /// constant value.
929     bool InConstantContext;
930 
931     /// Whether we're checking that an expression is a potential constant
932     /// expression. If so, do not fail on constructs that could become constant
933     /// later on (such as a use of an undefined global).
934     bool CheckingPotentialConstantExpression = false;
935 
936     /// Whether we're checking for an expression that has undefined behavior.
937     /// If so, we will produce warnings if we encounter an operation that is
938     /// always undefined.
939     bool CheckingForUndefinedBehavior = false;
940 
941     enum EvaluationMode {
942       /// Evaluate as a constant expression. Stop if we find that the expression
943       /// is not a constant expression.
944       EM_ConstantExpression,
945 
946       /// Evaluate as a constant expression. Stop if we find that the expression
947       /// is not a constant expression. Some expressions can be retried in the
948       /// optimizer if we don't constant fold them here, but in an unevaluated
949       /// context we try to fold them immediately since the optimizer never
950       /// gets a chance to look at it.
951       EM_ConstantExpressionUnevaluated,
952 
953       /// Fold the expression to a constant. Stop if we hit a side-effect that
954       /// we can't model.
955       EM_ConstantFold,
956 
957       /// Evaluate in any way we know how. Don't worry about side-effects that
958       /// can't be modeled.
959       EM_IgnoreSideEffects,
960     } EvalMode;
961 
962     /// Are we checking whether the expression is a potential constant
963     /// expression?
964     bool checkingPotentialConstantExpression() const override  {
965       return CheckingPotentialConstantExpression;
966     }
967 
968     /// Are we checking an expression for overflow?
969     // FIXME: We should check for any kind of undefined or suspicious behavior
970     // in such constructs, not just overflow.
971     bool checkingForUndefinedBehavior() const override {
972       return CheckingForUndefinedBehavior;
973     }
974 
975     EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
976         : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
977           CallStackDepth(0), NextCallIndex(1),
978           StepsLeft(C.getLangOpts().ConstexprStepLimit),
979           EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
980           BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()),
981           EvaluatingDecl((const ValueDecl *)nullptr),
982           EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
983           HasFoldFailureDiagnostic(false), InConstantContext(false),
984           EvalMode(Mode) {}
985 
986     ~EvalInfo() {
987       discardCleanups();
988     }
989 
990     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
991                            EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
992       EvaluatingDecl = Base;
993       IsEvaluatingDecl = EDK;
994       EvaluatingDeclValue = &Value;
995     }
996 
997     bool CheckCallLimit(SourceLocation Loc) {
998       // Don't perform any constexpr calls (other than the call we're checking)
999       // when checking a potential constant expression.
1000       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
1001         return false;
1002       if (NextCallIndex == 0) {
1003         // NextCallIndex has wrapped around.
1004         FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
1005         return false;
1006       }
1007       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
1008         return true;
1009       FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
1010         << getLangOpts().ConstexprCallDepth;
1011       return false;
1012     }
1013 
1014     std::pair<CallStackFrame *, unsigned>
1015     getCallFrameAndDepth(unsigned CallIndex) {
1016       assert(CallIndex && "no call index in getCallFrameAndDepth");
1017       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1018       // be null in this loop.
1019       unsigned Depth = CallStackDepth;
1020       CallStackFrame *Frame = CurrentCall;
1021       while (Frame->Index > CallIndex) {
1022         Frame = Frame->Caller;
1023         --Depth;
1024       }
1025       if (Frame->Index == CallIndex)
1026         return {Frame, Depth};
1027       return {nullptr, 0};
1028     }
1029 
1030     bool nextStep(const Stmt *S) {
1031       if (!StepsLeft) {
1032         FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1033         return false;
1034       }
1035       --StepsLeft;
1036       return true;
1037     }
1038 
1039     APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1040 
1041     Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) {
1042       Optional<DynAlloc*> Result;
1043       auto It = HeapAllocs.find(DA);
1044       if (It != HeapAllocs.end())
1045         Result = &It->second;
1046       return Result;
1047     }
1048 
1049     /// Get the allocated storage for the given parameter of the given call.
1050     APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1051       CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1052       return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1053                    : nullptr;
1054     }
1055 
1056     /// Information about a stack frame for std::allocator<T>::[de]allocate.
1057     struct StdAllocatorCaller {
1058       unsigned FrameIndex;
1059       QualType ElemType;
1060       explicit operator bool() const { return FrameIndex != 0; };
1061     };
1062 
1063     StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1064       for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1065            Call = Call->Caller) {
1066         const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1067         if (!MD)
1068           continue;
1069         const IdentifierInfo *FnII = MD->getIdentifier();
1070         if (!FnII || !FnII->isStr(FnName))
1071           continue;
1072 
1073         const auto *CTSD =
1074             dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1075         if (!CTSD)
1076           continue;
1077 
1078         const IdentifierInfo *ClassII = CTSD->getIdentifier();
1079         const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1080         if (CTSD->isInStdNamespace() && ClassII &&
1081             ClassII->isStr("allocator") && TAL.size() >= 1 &&
1082             TAL[0].getKind() == TemplateArgument::Type)
1083           return {Call->Index, TAL[0].getAsType()};
1084       }
1085 
1086       return {};
1087     }
1088 
1089     void performLifetimeExtension() {
1090       // Disable the cleanups for lifetime-extended temporaries.
1091       CleanupStack.erase(std::remove_if(CleanupStack.begin(),
1092                                         CleanupStack.end(),
1093                                         [](Cleanup &C) {
1094                                           return !C.isDestroyedAtEndOf(
1095                                               ScopeKind::FullExpression);
1096                                         }),
1097                          CleanupStack.end());
1098      }
1099 
1100     /// Throw away any remaining cleanups at the end of evaluation. If any
1101     /// cleanups would have had a side-effect, note that as an unmodeled
1102     /// side-effect and return false. Otherwise, return true.
1103     bool discardCleanups() {
1104       for (Cleanup &C : CleanupStack) {
1105         if (C.hasSideEffect() && !noteSideEffect()) {
1106           CleanupStack.clear();
1107           return false;
1108         }
1109       }
1110       CleanupStack.clear();
1111       return true;
1112     }
1113 
1114   private:
1115     interp::Frame *getCurrentFrame() override { return CurrentCall; }
1116     const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1117 
1118     bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1119     void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1120 
1121     void setFoldFailureDiagnostic(bool Flag) override {
1122       HasFoldFailureDiagnostic = Flag;
1123     }
1124 
1125     Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1126 
1127     ASTContext &getCtx() const override { return Ctx; }
1128 
1129     // If we have a prior diagnostic, it will be noting that the expression
1130     // isn't a constant expression. This diagnostic is more important,
1131     // unless we require this evaluation to produce a constant expression.
1132     //
1133     // FIXME: We might want to show both diagnostics to the user in
1134     // EM_ConstantFold mode.
1135     bool hasPriorDiagnostic() override {
1136       if (!EvalStatus.Diag->empty()) {
1137         switch (EvalMode) {
1138         case EM_ConstantFold:
1139         case EM_IgnoreSideEffects:
1140           if (!HasFoldFailureDiagnostic)
1141             break;
1142           // We've already failed to fold something. Keep that diagnostic.
1143           LLVM_FALLTHROUGH;
1144         case EM_ConstantExpression:
1145         case EM_ConstantExpressionUnevaluated:
1146           setActiveDiagnostic(false);
1147           return true;
1148         }
1149       }
1150       return false;
1151     }
1152 
1153     unsigned getCallStackDepth() override { return CallStackDepth; }
1154 
1155   public:
1156     /// Should we continue evaluation after encountering a side-effect that we
1157     /// couldn't model?
1158     bool keepEvaluatingAfterSideEffect() {
1159       switch (EvalMode) {
1160       case EM_IgnoreSideEffects:
1161         return true;
1162 
1163       case EM_ConstantExpression:
1164       case EM_ConstantExpressionUnevaluated:
1165       case EM_ConstantFold:
1166         // By default, assume any side effect might be valid in some other
1167         // evaluation of this expression from a different context.
1168         return checkingPotentialConstantExpression() ||
1169                checkingForUndefinedBehavior();
1170       }
1171       llvm_unreachable("Missed EvalMode case");
1172     }
1173 
1174     /// Note that we have had a side-effect, and determine whether we should
1175     /// keep evaluating.
1176     bool noteSideEffect() {
1177       EvalStatus.HasSideEffects = true;
1178       return keepEvaluatingAfterSideEffect();
1179     }
1180 
1181     /// Should we continue evaluation after encountering undefined behavior?
1182     bool keepEvaluatingAfterUndefinedBehavior() {
1183       switch (EvalMode) {
1184       case EM_IgnoreSideEffects:
1185       case EM_ConstantFold:
1186         return true;
1187 
1188       case EM_ConstantExpression:
1189       case EM_ConstantExpressionUnevaluated:
1190         return checkingForUndefinedBehavior();
1191       }
1192       llvm_unreachable("Missed EvalMode case");
1193     }
1194 
1195     /// Note that we hit something that was technically undefined behavior, but
1196     /// that we can evaluate past it (such as signed overflow or floating-point
1197     /// division by zero.)
1198     bool noteUndefinedBehavior() override {
1199       EvalStatus.HasUndefinedBehavior = true;
1200       return keepEvaluatingAfterUndefinedBehavior();
1201     }
1202 
1203     /// Should we continue evaluation as much as possible after encountering a
1204     /// construct which can't be reduced to a value?
1205     bool keepEvaluatingAfterFailure() const override {
1206       if (!StepsLeft)
1207         return false;
1208 
1209       switch (EvalMode) {
1210       case EM_ConstantExpression:
1211       case EM_ConstantExpressionUnevaluated:
1212       case EM_ConstantFold:
1213       case EM_IgnoreSideEffects:
1214         return checkingPotentialConstantExpression() ||
1215                checkingForUndefinedBehavior();
1216       }
1217       llvm_unreachable("Missed EvalMode case");
1218     }
1219 
1220     /// Notes that we failed to evaluate an expression that other expressions
1221     /// directly depend on, and determine if we should keep evaluating. This
1222     /// should only be called if we actually intend to keep evaluating.
1223     ///
1224     /// Call noteSideEffect() instead if we may be able to ignore the value that
1225     /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1226     ///
1227     /// (Foo(), 1)      // use noteSideEffect
1228     /// (Foo() || true) // use noteSideEffect
1229     /// Foo() + 1       // use noteFailure
1230     LLVM_NODISCARD bool noteFailure() {
1231       // Failure when evaluating some expression often means there is some
1232       // subexpression whose evaluation was skipped. Therefore, (because we
1233       // don't track whether we skipped an expression when unwinding after an
1234       // evaluation failure) every evaluation failure that bubbles up from a
1235       // subexpression implies that a side-effect has potentially happened. We
1236       // skip setting the HasSideEffects flag to true until we decide to
1237       // continue evaluating after that point, which happens here.
1238       bool KeepGoing = keepEvaluatingAfterFailure();
1239       EvalStatus.HasSideEffects |= KeepGoing;
1240       return KeepGoing;
1241     }
1242 
1243     class ArrayInitLoopIndex {
1244       EvalInfo &Info;
1245       uint64_t OuterIndex;
1246 
1247     public:
1248       ArrayInitLoopIndex(EvalInfo &Info)
1249           : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1250         Info.ArrayInitIndex = 0;
1251       }
1252       ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1253 
1254       operator uint64_t&() { return Info.ArrayInitIndex; }
1255     };
1256   };
1257 
1258   /// Object used to treat all foldable expressions as constant expressions.
1259   struct FoldConstant {
1260     EvalInfo &Info;
1261     bool Enabled;
1262     bool HadNoPriorDiags;
1263     EvalInfo::EvaluationMode OldMode;
1264 
1265     explicit FoldConstant(EvalInfo &Info, bool Enabled)
1266       : Info(Info),
1267         Enabled(Enabled),
1268         HadNoPriorDiags(Info.EvalStatus.Diag &&
1269                         Info.EvalStatus.Diag->empty() &&
1270                         !Info.EvalStatus.HasSideEffects),
1271         OldMode(Info.EvalMode) {
1272       if (Enabled)
1273         Info.EvalMode = EvalInfo::EM_ConstantFold;
1274     }
1275     void keepDiagnostics() { Enabled = false; }
1276     ~FoldConstant() {
1277       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1278           !Info.EvalStatus.HasSideEffects)
1279         Info.EvalStatus.Diag->clear();
1280       Info.EvalMode = OldMode;
1281     }
1282   };
1283 
1284   /// RAII object used to set the current evaluation mode to ignore
1285   /// side-effects.
1286   struct IgnoreSideEffectsRAII {
1287     EvalInfo &Info;
1288     EvalInfo::EvaluationMode OldMode;
1289     explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1290         : Info(Info), OldMode(Info.EvalMode) {
1291       Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1292     }
1293 
1294     ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1295   };
1296 
1297   /// RAII object used to optionally suppress diagnostics and side-effects from
1298   /// a speculative evaluation.
1299   class SpeculativeEvaluationRAII {
1300     EvalInfo *Info = nullptr;
1301     Expr::EvalStatus OldStatus;
1302     unsigned OldSpeculativeEvaluationDepth;
1303 
1304     void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1305       Info = Other.Info;
1306       OldStatus = Other.OldStatus;
1307       OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1308       Other.Info = nullptr;
1309     }
1310 
1311     void maybeRestoreState() {
1312       if (!Info)
1313         return;
1314 
1315       Info->EvalStatus = OldStatus;
1316       Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1317     }
1318 
1319   public:
1320     SpeculativeEvaluationRAII() = default;
1321 
1322     SpeculativeEvaluationRAII(
1323         EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1324         : Info(&Info), OldStatus(Info.EvalStatus),
1325           OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1326       Info.EvalStatus.Diag = NewDiag;
1327       Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1328     }
1329 
1330     SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1331     SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1332       moveFromAndCancel(std::move(Other));
1333     }
1334 
1335     SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1336       maybeRestoreState();
1337       moveFromAndCancel(std::move(Other));
1338       return *this;
1339     }
1340 
1341     ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1342   };
1343 
1344   /// RAII object wrapping a full-expression or block scope, and handling
1345   /// the ending of the lifetime of temporaries created within it.
1346   template<ScopeKind Kind>
1347   class ScopeRAII {
1348     EvalInfo &Info;
1349     unsigned OldStackSize;
1350   public:
1351     ScopeRAII(EvalInfo &Info)
1352         : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1353       // Push a new temporary version. This is needed to distinguish between
1354       // temporaries created in different iterations of a loop.
1355       Info.CurrentCall->pushTempVersion();
1356     }
1357     bool destroy(bool RunDestructors = true) {
1358       bool OK = cleanup(Info, RunDestructors, OldStackSize);
1359       OldStackSize = -1U;
1360       return OK;
1361     }
1362     ~ScopeRAII() {
1363       if (OldStackSize != -1U)
1364         destroy(false);
1365       // Body moved to a static method to encourage the compiler to inline away
1366       // instances of this class.
1367       Info.CurrentCall->popTempVersion();
1368     }
1369   private:
1370     static bool cleanup(EvalInfo &Info, bool RunDestructors,
1371                         unsigned OldStackSize) {
1372       assert(OldStackSize <= Info.CleanupStack.size() &&
1373              "running cleanups out of order?");
1374 
1375       // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1376       // for a full-expression scope.
1377       bool Success = true;
1378       for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1379         if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1380           if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1381             Success = false;
1382             break;
1383           }
1384         }
1385       }
1386 
1387       // Compact any retained cleanups.
1388       auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1389       if (Kind != ScopeKind::Block)
1390         NewEnd =
1391             std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1392               return C.isDestroyedAtEndOf(Kind);
1393             });
1394       Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1395       return Success;
1396     }
1397   };
1398   typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1399   typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1400   typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1401 }
1402 
1403 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1404                                          CheckSubobjectKind CSK) {
1405   if (Invalid)
1406     return false;
1407   if (isOnePastTheEnd()) {
1408     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1409       << CSK;
1410     setInvalid();
1411     return false;
1412   }
1413   // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1414   // must actually be at least one array element; even a VLA cannot have a
1415   // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1416   return true;
1417 }
1418 
1419 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1420                                                                 const Expr *E) {
1421   Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1422   // Do not set the designator as invalid: we can represent this situation,
1423   // and correct handling of __builtin_object_size requires us to do so.
1424 }
1425 
1426 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1427                                                     const Expr *E,
1428                                                     const APSInt &N) {
1429   // If we're complaining, we must be able to statically determine the size of
1430   // the most derived array.
1431   if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1432     Info.CCEDiag(E, diag::note_constexpr_array_index)
1433       << N << /*array*/ 0
1434       << static_cast<unsigned>(getMostDerivedArraySize());
1435   else
1436     Info.CCEDiag(E, diag::note_constexpr_array_index)
1437       << N << /*non-array*/ 1;
1438   setInvalid();
1439 }
1440 
1441 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1442                                const FunctionDecl *Callee, const LValue *This,
1443                                CallRef Call)
1444     : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1445       Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1446   Info.CurrentCall = this;
1447   ++Info.CallStackDepth;
1448 }
1449 
1450 CallStackFrame::~CallStackFrame() {
1451   assert(Info.CurrentCall == this && "calls retired out of order");
1452   --Info.CallStackDepth;
1453   Info.CurrentCall = Caller;
1454 }
1455 
1456 static bool isRead(AccessKinds AK) {
1457   return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1458 }
1459 
1460 static bool isModification(AccessKinds AK) {
1461   switch (AK) {
1462   case AK_Read:
1463   case AK_ReadObjectRepresentation:
1464   case AK_MemberCall:
1465   case AK_DynamicCast:
1466   case AK_TypeId:
1467     return false;
1468   case AK_Assign:
1469   case AK_Increment:
1470   case AK_Decrement:
1471   case AK_Construct:
1472   case AK_Destroy:
1473     return true;
1474   }
1475   llvm_unreachable("unknown access kind");
1476 }
1477 
1478 static bool isAnyAccess(AccessKinds AK) {
1479   return isRead(AK) || isModification(AK);
1480 }
1481 
1482 /// Is this an access per the C++ definition?
1483 static bool isFormalAccess(AccessKinds AK) {
1484   return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
1485 }
1486 
1487 /// Is this kind of axcess valid on an indeterminate object value?
1488 static bool isValidIndeterminateAccess(AccessKinds AK) {
1489   switch (AK) {
1490   case AK_Read:
1491   case AK_Increment:
1492   case AK_Decrement:
1493     // These need the object's value.
1494     return false;
1495 
1496   case AK_ReadObjectRepresentation:
1497   case AK_Assign:
1498   case AK_Construct:
1499   case AK_Destroy:
1500     // Construction and destruction don't need the value.
1501     return true;
1502 
1503   case AK_MemberCall:
1504   case AK_DynamicCast:
1505   case AK_TypeId:
1506     // These aren't really meaningful on scalars.
1507     return true;
1508   }
1509   llvm_unreachable("unknown access kind");
1510 }
1511 
1512 namespace {
1513   struct ComplexValue {
1514   private:
1515     bool IsInt;
1516 
1517   public:
1518     APSInt IntReal, IntImag;
1519     APFloat FloatReal, FloatImag;
1520 
1521     ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1522 
1523     void makeComplexFloat() { IsInt = false; }
1524     bool isComplexFloat() const { return !IsInt; }
1525     APFloat &getComplexFloatReal() { return FloatReal; }
1526     APFloat &getComplexFloatImag() { return FloatImag; }
1527 
1528     void makeComplexInt() { IsInt = true; }
1529     bool isComplexInt() const { return IsInt; }
1530     APSInt &getComplexIntReal() { return IntReal; }
1531     APSInt &getComplexIntImag() { return IntImag; }
1532 
1533     void moveInto(APValue &v) const {
1534       if (isComplexFloat())
1535         v = APValue(FloatReal, FloatImag);
1536       else
1537         v = APValue(IntReal, IntImag);
1538     }
1539     void setFrom(const APValue &v) {
1540       assert(v.isComplexFloat() || v.isComplexInt());
1541       if (v.isComplexFloat()) {
1542         makeComplexFloat();
1543         FloatReal = v.getComplexFloatReal();
1544         FloatImag = v.getComplexFloatImag();
1545       } else {
1546         makeComplexInt();
1547         IntReal = v.getComplexIntReal();
1548         IntImag = v.getComplexIntImag();
1549       }
1550     }
1551   };
1552 
1553   struct LValue {
1554     APValue::LValueBase Base;
1555     CharUnits Offset;
1556     SubobjectDesignator Designator;
1557     bool IsNullPtr : 1;
1558     bool InvalidBase : 1;
1559 
1560     const APValue::LValueBase getLValueBase() const { return Base; }
1561     CharUnits &getLValueOffset() { return Offset; }
1562     const CharUnits &getLValueOffset() const { return Offset; }
1563     SubobjectDesignator &getLValueDesignator() { return Designator; }
1564     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1565     bool isNullPointer() const { return IsNullPtr;}
1566 
1567     unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1568     unsigned getLValueVersion() const { return Base.getVersion(); }
1569 
1570     void moveInto(APValue &V) const {
1571       if (Designator.Invalid)
1572         V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1573       else {
1574         assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1575         V = APValue(Base, Offset, Designator.Entries,
1576                     Designator.IsOnePastTheEnd, IsNullPtr);
1577       }
1578     }
1579     void setFrom(ASTContext &Ctx, const APValue &V) {
1580       assert(V.isLValue() && "Setting LValue from a non-LValue?");
1581       Base = V.getLValueBase();
1582       Offset = V.getLValueOffset();
1583       InvalidBase = false;
1584       Designator = SubobjectDesignator(Ctx, V);
1585       IsNullPtr = V.isNullPointer();
1586     }
1587 
1588     void set(APValue::LValueBase B, bool BInvalid = false) {
1589 #ifndef NDEBUG
1590       // We only allow a few types of invalid bases. Enforce that here.
1591       if (BInvalid) {
1592         const auto *E = B.get<const Expr *>();
1593         assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1594                "Unexpected type of invalid base");
1595       }
1596 #endif
1597 
1598       Base = B;
1599       Offset = CharUnits::fromQuantity(0);
1600       InvalidBase = BInvalid;
1601       Designator = SubobjectDesignator(getType(B));
1602       IsNullPtr = false;
1603     }
1604 
1605     void setNull(ASTContext &Ctx, QualType PointerTy) {
1606       Base = (Expr *)nullptr;
1607       Offset =
1608           CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
1609       InvalidBase = false;
1610       Designator = SubobjectDesignator(PointerTy->getPointeeType());
1611       IsNullPtr = true;
1612     }
1613 
1614     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1615       set(B, true);
1616     }
1617 
1618     std::string toString(ASTContext &Ctx, QualType T) const {
1619       APValue Printable;
1620       moveInto(Printable);
1621       return Printable.getAsString(Ctx, T);
1622     }
1623 
1624   private:
1625     // Check that this LValue is not based on a null pointer. If it is, produce
1626     // a diagnostic and mark the designator as invalid.
1627     template <typename GenDiagType>
1628     bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1629       if (Designator.Invalid)
1630         return false;
1631       if (IsNullPtr) {
1632         GenDiag();
1633         Designator.setInvalid();
1634         return false;
1635       }
1636       return true;
1637     }
1638 
1639   public:
1640     bool checkNullPointer(EvalInfo &Info, const Expr *E,
1641                           CheckSubobjectKind CSK) {
1642       return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1643         Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1644       });
1645     }
1646 
1647     bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1648                                        AccessKinds AK) {
1649       return checkNullPointerDiagnosingWith([&Info, E, AK] {
1650         Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1651       });
1652     }
1653 
1654     // Check this LValue refers to an object. If not, set the designator to be
1655     // invalid and emit a diagnostic.
1656     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1657       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1658              Designator.checkSubobject(Info, E, CSK);
1659     }
1660 
1661     void addDecl(EvalInfo &Info, const Expr *E,
1662                  const Decl *D, bool Virtual = false) {
1663       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1664         Designator.addDeclUnchecked(D, Virtual);
1665     }
1666     void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1667       if (!Designator.Entries.empty()) {
1668         Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1669         Designator.setInvalid();
1670         return;
1671       }
1672       if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1673         assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1674         Designator.FirstEntryIsAnUnsizedArray = true;
1675         Designator.addUnsizedArrayUnchecked(ElemTy);
1676       }
1677     }
1678     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1679       if (checkSubobject(Info, E, CSK_ArrayToPointer))
1680         Designator.addArrayUnchecked(CAT);
1681     }
1682     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1683       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1684         Designator.addComplexUnchecked(EltTy, Imag);
1685     }
1686     void clearIsNullPointer() {
1687       IsNullPtr = false;
1688     }
1689     void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1690                               const APSInt &Index, CharUnits ElementSize) {
1691       // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1692       // but we're not required to diagnose it and it's valid in C++.)
1693       if (!Index)
1694         return;
1695 
1696       // Compute the new offset in the appropriate width, wrapping at 64 bits.
1697       // FIXME: When compiling for a 32-bit target, we should use 32-bit
1698       // offsets.
1699       uint64_t Offset64 = Offset.getQuantity();
1700       uint64_t ElemSize64 = ElementSize.getQuantity();
1701       uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1702       Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1703 
1704       if (checkNullPointer(Info, E, CSK_ArrayIndex))
1705         Designator.adjustIndex(Info, E, Index);
1706       clearIsNullPointer();
1707     }
1708     void adjustOffset(CharUnits N) {
1709       Offset += N;
1710       if (N.getQuantity())
1711         clearIsNullPointer();
1712     }
1713   };
1714 
1715   struct MemberPtr {
1716     MemberPtr() {}
1717     explicit MemberPtr(const ValueDecl *Decl) :
1718       DeclAndIsDerivedMember(Decl, false), Path() {}
1719 
1720     /// The member or (direct or indirect) field referred to by this member
1721     /// pointer, or 0 if this is a null member pointer.
1722     const ValueDecl *getDecl() const {
1723       return DeclAndIsDerivedMember.getPointer();
1724     }
1725     /// Is this actually a member of some type derived from the relevant class?
1726     bool isDerivedMember() const {
1727       return DeclAndIsDerivedMember.getInt();
1728     }
1729     /// Get the class which the declaration actually lives in.
1730     const CXXRecordDecl *getContainingRecord() const {
1731       return cast<CXXRecordDecl>(
1732           DeclAndIsDerivedMember.getPointer()->getDeclContext());
1733     }
1734 
1735     void moveInto(APValue &V) const {
1736       V = APValue(getDecl(), isDerivedMember(), Path);
1737     }
1738     void setFrom(const APValue &V) {
1739       assert(V.isMemberPointer());
1740       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1741       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1742       Path.clear();
1743       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1744       Path.insert(Path.end(), P.begin(), P.end());
1745     }
1746 
1747     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1748     /// whether the member is a member of some class derived from the class type
1749     /// of the member pointer.
1750     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1751     /// Path - The path of base/derived classes from the member declaration's
1752     /// class (exclusive) to the class type of the member pointer (inclusive).
1753     SmallVector<const CXXRecordDecl*, 4> Path;
1754 
1755     /// Perform a cast towards the class of the Decl (either up or down the
1756     /// hierarchy).
1757     bool castBack(const CXXRecordDecl *Class) {
1758       assert(!Path.empty());
1759       const CXXRecordDecl *Expected;
1760       if (Path.size() >= 2)
1761         Expected = Path[Path.size() - 2];
1762       else
1763         Expected = getContainingRecord();
1764       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1765         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1766         // if B does not contain the original member and is not a base or
1767         // derived class of the class containing the original member, the result
1768         // of the cast is undefined.
1769         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1770         // (D::*). We consider that to be a language defect.
1771         return false;
1772       }
1773       Path.pop_back();
1774       return true;
1775     }
1776     /// Perform a base-to-derived member pointer cast.
1777     bool castToDerived(const CXXRecordDecl *Derived) {
1778       if (!getDecl())
1779         return true;
1780       if (!isDerivedMember()) {
1781         Path.push_back(Derived);
1782         return true;
1783       }
1784       if (!castBack(Derived))
1785         return false;
1786       if (Path.empty())
1787         DeclAndIsDerivedMember.setInt(false);
1788       return true;
1789     }
1790     /// Perform a derived-to-base member pointer cast.
1791     bool castToBase(const CXXRecordDecl *Base) {
1792       if (!getDecl())
1793         return true;
1794       if (Path.empty())
1795         DeclAndIsDerivedMember.setInt(true);
1796       if (isDerivedMember()) {
1797         Path.push_back(Base);
1798         return true;
1799       }
1800       return castBack(Base);
1801     }
1802   };
1803 
1804   /// Compare two member pointers, which are assumed to be of the same type.
1805   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1806     if (!LHS.getDecl() || !RHS.getDecl())
1807       return !LHS.getDecl() && !RHS.getDecl();
1808     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1809       return false;
1810     return LHS.Path == RHS.Path;
1811   }
1812 }
1813 
1814 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1815 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1816                             const LValue &This, const Expr *E,
1817                             bool AllowNonLiteralTypes = false);
1818 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1819                            bool InvalidBaseOK = false);
1820 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1821                             bool InvalidBaseOK = false);
1822 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1823                                   EvalInfo &Info);
1824 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1825 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1826 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1827                                     EvalInfo &Info);
1828 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1829 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1830 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1831                            EvalInfo &Info);
1832 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1833 
1834 /// Evaluate an integer or fixed point expression into an APResult.
1835 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1836                                         EvalInfo &Info);
1837 
1838 /// Evaluate only a fixed point expression into an APResult.
1839 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1840                                EvalInfo &Info);
1841 
1842 //===----------------------------------------------------------------------===//
1843 // Misc utilities
1844 //===----------------------------------------------------------------------===//
1845 
1846 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1847 /// preserving its value (by extending by up to one bit as needed).
1848 static void negateAsSigned(APSInt &Int) {
1849   if (Int.isUnsigned() || Int.isMinSignedValue()) {
1850     Int = Int.extend(Int.getBitWidth() + 1);
1851     Int.setIsSigned(true);
1852   }
1853   Int = -Int;
1854 }
1855 
1856 template<typename KeyT>
1857 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1858                                          ScopeKind Scope, LValue &LV) {
1859   unsigned Version = getTempVersion();
1860   APValue::LValueBase Base(Key, Index, Version);
1861   LV.set(Base);
1862   return createLocal(Base, Key, T, Scope);
1863 }
1864 
1865 /// Allocate storage for a parameter of a function call made in this frame.
1866 APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1867                                      LValue &LV) {
1868   assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1869   APValue::LValueBase Base(PVD, Index, Args.Version);
1870   LV.set(Base);
1871   // We always destroy parameters at the end of the call, even if we'd allow
1872   // them to live to the end of the full-expression at runtime, in order to
1873   // give portable results and match other compilers.
1874   return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1875 }
1876 
1877 APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1878                                      QualType T, ScopeKind Scope) {
1879   assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1880   unsigned Version = Base.getVersion();
1881   APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1882   assert(Result.isAbsent() && "local created multiple times");
1883 
1884   // If we're creating a local immediately in the operand of a speculative
1885   // evaluation, don't register a cleanup to be run outside the speculative
1886   // evaluation context, since we won't actually be able to initialize this
1887   // object.
1888   if (Index <= Info.SpeculativeEvaluationDepth) {
1889     if (T.isDestructedType())
1890       Info.noteSideEffect();
1891   } else {
1892     Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1893   }
1894   return Result;
1895 }
1896 
1897 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1898   if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1899     FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1900     return nullptr;
1901   }
1902 
1903   DynamicAllocLValue DA(NumHeapAllocs++);
1904   LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1905   auto Result = HeapAllocs.emplace(std::piecewise_construct,
1906                                    std::forward_as_tuple(DA), std::tuple<>());
1907   assert(Result.second && "reused a heap alloc index?");
1908   Result.first->second.AllocExpr = E;
1909   return &Result.first->second.Value;
1910 }
1911 
1912 /// Produce a string describing the given constexpr call.
1913 void CallStackFrame::describe(raw_ostream &Out) {
1914   unsigned ArgIndex = 0;
1915   bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1916                       !isa<CXXConstructorDecl>(Callee) &&
1917                       cast<CXXMethodDecl>(Callee)->isInstance();
1918 
1919   if (!IsMemberCall)
1920     Out << *Callee << '(';
1921 
1922   if (This && IsMemberCall) {
1923     APValue Val;
1924     This->moveInto(Val);
1925     Val.printPretty(Out, Info.Ctx,
1926                     This->Designator.MostDerivedType);
1927     // FIXME: Add parens around Val if needed.
1928     Out << "->" << *Callee << '(';
1929     IsMemberCall = false;
1930   }
1931 
1932   for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1933        E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
1934     if (ArgIndex > (unsigned)IsMemberCall)
1935       Out << ", ";
1936 
1937     const ParmVarDecl *Param = *I;
1938     APValue *V = Info.getParamSlot(Arguments, Param);
1939     if (V)
1940       V->printPretty(Out, Info.Ctx, Param->getType());
1941     else
1942       Out << "<...>";
1943 
1944     if (ArgIndex == 0 && IsMemberCall)
1945       Out << "->" << *Callee << '(';
1946   }
1947 
1948   Out << ')';
1949 }
1950 
1951 /// Evaluate an expression to see if it had side-effects, and discard its
1952 /// result.
1953 /// \return \c true if the caller should keep evaluating.
1954 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1955   APValue Scratch;
1956   if (!Evaluate(Scratch, Info, E))
1957     // We don't need the value, but we might have skipped a side effect here.
1958     return Info.noteSideEffect();
1959   return true;
1960 }
1961 
1962 /// Should this call expression be treated as a string literal?
1963 static bool IsStringLiteralCall(const CallExpr *E) {
1964   unsigned Builtin = E->getBuiltinCallee();
1965   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1966           Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1967 }
1968 
1969 static bool IsGlobalLValue(APValue::LValueBase B) {
1970   // C++11 [expr.const]p3 An address constant expression is a prvalue core
1971   // constant expression of pointer type that evaluates to...
1972 
1973   // ... a null pointer value, or a prvalue core constant expression of type
1974   // std::nullptr_t.
1975   if (!B) return true;
1976 
1977   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1978     // ... the address of an object with static storage duration,
1979     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1980       return VD->hasGlobalStorage();
1981     // ... the address of a function,
1982     // ... the address of a GUID [MS extension],
1983     return isa<FunctionDecl>(D) || isa<MSGuidDecl>(D);
1984   }
1985 
1986   if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
1987     return true;
1988 
1989   const Expr *E = B.get<const Expr*>();
1990   switch (E->getStmtClass()) {
1991   default:
1992     return false;
1993   case Expr::CompoundLiteralExprClass: {
1994     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1995     return CLE->isFileScope() && CLE->isLValue();
1996   }
1997   case Expr::MaterializeTemporaryExprClass:
1998     // A materialized temporary might have been lifetime-extended to static
1999     // storage duration.
2000     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
2001   // A string literal has static storage duration.
2002   case Expr::StringLiteralClass:
2003   case Expr::PredefinedExprClass:
2004   case Expr::ObjCStringLiteralClass:
2005   case Expr::ObjCEncodeExprClass:
2006     return true;
2007   case Expr::ObjCBoxedExprClass:
2008     return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2009   case Expr::CallExprClass:
2010     return IsStringLiteralCall(cast<CallExpr>(E));
2011   // For GCC compatibility, &&label has static storage duration.
2012   case Expr::AddrLabelExprClass:
2013     return true;
2014   // A Block literal expression may be used as the initialization value for
2015   // Block variables at global or local static scope.
2016   case Expr::BlockExprClass:
2017     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2018   case Expr::ImplicitValueInitExprClass:
2019     // FIXME:
2020     // We can never form an lvalue with an implicit value initialization as its
2021     // base through expression evaluation, so these only appear in one case: the
2022     // implicit variable declaration we invent when checking whether a constexpr
2023     // constructor can produce a constant expression. We must assume that such
2024     // an expression might be a global lvalue.
2025     return true;
2026   }
2027 }
2028 
2029 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2030   return LVal.Base.dyn_cast<const ValueDecl*>();
2031 }
2032 
2033 static bool IsLiteralLValue(const LValue &Value) {
2034   if (Value.getLValueCallIndex())
2035     return false;
2036   const Expr *E = Value.Base.dyn_cast<const Expr*>();
2037   return E && !isa<MaterializeTemporaryExpr>(E);
2038 }
2039 
2040 static bool IsWeakLValue(const LValue &Value) {
2041   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2042   return Decl && Decl->isWeak();
2043 }
2044 
2045 static bool isZeroSized(const LValue &Value) {
2046   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2047   if (Decl && isa<VarDecl>(Decl)) {
2048     QualType Ty = Decl->getType();
2049     if (Ty->isArrayType())
2050       return Ty->isIncompleteType() ||
2051              Decl->getASTContext().getTypeSize(Ty) == 0;
2052   }
2053   return false;
2054 }
2055 
2056 static bool HasSameBase(const LValue &A, const LValue &B) {
2057   if (!A.getLValueBase())
2058     return !B.getLValueBase();
2059   if (!B.getLValueBase())
2060     return false;
2061 
2062   if (A.getLValueBase().getOpaqueValue() !=
2063       B.getLValueBase().getOpaqueValue())
2064     return false;
2065 
2066   return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2067          A.getLValueVersion() == B.getLValueVersion();
2068 }
2069 
2070 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2071   assert(Base && "no location for a null lvalue");
2072   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2073 
2074   // For a parameter, find the corresponding call stack frame (if it still
2075   // exists), and point at the parameter of the function definition we actually
2076   // invoked.
2077   if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2078     unsigned Idx = PVD->getFunctionScopeIndex();
2079     for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2080       if (F->Arguments.CallIndex == Base.getCallIndex() &&
2081           F->Arguments.Version == Base.getVersion() && F->Callee &&
2082           Idx < F->Callee->getNumParams()) {
2083         VD = F->Callee->getParamDecl(Idx);
2084         break;
2085       }
2086     }
2087   }
2088 
2089   if (VD)
2090     Info.Note(VD->getLocation(), diag::note_declared_at);
2091   else if (const Expr *E = Base.dyn_cast<const Expr*>())
2092     Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2093   else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2094     // FIXME: Produce a note for dangling pointers too.
2095     if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA))
2096       Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2097                 diag::note_constexpr_dynamic_alloc_here);
2098   }
2099   // We have no information to show for a typeid(T) object.
2100 }
2101 
2102 enum class CheckEvaluationResultKind {
2103   ConstantExpression,
2104   FullyInitialized,
2105 };
2106 
2107 /// Materialized temporaries that we've already checked to determine if they're
2108 /// initializsed by a constant expression.
2109 using CheckedTemporaries =
2110     llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
2111 
2112 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2113                                   EvalInfo &Info, SourceLocation DiagLoc,
2114                                   QualType Type, const APValue &Value,
2115                                   Expr::ConstExprUsage Usage,
2116                                   SourceLocation SubobjectLoc,
2117                                   CheckedTemporaries &CheckedTemps);
2118 
2119 /// Check that this reference or pointer core constant expression is a valid
2120 /// value for an address or reference constant expression. Return true if we
2121 /// can fold this expression, whether or not it's a constant expression.
2122 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2123                                           QualType Type, const LValue &LVal,
2124                                           Expr::ConstExprUsage Usage,
2125                                           CheckedTemporaries &CheckedTemps) {
2126   bool IsReferenceType = Type->isReferenceType();
2127 
2128   APValue::LValueBase Base = LVal.getLValueBase();
2129   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2130 
2131   if (auto *VD = LVal.getLValueBase().dyn_cast<const ValueDecl *>()) {
2132     if (auto *FD = dyn_cast<FunctionDecl>(VD)) {
2133       if (FD->isConsteval()) {
2134         Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2135             << !Type->isAnyPointerType();
2136         Info.Note(FD->getLocation(), diag::note_declared_at);
2137         return false;
2138       }
2139     }
2140   }
2141 
2142   // Check that the object is a global. Note that the fake 'this' object we
2143   // manufacture when checking potential constant expressions is conservatively
2144   // assumed to be global here.
2145   if (!IsGlobalLValue(Base)) {
2146     if (Info.getLangOpts().CPlusPlus11) {
2147       const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2148       Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2149         << IsReferenceType << !Designator.Entries.empty()
2150         << !!VD << VD;
2151 
2152       auto *VarD = dyn_cast_or_null<VarDecl>(VD);
2153       if (VarD && VarD->isConstexpr()) {
2154         // Non-static local constexpr variables have unintuitive semantics:
2155         //   constexpr int a = 1;
2156         //   constexpr const int *p = &a;
2157         // ... is invalid because the address of 'a' is not constant. Suggest
2158         // adding a 'static' in this case.
2159         Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2160             << VarD
2161             << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2162       } else {
2163         NoteLValueLocation(Info, Base);
2164       }
2165     } else {
2166       Info.FFDiag(Loc);
2167     }
2168     // Don't allow references to temporaries to escape.
2169     return false;
2170   }
2171   assert((Info.checkingPotentialConstantExpression() ||
2172           LVal.getLValueCallIndex() == 0) &&
2173          "have call index for global lvalue");
2174 
2175   if (Base.is<DynamicAllocLValue>()) {
2176     Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2177         << IsReferenceType << !Designator.Entries.empty();
2178     NoteLValueLocation(Info, Base);
2179     return false;
2180   }
2181 
2182   if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
2183     if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
2184       // Check if this is a thread-local variable.
2185       if (Var->getTLSKind())
2186         // FIXME: Diagnostic!
2187         return false;
2188 
2189       // A dllimport variable never acts like a constant.
2190       if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
2191         // FIXME: Diagnostic!
2192         return false;
2193     }
2194     if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
2195       // __declspec(dllimport) must be handled very carefully:
2196       // We must never initialize an expression with the thunk in C++.
2197       // Doing otherwise would allow the same id-expression to yield
2198       // different addresses for the same function in different translation
2199       // units.  However, this means that we must dynamically initialize the
2200       // expression with the contents of the import address table at runtime.
2201       //
2202       // The C language has no notion of ODR; furthermore, it has no notion of
2203       // dynamic initialization.  This means that we are permitted to
2204       // perform initialization with the address of the thunk.
2205       if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
2206           FD->hasAttr<DLLImportAttr>())
2207         // FIXME: Diagnostic!
2208         return false;
2209     }
2210   } else if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(
2211                  Base.dyn_cast<const Expr *>())) {
2212     if (CheckedTemps.insert(MTE).second) {
2213       QualType TempType = getType(Base);
2214       if (TempType.isDestructedType()) {
2215         Info.FFDiag(MTE->getExprLoc(),
2216                     diag::note_constexpr_unsupported_tempoarary_nontrivial_dtor)
2217             << TempType;
2218         return false;
2219       }
2220 
2221       APValue *V = MTE->getOrCreateValue(false);
2222       assert(V && "evasluation result refers to uninitialised temporary");
2223       if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2224                                  Info, MTE->getExprLoc(), TempType, *V,
2225                                  Usage, SourceLocation(), CheckedTemps))
2226         return false;
2227     }
2228   }
2229 
2230   // Allow address constant expressions to be past-the-end pointers. This is
2231   // an extension: the standard requires them to point to an object.
2232   if (!IsReferenceType)
2233     return true;
2234 
2235   // A reference constant expression must refer to an object.
2236   if (!Base) {
2237     // FIXME: diagnostic
2238     Info.CCEDiag(Loc);
2239     return true;
2240   }
2241 
2242   // Does this refer one past the end of some object?
2243   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2244     const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2245     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2246       << !Designator.Entries.empty() << !!VD << VD;
2247     NoteLValueLocation(Info, Base);
2248   }
2249 
2250   return true;
2251 }
2252 
2253 /// Member pointers are constant expressions unless they point to a
2254 /// non-virtual dllimport member function.
2255 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2256                                                  SourceLocation Loc,
2257                                                  QualType Type,
2258                                                  const APValue &Value,
2259                                                  Expr::ConstExprUsage Usage) {
2260   const ValueDecl *Member = Value.getMemberPointerDecl();
2261   const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2262   if (!FD)
2263     return true;
2264   if (FD->isConsteval()) {
2265     Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2266     Info.Note(FD->getLocation(), diag::note_declared_at);
2267     return false;
2268   }
2269   return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
2270          !FD->hasAttr<DLLImportAttr>();
2271 }
2272 
2273 /// Check that this core constant expression is of literal type, and if not,
2274 /// produce an appropriate diagnostic.
2275 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2276                              const LValue *This = nullptr) {
2277   if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
2278     return true;
2279 
2280   // C++1y: A constant initializer for an object o [...] may also invoke
2281   // constexpr constructors for o and its subobjects even if those objects
2282   // are of non-literal class types.
2283   //
2284   // C++11 missed this detail for aggregates, so classes like this:
2285   //   struct foo_t { union { int i; volatile int j; } u; };
2286   // are not (obviously) initializable like so:
2287   //   __attribute__((__require_constant_initialization__))
2288   //   static const foo_t x = {{0}};
2289   // because "i" is a subobject with non-literal initialization (due to the
2290   // volatile member of the union). See:
2291   //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2292   // Therefore, we use the C++1y behavior.
2293   if (This && Info.EvaluatingDecl == This->getLValueBase())
2294     return true;
2295 
2296   // Prvalue constant expressions must be of literal types.
2297   if (Info.getLangOpts().CPlusPlus11)
2298     Info.FFDiag(E, diag::note_constexpr_nonliteral)
2299       << E->getType();
2300   else
2301     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2302   return false;
2303 }
2304 
2305 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2306                                   EvalInfo &Info, SourceLocation DiagLoc,
2307                                   QualType Type, const APValue &Value,
2308                                   Expr::ConstExprUsage Usage,
2309                                   SourceLocation SubobjectLoc,
2310                                   CheckedTemporaries &CheckedTemps) {
2311   if (!Value.hasValue()) {
2312     Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2313       << true << Type;
2314     if (SubobjectLoc.isValid())
2315       Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2316     return false;
2317   }
2318 
2319   // We allow _Atomic(T) to be initialized from anything that T can be
2320   // initialized from.
2321   if (const AtomicType *AT = Type->getAs<AtomicType>())
2322     Type = AT->getValueType();
2323 
2324   // Core issue 1454: For a literal constant expression of array or class type,
2325   // each subobject of its value shall have been initialized by a constant
2326   // expression.
2327   if (Value.isArray()) {
2328     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2329     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2330       if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2331                                  Value.getArrayInitializedElt(I), Usage,
2332                                  SubobjectLoc, CheckedTemps))
2333         return false;
2334     }
2335     if (!Value.hasArrayFiller())
2336       return true;
2337     return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2338                                  Value.getArrayFiller(), Usage, SubobjectLoc,
2339                                  CheckedTemps);
2340   }
2341   if (Value.isUnion() && Value.getUnionField()) {
2342     return CheckEvaluationResult(
2343         CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2344         Value.getUnionValue(), Usage, Value.getUnionField()->getLocation(),
2345         CheckedTemps);
2346   }
2347   if (Value.isStruct()) {
2348     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2349     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2350       unsigned BaseIndex = 0;
2351       for (const CXXBaseSpecifier &BS : CD->bases()) {
2352         if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2353                                    Value.getStructBase(BaseIndex), Usage,
2354                                    BS.getBeginLoc(), CheckedTemps))
2355           return false;
2356         ++BaseIndex;
2357       }
2358     }
2359     for (const auto *I : RD->fields()) {
2360       if (I->isUnnamedBitfield())
2361         continue;
2362 
2363       if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2364                                  Value.getStructField(I->getFieldIndex()),
2365                                  Usage, I->getLocation(), CheckedTemps))
2366         return false;
2367     }
2368   }
2369 
2370   if (Value.isLValue() &&
2371       CERK == CheckEvaluationResultKind::ConstantExpression) {
2372     LValue LVal;
2373     LVal.setFrom(Info.Ctx, Value);
2374     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage,
2375                                          CheckedTemps);
2376   }
2377 
2378   if (Value.isMemberPointer() &&
2379       CERK == CheckEvaluationResultKind::ConstantExpression)
2380     return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
2381 
2382   // Everything else is fine.
2383   return true;
2384 }
2385 
2386 /// Check that this core constant expression value is a valid value for a
2387 /// constant expression. If not, report an appropriate diagnostic. Does not
2388 /// check that the expression is of literal type.
2389 static bool
2390 CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
2391                         const APValue &Value,
2392                         Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
2393   // Nothing to check for a constant expression of type 'cv void'.
2394   if (Type->isVoidType())
2395     return true;
2396 
2397   CheckedTemporaries CheckedTemps;
2398   return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2399                                Info, DiagLoc, Type, Value, Usage,
2400                                SourceLocation(), CheckedTemps);
2401 }
2402 
2403 /// Check that this evaluated value is fully-initialized and can be loaded by
2404 /// an lvalue-to-rvalue conversion.
2405 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2406                                   QualType Type, const APValue &Value) {
2407   CheckedTemporaries CheckedTemps;
2408   return CheckEvaluationResult(
2409       CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2410       Expr::EvaluateForCodeGen, SourceLocation(), CheckedTemps);
2411 }
2412 
2413 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2414 /// "the allocated storage is deallocated within the evaluation".
2415 static bool CheckMemoryLeaks(EvalInfo &Info) {
2416   if (!Info.HeapAllocs.empty()) {
2417     // We can still fold to a constant despite a compile-time memory leak,
2418     // so long as the heap allocation isn't referenced in the result (we check
2419     // that in CheckConstantExpression).
2420     Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2421                  diag::note_constexpr_memory_leak)
2422         << unsigned(Info.HeapAllocs.size() - 1);
2423   }
2424   return true;
2425 }
2426 
2427 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2428   // A null base expression indicates a null pointer.  These are always
2429   // evaluatable, and they are false unless the offset is zero.
2430   if (!Value.getLValueBase()) {
2431     Result = !Value.getLValueOffset().isZero();
2432     return true;
2433   }
2434 
2435   // We have a non-null base.  These are generally known to be true, but if it's
2436   // a weak declaration it can be null at runtime.
2437   Result = true;
2438   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2439   return !Decl || !Decl->isWeak();
2440 }
2441 
2442 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2443   switch (Val.getKind()) {
2444   case APValue::None:
2445   case APValue::Indeterminate:
2446     return false;
2447   case APValue::Int:
2448     Result = Val.getInt().getBoolValue();
2449     return true;
2450   case APValue::FixedPoint:
2451     Result = Val.getFixedPoint().getBoolValue();
2452     return true;
2453   case APValue::Float:
2454     Result = !Val.getFloat().isZero();
2455     return true;
2456   case APValue::ComplexInt:
2457     Result = Val.getComplexIntReal().getBoolValue() ||
2458              Val.getComplexIntImag().getBoolValue();
2459     return true;
2460   case APValue::ComplexFloat:
2461     Result = !Val.getComplexFloatReal().isZero() ||
2462              !Val.getComplexFloatImag().isZero();
2463     return true;
2464   case APValue::LValue:
2465     return EvalPointerValueAsBool(Val, Result);
2466   case APValue::MemberPointer:
2467     Result = Val.getMemberPointerDecl();
2468     return true;
2469   case APValue::Vector:
2470   case APValue::Array:
2471   case APValue::Struct:
2472   case APValue::Union:
2473   case APValue::AddrLabelDiff:
2474     return false;
2475   }
2476 
2477   llvm_unreachable("unknown APValue kind");
2478 }
2479 
2480 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2481                                        EvalInfo &Info) {
2482   assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
2483   APValue Val;
2484   if (!Evaluate(Val, Info, E))
2485     return false;
2486   return HandleConversionToBool(Val, Result);
2487 }
2488 
2489 template<typename T>
2490 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2491                            const T &SrcValue, QualType DestType) {
2492   Info.CCEDiag(E, diag::note_constexpr_overflow)
2493     << SrcValue << DestType;
2494   return Info.noteUndefinedBehavior();
2495 }
2496 
2497 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2498                                  QualType SrcType, const APFloat &Value,
2499                                  QualType DestType, APSInt &Result) {
2500   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2501   // Determine whether we are converting to unsigned or signed.
2502   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2503 
2504   Result = APSInt(DestWidth, !DestSigned);
2505   bool ignored;
2506   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2507       & APFloat::opInvalidOp)
2508     return HandleOverflow(Info, E, Value, DestType);
2509   return true;
2510 }
2511 
2512 /// Get rounding mode used for evaluation of the specified expression.
2513 /// \param[out] DynamicRM Is set to true is the requested rounding mode is
2514 ///                       dynamic.
2515 /// If rounding mode is unknown at compile time, still try to evaluate the
2516 /// expression. If the result is exact, it does not depend on rounding mode.
2517 /// So return "tonearest" mode instead of "dynamic".
2518 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E,
2519                                                 bool &DynamicRM) {
2520   llvm::RoundingMode RM =
2521       E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2522   DynamicRM = (RM == llvm::RoundingMode::Dynamic);
2523   if (DynamicRM)
2524     RM = llvm::RoundingMode::NearestTiesToEven;
2525   return RM;
2526 }
2527 
2528 /// Check if the given evaluation result is allowed for constant evaluation.
2529 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2530                                      APFloat::opStatus St) {
2531   // In a constant context, assume that any dynamic rounding mode or FP
2532   // exception state matches the default floating-point environment.
2533   if (Info.InConstantContext)
2534     return true;
2535 
2536   FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2537   if ((St & APFloat::opInexact) &&
2538       FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2539     // Inexact result means that it depends on rounding mode. If the requested
2540     // mode is dynamic, the evaluation cannot be made in compile time.
2541     Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2542     return false;
2543   }
2544 
2545   if ((St & APFloat::opStatus::opInvalidOp) &&
2546       FPO.getFPExceptionMode() != LangOptions::FPE_Ignore) {
2547     // There is no usefully definable result.
2548     Info.FFDiag(E);
2549     return false;
2550   }
2551 
2552   // FIXME: if:
2553   // - evaluation triggered other FP exception, and
2554   // - exception mode is not "ignore", and
2555   // - the expression being evaluated is not a part of global variable
2556   //   initializer,
2557   // the evaluation probably need to be rejected.
2558   return true;
2559 }
2560 
2561 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2562                                    QualType SrcType, QualType DestType,
2563                                    APFloat &Result) {
2564   assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E));
2565   bool DynamicRM;
2566   llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM);
2567   APFloat::opStatus St;
2568   APFloat Value = Result;
2569   bool ignored;
2570   St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2571   return checkFloatingPointResult(Info, E, St);
2572 }
2573 
2574 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2575                                  QualType DestType, QualType SrcType,
2576                                  const APSInt &Value) {
2577   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2578   // Figure out if this is a truncate, extend or noop cast.
2579   // If the input is signed, do a sign extend, noop, or truncate.
2580   APSInt Result = Value.extOrTrunc(DestWidth);
2581   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2582   if (DestType->isBooleanType())
2583     Result = Value.getBoolValue();
2584   return Result;
2585 }
2586 
2587 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2588                                  QualType SrcType, const APSInt &Value,
2589                                  QualType DestType, APFloat &Result) {
2590   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2591   Result.convertFromAPInt(Value, Value.isSigned(),
2592                           APFloat::rmNearestTiesToEven);
2593   return true;
2594 }
2595 
2596 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2597                                   APValue &Value, const FieldDecl *FD) {
2598   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2599 
2600   if (!Value.isInt()) {
2601     // Trying to store a pointer-cast-to-integer into a bitfield.
2602     // FIXME: In this case, we should provide the diagnostic for casting
2603     // a pointer to an integer.
2604     assert(Value.isLValue() && "integral value neither int nor lvalue?");
2605     Info.FFDiag(E);
2606     return false;
2607   }
2608 
2609   APSInt &Int = Value.getInt();
2610   unsigned OldBitWidth = Int.getBitWidth();
2611   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2612   if (NewBitWidth < OldBitWidth)
2613     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2614   return true;
2615 }
2616 
2617 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2618                                   llvm::APInt &Res) {
2619   APValue SVal;
2620   if (!Evaluate(SVal, Info, E))
2621     return false;
2622   if (SVal.isInt()) {
2623     Res = SVal.getInt();
2624     return true;
2625   }
2626   if (SVal.isFloat()) {
2627     Res = SVal.getFloat().bitcastToAPInt();
2628     return true;
2629   }
2630   if (SVal.isVector()) {
2631     QualType VecTy = E->getType();
2632     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2633     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2634     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2635     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2636     Res = llvm::APInt::getNullValue(VecSize);
2637     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2638       APValue &Elt = SVal.getVectorElt(i);
2639       llvm::APInt EltAsInt;
2640       if (Elt.isInt()) {
2641         EltAsInt = Elt.getInt();
2642       } else if (Elt.isFloat()) {
2643         EltAsInt = Elt.getFloat().bitcastToAPInt();
2644       } else {
2645         // Don't try to handle vectors of anything other than int or float
2646         // (not sure if it's possible to hit this case).
2647         Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2648         return false;
2649       }
2650       unsigned BaseEltSize = EltAsInt.getBitWidth();
2651       if (BigEndian)
2652         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2653       else
2654         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2655     }
2656     return true;
2657   }
2658   // Give up if the input isn't an int, float, or vector.  For example, we
2659   // reject "(v4i16)(intptr_t)&a".
2660   Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2661   return false;
2662 }
2663 
2664 /// Perform the given integer operation, which is known to need at most BitWidth
2665 /// bits, and check for overflow in the original type (if that type was not an
2666 /// unsigned type).
2667 template<typename Operation>
2668 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2669                                  const APSInt &LHS, const APSInt &RHS,
2670                                  unsigned BitWidth, Operation Op,
2671                                  APSInt &Result) {
2672   if (LHS.isUnsigned()) {
2673     Result = Op(LHS, RHS);
2674     return true;
2675   }
2676 
2677   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2678   Result = Value.trunc(LHS.getBitWidth());
2679   if (Result.extend(BitWidth) != Value) {
2680     if (Info.checkingForUndefinedBehavior())
2681       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2682                                        diag::warn_integer_constant_overflow)
2683           << Result.toString(10) << E->getType();
2684     else
2685       return HandleOverflow(Info, E, Value, E->getType());
2686   }
2687   return true;
2688 }
2689 
2690 /// Perform the given binary integer operation.
2691 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2692                               BinaryOperatorKind Opcode, APSInt RHS,
2693                               APSInt &Result) {
2694   switch (Opcode) {
2695   default:
2696     Info.FFDiag(E);
2697     return false;
2698   case BO_Mul:
2699     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2700                                 std::multiplies<APSInt>(), Result);
2701   case BO_Add:
2702     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2703                                 std::plus<APSInt>(), Result);
2704   case BO_Sub:
2705     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2706                                 std::minus<APSInt>(), Result);
2707   case BO_And: Result = LHS & RHS; return true;
2708   case BO_Xor: Result = LHS ^ RHS; return true;
2709   case BO_Or:  Result = LHS | RHS; return true;
2710   case BO_Div:
2711   case BO_Rem:
2712     if (RHS == 0) {
2713       Info.FFDiag(E, diag::note_expr_divide_by_zero);
2714       return false;
2715     }
2716     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2717     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2718     // this operation and gives the two's complement result.
2719     if (RHS.isNegative() && RHS.isAllOnesValue() &&
2720         LHS.isSigned() && LHS.isMinSignedValue())
2721       return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2722                             E->getType());
2723     return true;
2724   case BO_Shl: {
2725     if (Info.getLangOpts().OpenCL)
2726       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2727       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2728                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2729                     RHS.isUnsigned());
2730     else if (RHS.isSigned() && RHS.isNegative()) {
2731       // During constant-folding, a negative shift is an opposite shift. Such
2732       // a shift is not a constant expression.
2733       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2734       RHS = -RHS;
2735       goto shift_right;
2736     }
2737   shift_left:
2738     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2739     // the shifted type.
2740     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2741     if (SA != RHS) {
2742       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2743         << RHS << E->getType() << LHS.getBitWidth();
2744     } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2745       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2746       // operand, and must not overflow the corresponding unsigned type.
2747       // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2748       // E1 x 2^E2 module 2^N.
2749       if (LHS.isNegative())
2750         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2751       else if (LHS.countLeadingZeros() < SA)
2752         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2753     }
2754     Result = LHS << SA;
2755     return true;
2756   }
2757   case BO_Shr: {
2758     if (Info.getLangOpts().OpenCL)
2759       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2760       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2761                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2762                     RHS.isUnsigned());
2763     else if (RHS.isSigned() && RHS.isNegative()) {
2764       // During constant-folding, a negative shift is an opposite shift. Such a
2765       // shift is not a constant expression.
2766       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2767       RHS = -RHS;
2768       goto shift_left;
2769     }
2770   shift_right:
2771     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2772     // shifted type.
2773     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2774     if (SA != RHS)
2775       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2776         << RHS << E->getType() << LHS.getBitWidth();
2777     Result = LHS >> SA;
2778     return true;
2779   }
2780 
2781   case BO_LT: Result = LHS < RHS; return true;
2782   case BO_GT: Result = LHS > RHS; return true;
2783   case BO_LE: Result = LHS <= RHS; return true;
2784   case BO_GE: Result = LHS >= RHS; return true;
2785   case BO_EQ: Result = LHS == RHS; return true;
2786   case BO_NE: Result = LHS != RHS; return true;
2787   case BO_Cmp:
2788     llvm_unreachable("BO_Cmp should be handled elsewhere");
2789   }
2790 }
2791 
2792 /// Perform the given binary floating-point operation, in-place, on LHS.
2793 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2794                                   APFloat &LHS, BinaryOperatorKind Opcode,
2795                                   const APFloat &RHS) {
2796   bool DynamicRM;
2797   llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM);
2798   APFloat::opStatus St;
2799   switch (Opcode) {
2800   default:
2801     Info.FFDiag(E);
2802     return false;
2803   case BO_Mul:
2804     St = LHS.multiply(RHS, RM);
2805     break;
2806   case BO_Add:
2807     St = LHS.add(RHS, RM);
2808     break;
2809   case BO_Sub:
2810     St = LHS.subtract(RHS, RM);
2811     break;
2812   case BO_Div:
2813     // [expr.mul]p4:
2814     //   If the second operand of / or % is zero the behavior is undefined.
2815     if (RHS.isZero())
2816       Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2817     St = LHS.divide(RHS, RM);
2818     break;
2819   }
2820 
2821   // [expr.pre]p4:
2822   //   If during the evaluation of an expression, the result is not
2823   //   mathematically defined [...], the behavior is undefined.
2824   // FIXME: C++ rules require us to not conform to IEEE 754 here.
2825   if (LHS.isNaN()) {
2826     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2827     return Info.noteUndefinedBehavior();
2828   }
2829 
2830   return checkFloatingPointResult(Info, E, St);
2831 }
2832 
2833 static bool handleLogicalOpForVector(const APInt &LHSValue,
2834                                      BinaryOperatorKind Opcode,
2835                                      const APInt &RHSValue, APInt &Result) {
2836   bool LHS = (LHSValue != 0);
2837   bool RHS = (RHSValue != 0);
2838 
2839   if (Opcode == BO_LAnd)
2840     Result = LHS && RHS;
2841   else
2842     Result = LHS || RHS;
2843   return true;
2844 }
2845 static bool handleLogicalOpForVector(const APFloat &LHSValue,
2846                                      BinaryOperatorKind Opcode,
2847                                      const APFloat &RHSValue, APInt &Result) {
2848   bool LHS = !LHSValue.isZero();
2849   bool RHS = !RHSValue.isZero();
2850 
2851   if (Opcode == BO_LAnd)
2852     Result = LHS && RHS;
2853   else
2854     Result = LHS || RHS;
2855   return true;
2856 }
2857 
2858 static bool handleLogicalOpForVector(const APValue &LHSValue,
2859                                      BinaryOperatorKind Opcode,
2860                                      const APValue &RHSValue, APInt &Result) {
2861   // The result is always an int type, however operands match the first.
2862   if (LHSValue.getKind() == APValue::Int)
2863     return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2864                                     RHSValue.getInt(), Result);
2865   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2866   return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2867                                   RHSValue.getFloat(), Result);
2868 }
2869 
2870 template <typename APTy>
2871 static bool
2872 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
2873                                const APTy &RHSValue, APInt &Result) {
2874   switch (Opcode) {
2875   default:
2876     llvm_unreachable("unsupported binary operator");
2877   case BO_EQ:
2878     Result = (LHSValue == RHSValue);
2879     break;
2880   case BO_NE:
2881     Result = (LHSValue != RHSValue);
2882     break;
2883   case BO_LT:
2884     Result = (LHSValue < RHSValue);
2885     break;
2886   case BO_GT:
2887     Result = (LHSValue > RHSValue);
2888     break;
2889   case BO_LE:
2890     Result = (LHSValue <= RHSValue);
2891     break;
2892   case BO_GE:
2893     Result = (LHSValue >= RHSValue);
2894     break;
2895   }
2896 
2897   return true;
2898 }
2899 
2900 static bool handleCompareOpForVector(const APValue &LHSValue,
2901                                      BinaryOperatorKind Opcode,
2902                                      const APValue &RHSValue, APInt &Result) {
2903   // The result is always an int type, however operands match the first.
2904   if (LHSValue.getKind() == APValue::Int)
2905     return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
2906                                           RHSValue.getInt(), Result);
2907   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2908   return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
2909                                         RHSValue.getFloat(), Result);
2910 }
2911 
2912 // Perform binary operations for vector types, in place on the LHS.
2913 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
2914                                     BinaryOperatorKind Opcode,
2915                                     APValue &LHSValue,
2916                                     const APValue &RHSValue) {
2917   assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
2918          "Operation not supported on vector types");
2919 
2920   const auto *VT = E->getType()->castAs<VectorType>();
2921   unsigned NumElements = VT->getNumElements();
2922   QualType EltTy = VT->getElementType();
2923 
2924   // In the cases (typically C as I've observed) where we aren't evaluating
2925   // constexpr but are checking for cases where the LHS isn't yet evaluatable,
2926   // just give up.
2927   if (!LHSValue.isVector()) {
2928     assert(LHSValue.isLValue() &&
2929            "A vector result that isn't a vector OR uncalculated LValue");
2930     Info.FFDiag(E);
2931     return false;
2932   }
2933 
2934   assert(LHSValue.getVectorLength() == NumElements &&
2935          RHSValue.getVectorLength() == NumElements && "Different vector sizes");
2936 
2937   SmallVector<APValue, 4> ResultElements;
2938 
2939   for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
2940     APValue LHSElt = LHSValue.getVectorElt(EltNum);
2941     APValue RHSElt = RHSValue.getVectorElt(EltNum);
2942 
2943     if (EltTy->isIntegerType()) {
2944       APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
2945                        EltTy->isUnsignedIntegerType()};
2946       bool Success = true;
2947 
2948       if (BinaryOperator::isLogicalOp(Opcode))
2949         Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
2950       else if (BinaryOperator::isComparisonOp(Opcode))
2951         Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
2952       else
2953         Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
2954                                     RHSElt.getInt(), EltResult);
2955 
2956       if (!Success) {
2957         Info.FFDiag(E);
2958         return false;
2959       }
2960       ResultElements.emplace_back(EltResult);
2961 
2962     } else if (EltTy->isFloatingType()) {
2963       assert(LHSElt.getKind() == APValue::Float &&
2964              RHSElt.getKind() == APValue::Float &&
2965              "Mismatched LHS/RHS/Result Type");
2966       APFloat LHSFloat = LHSElt.getFloat();
2967 
2968       if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
2969                                  RHSElt.getFloat())) {
2970         Info.FFDiag(E);
2971         return false;
2972       }
2973 
2974       ResultElements.emplace_back(LHSFloat);
2975     }
2976   }
2977 
2978   LHSValue = APValue(ResultElements.data(), ResultElements.size());
2979   return true;
2980 }
2981 
2982 /// Cast an lvalue referring to a base subobject to a derived class, by
2983 /// truncating the lvalue's path to the given length.
2984 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2985                                const RecordDecl *TruncatedType,
2986                                unsigned TruncatedElements) {
2987   SubobjectDesignator &D = Result.Designator;
2988 
2989   // Check we actually point to a derived class object.
2990   if (TruncatedElements == D.Entries.size())
2991     return true;
2992   assert(TruncatedElements >= D.MostDerivedPathLength &&
2993          "not casting to a derived class");
2994   if (!Result.checkSubobject(Info, E, CSK_Derived))
2995     return false;
2996 
2997   // Truncate the path to the subobject, and remove any derived-to-base offsets.
2998   const RecordDecl *RD = TruncatedType;
2999   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3000     if (RD->isInvalidDecl()) return false;
3001     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3002     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3003     if (isVirtualBaseClass(D.Entries[I]))
3004       Result.Offset -= Layout.getVBaseClassOffset(Base);
3005     else
3006       Result.Offset -= Layout.getBaseClassOffset(Base);
3007     RD = Base;
3008   }
3009   D.Entries.resize(TruncatedElements);
3010   return true;
3011 }
3012 
3013 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3014                                    const CXXRecordDecl *Derived,
3015                                    const CXXRecordDecl *Base,
3016                                    const ASTRecordLayout *RL = nullptr) {
3017   if (!RL) {
3018     if (Derived->isInvalidDecl()) return false;
3019     RL = &Info.Ctx.getASTRecordLayout(Derived);
3020   }
3021 
3022   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3023   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3024   return true;
3025 }
3026 
3027 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3028                              const CXXRecordDecl *DerivedDecl,
3029                              const CXXBaseSpecifier *Base) {
3030   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3031 
3032   if (!Base->isVirtual())
3033     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3034 
3035   SubobjectDesignator &D = Obj.Designator;
3036   if (D.Invalid)
3037     return false;
3038 
3039   // Extract most-derived object and corresponding type.
3040   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3041   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3042     return false;
3043 
3044   // Find the virtual base class.
3045   if (DerivedDecl->isInvalidDecl()) return false;
3046   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3047   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3048   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3049   return true;
3050 }
3051 
3052 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3053                                  QualType Type, LValue &Result) {
3054   for (CastExpr::path_const_iterator PathI = E->path_begin(),
3055                                      PathE = E->path_end();
3056        PathI != PathE; ++PathI) {
3057     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3058                           *PathI))
3059       return false;
3060     Type = (*PathI)->getType();
3061   }
3062   return true;
3063 }
3064 
3065 /// Cast an lvalue referring to a derived class to a known base subobject.
3066 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3067                             const CXXRecordDecl *DerivedRD,
3068                             const CXXRecordDecl *BaseRD) {
3069   CXXBasePaths Paths(/*FindAmbiguities=*/false,
3070                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
3071   if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3072     llvm_unreachable("Class must be derived from the passed in base class!");
3073 
3074   for (CXXBasePathElement &Elem : Paths.front())
3075     if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3076       return false;
3077   return true;
3078 }
3079 
3080 /// Update LVal to refer to the given field, which must be a member of the type
3081 /// currently described by LVal.
3082 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3083                                const FieldDecl *FD,
3084                                const ASTRecordLayout *RL = nullptr) {
3085   if (!RL) {
3086     if (FD->getParent()->isInvalidDecl()) return false;
3087     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3088   }
3089 
3090   unsigned I = FD->getFieldIndex();
3091   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3092   LVal.addDecl(Info, E, FD);
3093   return true;
3094 }
3095 
3096 /// Update LVal to refer to the given indirect field.
3097 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3098                                        LValue &LVal,
3099                                        const IndirectFieldDecl *IFD) {
3100   for (const auto *C : IFD->chain())
3101     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3102       return false;
3103   return true;
3104 }
3105 
3106 /// Get the size of the given type in char units.
3107 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
3108                          QualType Type, CharUnits &Size) {
3109   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3110   // extension.
3111   if (Type->isVoidType() || Type->isFunctionType()) {
3112     Size = CharUnits::One();
3113     return true;
3114   }
3115 
3116   if (Type->isDependentType()) {
3117     Info.FFDiag(Loc);
3118     return false;
3119   }
3120 
3121   if (!Type->isConstantSizeType()) {
3122     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3123     // FIXME: Better diagnostic.
3124     Info.FFDiag(Loc);
3125     return false;
3126   }
3127 
3128   Size = Info.Ctx.getTypeSizeInChars(Type);
3129   return true;
3130 }
3131 
3132 /// Update a pointer value to model pointer arithmetic.
3133 /// \param Info - Information about the ongoing evaluation.
3134 /// \param E - The expression being evaluated, for diagnostic purposes.
3135 /// \param LVal - The pointer value to be updated.
3136 /// \param EltTy - The pointee type represented by LVal.
3137 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3138 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3139                                         LValue &LVal, QualType EltTy,
3140                                         APSInt Adjustment) {
3141   CharUnits SizeOfPointee;
3142   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3143     return false;
3144 
3145   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3146   return true;
3147 }
3148 
3149 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3150                                         LValue &LVal, QualType EltTy,
3151                                         int64_t Adjustment) {
3152   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3153                                      APSInt::get(Adjustment));
3154 }
3155 
3156 /// Update an lvalue to refer to a component of a complex number.
3157 /// \param Info - Information about the ongoing evaluation.
3158 /// \param LVal - The lvalue to be updated.
3159 /// \param EltTy - The complex number's component type.
3160 /// \param Imag - False for the real component, true for the imaginary.
3161 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3162                                        LValue &LVal, QualType EltTy,
3163                                        bool Imag) {
3164   if (Imag) {
3165     CharUnits SizeOfComponent;
3166     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3167       return false;
3168     LVal.Offset += SizeOfComponent;
3169   }
3170   LVal.addComplex(Info, E, EltTy, Imag);
3171   return true;
3172 }
3173 
3174 /// Try to evaluate the initializer for a variable declaration.
3175 ///
3176 /// \param Info   Information about the ongoing evaluation.
3177 /// \param E      An expression to be used when printing diagnostics.
3178 /// \param VD     The variable whose initializer should be obtained.
3179 /// \param Version The version of the variable within the frame.
3180 /// \param Frame  The frame in which the variable was created. Must be null
3181 ///               if this variable is not local to the evaluation.
3182 /// \param Result Filled in with a pointer to the value of the variable.
3183 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3184                                 const VarDecl *VD, CallStackFrame *Frame,
3185                                 unsigned Version, APValue *&Result) {
3186   APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3187 
3188   // If this is a local variable, dig out its value.
3189   if (Frame) {
3190     Result = Frame->getTemporary(VD, Version);
3191     if (Result)
3192       return true;
3193 
3194     if (!isa<ParmVarDecl>(VD)) {
3195       // Assume variables referenced within a lambda's call operator that were
3196       // not declared within the call operator are captures and during checking
3197       // of a potential constant expression, assume they are unknown constant
3198       // expressions.
3199       assert(isLambdaCallOperator(Frame->Callee) &&
3200              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3201              "missing value for local variable");
3202       if (Info.checkingPotentialConstantExpression())
3203         return false;
3204       // FIXME: This diagnostic is bogus; we do support captures. Is this code
3205       // still reachable at all?
3206       Info.FFDiag(E->getBeginLoc(),
3207                   diag::note_unimplemented_constexpr_lambda_feature_ast)
3208           << "captures not currently allowed";
3209       return false;
3210     }
3211   }
3212 
3213   if (isa<ParmVarDecl>(VD)) {
3214     // Assume parameters of a potential constant expression are usable in
3215     // constant expressions.
3216     if (!Info.checkingPotentialConstantExpression() ||
3217         !Info.CurrentCall->Callee ||
3218         !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3219       if (Info.getLangOpts().CPlusPlus11) {
3220         Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3221             << VD;
3222         NoteLValueLocation(Info, Base);
3223       } else {
3224         Info.FFDiag(E);
3225       }
3226     }
3227     return false;
3228   }
3229 
3230   // Dig out the initializer, and use the declaration which it's attached to.
3231   // FIXME: We should eventually check whether the variable has a reachable
3232   // initializing declaration.
3233   const Expr *Init = VD->getAnyInitializer(VD);
3234   if (!Init) {
3235     // Don't diagnose during potential constant expression checking; an
3236     // initializer might be added later.
3237     if (!Info.checkingPotentialConstantExpression()) {
3238       Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3239         << VD;
3240       NoteLValueLocation(Info, Base);
3241     }
3242     return false;
3243   }
3244 
3245   if (Init->isValueDependent()) {
3246     // The DeclRefExpr is not value-dependent, but the variable it refers to
3247     // has a value-dependent initializer. This should only happen in
3248     // constant-folding cases, where the variable is not actually of a suitable
3249     // type for use in a constant expression (otherwise the DeclRefExpr would
3250     // have been value-dependent too), so diagnose that.
3251     assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3252     if (!Info.checkingPotentialConstantExpression()) {
3253       Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3254                          ? diag::note_constexpr_ltor_non_constexpr
3255                          : diag::note_constexpr_ltor_non_integral, 1)
3256           << VD << VD->getType();
3257       NoteLValueLocation(Info, Base);
3258     }
3259     return false;
3260   }
3261 
3262   // If we're currently evaluating the initializer of this declaration, use that
3263   // in-flight value.
3264   if (declaresSameEntity(Info.EvaluatingDecl.dyn_cast<const ValueDecl *>(),
3265                          VD)) {
3266     Result = Info.EvaluatingDeclValue;
3267     return true;
3268   }
3269 
3270   // Check that we can fold the initializer. In C++, we will have already done
3271   // this in the cases where it matters for conformance.
3272   SmallVector<PartialDiagnosticAt, 8> Notes;
3273   if (!VD->evaluateValue(Notes)) {
3274     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
3275               Notes.size() + 1) << VD;
3276     NoteLValueLocation(Info, Base);
3277     Info.addNotes(Notes);
3278     return false;
3279   }
3280 
3281   // Check that the variable is actually usable in constant expressions.
3282   if (!VD->checkInitIsICE()) {
3283     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
3284                  Notes.size() + 1) << VD;
3285     NoteLValueLocation(Info, Base);
3286     Info.addNotes(Notes);
3287   }
3288 
3289   // Never use the initializer of a weak variable, not even for constant
3290   // folding. We can't be sure that this is the definition that will be used.
3291   if (VD->isWeak()) {
3292     Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3293     NoteLValueLocation(Info, Base);
3294     return false;
3295   }
3296 
3297   Result = VD->getEvaluatedValue();
3298   return true;
3299 }
3300 
3301 static bool IsConstNonVolatile(QualType T) {
3302   Qualifiers Quals = T.getQualifiers();
3303   return Quals.hasConst() && !Quals.hasVolatile();
3304 }
3305 
3306 /// Get the base index of the given base class within an APValue representing
3307 /// the given derived class.
3308 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3309                              const CXXRecordDecl *Base) {
3310   Base = Base->getCanonicalDecl();
3311   unsigned Index = 0;
3312   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3313          E = Derived->bases_end(); I != E; ++I, ++Index) {
3314     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3315       return Index;
3316   }
3317 
3318   llvm_unreachable("base class missing from derived class's bases list");
3319 }
3320 
3321 /// Extract the value of a character from a string literal.
3322 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3323                                             uint64_t Index) {
3324   assert(!isa<SourceLocExpr>(Lit) &&
3325          "SourceLocExpr should have already been converted to a StringLiteral");
3326 
3327   // FIXME: Support MakeStringConstant
3328   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3329     std::string Str;
3330     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3331     assert(Index <= Str.size() && "Index too large");
3332     return APSInt::getUnsigned(Str.c_str()[Index]);
3333   }
3334 
3335   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3336     Lit = PE->getFunctionName();
3337   const StringLiteral *S = cast<StringLiteral>(Lit);
3338   const ConstantArrayType *CAT =
3339       Info.Ctx.getAsConstantArrayType(S->getType());
3340   assert(CAT && "string literal isn't an array");
3341   QualType CharType = CAT->getElementType();
3342   assert(CharType->isIntegerType() && "unexpected character type");
3343 
3344   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3345                CharType->isUnsignedIntegerType());
3346   if (Index < S->getLength())
3347     Value = S->getCodeUnit(Index);
3348   return Value;
3349 }
3350 
3351 // Expand a string literal into an array of characters.
3352 //
3353 // FIXME: This is inefficient; we should probably introduce something similar
3354 // to the LLVM ConstantDataArray to make this cheaper.
3355 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3356                                 APValue &Result,
3357                                 QualType AllocType = QualType()) {
3358   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3359       AllocType.isNull() ? S->getType() : AllocType);
3360   assert(CAT && "string literal isn't an array");
3361   QualType CharType = CAT->getElementType();
3362   assert(CharType->isIntegerType() && "unexpected character type");
3363 
3364   unsigned Elts = CAT->getSize().getZExtValue();
3365   Result = APValue(APValue::UninitArray(),
3366                    std::min(S->getLength(), Elts), Elts);
3367   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3368                CharType->isUnsignedIntegerType());
3369   if (Result.hasArrayFiller())
3370     Result.getArrayFiller() = APValue(Value);
3371   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3372     Value = S->getCodeUnit(I);
3373     Result.getArrayInitializedElt(I) = APValue(Value);
3374   }
3375 }
3376 
3377 // Expand an array so that it has more than Index filled elements.
3378 static void expandArray(APValue &Array, unsigned Index) {
3379   unsigned Size = Array.getArraySize();
3380   assert(Index < Size);
3381 
3382   // Always at least double the number of elements for which we store a value.
3383   unsigned OldElts = Array.getArrayInitializedElts();
3384   unsigned NewElts = std::max(Index+1, OldElts * 2);
3385   NewElts = std::min(Size, std::max(NewElts, 8u));
3386 
3387   // Copy the data across.
3388   APValue NewValue(APValue::UninitArray(), NewElts, Size);
3389   for (unsigned I = 0; I != OldElts; ++I)
3390     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3391   for (unsigned I = OldElts; I != NewElts; ++I)
3392     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3393   if (NewValue.hasArrayFiller())
3394     NewValue.getArrayFiller() = Array.getArrayFiller();
3395   Array.swap(NewValue);
3396 }
3397 
3398 /// Determine whether a type would actually be read by an lvalue-to-rvalue
3399 /// conversion. If it's of class type, we may assume that the copy operation
3400 /// is trivial. Note that this is never true for a union type with fields
3401 /// (because the copy always "reads" the active member) and always true for
3402 /// a non-class type.
3403 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3404 static bool isReadByLvalueToRvalueConversion(QualType T) {
3405   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3406   return !RD || isReadByLvalueToRvalueConversion(RD);
3407 }
3408 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3409   // FIXME: A trivial copy of a union copies the object representation, even if
3410   // the union is empty.
3411   if (RD->isUnion())
3412     return !RD->field_empty();
3413   if (RD->isEmpty())
3414     return false;
3415 
3416   for (auto *Field : RD->fields())
3417     if (!Field->isUnnamedBitfield() &&
3418         isReadByLvalueToRvalueConversion(Field->getType()))
3419       return true;
3420 
3421   for (auto &BaseSpec : RD->bases())
3422     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3423       return true;
3424 
3425   return false;
3426 }
3427 
3428 /// Diagnose an attempt to read from any unreadable field within the specified
3429 /// type, which might be a class type.
3430 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3431                                   QualType T) {
3432   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3433   if (!RD)
3434     return false;
3435 
3436   if (!RD->hasMutableFields())
3437     return false;
3438 
3439   for (auto *Field : RD->fields()) {
3440     // If we're actually going to read this field in some way, then it can't
3441     // be mutable. If we're in a union, then assigning to a mutable field
3442     // (even an empty one) can change the active member, so that's not OK.
3443     // FIXME: Add core issue number for the union case.
3444     if (Field->isMutable() &&
3445         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3446       Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3447       Info.Note(Field->getLocation(), diag::note_declared_at);
3448       return true;
3449     }
3450 
3451     if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3452       return true;
3453   }
3454 
3455   for (auto &BaseSpec : RD->bases())
3456     if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3457       return true;
3458 
3459   // All mutable fields were empty, and thus not actually read.
3460   return false;
3461 }
3462 
3463 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3464                                         APValue::LValueBase Base,
3465                                         bool MutableSubobject = false) {
3466   // A temporary we created.
3467   if (Base.getCallIndex())
3468     return true;
3469 
3470   auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3471   if (!Evaluating)
3472     return false;
3473 
3474   auto *BaseD = Base.dyn_cast<const ValueDecl*>();
3475 
3476   switch (Info.IsEvaluatingDecl) {
3477   case EvalInfo::EvaluatingDeclKind::None:
3478     return false;
3479 
3480   case EvalInfo::EvaluatingDeclKind::Ctor:
3481     // The variable whose initializer we're evaluating.
3482     if (BaseD)
3483       return declaresSameEntity(Evaluating, BaseD);
3484 
3485     // A temporary lifetime-extended by the variable whose initializer we're
3486     // evaluating.
3487     if (auto *BaseE = Base.dyn_cast<const Expr *>())
3488       if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3489         return declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating);
3490     return false;
3491 
3492   case EvalInfo::EvaluatingDeclKind::Dtor:
3493     // C++2a [expr.const]p6:
3494     //   [during constant destruction] the lifetime of a and its non-mutable
3495     //   subobjects (but not its mutable subobjects) [are] considered to start
3496     //   within e.
3497     //
3498     // FIXME: We can meaningfully extend this to cover non-const objects, but
3499     // we will need special handling: we should be able to access only
3500     // subobjects of such objects that are themselves declared const.
3501     if (!BaseD ||
3502         !(BaseD->getType().isConstQualified() ||
3503           BaseD->getType()->isReferenceType()) ||
3504         MutableSubobject)
3505       return false;
3506     return declaresSameEntity(Evaluating, BaseD);
3507   }
3508 
3509   llvm_unreachable("unknown evaluating decl kind");
3510 }
3511 
3512 namespace {
3513 /// A handle to a complete object (an object that is not a subobject of
3514 /// another object).
3515 struct CompleteObject {
3516   /// The identity of the object.
3517   APValue::LValueBase Base;
3518   /// The value of the complete object.
3519   APValue *Value;
3520   /// The type of the complete object.
3521   QualType Type;
3522 
3523   CompleteObject() : Value(nullptr) {}
3524   CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3525       : Base(Base), Value(Value), Type(Type) {}
3526 
3527   bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3528     // If this isn't a "real" access (eg, if it's just accessing the type
3529     // info), allow it. We assume the type doesn't change dynamically for
3530     // subobjects of constexpr objects (even though we'd hit UB here if it
3531     // did). FIXME: Is this right?
3532     if (!isAnyAccess(AK))
3533       return true;
3534 
3535     // In C++14 onwards, it is permitted to read a mutable member whose
3536     // lifetime began within the evaluation.
3537     // FIXME: Should we also allow this in C++11?
3538     if (!Info.getLangOpts().CPlusPlus14)
3539       return false;
3540     return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3541   }
3542 
3543   explicit operator bool() const { return !Type.isNull(); }
3544 };
3545 } // end anonymous namespace
3546 
3547 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3548                                  bool IsMutable = false) {
3549   // C++ [basic.type.qualifier]p1:
3550   // - A const object is an object of type const T or a non-mutable subobject
3551   //   of a const object.
3552   if (ObjType.isConstQualified() && !IsMutable)
3553     SubobjType.addConst();
3554   // - A volatile object is an object of type const T or a subobject of a
3555   //   volatile object.
3556   if (ObjType.isVolatileQualified())
3557     SubobjType.addVolatile();
3558   return SubobjType;
3559 }
3560 
3561 /// Find the designated sub-object of an rvalue.
3562 template<typename SubobjectHandler>
3563 typename SubobjectHandler::result_type
3564 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3565               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3566   if (Sub.Invalid)
3567     // A diagnostic will have already been produced.
3568     return handler.failed();
3569   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3570     if (Info.getLangOpts().CPlusPlus11)
3571       Info.FFDiag(E, Sub.isOnePastTheEnd()
3572                          ? diag::note_constexpr_access_past_end
3573                          : diag::note_constexpr_access_unsized_array)
3574           << handler.AccessKind;
3575     else
3576       Info.FFDiag(E);
3577     return handler.failed();
3578   }
3579 
3580   APValue *O = Obj.Value;
3581   QualType ObjType = Obj.Type;
3582   const FieldDecl *LastField = nullptr;
3583   const FieldDecl *VolatileField = nullptr;
3584 
3585   // Walk the designator's path to find the subobject.
3586   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3587     // Reading an indeterminate value is undefined, but assigning over one is OK.
3588     if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3589         (O->isIndeterminate() &&
3590          !isValidIndeterminateAccess(handler.AccessKind))) {
3591       if (!Info.checkingPotentialConstantExpression())
3592         Info.FFDiag(E, diag::note_constexpr_access_uninit)
3593             << handler.AccessKind << O->isIndeterminate();
3594       return handler.failed();
3595     }
3596 
3597     // C++ [class.ctor]p5, C++ [class.dtor]p5:
3598     //    const and volatile semantics are not applied on an object under
3599     //    {con,de}struction.
3600     if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3601         ObjType->isRecordType() &&
3602         Info.isEvaluatingCtorDtor(
3603             Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3604                                          Sub.Entries.begin() + I)) !=
3605                           ConstructionPhase::None) {
3606       ObjType = Info.Ctx.getCanonicalType(ObjType);
3607       ObjType.removeLocalConst();
3608       ObjType.removeLocalVolatile();
3609     }
3610 
3611     // If this is our last pass, check that the final object type is OK.
3612     if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3613       // Accesses to volatile objects are prohibited.
3614       if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3615         if (Info.getLangOpts().CPlusPlus) {
3616           int DiagKind;
3617           SourceLocation Loc;
3618           const NamedDecl *Decl = nullptr;
3619           if (VolatileField) {
3620             DiagKind = 2;
3621             Loc = VolatileField->getLocation();
3622             Decl = VolatileField;
3623           } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3624             DiagKind = 1;
3625             Loc = VD->getLocation();
3626             Decl = VD;
3627           } else {
3628             DiagKind = 0;
3629             if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3630               Loc = E->getExprLoc();
3631           }
3632           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3633               << handler.AccessKind << DiagKind << Decl;
3634           Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3635         } else {
3636           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3637         }
3638         return handler.failed();
3639       }
3640 
3641       // If we are reading an object of class type, there may still be more
3642       // things we need to check: if there are any mutable subobjects, we
3643       // cannot perform this read. (This only happens when performing a trivial
3644       // copy or assignment.)
3645       if (ObjType->isRecordType() &&
3646           !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3647           diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3648         return handler.failed();
3649     }
3650 
3651     if (I == N) {
3652       if (!handler.found(*O, ObjType))
3653         return false;
3654 
3655       // If we modified a bit-field, truncate it to the right width.
3656       if (isModification(handler.AccessKind) &&
3657           LastField && LastField->isBitField() &&
3658           !truncateBitfieldValue(Info, E, *O, LastField))
3659         return false;
3660 
3661       return true;
3662     }
3663 
3664     LastField = nullptr;
3665     if (ObjType->isArrayType()) {
3666       // Next subobject is an array element.
3667       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3668       assert(CAT && "vla in literal type?");
3669       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3670       if (CAT->getSize().ule(Index)) {
3671         // Note, it should not be possible to form a pointer with a valid
3672         // designator which points more than one past the end of the array.
3673         if (Info.getLangOpts().CPlusPlus11)
3674           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3675             << handler.AccessKind;
3676         else
3677           Info.FFDiag(E);
3678         return handler.failed();
3679       }
3680 
3681       ObjType = CAT->getElementType();
3682 
3683       if (O->getArrayInitializedElts() > Index)
3684         O = &O->getArrayInitializedElt(Index);
3685       else if (!isRead(handler.AccessKind)) {
3686         expandArray(*O, Index);
3687         O = &O->getArrayInitializedElt(Index);
3688       } else
3689         O = &O->getArrayFiller();
3690     } else if (ObjType->isAnyComplexType()) {
3691       // Next subobject is a complex number.
3692       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3693       if (Index > 1) {
3694         if (Info.getLangOpts().CPlusPlus11)
3695           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3696             << handler.AccessKind;
3697         else
3698           Info.FFDiag(E);
3699         return handler.failed();
3700       }
3701 
3702       ObjType = getSubobjectType(
3703           ObjType, ObjType->castAs<ComplexType>()->getElementType());
3704 
3705       assert(I == N - 1 && "extracting subobject of scalar?");
3706       if (O->isComplexInt()) {
3707         return handler.found(Index ? O->getComplexIntImag()
3708                                    : O->getComplexIntReal(), ObjType);
3709       } else {
3710         assert(O->isComplexFloat());
3711         return handler.found(Index ? O->getComplexFloatImag()
3712                                    : O->getComplexFloatReal(), ObjType);
3713       }
3714     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3715       if (Field->isMutable() &&
3716           !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3717         Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3718           << handler.AccessKind << Field;
3719         Info.Note(Field->getLocation(), diag::note_declared_at);
3720         return handler.failed();
3721       }
3722 
3723       // Next subobject is a class, struct or union field.
3724       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3725       if (RD->isUnion()) {
3726         const FieldDecl *UnionField = O->getUnionField();
3727         if (!UnionField ||
3728             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3729           if (I == N - 1 && handler.AccessKind == AK_Construct) {
3730             // Placement new onto an inactive union member makes it active.
3731             O->setUnion(Field, APValue());
3732           } else {
3733             // FIXME: If O->getUnionValue() is absent, report that there's no
3734             // active union member rather than reporting the prior active union
3735             // member. We'll need to fix nullptr_t to not use APValue() as its
3736             // representation first.
3737             Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3738                 << handler.AccessKind << Field << !UnionField << UnionField;
3739             return handler.failed();
3740           }
3741         }
3742         O = &O->getUnionValue();
3743       } else
3744         O = &O->getStructField(Field->getFieldIndex());
3745 
3746       ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3747       LastField = Field;
3748       if (Field->getType().isVolatileQualified())
3749         VolatileField = Field;
3750     } else {
3751       // Next subobject is a base class.
3752       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3753       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3754       O = &O->getStructBase(getBaseIndex(Derived, Base));
3755 
3756       ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3757     }
3758   }
3759 }
3760 
3761 namespace {
3762 struct ExtractSubobjectHandler {
3763   EvalInfo &Info;
3764   const Expr *E;
3765   APValue &Result;
3766   const AccessKinds AccessKind;
3767 
3768   typedef bool result_type;
3769   bool failed() { return false; }
3770   bool found(APValue &Subobj, QualType SubobjType) {
3771     Result = Subobj;
3772     if (AccessKind == AK_ReadObjectRepresentation)
3773       return true;
3774     return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3775   }
3776   bool found(APSInt &Value, QualType SubobjType) {
3777     Result = APValue(Value);
3778     return true;
3779   }
3780   bool found(APFloat &Value, QualType SubobjType) {
3781     Result = APValue(Value);
3782     return true;
3783   }
3784 };
3785 } // end anonymous namespace
3786 
3787 /// Extract the designated sub-object of an rvalue.
3788 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3789                              const CompleteObject &Obj,
3790                              const SubobjectDesignator &Sub, APValue &Result,
3791                              AccessKinds AK = AK_Read) {
3792   assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3793   ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3794   return findSubobject(Info, E, Obj, Sub, Handler);
3795 }
3796 
3797 namespace {
3798 struct ModifySubobjectHandler {
3799   EvalInfo &Info;
3800   APValue &NewVal;
3801   const Expr *E;
3802 
3803   typedef bool result_type;
3804   static const AccessKinds AccessKind = AK_Assign;
3805 
3806   bool checkConst(QualType QT) {
3807     // Assigning to a const object has undefined behavior.
3808     if (QT.isConstQualified()) {
3809       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3810       return false;
3811     }
3812     return true;
3813   }
3814 
3815   bool failed() { return false; }
3816   bool found(APValue &Subobj, QualType SubobjType) {
3817     if (!checkConst(SubobjType))
3818       return false;
3819     // We've been given ownership of NewVal, so just swap it in.
3820     Subobj.swap(NewVal);
3821     return true;
3822   }
3823   bool found(APSInt &Value, QualType SubobjType) {
3824     if (!checkConst(SubobjType))
3825       return false;
3826     if (!NewVal.isInt()) {
3827       // Maybe trying to write a cast pointer value into a complex?
3828       Info.FFDiag(E);
3829       return false;
3830     }
3831     Value = NewVal.getInt();
3832     return true;
3833   }
3834   bool found(APFloat &Value, QualType SubobjType) {
3835     if (!checkConst(SubobjType))
3836       return false;
3837     Value = NewVal.getFloat();
3838     return true;
3839   }
3840 };
3841 } // end anonymous namespace
3842 
3843 const AccessKinds ModifySubobjectHandler::AccessKind;
3844 
3845 /// Update the designated sub-object of an rvalue to the given value.
3846 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3847                             const CompleteObject &Obj,
3848                             const SubobjectDesignator &Sub,
3849                             APValue &NewVal) {
3850   ModifySubobjectHandler Handler = { Info, NewVal, E };
3851   return findSubobject(Info, E, Obj, Sub, Handler);
3852 }
3853 
3854 /// Find the position where two subobject designators diverge, or equivalently
3855 /// the length of the common initial subsequence.
3856 static unsigned FindDesignatorMismatch(QualType ObjType,
3857                                        const SubobjectDesignator &A,
3858                                        const SubobjectDesignator &B,
3859                                        bool &WasArrayIndex) {
3860   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3861   for (/**/; I != N; ++I) {
3862     if (!ObjType.isNull() &&
3863         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3864       // Next subobject is an array element.
3865       if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3866         WasArrayIndex = true;
3867         return I;
3868       }
3869       if (ObjType->isAnyComplexType())
3870         ObjType = ObjType->castAs<ComplexType>()->getElementType();
3871       else
3872         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3873     } else {
3874       if (A.Entries[I].getAsBaseOrMember() !=
3875           B.Entries[I].getAsBaseOrMember()) {
3876         WasArrayIndex = false;
3877         return I;
3878       }
3879       if (const FieldDecl *FD = getAsField(A.Entries[I]))
3880         // Next subobject is a field.
3881         ObjType = FD->getType();
3882       else
3883         // Next subobject is a base class.
3884         ObjType = QualType();
3885     }
3886   }
3887   WasArrayIndex = false;
3888   return I;
3889 }
3890 
3891 /// Determine whether the given subobject designators refer to elements of the
3892 /// same array object.
3893 static bool AreElementsOfSameArray(QualType ObjType,
3894                                    const SubobjectDesignator &A,
3895                                    const SubobjectDesignator &B) {
3896   if (A.Entries.size() != B.Entries.size())
3897     return false;
3898 
3899   bool IsArray = A.MostDerivedIsArrayElement;
3900   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3901     // A is a subobject of the array element.
3902     return false;
3903 
3904   // If A (and B) designates an array element, the last entry will be the array
3905   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3906   // of length 1' case, and the entire path must match.
3907   bool WasArrayIndex;
3908   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3909   return CommonLength >= A.Entries.size() - IsArray;
3910 }
3911 
3912 /// Find the complete object to which an LValue refers.
3913 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3914                                          AccessKinds AK, const LValue &LVal,
3915                                          QualType LValType) {
3916   if (LVal.InvalidBase) {
3917     Info.FFDiag(E);
3918     return CompleteObject();
3919   }
3920 
3921   if (!LVal.Base) {
3922     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3923     return CompleteObject();
3924   }
3925 
3926   CallStackFrame *Frame = nullptr;
3927   unsigned Depth = 0;
3928   if (LVal.getLValueCallIndex()) {
3929     std::tie(Frame, Depth) =
3930         Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3931     if (!Frame) {
3932       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3933         << AK << LVal.Base.is<const ValueDecl*>();
3934       NoteLValueLocation(Info, LVal.Base);
3935       return CompleteObject();
3936     }
3937   }
3938 
3939   bool IsAccess = isAnyAccess(AK);
3940 
3941   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3942   // is not a constant expression (even if the object is non-volatile). We also
3943   // apply this rule to C++98, in order to conform to the expected 'volatile'
3944   // semantics.
3945   if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
3946     if (Info.getLangOpts().CPlusPlus)
3947       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3948         << AK << LValType;
3949     else
3950       Info.FFDiag(E);
3951     return CompleteObject();
3952   }
3953 
3954   // Compute value storage location and type of base object.
3955   APValue *BaseVal = nullptr;
3956   QualType BaseType = getType(LVal.Base);
3957 
3958   if (const ConstantExpr *CE =
3959           dyn_cast_or_null<ConstantExpr>(LVal.Base.dyn_cast<const Expr *>())) {
3960     /// Nested immediate invocation have been previously removed so if we found
3961     /// a ConstantExpr it can only be the EvaluatingDecl.
3962     assert(CE->isImmediateInvocation() && CE == Info.EvaluatingDecl);
3963     (void)CE;
3964     BaseVal = Info.EvaluatingDeclValue;
3965   } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
3966     // Allow reading from a GUID declaration.
3967     if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
3968       if (isModification(AK)) {
3969         // All the remaining cases do not permit modification of the object.
3970         Info.FFDiag(E, diag::note_constexpr_modify_global);
3971         return CompleteObject();
3972       }
3973       APValue &V = GD->getAsAPValue();
3974       if (V.isAbsent()) {
3975         Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
3976             << GD->getType();
3977         return CompleteObject();
3978       }
3979       return CompleteObject(LVal.Base, &V, GD->getType());
3980     }
3981 
3982     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3983     // In C++11, constexpr, non-volatile variables initialized with constant
3984     // expressions are constant expressions too. Inside constexpr functions,
3985     // parameters are constant expressions even if they're non-const.
3986     // In C++1y, objects local to a constant expression (those with a Frame) are
3987     // both readable and writable inside constant expressions.
3988     // In C, such things can also be folded, although they are not ICEs.
3989     const VarDecl *VD = dyn_cast<VarDecl>(D);
3990     if (VD) {
3991       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3992         VD = VDef;
3993     }
3994     if (!VD || VD->isInvalidDecl()) {
3995       Info.FFDiag(E);
3996       return CompleteObject();
3997     }
3998 
3999     // In OpenCL if a variable is in constant address space it is a const value.
4000     bool IsConstant = BaseType.isConstQualified() ||
4001                       (Info.getLangOpts().OpenCL &&
4002                        BaseType.getAddressSpace() == LangAS::opencl_constant);
4003 
4004     // Unless we're looking at a local variable or argument in a constexpr call,
4005     // the variable we're reading must be const.
4006     if (!Frame) {
4007       if (IsAccess && isa<ParmVarDecl>(VD)) {
4008         // Access of a parameter that's not associated with a frame isn't going
4009         // to work out, but we can leave it to evaluateVarDeclInit to provide a
4010         // suitable diagnostic.
4011       } else if (Info.getLangOpts().CPlusPlus14 &&
4012                  lifetimeStartedInEvaluation(Info, LVal.Base)) {
4013         // OK, we can read and modify an object if we're in the process of
4014         // evaluating its initializer, because its lifetime began in this
4015         // evaluation.
4016       } else if (isModification(AK)) {
4017         // All the remaining cases do not permit modification of the object.
4018         Info.FFDiag(E, diag::note_constexpr_modify_global);
4019         return CompleteObject();
4020       } else if (VD->isConstexpr()) {
4021         // OK, we can read this variable.
4022       } else if (BaseType->isIntegralOrEnumerationType()) {
4023         // In OpenCL if a variable is in constant address space it is a const
4024         // value.
4025         if (!IsConstant) {
4026           if (!IsAccess)
4027             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4028           if (Info.getLangOpts().CPlusPlus) {
4029             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4030             Info.Note(VD->getLocation(), diag::note_declared_at);
4031           } else {
4032             Info.FFDiag(E);
4033           }
4034           return CompleteObject();
4035         }
4036       } else if (!IsAccess) {
4037         return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4038       } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
4039                  BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4040         // This variable might end up being constexpr. Don't diagnose it yet.
4041       } else if (IsConstant) {
4042         // Keep evaluating to see what we can do. In particular, we support
4043         // folding of const floating-point types, in order to make static const
4044         // data members of such types (supported as an extension) more useful.
4045         if (Info.getLangOpts().CPlusPlus) {
4046           Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4047                               ? diag::note_constexpr_ltor_non_constexpr
4048                               : diag::note_constexpr_ltor_non_integral, 1)
4049               << VD << BaseType;
4050           Info.Note(VD->getLocation(), diag::note_declared_at);
4051         } else {
4052           Info.CCEDiag(E);
4053         }
4054       } else {
4055         // Never allow reading a non-const value.
4056         if (Info.getLangOpts().CPlusPlus) {
4057           Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4058                              ? diag::note_constexpr_ltor_non_constexpr
4059                              : diag::note_constexpr_ltor_non_integral, 1)
4060               << VD << BaseType;
4061           Info.Note(VD->getLocation(), diag::note_declared_at);
4062         } else {
4063           Info.FFDiag(E);
4064         }
4065         return CompleteObject();
4066       }
4067     }
4068 
4069     if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
4070       return CompleteObject();
4071   } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4072     Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
4073     if (!Alloc) {
4074       Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4075       return CompleteObject();
4076     }
4077     return CompleteObject(LVal.Base, &(*Alloc)->Value,
4078                           LVal.Base.getDynamicAllocType());
4079   } else {
4080     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4081 
4082     if (!Frame) {
4083       if (const MaterializeTemporaryExpr *MTE =
4084               dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4085         assert(MTE->getStorageDuration() == SD_Static &&
4086                "should have a frame for a non-global materialized temporary");
4087 
4088         // Per C++1y [expr.const]p2:
4089         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4090         //   - a [...] glvalue of integral or enumeration type that refers to
4091         //     a non-volatile const object [...]
4092         //   [...]
4093         //   - a [...] glvalue of literal type that refers to a non-volatile
4094         //     object whose lifetime began within the evaluation of e.
4095         //
4096         // C++11 misses the 'began within the evaluation of e' check and
4097         // instead allows all temporaries, including things like:
4098         //   int &&r = 1;
4099         //   int x = ++r;
4100         //   constexpr int k = r;
4101         // Therefore we use the C++14 rules in C++11 too.
4102         //
4103         // Note that temporaries whose lifetimes began while evaluating a
4104         // variable's constructor are not usable while evaluating the
4105         // corresponding destructor, not even if they're of const-qualified
4106         // types.
4107         if (!(BaseType.isConstQualified() &&
4108               BaseType->isIntegralOrEnumerationType()) &&
4109             !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4110           if (!IsAccess)
4111             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4112           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4113           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4114           return CompleteObject();
4115         }
4116 
4117         BaseVal = MTE->getOrCreateValue(false);
4118         assert(BaseVal && "got reference to unevaluated temporary");
4119       } else {
4120         if (!IsAccess)
4121           return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4122         APValue Val;
4123         LVal.moveInto(Val);
4124         Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4125             << AK
4126             << Val.getAsString(Info.Ctx,
4127                                Info.Ctx.getLValueReferenceType(LValType));
4128         NoteLValueLocation(Info, LVal.Base);
4129         return CompleteObject();
4130       }
4131     } else {
4132       BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4133       assert(BaseVal && "missing value for temporary");
4134     }
4135   }
4136 
4137   // In C++14, we can't safely access any mutable state when we might be
4138   // evaluating after an unmodeled side effect. Parameters are modeled as state
4139   // in the caller, but aren't visible once the call returns, so they can be
4140   // modified in a speculatively-evaluated call.
4141   //
4142   // FIXME: Not all local state is mutable. Allow local constant subobjects
4143   // to be read here (but take care with 'mutable' fields).
4144   unsigned VisibleDepth = Depth;
4145   if (llvm::isa_and_nonnull<ParmVarDecl>(
4146           LVal.Base.dyn_cast<const ValueDecl *>()))
4147     ++VisibleDepth;
4148   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4149        Info.EvalStatus.HasSideEffects) ||
4150       (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4151     return CompleteObject();
4152 
4153   return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4154 }
4155 
4156 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4157 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4158 /// glvalue referred to by an entity of reference type.
4159 ///
4160 /// \param Info - Information about the ongoing evaluation.
4161 /// \param Conv - The expression for which we are performing the conversion.
4162 ///               Used for diagnostics.
4163 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4164 ///               case of a non-class type).
4165 /// \param LVal - The glvalue on which we are attempting to perform this action.
4166 /// \param RVal - The produced value will be placed here.
4167 /// \param WantObjectRepresentation - If true, we're looking for the object
4168 ///               representation rather than the value, and in particular,
4169 ///               there is no requirement that the result be fully initialized.
4170 static bool
4171 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
4172                                const LValue &LVal, APValue &RVal,
4173                                bool WantObjectRepresentation = false) {
4174   if (LVal.Designator.Invalid)
4175     return false;
4176 
4177   // Check for special cases where there is no existing APValue to look at.
4178   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4179 
4180   AccessKinds AK =
4181       WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4182 
4183   if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4184     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4185       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4186       // initializer until now for such expressions. Such an expression can't be
4187       // an ICE in C, so this only matters for fold.
4188       if (Type.isVolatileQualified()) {
4189         Info.FFDiag(Conv);
4190         return false;
4191       }
4192       APValue Lit;
4193       if (!Evaluate(Lit, Info, CLE->getInitializer()))
4194         return false;
4195       CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4196       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4197     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4198       // Special-case character extraction so we don't have to construct an
4199       // APValue for the whole string.
4200       assert(LVal.Designator.Entries.size() <= 1 &&
4201              "Can only read characters from string literals");
4202       if (LVal.Designator.Entries.empty()) {
4203         // Fail for now for LValue to RValue conversion of an array.
4204         // (This shouldn't show up in C/C++, but it could be triggered by a
4205         // weird EvaluateAsRValue call from a tool.)
4206         Info.FFDiag(Conv);
4207         return false;
4208       }
4209       if (LVal.Designator.isOnePastTheEnd()) {
4210         if (Info.getLangOpts().CPlusPlus11)
4211           Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4212         else
4213           Info.FFDiag(Conv);
4214         return false;
4215       }
4216       uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4217       RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4218       return true;
4219     }
4220   }
4221 
4222   CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4223   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4224 }
4225 
4226 /// Perform an assignment of Val to LVal. Takes ownership of Val.
4227 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4228                              QualType LValType, APValue &Val) {
4229   if (LVal.Designator.Invalid)
4230     return false;
4231 
4232   if (!Info.getLangOpts().CPlusPlus14) {
4233     Info.FFDiag(E);
4234     return false;
4235   }
4236 
4237   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4238   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4239 }
4240 
4241 namespace {
4242 struct CompoundAssignSubobjectHandler {
4243   EvalInfo &Info;
4244   const CompoundAssignOperator *E;
4245   QualType PromotedLHSType;
4246   BinaryOperatorKind Opcode;
4247   const APValue &RHS;
4248 
4249   static const AccessKinds AccessKind = AK_Assign;
4250 
4251   typedef bool result_type;
4252 
4253   bool checkConst(QualType QT) {
4254     // Assigning to a const object has undefined behavior.
4255     if (QT.isConstQualified()) {
4256       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4257       return false;
4258     }
4259     return true;
4260   }
4261 
4262   bool failed() { return false; }
4263   bool found(APValue &Subobj, QualType SubobjType) {
4264     switch (Subobj.getKind()) {
4265     case APValue::Int:
4266       return found(Subobj.getInt(), SubobjType);
4267     case APValue::Float:
4268       return found(Subobj.getFloat(), SubobjType);
4269     case APValue::ComplexInt:
4270     case APValue::ComplexFloat:
4271       // FIXME: Implement complex compound assignment.
4272       Info.FFDiag(E);
4273       return false;
4274     case APValue::LValue:
4275       return foundPointer(Subobj, SubobjType);
4276     case APValue::Vector:
4277       return foundVector(Subobj, SubobjType);
4278     default:
4279       // FIXME: can this happen?
4280       Info.FFDiag(E);
4281       return false;
4282     }
4283   }
4284 
4285   bool foundVector(APValue &Value, QualType SubobjType) {
4286     if (!checkConst(SubobjType))
4287       return false;
4288 
4289     if (!SubobjType->isVectorType()) {
4290       Info.FFDiag(E);
4291       return false;
4292     }
4293     return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4294   }
4295 
4296   bool found(APSInt &Value, QualType SubobjType) {
4297     if (!checkConst(SubobjType))
4298       return false;
4299 
4300     if (!SubobjType->isIntegerType()) {
4301       // We don't support compound assignment on integer-cast-to-pointer
4302       // values.
4303       Info.FFDiag(E);
4304       return false;
4305     }
4306 
4307     if (RHS.isInt()) {
4308       APSInt LHS =
4309           HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4310       if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4311         return false;
4312       Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4313       return true;
4314     } else if (RHS.isFloat()) {
4315       APFloat FValue(0.0);
4316       return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
4317                                   FValue) &&
4318              handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4319              HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4320                                   Value);
4321     }
4322 
4323     Info.FFDiag(E);
4324     return false;
4325   }
4326   bool found(APFloat &Value, QualType SubobjType) {
4327     return checkConst(SubobjType) &&
4328            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4329                                   Value) &&
4330            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4331            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4332   }
4333   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4334     if (!checkConst(SubobjType))
4335       return false;
4336 
4337     QualType PointeeType;
4338     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4339       PointeeType = PT->getPointeeType();
4340 
4341     if (PointeeType.isNull() || !RHS.isInt() ||
4342         (Opcode != BO_Add && Opcode != BO_Sub)) {
4343       Info.FFDiag(E);
4344       return false;
4345     }
4346 
4347     APSInt Offset = RHS.getInt();
4348     if (Opcode == BO_Sub)
4349       negateAsSigned(Offset);
4350 
4351     LValue LVal;
4352     LVal.setFrom(Info.Ctx, Subobj);
4353     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4354       return false;
4355     LVal.moveInto(Subobj);
4356     return true;
4357   }
4358 };
4359 } // end anonymous namespace
4360 
4361 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4362 
4363 /// Perform a compound assignment of LVal <op>= RVal.
4364 static bool handleCompoundAssignment(EvalInfo &Info,
4365                                      const CompoundAssignOperator *E,
4366                                      const LValue &LVal, QualType LValType,
4367                                      QualType PromotedLValType,
4368                                      BinaryOperatorKind Opcode,
4369                                      const APValue &RVal) {
4370   if (LVal.Designator.Invalid)
4371     return false;
4372 
4373   if (!Info.getLangOpts().CPlusPlus14) {
4374     Info.FFDiag(E);
4375     return false;
4376   }
4377 
4378   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4379   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4380                                              RVal };
4381   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4382 }
4383 
4384 namespace {
4385 struct IncDecSubobjectHandler {
4386   EvalInfo &Info;
4387   const UnaryOperator *E;
4388   AccessKinds AccessKind;
4389   APValue *Old;
4390 
4391   typedef bool result_type;
4392 
4393   bool checkConst(QualType QT) {
4394     // Assigning to a const object has undefined behavior.
4395     if (QT.isConstQualified()) {
4396       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4397       return false;
4398     }
4399     return true;
4400   }
4401 
4402   bool failed() { return false; }
4403   bool found(APValue &Subobj, QualType SubobjType) {
4404     // Stash the old value. Also clear Old, so we don't clobber it later
4405     // if we're post-incrementing a complex.
4406     if (Old) {
4407       *Old = Subobj;
4408       Old = nullptr;
4409     }
4410 
4411     switch (Subobj.getKind()) {
4412     case APValue::Int:
4413       return found(Subobj.getInt(), SubobjType);
4414     case APValue::Float:
4415       return found(Subobj.getFloat(), SubobjType);
4416     case APValue::ComplexInt:
4417       return found(Subobj.getComplexIntReal(),
4418                    SubobjType->castAs<ComplexType>()->getElementType()
4419                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4420     case APValue::ComplexFloat:
4421       return found(Subobj.getComplexFloatReal(),
4422                    SubobjType->castAs<ComplexType>()->getElementType()
4423                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4424     case APValue::LValue:
4425       return foundPointer(Subobj, SubobjType);
4426     default:
4427       // FIXME: can this happen?
4428       Info.FFDiag(E);
4429       return false;
4430     }
4431   }
4432   bool found(APSInt &Value, QualType SubobjType) {
4433     if (!checkConst(SubobjType))
4434       return false;
4435 
4436     if (!SubobjType->isIntegerType()) {
4437       // We don't support increment / decrement on integer-cast-to-pointer
4438       // values.
4439       Info.FFDiag(E);
4440       return false;
4441     }
4442 
4443     if (Old) *Old = APValue(Value);
4444 
4445     // bool arithmetic promotes to int, and the conversion back to bool
4446     // doesn't reduce mod 2^n, so special-case it.
4447     if (SubobjType->isBooleanType()) {
4448       if (AccessKind == AK_Increment)
4449         Value = 1;
4450       else
4451         Value = !Value;
4452       return true;
4453     }
4454 
4455     bool WasNegative = Value.isNegative();
4456     if (AccessKind == AK_Increment) {
4457       ++Value;
4458 
4459       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4460         APSInt ActualValue(Value, /*IsUnsigned*/true);
4461         return HandleOverflow(Info, E, ActualValue, SubobjType);
4462       }
4463     } else {
4464       --Value;
4465 
4466       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4467         unsigned BitWidth = Value.getBitWidth();
4468         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4469         ActualValue.setBit(BitWidth);
4470         return HandleOverflow(Info, E, ActualValue, SubobjType);
4471       }
4472     }
4473     return true;
4474   }
4475   bool found(APFloat &Value, QualType SubobjType) {
4476     if (!checkConst(SubobjType))
4477       return false;
4478 
4479     if (Old) *Old = APValue(Value);
4480 
4481     APFloat One(Value.getSemantics(), 1);
4482     if (AccessKind == AK_Increment)
4483       Value.add(One, APFloat::rmNearestTiesToEven);
4484     else
4485       Value.subtract(One, APFloat::rmNearestTiesToEven);
4486     return true;
4487   }
4488   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4489     if (!checkConst(SubobjType))
4490       return false;
4491 
4492     QualType PointeeType;
4493     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4494       PointeeType = PT->getPointeeType();
4495     else {
4496       Info.FFDiag(E);
4497       return false;
4498     }
4499 
4500     LValue LVal;
4501     LVal.setFrom(Info.Ctx, Subobj);
4502     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4503                                      AccessKind == AK_Increment ? 1 : -1))
4504       return false;
4505     LVal.moveInto(Subobj);
4506     return true;
4507   }
4508 };
4509 } // end anonymous namespace
4510 
4511 /// Perform an increment or decrement on LVal.
4512 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4513                          QualType LValType, bool IsIncrement, APValue *Old) {
4514   if (LVal.Designator.Invalid)
4515     return false;
4516 
4517   if (!Info.getLangOpts().CPlusPlus14) {
4518     Info.FFDiag(E);
4519     return false;
4520   }
4521 
4522   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4523   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4524   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4525   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4526 }
4527 
4528 /// Build an lvalue for the object argument of a member function call.
4529 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4530                                    LValue &This) {
4531   if (Object->getType()->isPointerType() && Object->isRValue())
4532     return EvaluatePointer(Object, This, Info);
4533 
4534   if (Object->isGLValue())
4535     return EvaluateLValue(Object, This, Info);
4536 
4537   if (Object->getType()->isLiteralType(Info.Ctx))
4538     return EvaluateTemporary(Object, This, Info);
4539 
4540   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4541   return false;
4542 }
4543 
4544 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
4545 /// lvalue referring to the result.
4546 ///
4547 /// \param Info - Information about the ongoing evaluation.
4548 /// \param LV - An lvalue referring to the base of the member pointer.
4549 /// \param RHS - The member pointer expression.
4550 /// \param IncludeMember - Specifies whether the member itself is included in
4551 ///        the resulting LValue subobject designator. This is not possible when
4552 ///        creating a bound member function.
4553 /// \return The field or method declaration to which the member pointer refers,
4554 ///         or 0 if evaluation fails.
4555 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4556                                                   QualType LVType,
4557                                                   LValue &LV,
4558                                                   const Expr *RHS,
4559                                                   bool IncludeMember = true) {
4560   MemberPtr MemPtr;
4561   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4562     return nullptr;
4563 
4564   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4565   // member value, the behavior is undefined.
4566   if (!MemPtr.getDecl()) {
4567     // FIXME: Specific diagnostic.
4568     Info.FFDiag(RHS);
4569     return nullptr;
4570   }
4571 
4572   if (MemPtr.isDerivedMember()) {
4573     // This is a member of some derived class. Truncate LV appropriately.
4574     // The end of the derived-to-base path for the base object must match the
4575     // derived-to-base path for the member pointer.
4576     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4577         LV.Designator.Entries.size()) {
4578       Info.FFDiag(RHS);
4579       return nullptr;
4580     }
4581     unsigned PathLengthToMember =
4582         LV.Designator.Entries.size() - MemPtr.Path.size();
4583     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4584       const CXXRecordDecl *LVDecl = getAsBaseClass(
4585           LV.Designator.Entries[PathLengthToMember + I]);
4586       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4587       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4588         Info.FFDiag(RHS);
4589         return nullptr;
4590       }
4591     }
4592 
4593     // Truncate the lvalue to the appropriate derived class.
4594     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4595                             PathLengthToMember))
4596       return nullptr;
4597   } else if (!MemPtr.Path.empty()) {
4598     // Extend the LValue path with the member pointer's path.
4599     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4600                                   MemPtr.Path.size() + IncludeMember);
4601 
4602     // Walk down to the appropriate base class.
4603     if (const PointerType *PT = LVType->getAs<PointerType>())
4604       LVType = PT->getPointeeType();
4605     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4606     assert(RD && "member pointer access on non-class-type expression");
4607     // The first class in the path is that of the lvalue.
4608     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4609       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4610       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4611         return nullptr;
4612       RD = Base;
4613     }
4614     // Finally cast to the class containing the member.
4615     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4616                                 MemPtr.getContainingRecord()))
4617       return nullptr;
4618   }
4619 
4620   // Add the member. Note that we cannot build bound member functions here.
4621   if (IncludeMember) {
4622     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4623       if (!HandleLValueMember(Info, RHS, LV, FD))
4624         return nullptr;
4625     } else if (const IndirectFieldDecl *IFD =
4626                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4627       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4628         return nullptr;
4629     } else {
4630       llvm_unreachable("can't construct reference to bound member function");
4631     }
4632   }
4633 
4634   return MemPtr.getDecl();
4635 }
4636 
4637 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4638                                                   const BinaryOperator *BO,
4639                                                   LValue &LV,
4640                                                   bool IncludeMember = true) {
4641   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4642 
4643   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4644     if (Info.noteFailure()) {
4645       MemberPtr MemPtr;
4646       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4647     }
4648     return nullptr;
4649   }
4650 
4651   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4652                                    BO->getRHS(), IncludeMember);
4653 }
4654 
4655 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4656 /// the provided lvalue, which currently refers to the base object.
4657 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4658                                     LValue &Result) {
4659   SubobjectDesignator &D = Result.Designator;
4660   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4661     return false;
4662 
4663   QualType TargetQT = E->getType();
4664   if (const PointerType *PT = TargetQT->getAs<PointerType>())
4665     TargetQT = PT->getPointeeType();
4666 
4667   // Check this cast lands within the final derived-to-base subobject path.
4668   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4669     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4670       << D.MostDerivedType << TargetQT;
4671     return false;
4672   }
4673 
4674   // Check the type of the final cast. We don't need to check the path,
4675   // since a cast can only be formed if the path is unique.
4676   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4677   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4678   const CXXRecordDecl *FinalType;
4679   if (NewEntriesSize == D.MostDerivedPathLength)
4680     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4681   else
4682     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4683   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4684     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4685       << D.MostDerivedType << TargetQT;
4686     return false;
4687   }
4688 
4689   // Truncate the lvalue to the appropriate derived class.
4690   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4691 }
4692 
4693 /// Get the value to use for a default-initialized object of type T.
4694 /// Return false if it encounters something invalid.
4695 static bool getDefaultInitValue(QualType T, APValue &Result) {
4696   bool Success = true;
4697   if (auto *RD = T->getAsCXXRecordDecl()) {
4698     if (RD->isInvalidDecl()) {
4699       Result = APValue();
4700       return false;
4701     }
4702     if (RD->isUnion()) {
4703       Result = APValue((const FieldDecl *)nullptr);
4704       return true;
4705     }
4706     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4707                      std::distance(RD->field_begin(), RD->field_end()));
4708 
4709     unsigned Index = 0;
4710     for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4711                                                   End = RD->bases_end();
4712          I != End; ++I, ++Index)
4713       Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index));
4714 
4715     for (const auto *I : RD->fields()) {
4716       if (I->isUnnamedBitfield())
4717         continue;
4718       Success &= getDefaultInitValue(I->getType(),
4719                                      Result.getStructField(I->getFieldIndex()));
4720     }
4721     return Success;
4722   }
4723 
4724   if (auto *AT =
4725           dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4726     Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4727     if (Result.hasArrayFiller())
4728       Success &=
4729           getDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
4730 
4731     return Success;
4732   }
4733 
4734   Result = APValue::IndeterminateValue();
4735   return true;
4736 }
4737 
4738 namespace {
4739 enum EvalStmtResult {
4740   /// Evaluation failed.
4741   ESR_Failed,
4742   /// Hit a 'return' statement.
4743   ESR_Returned,
4744   /// Evaluation succeeded.
4745   ESR_Succeeded,
4746   /// Hit a 'continue' statement.
4747   ESR_Continue,
4748   /// Hit a 'break' statement.
4749   ESR_Break,
4750   /// Still scanning for 'case' or 'default' statement.
4751   ESR_CaseNotFound
4752 };
4753 }
4754 
4755 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4756   // We don't need to evaluate the initializer for a static local.
4757   if (!VD->hasLocalStorage())
4758     return true;
4759 
4760   LValue Result;
4761   APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
4762                                                    ScopeKind::Block, Result);
4763 
4764   const Expr *InitE = VD->getInit();
4765   if (!InitE)
4766     return getDefaultInitValue(VD->getType(), Val);
4767 
4768   if (InitE->isValueDependent())
4769     return false;
4770 
4771   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4772     // Wipe out any partially-computed value, to allow tracking that this
4773     // evaluation failed.
4774     Val = APValue();
4775     return false;
4776   }
4777 
4778   return true;
4779 }
4780 
4781 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4782   bool OK = true;
4783 
4784   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4785     OK &= EvaluateVarDecl(Info, VD);
4786 
4787   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4788     for (auto *BD : DD->bindings())
4789       if (auto *VD = BD->getHoldingVar())
4790         OK &= EvaluateDecl(Info, VD);
4791 
4792   return OK;
4793 }
4794 
4795 
4796 /// Evaluate a condition (either a variable declaration or an expression).
4797 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4798                          const Expr *Cond, bool &Result) {
4799   FullExpressionRAII Scope(Info);
4800   if (CondDecl && !EvaluateDecl(Info, CondDecl))
4801     return false;
4802   if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4803     return false;
4804   return Scope.destroy();
4805 }
4806 
4807 namespace {
4808 /// A location where the result (returned value) of evaluating a
4809 /// statement should be stored.
4810 struct StmtResult {
4811   /// The APValue that should be filled in with the returned value.
4812   APValue &Value;
4813   /// The location containing the result, if any (used to support RVO).
4814   const LValue *Slot;
4815 };
4816 
4817 struct TempVersionRAII {
4818   CallStackFrame &Frame;
4819 
4820   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4821     Frame.pushTempVersion();
4822   }
4823 
4824   ~TempVersionRAII() {
4825     Frame.popTempVersion();
4826   }
4827 };
4828 
4829 }
4830 
4831 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4832                                    const Stmt *S,
4833                                    const SwitchCase *SC = nullptr);
4834 
4835 /// Evaluate the body of a loop, and translate the result as appropriate.
4836 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4837                                        const Stmt *Body,
4838                                        const SwitchCase *Case = nullptr) {
4839   BlockScopeRAII Scope(Info);
4840 
4841   EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4842   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4843     ESR = ESR_Failed;
4844 
4845   switch (ESR) {
4846   case ESR_Break:
4847     return ESR_Succeeded;
4848   case ESR_Succeeded:
4849   case ESR_Continue:
4850     return ESR_Continue;
4851   case ESR_Failed:
4852   case ESR_Returned:
4853   case ESR_CaseNotFound:
4854     return ESR;
4855   }
4856   llvm_unreachable("Invalid EvalStmtResult!");
4857 }
4858 
4859 /// Evaluate a switch statement.
4860 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4861                                      const SwitchStmt *SS) {
4862   BlockScopeRAII Scope(Info);
4863 
4864   // Evaluate the switch condition.
4865   APSInt Value;
4866   {
4867     if (const Stmt *Init = SS->getInit()) {
4868       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4869       if (ESR != ESR_Succeeded) {
4870         if (ESR != ESR_Failed && !Scope.destroy())
4871           ESR = ESR_Failed;
4872         return ESR;
4873       }
4874     }
4875 
4876     FullExpressionRAII CondScope(Info);
4877     if (SS->getConditionVariable() &&
4878         !EvaluateDecl(Info, SS->getConditionVariable()))
4879       return ESR_Failed;
4880     if (!EvaluateInteger(SS->getCond(), Value, Info))
4881       return ESR_Failed;
4882     if (!CondScope.destroy())
4883       return ESR_Failed;
4884   }
4885 
4886   // Find the switch case corresponding to the value of the condition.
4887   // FIXME: Cache this lookup.
4888   const SwitchCase *Found = nullptr;
4889   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4890        SC = SC->getNextSwitchCase()) {
4891     if (isa<DefaultStmt>(SC)) {
4892       Found = SC;
4893       continue;
4894     }
4895 
4896     const CaseStmt *CS = cast<CaseStmt>(SC);
4897     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4898     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4899                               : LHS;
4900     if (LHS <= Value && Value <= RHS) {
4901       Found = SC;
4902       break;
4903     }
4904   }
4905 
4906   if (!Found)
4907     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4908 
4909   // Search the switch body for the switch case and evaluate it from there.
4910   EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
4911   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4912     return ESR_Failed;
4913 
4914   switch (ESR) {
4915   case ESR_Break:
4916     return ESR_Succeeded;
4917   case ESR_Succeeded:
4918   case ESR_Continue:
4919   case ESR_Failed:
4920   case ESR_Returned:
4921     return ESR;
4922   case ESR_CaseNotFound:
4923     // This can only happen if the switch case is nested within a statement
4924     // expression. We have no intention of supporting that.
4925     Info.FFDiag(Found->getBeginLoc(),
4926                 diag::note_constexpr_stmt_expr_unsupported);
4927     return ESR_Failed;
4928   }
4929   llvm_unreachable("Invalid EvalStmtResult!");
4930 }
4931 
4932 // Evaluate a statement.
4933 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4934                                    const Stmt *S, const SwitchCase *Case) {
4935   if (!Info.nextStep(S))
4936     return ESR_Failed;
4937 
4938   // If we're hunting down a 'case' or 'default' label, recurse through
4939   // substatements until we hit the label.
4940   if (Case) {
4941     switch (S->getStmtClass()) {
4942     case Stmt::CompoundStmtClass:
4943       // FIXME: Precompute which substatement of a compound statement we
4944       // would jump to, and go straight there rather than performing a
4945       // linear scan each time.
4946     case Stmt::LabelStmtClass:
4947     case Stmt::AttributedStmtClass:
4948     case Stmt::DoStmtClass:
4949       break;
4950 
4951     case Stmt::CaseStmtClass:
4952     case Stmt::DefaultStmtClass:
4953       if (Case == S)
4954         Case = nullptr;
4955       break;
4956 
4957     case Stmt::IfStmtClass: {
4958       // FIXME: Precompute which side of an 'if' we would jump to, and go
4959       // straight there rather than scanning both sides.
4960       const IfStmt *IS = cast<IfStmt>(S);
4961 
4962       // Wrap the evaluation in a block scope, in case it's a DeclStmt
4963       // preceded by our switch label.
4964       BlockScopeRAII Scope(Info);
4965 
4966       // Step into the init statement in case it brings an (uninitialized)
4967       // variable into scope.
4968       if (const Stmt *Init = IS->getInit()) {
4969         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
4970         if (ESR != ESR_CaseNotFound) {
4971           assert(ESR != ESR_Succeeded);
4972           return ESR;
4973         }
4974       }
4975 
4976       // Condition variable must be initialized if it exists.
4977       // FIXME: We can skip evaluating the body if there's a condition
4978       // variable, as there can't be any case labels within it.
4979       // (The same is true for 'for' statements.)
4980 
4981       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
4982       if (ESR == ESR_Failed)
4983         return ESR;
4984       if (ESR != ESR_CaseNotFound)
4985         return Scope.destroy() ? ESR : ESR_Failed;
4986       if (!IS->getElse())
4987         return ESR_CaseNotFound;
4988 
4989       ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
4990       if (ESR == ESR_Failed)
4991         return ESR;
4992       if (ESR != ESR_CaseNotFound)
4993         return Scope.destroy() ? ESR : ESR_Failed;
4994       return ESR_CaseNotFound;
4995     }
4996 
4997     case Stmt::WhileStmtClass: {
4998       EvalStmtResult ESR =
4999           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5000       if (ESR != ESR_Continue)
5001         return ESR;
5002       break;
5003     }
5004 
5005     case Stmt::ForStmtClass: {
5006       const ForStmt *FS = cast<ForStmt>(S);
5007       BlockScopeRAII Scope(Info);
5008 
5009       // Step into the init statement in case it brings an (uninitialized)
5010       // variable into scope.
5011       if (const Stmt *Init = FS->getInit()) {
5012         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5013         if (ESR != ESR_CaseNotFound) {
5014           assert(ESR != ESR_Succeeded);
5015           return ESR;
5016         }
5017       }
5018 
5019       EvalStmtResult ESR =
5020           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5021       if (ESR != ESR_Continue)
5022         return ESR;
5023       if (FS->getInc()) {
5024         FullExpressionRAII IncScope(Info);
5025         if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
5026           return ESR_Failed;
5027       }
5028       break;
5029     }
5030 
5031     case Stmt::DeclStmtClass: {
5032       // Start the lifetime of any uninitialized variables we encounter. They
5033       // might be used by the selected branch of the switch.
5034       const DeclStmt *DS = cast<DeclStmt>(S);
5035       for (const auto *D : DS->decls()) {
5036         if (const auto *VD = dyn_cast<VarDecl>(D)) {
5037           if (VD->hasLocalStorage() && !VD->getInit())
5038             if (!EvaluateVarDecl(Info, VD))
5039               return ESR_Failed;
5040           // FIXME: If the variable has initialization that can't be jumped
5041           // over, bail out of any immediately-surrounding compound-statement
5042           // too. There can't be any case labels here.
5043         }
5044       }
5045       return ESR_CaseNotFound;
5046     }
5047 
5048     default:
5049       return ESR_CaseNotFound;
5050     }
5051   }
5052 
5053   switch (S->getStmtClass()) {
5054   default:
5055     if (const Expr *E = dyn_cast<Expr>(S)) {
5056       // Don't bother evaluating beyond an expression-statement which couldn't
5057       // be evaluated.
5058       // FIXME: Do we need the FullExpressionRAII object here?
5059       // VisitExprWithCleanups should create one when necessary.
5060       FullExpressionRAII Scope(Info);
5061       if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5062         return ESR_Failed;
5063       return ESR_Succeeded;
5064     }
5065 
5066     Info.FFDiag(S->getBeginLoc());
5067     return ESR_Failed;
5068 
5069   case Stmt::NullStmtClass:
5070     return ESR_Succeeded;
5071 
5072   case Stmt::DeclStmtClass: {
5073     const DeclStmt *DS = cast<DeclStmt>(S);
5074     for (const auto *D : DS->decls()) {
5075       // Each declaration initialization is its own full-expression.
5076       FullExpressionRAII Scope(Info);
5077       if (!EvaluateDecl(Info, D) && !Info.noteFailure())
5078         return ESR_Failed;
5079       if (!Scope.destroy())
5080         return ESR_Failed;
5081     }
5082     return ESR_Succeeded;
5083   }
5084 
5085   case Stmt::ReturnStmtClass: {
5086     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5087     FullExpressionRAII Scope(Info);
5088     if (RetExpr &&
5089         !(Result.Slot
5090               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5091               : Evaluate(Result.Value, Info, RetExpr)))
5092       return ESR_Failed;
5093     return Scope.destroy() ? ESR_Returned : ESR_Failed;
5094   }
5095 
5096   case Stmt::CompoundStmtClass: {
5097     BlockScopeRAII Scope(Info);
5098 
5099     const CompoundStmt *CS = cast<CompoundStmt>(S);
5100     for (const auto *BI : CS->body()) {
5101       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5102       if (ESR == ESR_Succeeded)
5103         Case = nullptr;
5104       else if (ESR != ESR_CaseNotFound) {
5105         if (ESR != ESR_Failed && !Scope.destroy())
5106           return ESR_Failed;
5107         return ESR;
5108       }
5109     }
5110     if (Case)
5111       return ESR_CaseNotFound;
5112     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5113   }
5114 
5115   case Stmt::IfStmtClass: {
5116     const IfStmt *IS = cast<IfStmt>(S);
5117 
5118     // Evaluate the condition, as either a var decl or as an expression.
5119     BlockScopeRAII Scope(Info);
5120     if (const Stmt *Init = IS->getInit()) {
5121       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5122       if (ESR != ESR_Succeeded) {
5123         if (ESR != ESR_Failed && !Scope.destroy())
5124           return ESR_Failed;
5125         return ESR;
5126       }
5127     }
5128     bool Cond;
5129     if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
5130       return ESR_Failed;
5131 
5132     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5133       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5134       if (ESR != ESR_Succeeded) {
5135         if (ESR != ESR_Failed && !Scope.destroy())
5136           return ESR_Failed;
5137         return ESR;
5138       }
5139     }
5140     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5141   }
5142 
5143   case Stmt::WhileStmtClass: {
5144     const WhileStmt *WS = cast<WhileStmt>(S);
5145     while (true) {
5146       BlockScopeRAII Scope(Info);
5147       bool Continue;
5148       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5149                         Continue))
5150         return ESR_Failed;
5151       if (!Continue)
5152         break;
5153 
5154       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5155       if (ESR != ESR_Continue) {
5156         if (ESR != ESR_Failed && !Scope.destroy())
5157           return ESR_Failed;
5158         return ESR;
5159       }
5160       if (!Scope.destroy())
5161         return ESR_Failed;
5162     }
5163     return ESR_Succeeded;
5164   }
5165 
5166   case Stmt::DoStmtClass: {
5167     const DoStmt *DS = cast<DoStmt>(S);
5168     bool Continue;
5169     do {
5170       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5171       if (ESR != ESR_Continue)
5172         return ESR;
5173       Case = nullptr;
5174 
5175       FullExpressionRAII CondScope(Info);
5176       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5177           !CondScope.destroy())
5178         return ESR_Failed;
5179     } while (Continue);
5180     return ESR_Succeeded;
5181   }
5182 
5183   case Stmt::ForStmtClass: {
5184     const ForStmt *FS = cast<ForStmt>(S);
5185     BlockScopeRAII ForScope(Info);
5186     if (FS->getInit()) {
5187       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5188       if (ESR != ESR_Succeeded) {
5189         if (ESR != ESR_Failed && !ForScope.destroy())
5190           return ESR_Failed;
5191         return ESR;
5192       }
5193     }
5194     while (true) {
5195       BlockScopeRAII IterScope(Info);
5196       bool Continue = true;
5197       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5198                                          FS->getCond(), Continue))
5199         return ESR_Failed;
5200       if (!Continue)
5201         break;
5202 
5203       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5204       if (ESR != ESR_Continue) {
5205         if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5206           return ESR_Failed;
5207         return ESR;
5208       }
5209 
5210       if (FS->getInc()) {
5211         FullExpressionRAII IncScope(Info);
5212         if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
5213           return ESR_Failed;
5214       }
5215 
5216       if (!IterScope.destroy())
5217         return ESR_Failed;
5218     }
5219     return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5220   }
5221 
5222   case Stmt::CXXForRangeStmtClass: {
5223     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5224     BlockScopeRAII Scope(Info);
5225 
5226     // Evaluate the init-statement if present.
5227     if (FS->getInit()) {
5228       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5229       if (ESR != ESR_Succeeded) {
5230         if (ESR != ESR_Failed && !Scope.destroy())
5231           return ESR_Failed;
5232         return ESR;
5233       }
5234     }
5235 
5236     // Initialize the __range variable.
5237     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5238     if (ESR != ESR_Succeeded) {
5239       if (ESR != ESR_Failed && !Scope.destroy())
5240         return ESR_Failed;
5241       return ESR;
5242     }
5243 
5244     // Create the __begin and __end iterators.
5245     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5246     if (ESR != ESR_Succeeded) {
5247       if (ESR != ESR_Failed && !Scope.destroy())
5248         return ESR_Failed;
5249       return ESR;
5250     }
5251     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5252     if (ESR != ESR_Succeeded) {
5253       if (ESR != ESR_Failed && !Scope.destroy())
5254         return ESR_Failed;
5255       return ESR;
5256     }
5257 
5258     while (true) {
5259       // Condition: __begin != __end.
5260       {
5261         bool Continue = true;
5262         FullExpressionRAII CondExpr(Info);
5263         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5264           return ESR_Failed;
5265         if (!Continue)
5266           break;
5267       }
5268 
5269       // User's variable declaration, initialized by *__begin.
5270       BlockScopeRAII InnerScope(Info);
5271       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5272       if (ESR != ESR_Succeeded) {
5273         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5274           return ESR_Failed;
5275         return ESR;
5276       }
5277 
5278       // Loop body.
5279       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5280       if (ESR != ESR_Continue) {
5281         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5282           return ESR_Failed;
5283         return ESR;
5284       }
5285 
5286       // Increment: ++__begin
5287       if (!EvaluateIgnoredValue(Info, FS->getInc()))
5288         return ESR_Failed;
5289 
5290       if (!InnerScope.destroy())
5291         return ESR_Failed;
5292     }
5293 
5294     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5295   }
5296 
5297   case Stmt::SwitchStmtClass:
5298     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5299 
5300   case Stmt::ContinueStmtClass:
5301     return ESR_Continue;
5302 
5303   case Stmt::BreakStmtClass:
5304     return ESR_Break;
5305 
5306   case Stmt::LabelStmtClass:
5307     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5308 
5309   case Stmt::AttributedStmtClass:
5310     // As a general principle, C++11 attributes can be ignored without
5311     // any semantic impact.
5312     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
5313                         Case);
5314 
5315   case Stmt::CaseStmtClass:
5316   case Stmt::DefaultStmtClass:
5317     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5318   case Stmt::CXXTryStmtClass:
5319     // Evaluate try blocks by evaluating all sub statements.
5320     return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5321   }
5322 }
5323 
5324 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5325 /// default constructor. If so, we'll fold it whether or not it's marked as
5326 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
5327 /// so we need special handling.
5328 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5329                                            const CXXConstructorDecl *CD,
5330                                            bool IsValueInitialization) {
5331   if (!CD->isTrivial() || !CD->isDefaultConstructor())
5332     return false;
5333 
5334   // Value-initialization does not call a trivial default constructor, so such a
5335   // call is a core constant expression whether or not the constructor is
5336   // constexpr.
5337   if (!CD->isConstexpr() && !IsValueInitialization) {
5338     if (Info.getLangOpts().CPlusPlus11) {
5339       // FIXME: If DiagDecl is an implicitly-declared special member function,
5340       // we should be much more explicit about why it's not constexpr.
5341       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5342         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5343       Info.Note(CD->getLocation(), diag::note_declared_at);
5344     } else {
5345       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5346     }
5347   }
5348   return true;
5349 }
5350 
5351 /// CheckConstexprFunction - Check that a function can be called in a constant
5352 /// expression.
5353 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5354                                    const FunctionDecl *Declaration,
5355                                    const FunctionDecl *Definition,
5356                                    const Stmt *Body) {
5357   // Potential constant expressions can contain calls to declared, but not yet
5358   // defined, constexpr functions.
5359   if (Info.checkingPotentialConstantExpression() && !Definition &&
5360       Declaration->isConstexpr())
5361     return false;
5362 
5363   // Bail out if the function declaration itself is invalid.  We will
5364   // have produced a relevant diagnostic while parsing it, so just
5365   // note the problematic sub-expression.
5366   if (Declaration->isInvalidDecl()) {
5367     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5368     return false;
5369   }
5370 
5371   // DR1872: An instantiated virtual constexpr function can't be called in a
5372   // constant expression (prior to C++20). We can still constant-fold such a
5373   // call.
5374   if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5375       cast<CXXMethodDecl>(Declaration)->isVirtual())
5376     Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5377 
5378   if (Definition && Definition->isInvalidDecl()) {
5379     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5380     return false;
5381   }
5382 
5383   if (const auto *CtorDecl = dyn_cast_or_null<CXXConstructorDecl>(Definition)) {
5384     for (const auto *InitExpr : CtorDecl->inits()) {
5385       if (InitExpr->getInit() && InitExpr->getInit()->containsErrors())
5386         return false;
5387     }
5388   }
5389 
5390   // Can we evaluate this function call?
5391   if (Definition && Definition->isConstexpr() && Body)
5392     return true;
5393 
5394   if (Info.getLangOpts().CPlusPlus11) {
5395     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5396 
5397     // If this function is not constexpr because it is an inherited
5398     // non-constexpr constructor, diagnose that directly.
5399     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5400     if (CD && CD->isInheritingConstructor()) {
5401       auto *Inherited = CD->getInheritedConstructor().getConstructor();
5402       if (!Inherited->isConstexpr())
5403         DiagDecl = CD = Inherited;
5404     }
5405 
5406     // FIXME: If DiagDecl is an implicitly-declared special member function
5407     // or an inheriting constructor, we should be much more explicit about why
5408     // it's not constexpr.
5409     if (CD && CD->isInheritingConstructor())
5410       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5411         << CD->getInheritedConstructor().getConstructor()->getParent();
5412     else
5413       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5414         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5415     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5416   } else {
5417     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5418   }
5419   return false;
5420 }
5421 
5422 namespace {
5423 struct CheckDynamicTypeHandler {
5424   AccessKinds AccessKind;
5425   typedef bool result_type;
5426   bool failed() { return false; }
5427   bool found(APValue &Subobj, QualType SubobjType) { return true; }
5428   bool found(APSInt &Value, QualType SubobjType) { return true; }
5429   bool found(APFloat &Value, QualType SubobjType) { return true; }
5430 };
5431 } // end anonymous namespace
5432 
5433 /// Check that we can access the notional vptr of an object / determine its
5434 /// dynamic type.
5435 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5436                              AccessKinds AK, bool Polymorphic) {
5437   if (This.Designator.Invalid)
5438     return false;
5439 
5440   CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5441 
5442   if (!Obj)
5443     return false;
5444 
5445   if (!Obj.Value) {
5446     // The object is not usable in constant expressions, so we can't inspect
5447     // its value to see if it's in-lifetime or what the active union members
5448     // are. We can still check for a one-past-the-end lvalue.
5449     if (This.Designator.isOnePastTheEnd() ||
5450         This.Designator.isMostDerivedAnUnsizedArray()) {
5451       Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5452                          ? diag::note_constexpr_access_past_end
5453                          : diag::note_constexpr_access_unsized_array)
5454           << AK;
5455       return false;
5456     } else if (Polymorphic) {
5457       // Conservatively refuse to perform a polymorphic operation if we would
5458       // not be able to read a notional 'vptr' value.
5459       APValue Val;
5460       This.moveInto(Val);
5461       QualType StarThisType =
5462           Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5463       Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5464           << AK << Val.getAsString(Info.Ctx, StarThisType);
5465       return false;
5466     }
5467     return true;
5468   }
5469 
5470   CheckDynamicTypeHandler Handler{AK};
5471   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5472 }
5473 
5474 /// Check that the pointee of the 'this' pointer in a member function call is
5475 /// either within its lifetime or in its period of construction or destruction.
5476 static bool
5477 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5478                                      const LValue &This,
5479                                      const CXXMethodDecl *NamedMember) {
5480   return checkDynamicType(
5481       Info, E, This,
5482       isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5483 }
5484 
5485 struct DynamicType {
5486   /// The dynamic class type of the object.
5487   const CXXRecordDecl *Type;
5488   /// The corresponding path length in the lvalue.
5489   unsigned PathLength;
5490 };
5491 
5492 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5493                                              unsigned PathLength) {
5494   assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5495       Designator.Entries.size() && "invalid path length");
5496   return (PathLength == Designator.MostDerivedPathLength)
5497              ? Designator.MostDerivedType->getAsCXXRecordDecl()
5498              : getAsBaseClass(Designator.Entries[PathLength - 1]);
5499 }
5500 
5501 /// Determine the dynamic type of an object.
5502 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
5503                                                 LValue &This, AccessKinds AK) {
5504   // If we don't have an lvalue denoting an object of class type, there is no
5505   // meaningful dynamic type. (We consider objects of non-class type to have no
5506   // dynamic type.)
5507   if (!checkDynamicType(Info, E, This, AK, true))
5508     return None;
5509 
5510   // Refuse to compute a dynamic type in the presence of virtual bases. This
5511   // shouldn't happen other than in constant-folding situations, since literal
5512   // types can't have virtual bases.
5513   //
5514   // Note that consumers of DynamicType assume that the type has no virtual
5515   // bases, and will need modifications if this restriction is relaxed.
5516   const CXXRecordDecl *Class =
5517       This.Designator.MostDerivedType->getAsCXXRecordDecl();
5518   if (!Class || Class->getNumVBases()) {
5519     Info.FFDiag(E);
5520     return None;
5521   }
5522 
5523   // FIXME: For very deep class hierarchies, it might be beneficial to use a
5524   // binary search here instead. But the overwhelmingly common case is that
5525   // we're not in the middle of a constructor, so it probably doesn't matter
5526   // in practice.
5527   ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5528   for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5529        PathLength <= Path.size(); ++PathLength) {
5530     switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5531                                       Path.slice(0, PathLength))) {
5532     case ConstructionPhase::Bases:
5533     case ConstructionPhase::DestroyingBases:
5534       // We're constructing or destroying a base class. This is not the dynamic
5535       // type.
5536       break;
5537 
5538     case ConstructionPhase::None:
5539     case ConstructionPhase::AfterBases:
5540     case ConstructionPhase::AfterFields:
5541     case ConstructionPhase::Destroying:
5542       // We've finished constructing the base classes and not yet started
5543       // destroying them again, so this is the dynamic type.
5544       return DynamicType{getBaseClassType(This.Designator, PathLength),
5545                          PathLength};
5546     }
5547   }
5548 
5549   // CWG issue 1517: we're constructing a base class of the object described by
5550   // 'This', so that object has not yet begun its period of construction and
5551   // any polymorphic operation on it results in undefined behavior.
5552   Info.FFDiag(E);
5553   return None;
5554 }
5555 
5556 /// Perform virtual dispatch.
5557 static const CXXMethodDecl *HandleVirtualDispatch(
5558     EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5559     llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5560   Optional<DynamicType> DynType = ComputeDynamicType(
5561       Info, E, This,
5562       isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5563   if (!DynType)
5564     return nullptr;
5565 
5566   // Find the final overrider. It must be declared in one of the classes on the
5567   // path from the dynamic type to the static type.
5568   // FIXME: If we ever allow literal types to have virtual base classes, that
5569   // won't be true.
5570   const CXXMethodDecl *Callee = Found;
5571   unsigned PathLength = DynType->PathLength;
5572   for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5573     const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5574     const CXXMethodDecl *Overrider =
5575         Found->getCorrespondingMethodDeclaredInClass(Class, false);
5576     if (Overrider) {
5577       Callee = Overrider;
5578       break;
5579     }
5580   }
5581 
5582   // C++2a [class.abstract]p6:
5583   //   the effect of making a virtual call to a pure virtual function [...] is
5584   //   undefined
5585   if (Callee->isPure()) {
5586     Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5587     Info.Note(Callee->getLocation(), diag::note_declared_at);
5588     return nullptr;
5589   }
5590 
5591   // If necessary, walk the rest of the path to determine the sequence of
5592   // covariant adjustment steps to apply.
5593   if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5594                                        Found->getReturnType())) {
5595     CovariantAdjustmentPath.push_back(Callee->getReturnType());
5596     for (unsigned CovariantPathLength = PathLength + 1;
5597          CovariantPathLength != This.Designator.Entries.size();
5598          ++CovariantPathLength) {
5599       const CXXRecordDecl *NextClass =
5600           getBaseClassType(This.Designator, CovariantPathLength);
5601       const CXXMethodDecl *Next =
5602           Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5603       if (Next && !Info.Ctx.hasSameUnqualifiedType(
5604                       Next->getReturnType(), CovariantAdjustmentPath.back()))
5605         CovariantAdjustmentPath.push_back(Next->getReturnType());
5606     }
5607     if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5608                                          CovariantAdjustmentPath.back()))
5609       CovariantAdjustmentPath.push_back(Found->getReturnType());
5610   }
5611 
5612   // Perform 'this' adjustment.
5613   if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5614     return nullptr;
5615 
5616   return Callee;
5617 }
5618 
5619 /// Perform the adjustment from a value returned by a virtual function to
5620 /// a value of the statically expected type, which may be a pointer or
5621 /// reference to a base class of the returned type.
5622 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5623                                             APValue &Result,
5624                                             ArrayRef<QualType> Path) {
5625   assert(Result.isLValue() &&
5626          "unexpected kind of APValue for covariant return");
5627   if (Result.isNullPointer())
5628     return true;
5629 
5630   LValue LVal;
5631   LVal.setFrom(Info.Ctx, Result);
5632 
5633   const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5634   for (unsigned I = 1; I != Path.size(); ++I) {
5635     const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5636     assert(OldClass && NewClass && "unexpected kind of covariant return");
5637     if (OldClass != NewClass &&
5638         !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5639       return false;
5640     OldClass = NewClass;
5641   }
5642 
5643   LVal.moveInto(Result);
5644   return true;
5645 }
5646 
5647 /// Determine whether \p Base, which is known to be a direct base class of
5648 /// \p Derived, is a public base class.
5649 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5650                               const CXXRecordDecl *Base) {
5651   for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5652     auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5653     if (BaseClass && declaresSameEntity(BaseClass, Base))
5654       return BaseSpec.getAccessSpecifier() == AS_public;
5655   }
5656   llvm_unreachable("Base is not a direct base of Derived");
5657 }
5658 
5659 /// Apply the given dynamic cast operation on the provided lvalue.
5660 ///
5661 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
5662 /// to find a suitable target subobject.
5663 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5664                               LValue &Ptr) {
5665   // We can't do anything with a non-symbolic pointer value.
5666   SubobjectDesignator &D = Ptr.Designator;
5667   if (D.Invalid)
5668     return false;
5669 
5670   // C++ [expr.dynamic.cast]p6:
5671   //   If v is a null pointer value, the result is a null pointer value.
5672   if (Ptr.isNullPointer() && !E->isGLValue())
5673     return true;
5674 
5675   // For all the other cases, we need the pointer to point to an object within
5676   // its lifetime / period of construction / destruction, and we need to know
5677   // its dynamic type.
5678   Optional<DynamicType> DynType =
5679       ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5680   if (!DynType)
5681     return false;
5682 
5683   // C++ [expr.dynamic.cast]p7:
5684   //   If T is "pointer to cv void", then the result is a pointer to the most
5685   //   derived object
5686   if (E->getType()->isVoidPointerType())
5687     return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5688 
5689   const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5690   assert(C && "dynamic_cast target is not void pointer nor class");
5691   CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5692 
5693   auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5694     // C++ [expr.dynamic.cast]p9:
5695     if (!E->isGLValue()) {
5696       //   The value of a failed cast to pointer type is the null pointer value
5697       //   of the required result type.
5698       Ptr.setNull(Info.Ctx, E->getType());
5699       return true;
5700     }
5701 
5702     //   A failed cast to reference type throws [...] std::bad_cast.
5703     unsigned DiagKind;
5704     if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5705                    DynType->Type->isDerivedFrom(C)))
5706       DiagKind = 0;
5707     else if (!Paths || Paths->begin() == Paths->end())
5708       DiagKind = 1;
5709     else if (Paths->isAmbiguous(CQT))
5710       DiagKind = 2;
5711     else {
5712       assert(Paths->front().Access != AS_public && "why did the cast fail?");
5713       DiagKind = 3;
5714     }
5715     Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5716         << DiagKind << Ptr.Designator.getType(Info.Ctx)
5717         << Info.Ctx.getRecordType(DynType->Type)
5718         << E->getType().getUnqualifiedType();
5719     return false;
5720   };
5721 
5722   // Runtime check, phase 1:
5723   //   Walk from the base subobject towards the derived object looking for the
5724   //   target type.
5725   for (int PathLength = Ptr.Designator.Entries.size();
5726        PathLength >= (int)DynType->PathLength; --PathLength) {
5727     const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5728     if (declaresSameEntity(Class, C))
5729       return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5730     // We can only walk across public inheritance edges.
5731     if (PathLength > (int)DynType->PathLength &&
5732         !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5733                            Class))
5734       return RuntimeCheckFailed(nullptr);
5735   }
5736 
5737   // Runtime check, phase 2:
5738   //   Search the dynamic type for an unambiguous public base of type C.
5739   CXXBasePaths Paths(/*FindAmbiguities=*/true,
5740                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
5741   if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5742       Paths.front().Access == AS_public) {
5743     // Downcast to the dynamic type...
5744     if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5745       return false;
5746     // ... then upcast to the chosen base class subobject.
5747     for (CXXBasePathElement &Elem : Paths.front())
5748       if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5749         return false;
5750     return true;
5751   }
5752 
5753   // Otherwise, the runtime check fails.
5754   return RuntimeCheckFailed(&Paths);
5755 }
5756 
5757 namespace {
5758 struct StartLifetimeOfUnionMemberHandler {
5759   EvalInfo &Info;
5760   const Expr *LHSExpr;
5761   const FieldDecl *Field;
5762   bool DuringInit;
5763   bool Failed = false;
5764   static const AccessKinds AccessKind = AK_Assign;
5765 
5766   typedef bool result_type;
5767   bool failed() { return Failed; }
5768   bool found(APValue &Subobj, QualType SubobjType) {
5769     // We are supposed to perform no initialization but begin the lifetime of
5770     // the object. We interpret that as meaning to do what default
5771     // initialization of the object would do if all constructors involved were
5772     // trivial:
5773     //  * All base, non-variant member, and array element subobjects' lifetimes
5774     //    begin
5775     //  * No variant members' lifetimes begin
5776     //  * All scalar subobjects whose lifetimes begin have indeterminate values
5777     assert(SubobjType->isUnionType());
5778     if (declaresSameEntity(Subobj.getUnionField(), Field)) {
5779       // This union member is already active. If it's also in-lifetime, there's
5780       // nothing to do.
5781       if (Subobj.getUnionValue().hasValue())
5782         return true;
5783     } else if (DuringInit) {
5784       // We're currently in the process of initializing a different union
5785       // member.  If we carried on, that initialization would attempt to
5786       // store to an inactive union member, resulting in undefined behavior.
5787       Info.FFDiag(LHSExpr,
5788                   diag::note_constexpr_union_member_change_during_init);
5789       return false;
5790     }
5791     APValue Result;
5792     Failed = !getDefaultInitValue(Field->getType(), Result);
5793     Subobj.setUnion(Field, Result);
5794     return true;
5795   }
5796   bool found(APSInt &Value, QualType SubobjType) {
5797     llvm_unreachable("wrong value kind for union object");
5798   }
5799   bool found(APFloat &Value, QualType SubobjType) {
5800     llvm_unreachable("wrong value kind for union object");
5801   }
5802 };
5803 } // end anonymous namespace
5804 
5805 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5806 
5807 /// Handle a builtin simple-assignment or a call to a trivial assignment
5808 /// operator whose left-hand side might involve a union member access. If it
5809 /// does, implicitly start the lifetime of any accessed union elements per
5810 /// C++20 [class.union]5.
5811 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5812                                           const LValue &LHS) {
5813   if (LHS.InvalidBase || LHS.Designator.Invalid)
5814     return false;
5815 
5816   llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5817   // C++ [class.union]p5:
5818   //   define the set S(E) of subexpressions of E as follows:
5819   unsigned PathLength = LHS.Designator.Entries.size();
5820   for (const Expr *E = LHSExpr; E != nullptr;) {
5821     //   -- If E is of the form A.B, S(E) contains the elements of S(A)...
5822     if (auto *ME = dyn_cast<MemberExpr>(E)) {
5823       auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5824       // Note that we can't implicitly start the lifetime of a reference,
5825       // so we don't need to proceed any further if we reach one.
5826       if (!FD || FD->getType()->isReferenceType())
5827         break;
5828 
5829       //    ... and also contains A.B if B names a union member ...
5830       if (FD->getParent()->isUnion()) {
5831         //    ... of a non-class, non-array type, or of a class type with a
5832         //    trivial default constructor that is not deleted, or an array of
5833         //    such types.
5834         auto *RD =
5835             FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5836         if (!RD || RD->hasTrivialDefaultConstructor())
5837           UnionPathLengths.push_back({PathLength - 1, FD});
5838       }
5839 
5840       E = ME->getBase();
5841       --PathLength;
5842       assert(declaresSameEntity(FD,
5843                                 LHS.Designator.Entries[PathLength]
5844                                     .getAsBaseOrMember().getPointer()));
5845 
5846       //   -- If E is of the form A[B] and is interpreted as a built-in array
5847       //      subscripting operator, S(E) is [S(the array operand, if any)].
5848     } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5849       // Step over an ArrayToPointerDecay implicit cast.
5850       auto *Base = ASE->getBase()->IgnoreImplicit();
5851       if (!Base->getType()->isArrayType())
5852         break;
5853 
5854       E = Base;
5855       --PathLength;
5856 
5857     } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5858       // Step over a derived-to-base conversion.
5859       E = ICE->getSubExpr();
5860       if (ICE->getCastKind() == CK_NoOp)
5861         continue;
5862       if (ICE->getCastKind() != CK_DerivedToBase &&
5863           ICE->getCastKind() != CK_UncheckedDerivedToBase)
5864         break;
5865       // Walk path backwards as we walk up from the base to the derived class.
5866       for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
5867         --PathLength;
5868         (void)Elt;
5869         assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
5870                                   LHS.Designator.Entries[PathLength]
5871                                       .getAsBaseOrMember().getPointer()));
5872       }
5873 
5874     //   -- Otherwise, S(E) is empty.
5875     } else {
5876       break;
5877     }
5878   }
5879 
5880   // Common case: no unions' lifetimes are started.
5881   if (UnionPathLengths.empty())
5882     return true;
5883 
5884   //   if modification of X [would access an inactive union member], an object
5885   //   of the type of X is implicitly created
5886   CompleteObject Obj =
5887       findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
5888   if (!Obj)
5889     return false;
5890   for (std::pair<unsigned, const FieldDecl *> LengthAndField :
5891            llvm::reverse(UnionPathLengths)) {
5892     // Form a designator for the union object.
5893     SubobjectDesignator D = LHS.Designator;
5894     D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
5895 
5896     bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
5897                       ConstructionPhase::AfterBases;
5898     StartLifetimeOfUnionMemberHandler StartLifetime{
5899         Info, LHSExpr, LengthAndField.second, DuringInit};
5900     if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
5901       return false;
5902   }
5903 
5904   return true;
5905 }
5906 
5907 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
5908                             CallRef Call, EvalInfo &Info,
5909                             bool NonNull = false) {
5910   LValue LV;
5911   // Create the parameter slot and register its destruction. For a vararg
5912   // argument, create a temporary.
5913   // FIXME: For calling conventions that destroy parameters in the callee,
5914   // should we consider performing destruction when the function returns
5915   // instead?
5916   APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
5917                    : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
5918                                                        ScopeKind::Call, LV);
5919   if (!EvaluateInPlace(V, Info, LV, Arg))
5920     return false;
5921 
5922   // Passing a null pointer to an __attribute__((nonnull)) parameter results in
5923   // undefined behavior, so is non-constant.
5924   if (NonNull && V.isLValue() && V.isNullPointer()) {
5925     Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
5926     return false;
5927   }
5928 
5929   return true;
5930 }
5931 
5932 /// Evaluate the arguments to a function call.
5933 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
5934                          EvalInfo &Info, const FunctionDecl *Callee,
5935                          bool RightToLeft = false) {
5936   bool Success = true;
5937   llvm::SmallBitVector ForbiddenNullArgs;
5938   if (Callee->hasAttr<NonNullAttr>()) {
5939     ForbiddenNullArgs.resize(Args.size());
5940     for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
5941       if (!Attr->args_size()) {
5942         ForbiddenNullArgs.set();
5943         break;
5944       } else
5945         for (auto Idx : Attr->args()) {
5946           unsigned ASTIdx = Idx.getASTIndex();
5947           if (ASTIdx >= Args.size())
5948             continue;
5949           ForbiddenNullArgs[ASTIdx] = 1;
5950         }
5951     }
5952   }
5953   for (unsigned I = 0; I < Args.size(); I++) {
5954     unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
5955     const ParmVarDecl *PVD =
5956         Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
5957     bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
5958     if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) {
5959       // If we're checking for a potential constant expression, evaluate all
5960       // initializers even if some of them fail.
5961       if (!Info.noteFailure())
5962         return false;
5963       Success = false;
5964     }
5965   }
5966   return Success;
5967 }
5968 
5969 /// Perform a trivial copy from Param, which is the parameter of a copy or move
5970 /// constructor or assignment operator.
5971 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
5972                               const Expr *E, APValue &Result,
5973                               bool CopyObjectRepresentation) {
5974   // Find the reference argument.
5975   CallStackFrame *Frame = Info.CurrentCall;
5976   APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
5977   if (!RefValue) {
5978     Info.FFDiag(E);
5979     return false;
5980   }
5981 
5982   // Copy out the contents of the RHS object.
5983   LValue RefLValue;
5984   RefLValue.setFrom(Info.Ctx, *RefValue);
5985   return handleLValueToRValueConversion(
5986       Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
5987       CopyObjectRepresentation);
5988 }
5989 
5990 /// Evaluate a function call.
5991 static bool HandleFunctionCall(SourceLocation CallLoc,
5992                                const FunctionDecl *Callee, const LValue *This,
5993                                ArrayRef<const Expr *> Args, CallRef Call,
5994                                const Stmt *Body, EvalInfo &Info,
5995                                APValue &Result, const LValue *ResultSlot) {
5996   if (!Info.CheckCallLimit(CallLoc))
5997     return false;
5998 
5999   CallStackFrame Frame(Info, CallLoc, Callee, This, Call);
6000 
6001   // For a trivial copy or move assignment, perform an APValue copy. This is
6002   // essential for unions, where the operations performed by the assignment
6003   // operator cannot be represented as statements.
6004   //
6005   // Skip this for non-union classes with no fields; in that case, the defaulted
6006   // copy/move does not actually read the object.
6007   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6008   if (MD && MD->isDefaulted() &&
6009       (MD->getParent()->isUnion() ||
6010        (MD->isTrivial() &&
6011         isReadByLvalueToRvalueConversion(MD->getParent())))) {
6012     assert(This &&
6013            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
6014     APValue RHSValue;
6015     if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6016                            MD->getParent()->isUnion()))
6017       return false;
6018     if (Info.getLangOpts().CPlusPlus20 && MD->isTrivial() &&
6019         !HandleUnionActiveMemberChange(Info, Args[0], *This))
6020       return false;
6021     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
6022                           RHSValue))
6023       return false;
6024     This->moveInto(Result);
6025     return true;
6026   } else if (MD && isLambdaCallOperator(MD)) {
6027     // We're in a lambda; determine the lambda capture field maps unless we're
6028     // just constexpr checking a lambda's call operator. constexpr checking is
6029     // done before the captures have been added to the closure object (unless
6030     // we're inferring constexpr-ness), so we don't have access to them in this
6031     // case. But since we don't need the captures to constexpr check, we can
6032     // just ignore them.
6033     if (!Info.checkingPotentialConstantExpression())
6034       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6035                                         Frame.LambdaThisCaptureField);
6036   }
6037 
6038   StmtResult Ret = {Result, ResultSlot};
6039   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6040   if (ESR == ESR_Succeeded) {
6041     if (Callee->getReturnType()->isVoidType())
6042       return true;
6043     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6044   }
6045   return ESR == ESR_Returned;
6046 }
6047 
6048 /// Evaluate a constructor call.
6049 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6050                                   CallRef Call,
6051                                   const CXXConstructorDecl *Definition,
6052                                   EvalInfo &Info, APValue &Result) {
6053   SourceLocation CallLoc = E->getExprLoc();
6054   if (!Info.CheckCallLimit(CallLoc))
6055     return false;
6056 
6057   const CXXRecordDecl *RD = Definition->getParent();
6058   if (RD->getNumVBases()) {
6059     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6060     return false;
6061   }
6062 
6063   EvalInfo::EvaluatingConstructorRAII EvalObj(
6064       Info,
6065       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6066       RD->getNumBases());
6067   CallStackFrame Frame(Info, CallLoc, Definition, &This, Call);
6068 
6069   // FIXME: Creating an APValue just to hold a nonexistent return value is
6070   // wasteful.
6071   APValue RetVal;
6072   StmtResult Ret = {RetVal, nullptr};
6073 
6074   // If it's a delegating constructor, delegate.
6075   if (Definition->isDelegatingConstructor()) {
6076     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
6077     {
6078       FullExpressionRAII InitScope(Info);
6079       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6080           !InitScope.destroy())
6081         return false;
6082     }
6083     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6084   }
6085 
6086   // For a trivial copy or move constructor, perform an APValue copy. This is
6087   // essential for unions (or classes with anonymous union members), where the
6088   // operations performed by the constructor cannot be represented by
6089   // ctor-initializers.
6090   //
6091   // Skip this for empty non-union classes; we should not perform an
6092   // lvalue-to-rvalue conversion on them because their copy constructor does not
6093   // actually read them.
6094   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6095       (Definition->getParent()->isUnion() ||
6096        (Definition->isTrivial() &&
6097         isReadByLvalueToRvalueConversion(Definition->getParent())))) {
6098     return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6099                              Definition->getParent()->isUnion());
6100   }
6101 
6102   // Reserve space for the struct members.
6103   if (!Result.hasValue()) {
6104     if (!RD->isUnion())
6105       Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6106                        std::distance(RD->field_begin(), RD->field_end()));
6107     else
6108       // A union starts with no active member.
6109       Result = APValue((const FieldDecl*)nullptr);
6110   }
6111 
6112   if (RD->isInvalidDecl()) return false;
6113   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6114 
6115   // A scope for temporaries lifetime-extended by reference members.
6116   BlockScopeRAII LifetimeExtendedScope(Info);
6117 
6118   bool Success = true;
6119   unsigned BasesSeen = 0;
6120 #ifndef NDEBUG
6121   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
6122 #endif
6123   CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
6124   auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6125     // We might be initializing the same field again if this is an indirect
6126     // field initialization.
6127     if (FieldIt == RD->field_end() ||
6128         FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6129       assert(Indirect && "fields out of order?");
6130       return;
6131     }
6132 
6133     // Default-initialize any fields with no explicit initializer.
6134     for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6135       assert(FieldIt != RD->field_end() && "missing field?");
6136       if (!FieldIt->isUnnamedBitfield())
6137         Success &= getDefaultInitValue(
6138             FieldIt->getType(),
6139             Result.getStructField(FieldIt->getFieldIndex()));
6140     }
6141     ++FieldIt;
6142   };
6143   for (const auto *I : Definition->inits()) {
6144     LValue Subobject = This;
6145     LValue SubobjectParent = This;
6146     APValue *Value = &Result;
6147 
6148     // Determine the subobject to initialize.
6149     FieldDecl *FD = nullptr;
6150     if (I->isBaseInitializer()) {
6151       QualType BaseType(I->getBaseClass(), 0);
6152 #ifndef NDEBUG
6153       // Non-virtual base classes are initialized in the order in the class
6154       // definition. We have already checked for virtual base classes.
6155       assert(!BaseIt->isVirtual() && "virtual base for literal type");
6156       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
6157              "base class initializers not in expected order");
6158       ++BaseIt;
6159 #endif
6160       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6161                                   BaseType->getAsCXXRecordDecl(), &Layout))
6162         return false;
6163       Value = &Result.getStructBase(BasesSeen++);
6164     } else if ((FD = I->getMember())) {
6165       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6166         return false;
6167       if (RD->isUnion()) {
6168         Result = APValue(FD);
6169         Value = &Result.getUnionValue();
6170       } else {
6171         SkipToField(FD, false);
6172         Value = &Result.getStructField(FD->getFieldIndex());
6173       }
6174     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6175       // Walk the indirect field decl's chain to find the object to initialize,
6176       // and make sure we've initialized every step along it.
6177       auto IndirectFieldChain = IFD->chain();
6178       for (auto *C : IndirectFieldChain) {
6179         FD = cast<FieldDecl>(C);
6180         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6181         // Switch the union field if it differs. This happens if we had
6182         // preceding zero-initialization, and we're now initializing a union
6183         // subobject other than the first.
6184         // FIXME: In this case, the values of the other subobjects are
6185         // specified, since zero-initialization sets all padding bits to zero.
6186         if (!Value->hasValue() ||
6187             (Value->isUnion() && Value->getUnionField() != FD)) {
6188           if (CD->isUnion())
6189             *Value = APValue(FD);
6190           else
6191             // FIXME: This immediately starts the lifetime of all members of
6192             // an anonymous struct. It would be preferable to strictly start
6193             // member lifetime in initialization order.
6194             Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
6195         }
6196         // Store Subobject as its parent before updating it for the last element
6197         // in the chain.
6198         if (C == IndirectFieldChain.back())
6199           SubobjectParent = Subobject;
6200         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6201           return false;
6202         if (CD->isUnion())
6203           Value = &Value->getUnionValue();
6204         else {
6205           if (C == IndirectFieldChain.front() && !RD->isUnion())
6206             SkipToField(FD, true);
6207           Value = &Value->getStructField(FD->getFieldIndex());
6208         }
6209       }
6210     } else {
6211       llvm_unreachable("unknown base initializer kind");
6212     }
6213 
6214     // Need to override This for implicit field initializers as in this case
6215     // This refers to innermost anonymous struct/union containing initializer,
6216     // not to currently constructed class.
6217     const Expr *Init = I->getInit();
6218     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6219                                   isa<CXXDefaultInitExpr>(Init));
6220     FullExpressionRAII InitScope(Info);
6221     if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6222         (FD && FD->isBitField() &&
6223          !truncateBitfieldValue(Info, Init, *Value, FD))) {
6224       // If we're checking for a potential constant expression, evaluate all
6225       // initializers even if some of them fail.
6226       if (!Info.noteFailure())
6227         return false;
6228       Success = false;
6229     }
6230 
6231     // This is the point at which the dynamic type of the object becomes this
6232     // class type.
6233     if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6234       EvalObj.finishedConstructingBases();
6235   }
6236 
6237   // Default-initialize any remaining fields.
6238   if (!RD->isUnion()) {
6239     for (; FieldIt != RD->field_end(); ++FieldIt) {
6240       if (!FieldIt->isUnnamedBitfield())
6241         Success &= getDefaultInitValue(
6242             FieldIt->getType(),
6243             Result.getStructField(FieldIt->getFieldIndex()));
6244     }
6245   }
6246 
6247   EvalObj.finishedConstructingFields();
6248 
6249   return Success &&
6250          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6251          LifetimeExtendedScope.destroy();
6252 }
6253 
6254 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6255                                   ArrayRef<const Expr*> Args,
6256                                   const CXXConstructorDecl *Definition,
6257                                   EvalInfo &Info, APValue &Result) {
6258   CallScopeRAII CallScope(Info);
6259   CallRef Call = Info.CurrentCall->createCall(Definition);
6260   if (!EvaluateArgs(Args, Call, Info, Definition))
6261     return false;
6262 
6263   return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6264          CallScope.destroy();
6265 }
6266 
6267 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
6268                                   const LValue &This, APValue &Value,
6269                                   QualType T) {
6270   // Objects can only be destroyed while they're within their lifetimes.
6271   // FIXME: We have no representation for whether an object of type nullptr_t
6272   // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6273   // as indeterminate instead?
6274   if (Value.isAbsent() && !T->isNullPtrType()) {
6275     APValue Printable;
6276     This.moveInto(Printable);
6277     Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
6278       << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6279     return false;
6280   }
6281 
6282   // Invent an expression for location purposes.
6283   // FIXME: We shouldn't need to do this.
6284   OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue);
6285 
6286   // For arrays, destroy elements right-to-left.
6287   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6288     uint64_t Size = CAT->getSize().getZExtValue();
6289     QualType ElemT = CAT->getElementType();
6290 
6291     LValue ElemLV = This;
6292     ElemLV.addArray(Info, &LocE, CAT);
6293     if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6294       return false;
6295 
6296     // Ensure that we have actual array elements available to destroy; the
6297     // destructors might mutate the value, so we can't run them on the array
6298     // filler.
6299     if (Size && Size > Value.getArrayInitializedElts())
6300       expandArray(Value, Value.getArraySize() - 1);
6301 
6302     for (; Size != 0; --Size) {
6303       APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6304       if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6305           !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
6306         return false;
6307     }
6308 
6309     // End the lifetime of this array now.
6310     Value = APValue();
6311     return true;
6312   }
6313 
6314   const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6315   if (!RD) {
6316     if (T.isDestructedType()) {
6317       Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
6318       return false;
6319     }
6320 
6321     Value = APValue();
6322     return true;
6323   }
6324 
6325   if (RD->getNumVBases()) {
6326     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6327     return false;
6328   }
6329 
6330   const CXXDestructorDecl *DD = RD->getDestructor();
6331   if (!DD && !RD->hasTrivialDestructor()) {
6332     Info.FFDiag(CallLoc);
6333     return false;
6334   }
6335 
6336   if (!DD || DD->isTrivial() ||
6337       (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6338     // A trivial destructor just ends the lifetime of the object. Check for
6339     // this case before checking for a body, because we might not bother
6340     // building a body for a trivial destructor. Note that it doesn't matter
6341     // whether the destructor is constexpr in this case; all trivial
6342     // destructors are constexpr.
6343     //
6344     // If an anonymous union would be destroyed, some enclosing destructor must
6345     // have been explicitly defined, and the anonymous union destruction should
6346     // have no effect.
6347     Value = APValue();
6348     return true;
6349   }
6350 
6351   if (!Info.CheckCallLimit(CallLoc))
6352     return false;
6353 
6354   const FunctionDecl *Definition = nullptr;
6355   const Stmt *Body = DD->getBody(Definition);
6356 
6357   if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
6358     return false;
6359 
6360   CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef());
6361 
6362   // We're now in the period of destruction of this object.
6363   unsigned BasesLeft = RD->getNumBases();
6364   EvalInfo::EvaluatingDestructorRAII EvalObj(
6365       Info,
6366       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6367   if (!EvalObj.DidInsert) {
6368     // C++2a [class.dtor]p19:
6369     //   the behavior is undefined if the destructor is invoked for an object
6370     //   whose lifetime has ended
6371     // (Note that formally the lifetime ends when the period of destruction
6372     // begins, even though certain uses of the object remain valid until the
6373     // period of destruction ends.)
6374     Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
6375     return false;
6376   }
6377 
6378   // FIXME: Creating an APValue just to hold a nonexistent return value is
6379   // wasteful.
6380   APValue RetVal;
6381   StmtResult Ret = {RetVal, nullptr};
6382   if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6383     return false;
6384 
6385   // A union destructor does not implicitly destroy its members.
6386   if (RD->isUnion())
6387     return true;
6388 
6389   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6390 
6391   // We don't have a good way to iterate fields in reverse, so collect all the
6392   // fields first and then walk them backwards.
6393   SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
6394   for (const FieldDecl *FD : llvm::reverse(Fields)) {
6395     if (FD->isUnnamedBitfield())
6396       continue;
6397 
6398     LValue Subobject = This;
6399     if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6400       return false;
6401 
6402     APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6403     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6404                                FD->getType()))
6405       return false;
6406   }
6407 
6408   if (BasesLeft != 0)
6409     EvalObj.startedDestroyingBases();
6410 
6411   // Destroy base classes in reverse order.
6412   for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6413     --BasesLeft;
6414 
6415     QualType BaseType = Base.getType();
6416     LValue Subobject = This;
6417     if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
6418                                 BaseType->getAsCXXRecordDecl(), &Layout))
6419       return false;
6420 
6421     APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
6422     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6423                                BaseType))
6424       return false;
6425   }
6426   assert(BasesLeft == 0 && "NumBases was wrong?");
6427 
6428   // The period of destruction ends now. The object is gone.
6429   Value = APValue();
6430   return true;
6431 }
6432 
6433 namespace {
6434 struct DestroyObjectHandler {
6435   EvalInfo &Info;
6436   const Expr *E;
6437   const LValue &This;
6438   const AccessKinds AccessKind;
6439 
6440   typedef bool result_type;
6441   bool failed() { return false; }
6442   bool found(APValue &Subobj, QualType SubobjType) {
6443     return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
6444                                  SubobjType);
6445   }
6446   bool found(APSInt &Value, QualType SubobjType) {
6447     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6448     return false;
6449   }
6450   bool found(APFloat &Value, QualType SubobjType) {
6451     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6452     return false;
6453   }
6454 };
6455 }
6456 
6457 /// Perform a destructor or pseudo-destructor call on the given object, which
6458 /// might in general not be a complete object.
6459 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6460                               const LValue &This, QualType ThisType) {
6461   CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6462   DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6463   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6464 }
6465 
6466 /// Destroy and end the lifetime of the given complete object.
6467 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6468                               APValue::LValueBase LVBase, APValue &Value,
6469                               QualType T) {
6470   // If we've had an unmodeled side-effect, we can't rely on mutable state
6471   // (such as the object we're about to destroy) being correct.
6472   if (Info.EvalStatus.HasSideEffects)
6473     return false;
6474 
6475   LValue LV;
6476   LV.set({LVBase});
6477   return HandleDestructionImpl(Info, Loc, LV, Value, T);
6478 }
6479 
6480 /// Perform a call to 'perator new' or to `__builtin_operator_new'.
6481 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6482                                   LValue &Result) {
6483   if (Info.checkingPotentialConstantExpression() ||
6484       Info.SpeculativeEvaluationDepth)
6485     return false;
6486 
6487   // This is permitted only within a call to std::allocator<T>::allocate.
6488   auto Caller = Info.getStdAllocatorCaller("allocate");
6489   if (!Caller) {
6490     Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
6491                                      ? diag::note_constexpr_new_untyped
6492                                      : diag::note_constexpr_new);
6493     return false;
6494   }
6495 
6496   QualType ElemType = Caller.ElemType;
6497   if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6498     Info.FFDiag(E->getExprLoc(),
6499                 diag::note_constexpr_new_not_complete_object_type)
6500         << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6501     return false;
6502   }
6503 
6504   APSInt ByteSize;
6505   if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6506     return false;
6507   bool IsNothrow = false;
6508   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6509     EvaluateIgnoredValue(Info, E->getArg(I));
6510     IsNothrow |= E->getType()->isNothrowT();
6511   }
6512 
6513   CharUnits ElemSize;
6514   if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6515     return false;
6516   APInt Size, Remainder;
6517   APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6518   APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6519   if (Remainder != 0) {
6520     // This likely indicates a bug in the implementation of 'std::allocator'.
6521     Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6522         << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6523     return false;
6524   }
6525 
6526   if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
6527     if (IsNothrow) {
6528       Result.setNull(Info.Ctx, E->getType());
6529       return true;
6530     }
6531 
6532     Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
6533     return false;
6534   }
6535 
6536   QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
6537                                                      ArrayType::Normal, 0);
6538   APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6539   *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6540   Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6541   return true;
6542 }
6543 
6544 static bool hasVirtualDestructor(QualType T) {
6545   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6546     if (CXXDestructorDecl *DD = RD->getDestructor())
6547       return DD->isVirtual();
6548   return false;
6549 }
6550 
6551 static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6552   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6553     if (CXXDestructorDecl *DD = RD->getDestructor())
6554       return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6555   return nullptr;
6556 }
6557 
6558 /// Check that the given object is a suitable pointer to a heap allocation that
6559 /// still exists and is of the right kind for the purpose of a deletion.
6560 ///
6561 /// On success, returns the heap allocation to deallocate. On failure, produces
6562 /// a diagnostic and returns None.
6563 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6564                                             const LValue &Pointer,
6565                                             DynAlloc::Kind DeallocKind) {
6566   auto PointerAsString = [&] {
6567     return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6568   };
6569 
6570   DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6571   if (!DA) {
6572     Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6573         << PointerAsString();
6574     if (Pointer.Base)
6575       NoteLValueLocation(Info, Pointer.Base);
6576     return None;
6577   }
6578 
6579   Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6580   if (!Alloc) {
6581     Info.FFDiag(E, diag::note_constexpr_double_delete);
6582     return None;
6583   }
6584 
6585   QualType AllocType = Pointer.Base.getDynamicAllocType();
6586   if (DeallocKind != (*Alloc)->getKind()) {
6587     Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6588         << DeallocKind << (*Alloc)->getKind() << AllocType;
6589     NoteLValueLocation(Info, Pointer.Base);
6590     return None;
6591   }
6592 
6593   bool Subobject = false;
6594   if (DeallocKind == DynAlloc::New) {
6595     Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6596                 Pointer.Designator.isOnePastTheEnd();
6597   } else {
6598     Subobject = Pointer.Designator.Entries.size() != 1 ||
6599                 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6600   }
6601   if (Subobject) {
6602     Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6603         << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6604     return None;
6605   }
6606 
6607   return Alloc;
6608 }
6609 
6610 // Perform a call to 'operator delete' or '__builtin_operator_delete'.
6611 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6612   if (Info.checkingPotentialConstantExpression() ||
6613       Info.SpeculativeEvaluationDepth)
6614     return false;
6615 
6616   // This is permitted only within a call to std::allocator<T>::deallocate.
6617   if (!Info.getStdAllocatorCaller("deallocate")) {
6618     Info.FFDiag(E->getExprLoc());
6619     return true;
6620   }
6621 
6622   LValue Pointer;
6623   if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6624     return false;
6625   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6626     EvaluateIgnoredValue(Info, E->getArg(I));
6627 
6628   if (Pointer.Designator.Invalid)
6629     return false;
6630 
6631   // Deleting a null pointer has no effect.
6632   if (Pointer.isNullPointer())
6633     return true;
6634 
6635   if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6636     return false;
6637 
6638   Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6639   return true;
6640 }
6641 
6642 //===----------------------------------------------------------------------===//
6643 // Generic Evaluation
6644 //===----------------------------------------------------------------------===//
6645 namespace {
6646 
6647 class BitCastBuffer {
6648   // FIXME: We're going to need bit-level granularity when we support
6649   // bit-fields.
6650   // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6651   // we don't support a host or target where that is the case. Still, we should
6652   // use a more generic type in case we ever do.
6653   SmallVector<Optional<unsigned char>, 32> Bytes;
6654 
6655   static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6656                 "Need at least 8 bit unsigned char");
6657 
6658   bool TargetIsLittleEndian;
6659 
6660 public:
6661   BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6662       : Bytes(Width.getQuantity()),
6663         TargetIsLittleEndian(TargetIsLittleEndian) {}
6664 
6665   LLVM_NODISCARD
6666   bool readObject(CharUnits Offset, CharUnits Width,
6667                   SmallVectorImpl<unsigned char> &Output) const {
6668     for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6669       // If a byte of an integer is uninitialized, then the whole integer is
6670       // uninitalized.
6671       if (!Bytes[I.getQuantity()])
6672         return false;
6673       Output.push_back(*Bytes[I.getQuantity()]);
6674     }
6675     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6676       std::reverse(Output.begin(), Output.end());
6677     return true;
6678   }
6679 
6680   void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6681     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6682       std::reverse(Input.begin(), Input.end());
6683 
6684     size_t Index = 0;
6685     for (unsigned char Byte : Input) {
6686       assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
6687       Bytes[Offset.getQuantity() + Index] = Byte;
6688       ++Index;
6689     }
6690   }
6691 
6692   size_t size() { return Bytes.size(); }
6693 };
6694 
6695 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6696 /// target would represent the value at runtime.
6697 class APValueToBufferConverter {
6698   EvalInfo &Info;
6699   BitCastBuffer Buffer;
6700   const CastExpr *BCE;
6701 
6702   APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6703                            const CastExpr *BCE)
6704       : Info(Info),
6705         Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6706         BCE(BCE) {}
6707 
6708   bool visit(const APValue &Val, QualType Ty) {
6709     return visit(Val, Ty, CharUnits::fromQuantity(0));
6710   }
6711 
6712   // Write out Val with type Ty into Buffer starting at Offset.
6713   bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6714     assert((size_t)Offset.getQuantity() <= Buffer.size());
6715 
6716     // As a special case, nullptr_t has an indeterminate value.
6717     if (Ty->isNullPtrType())
6718       return true;
6719 
6720     // Dig through Src to find the byte at SrcOffset.
6721     switch (Val.getKind()) {
6722     case APValue::Indeterminate:
6723     case APValue::None:
6724       return true;
6725 
6726     case APValue::Int:
6727       return visitInt(Val.getInt(), Ty, Offset);
6728     case APValue::Float:
6729       return visitFloat(Val.getFloat(), Ty, Offset);
6730     case APValue::Array:
6731       return visitArray(Val, Ty, Offset);
6732     case APValue::Struct:
6733       return visitRecord(Val, Ty, Offset);
6734 
6735     case APValue::ComplexInt:
6736     case APValue::ComplexFloat:
6737     case APValue::Vector:
6738     case APValue::FixedPoint:
6739       // FIXME: We should support these.
6740 
6741     case APValue::Union:
6742     case APValue::MemberPointer:
6743     case APValue::AddrLabelDiff: {
6744       Info.FFDiag(BCE->getBeginLoc(),
6745                   diag::note_constexpr_bit_cast_unsupported_type)
6746           << Ty;
6747       return false;
6748     }
6749 
6750     case APValue::LValue:
6751       llvm_unreachable("LValue subobject in bit_cast?");
6752     }
6753     llvm_unreachable("Unhandled APValue::ValueKind");
6754   }
6755 
6756   bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
6757     const RecordDecl *RD = Ty->getAsRecordDecl();
6758     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6759 
6760     // Visit the base classes.
6761     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6762       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6763         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6764         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6765 
6766         if (!visitRecord(Val.getStructBase(I), BS.getType(),
6767                          Layout.getBaseClassOffset(BaseDecl) + Offset))
6768           return false;
6769       }
6770     }
6771 
6772     // Visit the fields.
6773     unsigned FieldIdx = 0;
6774     for (FieldDecl *FD : RD->fields()) {
6775       if (FD->isBitField()) {
6776         Info.FFDiag(BCE->getBeginLoc(),
6777                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6778         return false;
6779       }
6780 
6781       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6782 
6783       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
6784              "only bit-fields can have sub-char alignment");
6785       CharUnits FieldOffset =
6786           Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
6787       QualType FieldTy = FD->getType();
6788       if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
6789         return false;
6790       ++FieldIdx;
6791     }
6792 
6793     return true;
6794   }
6795 
6796   bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
6797     const auto *CAT =
6798         dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
6799     if (!CAT)
6800       return false;
6801 
6802     CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
6803     unsigned NumInitializedElts = Val.getArrayInitializedElts();
6804     unsigned ArraySize = Val.getArraySize();
6805     // First, initialize the initialized elements.
6806     for (unsigned I = 0; I != NumInitializedElts; ++I) {
6807       const APValue &SubObj = Val.getArrayInitializedElt(I);
6808       if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
6809         return false;
6810     }
6811 
6812     // Next, initialize the rest of the array using the filler.
6813     if (Val.hasArrayFiller()) {
6814       const APValue &Filler = Val.getArrayFiller();
6815       for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
6816         if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
6817           return false;
6818       }
6819     }
6820 
6821     return true;
6822   }
6823 
6824   bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
6825     APSInt AdjustedVal = Val;
6826     unsigned Width = AdjustedVal.getBitWidth();
6827     if (Ty->isBooleanType()) {
6828       Width = Info.Ctx.getTypeSize(Ty);
6829       AdjustedVal = AdjustedVal.extend(Width);
6830     }
6831 
6832     SmallVector<unsigned char, 8> Bytes(Width / 8);
6833     llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
6834     Buffer.writeObject(Offset, Bytes);
6835     return true;
6836   }
6837 
6838   bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
6839     APSInt AsInt(Val.bitcastToAPInt());
6840     return visitInt(AsInt, Ty, Offset);
6841   }
6842 
6843 public:
6844   static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
6845                                          const CastExpr *BCE) {
6846     CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
6847     APValueToBufferConverter Converter(Info, DstSize, BCE);
6848     if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
6849       return None;
6850     return Converter.Buffer;
6851   }
6852 };
6853 
6854 /// Write an BitCastBuffer into an APValue.
6855 class BufferToAPValueConverter {
6856   EvalInfo &Info;
6857   const BitCastBuffer &Buffer;
6858   const CastExpr *BCE;
6859 
6860   BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
6861                            const CastExpr *BCE)
6862       : Info(Info), Buffer(Buffer), BCE(BCE) {}
6863 
6864   // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
6865   // with an invalid type, so anything left is a deficiency on our part (FIXME).
6866   // Ideally this will be unreachable.
6867   llvm::NoneType unsupportedType(QualType Ty) {
6868     Info.FFDiag(BCE->getBeginLoc(),
6869                 diag::note_constexpr_bit_cast_unsupported_type)
6870         << Ty;
6871     return None;
6872   }
6873 
6874   llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) {
6875     Info.FFDiag(BCE->getBeginLoc(),
6876                 diag::note_constexpr_bit_cast_unrepresentable_value)
6877         << Ty << Val.toString(/*Radix=*/10);
6878     return None;
6879   }
6880 
6881   Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
6882                           const EnumType *EnumSugar = nullptr) {
6883     if (T->isNullPtrType()) {
6884       uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
6885       return APValue((Expr *)nullptr,
6886                      /*Offset=*/CharUnits::fromQuantity(NullValue),
6887                      APValue::NoLValuePath{}, /*IsNullPtr=*/true);
6888     }
6889 
6890     CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
6891 
6892     // Work around floating point types that contain unused padding bytes. This
6893     // is really just `long double` on x86, which is the only fundamental type
6894     // with padding bytes.
6895     if (T->isRealFloatingType()) {
6896       const llvm::fltSemantics &Semantics =
6897           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
6898       unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
6899       assert(NumBits % 8 == 0);
6900       CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
6901       if (NumBytes != SizeOf)
6902         SizeOf = NumBytes;
6903     }
6904 
6905     SmallVector<uint8_t, 8> Bytes;
6906     if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
6907       // If this is std::byte or unsigned char, then its okay to store an
6908       // indeterminate value.
6909       bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
6910       bool IsUChar =
6911           !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
6912                          T->isSpecificBuiltinType(BuiltinType::Char_U));
6913       if (!IsStdByte && !IsUChar) {
6914         QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
6915         Info.FFDiag(BCE->getExprLoc(),
6916                     diag::note_constexpr_bit_cast_indet_dest)
6917             << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
6918         return None;
6919       }
6920 
6921       return APValue::IndeterminateValue();
6922     }
6923 
6924     APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
6925     llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
6926 
6927     if (T->isIntegralOrEnumerationType()) {
6928       Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
6929 
6930       unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
6931       if (IntWidth != Val.getBitWidth()) {
6932         APSInt Truncated = Val.trunc(IntWidth);
6933         if (Truncated.extend(Val.getBitWidth()) != Val)
6934           return unrepresentableValue(QualType(T, 0), Val);
6935         Val = Truncated;
6936       }
6937 
6938       return APValue(Val);
6939     }
6940 
6941     if (T->isRealFloatingType()) {
6942       const llvm::fltSemantics &Semantics =
6943           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
6944       return APValue(APFloat(Semantics, Val));
6945     }
6946 
6947     return unsupportedType(QualType(T, 0));
6948   }
6949 
6950   Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
6951     const RecordDecl *RD = RTy->getAsRecordDecl();
6952     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6953 
6954     unsigned NumBases = 0;
6955     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6956       NumBases = CXXRD->getNumBases();
6957 
6958     APValue ResultVal(APValue::UninitStruct(), NumBases,
6959                       std::distance(RD->field_begin(), RD->field_end()));
6960 
6961     // Visit the base classes.
6962     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6963       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6964         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6965         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6966         if (BaseDecl->isEmpty() ||
6967             Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
6968           continue;
6969 
6970         Optional<APValue> SubObj = visitType(
6971             BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
6972         if (!SubObj)
6973           return None;
6974         ResultVal.getStructBase(I) = *SubObj;
6975       }
6976     }
6977 
6978     // Visit the fields.
6979     unsigned FieldIdx = 0;
6980     for (FieldDecl *FD : RD->fields()) {
6981       // FIXME: We don't currently support bit-fields. A lot of the logic for
6982       // this is in CodeGen, so we need to factor it around.
6983       if (FD->isBitField()) {
6984         Info.FFDiag(BCE->getBeginLoc(),
6985                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6986         return None;
6987       }
6988 
6989       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6990       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
6991 
6992       CharUnits FieldOffset =
6993           CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
6994           Offset;
6995       QualType FieldTy = FD->getType();
6996       Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
6997       if (!SubObj)
6998         return None;
6999       ResultVal.getStructField(FieldIdx) = *SubObj;
7000       ++FieldIdx;
7001     }
7002 
7003     return ResultVal;
7004   }
7005 
7006   Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7007     QualType RepresentationType = Ty->getDecl()->getIntegerType();
7008     assert(!RepresentationType.isNull() &&
7009            "enum forward decl should be caught by Sema");
7010     const auto *AsBuiltin =
7011         RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7012     // Recurse into the underlying type. Treat std::byte transparently as
7013     // unsigned char.
7014     return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7015   }
7016 
7017   Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7018     size_t Size = Ty->getSize().getLimitedValue();
7019     CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7020 
7021     APValue ArrayValue(APValue::UninitArray(), Size, Size);
7022     for (size_t I = 0; I != Size; ++I) {
7023       Optional<APValue> ElementValue =
7024           visitType(Ty->getElementType(), Offset + I * ElementWidth);
7025       if (!ElementValue)
7026         return None;
7027       ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7028     }
7029 
7030     return ArrayValue;
7031   }
7032 
7033   Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7034     return unsupportedType(QualType(Ty, 0));
7035   }
7036 
7037   Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7038     QualType Can = Ty.getCanonicalType();
7039 
7040     switch (Can->getTypeClass()) {
7041 #define TYPE(Class, Base)                                                      \
7042   case Type::Class:                                                            \
7043     return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7044 #define ABSTRACT_TYPE(Class, Base)
7045 #define NON_CANONICAL_TYPE(Class, Base)                                        \
7046   case Type::Class:                                                            \
7047     llvm_unreachable("non-canonical type should be impossible!");
7048 #define DEPENDENT_TYPE(Class, Base)                                            \
7049   case Type::Class:                                                            \
7050     llvm_unreachable(                                                          \
7051         "dependent types aren't supported in the constant evaluator!");
7052 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)                            \
7053   case Type::Class:                                                            \
7054     llvm_unreachable("either dependent or not canonical!");
7055 #include "clang/AST/TypeNodes.inc"
7056     }
7057     llvm_unreachable("Unhandled Type::TypeClass");
7058   }
7059 
7060 public:
7061   // Pull out a full value of type DstType.
7062   static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7063                                    const CastExpr *BCE) {
7064     BufferToAPValueConverter Converter(Info, Buffer, BCE);
7065     return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7066   }
7067 };
7068 
7069 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7070                                                  QualType Ty, EvalInfo *Info,
7071                                                  const ASTContext &Ctx,
7072                                                  bool CheckingDest) {
7073   Ty = Ty.getCanonicalType();
7074 
7075   auto diag = [&](int Reason) {
7076     if (Info)
7077       Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7078           << CheckingDest << (Reason == 4) << Reason;
7079     return false;
7080   };
7081   auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7082     if (Info)
7083       Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7084           << NoteTy << Construct << Ty;
7085     return false;
7086   };
7087 
7088   if (Ty->isUnionType())
7089     return diag(0);
7090   if (Ty->isPointerType())
7091     return diag(1);
7092   if (Ty->isMemberPointerType())
7093     return diag(2);
7094   if (Ty.isVolatileQualified())
7095     return diag(3);
7096 
7097   if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7098     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7099       for (CXXBaseSpecifier &BS : CXXRD->bases())
7100         if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7101                                                   CheckingDest))
7102           return note(1, BS.getType(), BS.getBeginLoc());
7103     }
7104     for (FieldDecl *FD : Record->fields()) {
7105       if (FD->getType()->isReferenceType())
7106         return diag(4);
7107       if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7108                                                 CheckingDest))
7109         return note(0, FD->getType(), FD->getBeginLoc());
7110     }
7111   }
7112 
7113   if (Ty->isArrayType() &&
7114       !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7115                                             Info, Ctx, CheckingDest))
7116     return false;
7117 
7118   return true;
7119 }
7120 
7121 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
7122                                              const ASTContext &Ctx,
7123                                              const CastExpr *BCE) {
7124   bool DestOK = checkBitCastConstexprEligibilityType(
7125       BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
7126   bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
7127                                 BCE->getBeginLoc(),
7128                                 BCE->getSubExpr()->getType(), Info, Ctx, false);
7129   return SourceOK;
7130 }
7131 
7132 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7133                                         APValue &SourceValue,
7134                                         const CastExpr *BCE) {
7135   assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7136          "no host or target supports non 8-bit chars");
7137   assert(SourceValue.isLValue() &&
7138          "LValueToRValueBitcast requires an lvalue operand!");
7139 
7140   if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
7141     return false;
7142 
7143   LValue SourceLValue;
7144   APValue SourceRValue;
7145   SourceLValue.setFrom(Info.Ctx, SourceValue);
7146   if (!handleLValueToRValueConversion(
7147           Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
7148           SourceRValue, /*WantObjectRepresentation=*/true))
7149     return false;
7150 
7151   // Read out SourceValue into a char buffer.
7152   Optional<BitCastBuffer> Buffer =
7153       APValueToBufferConverter::convert(Info, SourceRValue, BCE);
7154   if (!Buffer)
7155     return false;
7156 
7157   // Write out the buffer into a new APValue.
7158   Optional<APValue> MaybeDestValue =
7159       BufferToAPValueConverter::convert(Info, *Buffer, BCE);
7160   if (!MaybeDestValue)
7161     return false;
7162 
7163   DestValue = std::move(*MaybeDestValue);
7164   return true;
7165 }
7166 
7167 template <class Derived>
7168 class ExprEvaluatorBase
7169   : public ConstStmtVisitor<Derived, bool> {
7170 private:
7171   Derived &getDerived() { return static_cast<Derived&>(*this); }
7172   bool DerivedSuccess(const APValue &V, const Expr *E) {
7173     return getDerived().Success(V, E);
7174   }
7175   bool DerivedZeroInitialization(const Expr *E) {
7176     return getDerived().ZeroInitialization(E);
7177   }
7178 
7179   // Check whether a conditional operator with a non-constant condition is a
7180   // potential constant expression. If neither arm is a potential constant
7181   // expression, then the conditional operator is not either.
7182   template<typename ConditionalOperator>
7183   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7184     assert(Info.checkingPotentialConstantExpression());
7185 
7186     // Speculatively evaluate both arms.
7187     SmallVector<PartialDiagnosticAt, 8> Diag;
7188     {
7189       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7190       StmtVisitorTy::Visit(E->getFalseExpr());
7191       if (Diag.empty())
7192         return;
7193     }
7194 
7195     {
7196       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7197       Diag.clear();
7198       StmtVisitorTy::Visit(E->getTrueExpr());
7199       if (Diag.empty())
7200         return;
7201     }
7202 
7203     Error(E, diag::note_constexpr_conditional_never_const);
7204   }
7205 
7206 
7207   template<typename ConditionalOperator>
7208   bool HandleConditionalOperator(const ConditionalOperator *E) {
7209     bool BoolResult;
7210     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7211       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7212         CheckPotentialConstantConditional(E);
7213         return false;
7214       }
7215       if (Info.noteFailure()) {
7216         StmtVisitorTy::Visit(E->getTrueExpr());
7217         StmtVisitorTy::Visit(E->getFalseExpr());
7218       }
7219       return false;
7220     }
7221 
7222     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
7223     return StmtVisitorTy::Visit(EvalExpr);
7224   }
7225 
7226 protected:
7227   EvalInfo &Info;
7228   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
7229   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
7230 
7231   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7232     return Info.CCEDiag(E, D);
7233   }
7234 
7235   bool ZeroInitialization(const Expr *E) { return Error(E); }
7236 
7237 public:
7238   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
7239 
7240   EvalInfo &getEvalInfo() { return Info; }
7241 
7242   /// Report an evaluation error. This should only be called when an error is
7243   /// first discovered. When propagating an error, just return false.
7244   bool Error(const Expr *E, diag::kind D) {
7245     Info.FFDiag(E, D);
7246     return false;
7247   }
7248   bool Error(const Expr *E) {
7249     return Error(E, diag::note_invalid_subexpr_in_const_expr);
7250   }
7251 
7252   bool VisitStmt(const Stmt *) {
7253     llvm_unreachable("Expression evaluator should not be called on stmts");
7254   }
7255   bool VisitExpr(const Expr *E) {
7256     return Error(E);
7257   }
7258 
7259   bool VisitConstantExpr(const ConstantExpr *E) {
7260     if (E->hasAPValueResult())
7261       return DerivedSuccess(E->getAPValueResult(), E);
7262 
7263     return StmtVisitorTy::Visit(E->getSubExpr());
7264   }
7265 
7266   bool VisitParenExpr(const ParenExpr *E)
7267     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7268   bool VisitUnaryExtension(const UnaryOperator *E)
7269     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7270   bool VisitUnaryPlus(const UnaryOperator *E)
7271     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7272   bool VisitChooseExpr(const ChooseExpr *E)
7273     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
7274   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
7275     { return StmtVisitorTy::Visit(E->getResultExpr()); }
7276   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
7277     { return StmtVisitorTy::Visit(E->getReplacement()); }
7278   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7279     TempVersionRAII RAII(*Info.CurrentCall);
7280     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7281     return StmtVisitorTy::Visit(E->getExpr());
7282   }
7283   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7284     TempVersionRAII RAII(*Info.CurrentCall);
7285     // The initializer may not have been parsed yet, or might be erroneous.
7286     if (!E->getExpr())
7287       return Error(E);
7288     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7289     return StmtVisitorTy::Visit(E->getExpr());
7290   }
7291 
7292   bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7293     FullExpressionRAII Scope(Info);
7294     return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
7295   }
7296 
7297   // Temporaries are registered when created, so we don't care about
7298   // CXXBindTemporaryExpr.
7299   bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7300     return StmtVisitorTy::Visit(E->getSubExpr());
7301   }
7302 
7303   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7304     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7305     return static_cast<Derived*>(this)->VisitCastExpr(E);
7306   }
7307   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7308     if (!Info.Ctx.getLangOpts().CPlusPlus20)
7309       CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
7310     return static_cast<Derived*>(this)->VisitCastExpr(E);
7311   }
7312   bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7313     return static_cast<Derived*>(this)->VisitCastExpr(E);
7314   }
7315 
7316   bool VisitBinaryOperator(const BinaryOperator *E) {
7317     switch (E->getOpcode()) {
7318     default:
7319       return Error(E);
7320 
7321     case BO_Comma:
7322       VisitIgnoredValue(E->getLHS());
7323       return StmtVisitorTy::Visit(E->getRHS());
7324 
7325     case BO_PtrMemD:
7326     case BO_PtrMemI: {
7327       LValue Obj;
7328       if (!HandleMemberPointerAccess(Info, E, Obj))
7329         return false;
7330       APValue Result;
7331       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7332         return false;
7333       return DerivedSuccess(Result, E);
7334     }
7335     }
7336   }
7337 
7338   bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
7339     return StmtVisitorTy::Visit(E->getSemanticForm());
7340   }
7341 
7342   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7343     // Evaluate and cache the common expression. We treat it as a temporary,
7344     // even though it's not quite the same thing.
7345     LValue CommonLV;
7346     if (!Evaluate(Info.CurrentCall->createTemporary(
7347                       E->getOpaqueValue(),
7348                       getStorageType(Info.Ctx, E->getOpaqueValue()),
7349                       ScopeKind::FullExpression, CommonLV),
7350                   Info, E->getCommon()))
7351       return false;
7352 
7353     return HandleConditionalOperator(E);
7354   }
7355 
7356   bool VisitConditionalOperator(const ConditionalOperator *E) {
7357     bool IsBcpCall = false;
7358     // If the condition (ignoring parens) is a __builtin_constant_p call,
7359     // the result is a constant expression if it can be folded without
7360     // side-effects. This is an important GNU extension. See GCC PR38377
7361     // for discussion.
7362     if (const CallExpr *CallCE =
7363           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7364       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7365         IsBcpCall = true;
7366 
7367     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7368     // constant expression; we can't check whether it's potentially foldable.
7369     // FIXME: We should instead treat __builtin_constant_p as non-constant if
7370     // it would return 'false' in this mode.
7371     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
7372       return false;
7373 
7374     FoldConstant Fold(Info, IsBcpCall);
7375     if (!HandleConditionalOperator(E)) {
7376       Fold.keepDiagnostics();
7377       return false;
7378     }
7379 
7380     return true;
7381   }
7382 
7383   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7384     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
7385       return DerivedSuccess(*Value, E);
7386 
7387     const Expr *Source = E->getSourceExpr();
7388     if (!Source)
7389       return Error(E);
7390     if (Source == E) { // sanity checking.
7391       assert(0 && "OpaqueValueExpr recursively refers to itself");
7392       return Error(E);
7393     }
7394     return StmtVisitorTy::Visit(Source);
7395   }
7396 
7397   bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7398     for (const Expr *SemE : E->semantics()) {
7399       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7400         // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7401         // result expression: there could be two different LValues that would
7402         // refer to the same object in that case, and we can't model that.
7403         if (SemE == E->getResultExpr())
7404           return Error(E);
7405 
7406         // Unique OVEs get evaluated if and when we encounter them when
7407         // emitting the rest of the semantic form, rather than eagerly.
7408         if (OVE->isUnique())
7409           continue;
7410 
7411         LValue LV;
7412         if (!Evaluate(Info.CurrentCall->createTemporary(
7413                           OVE, getStorageType(Info.Ctx, OVE),
7414                           ScopeKind::FullExpression, LV),
7415                       Info, OVE->getSourceExpr()))
7416           return false;
7417       } else if (SemE == E->getResultExpr()) {
7418         if (!StmtVisitorTy::Visit(SemE))
7419           return false;
7420       } else {
7421         if (!EvaluateIgnoredValue(Info, SemE))
7422           return false;
7423       }
7424     }
7425     return true;
7426   }
7427 
7428   bool VisitCallExpr(const CallExpr *E) {
7429     APValue Result;
7430     if (!handleCallExpr(E, Result, nullptr))
7431       return false;
7432     return DerivedSuccess(Result, E);
7433   }
7434 
7435   bool handleCallExpr(const CallExpr *E, APValue &Result,
7436                      const LValue *ResultSlot) {
7437     CallScopeRAII CallScope(Info);
7438 
7439     const Expr *Callee = E->getCallee()->IgnoreParens();
7440     QualType CalleeType = Callee->getType();
7441 
7442     const FunctionDecl *FD = nullptr;
7443     LValue *This = nullptr, ThisVal;
7444     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
7445     bool HasQualifier = false;
7446 
7447     CallRef Call;
7448 
7449     // Extract function decl and 'this' pointer from the callee.
7450     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7451       const CXXMethodDecl *Member = nullptr;
7452       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7453         // Explicit bound member calls, such as x.f() or p->g();
7454         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7455           return false;
7456         Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7457         if (!Member)
7458           return Error(Callee);
7459         This = &ThisVal;
7460         HasQualifier = ME->hasQualifier();
7461       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
7462         // Indirect bound member calls ('.*' or '->*').
7463         const ValueDecl *D =
7464             HandleMemberPointerAccess(Info, BE, ThisVal, false);
7465         if (!D)
7466           return false;
7467         Member = dyn_cast<CXXMethodDecl>(D);
7468         if (!Member)
7469           return Error(Callee);
7470         This = &ThisVal;
7471       } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7472         if (!Info.getLangOpts().CPlusPlus20)
7473           Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7474         return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7475                HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7476       } else
7477         return Error(Callee);
7478       FD = Member;
7479     } else if (CalleeType->isFunctionPointerType()) {
7480       LValue CalleeLV;
7481       if (!EvaluatePointer(Callee, CalleeLV, Info))
7482         return false;
7483 
7484       if (!CalleeLV.getLValueOffset().isZero())
7485         return Error(Callee);
7486       FD = dyn_cast_or_null<FunctionDecl>(
7487           CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
7488       if (!FD)
7489         return Error(Callee);
7490       // Don't call function pointers which have been cast to some other type.
7491       // Per DR (no number yet), the caller and callee can differ in noexcept.
7492       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7493         CalleeType->getPointeeType(), FD->getType())) {
7494         return Error(E);
7495       }
7496 
7497       // For an (overloaded) assignment expression, evaluate the RHS before the
7498       // LHS.
7499       auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
7500       if (OCE && OCE->isAssignmentOp()) {
7501         assert(Args.size() == 2 && "wrong number of arguments in assignment");
7502         Call = Info.CurrentCall->createCall(FD);
7503         if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call,
7504                           Info, FD, /*RightToLeft=*/true))
7505           return false;
7506       }
7507 
7508       // Overloaded operator calls to member functions are represented as normal
7509       // calls with '*this' as the first argument.
7510       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7511       if (MD && !MD->isStatic()) {
7512         // FIXME: When selecting an implicit conversion for an overloaded
7513         // operator delete, we sometimes try to evaluate calls to conversion
7514         // operators without a 'this' parameter!
7515         if (Args.empty())
7516           return Error(E);
7517 
7518         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7519           return false;
7520         This = &ThisVal;
7521         Args = Args.slice(1);
7522       } else if (MD && MD->isLambdaStaticInvoker()) {
7523         // Map the static invoker for the lambda back to the call operator.
7524         // Conveniently, we don't have to slice out the 'this' argument (as is
7525         // being done for the non-static case), since a static member function
7526         // doesn't have an implicit argument passed in.
7527         const CXXRecordDecl *ClosureClass = MD->getParent();
7528         assert(
7529             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7530             "Number of captures must be zero for conversion to function-ptr");
7531 
7532         const CXXMethodDecl *LambdaCallOp =
7533             ClosureClass->getLambdaCallOperator();
7534 
7535         // Set 'FD', the function that will be called below, to the call
7536         // operator.  If the closure object represents a generic lambda, find
7537         // the corresponding specialization of the call operator.
7538 
7539         if (ClosureClass->isGenericLambda()) {
7540           assert(MD->isFunctionTemplateSpecialization() &&
7541                  "A generic lambda's static-invoker function must be a "
7542                  "template specialization");
7543           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7544           FunctionTemplateDecl *CallOpTemplate =
7545               LambdaCallOp->getDescribedFunctionTemplate();
7546           void *InsertPos = nullptr;
7547           FunctionDecl *CorrespondingCallOpSpecialization =
7548               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7549           assert(CorrespondingCallOpSpecialization &&
7550                  "We must always have a function call operator specialization "
7551                  "that corresponds to our static invoker specialization");
7552           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7553         } else
7554           FD = LambdaCallOp;
7555       } else if (FD->isReplaceableGlobalAllocationFunction()) {
7556         if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7557             FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7558           LValue Ptr;
7559           if (!HandleOperatorNewCall(Info, E, Ptr))
7560             return false;
7561           Ptr.moveInto(Result);
7562           return CallScope.destroy();
7563         } else {
7564           return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
7565         }
7566       }
7567     } else
7568       return Error(E);
7569 
7570     // Evaluate the arguments now if we've not already done so.
7571     if (!Call) {
7572       Call = Info.CurrentCall->createCall(FD);
7573       if (!EvaluateArgs(Args, Call, Info, FD))
7574         return false;
7575     }
7576 
7577     SmallVector<QualType, 4> CovariantAdjustmentPath;
7578     if (This) {
7579       auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7580       if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
7581         // Perform virtual dispatch, if necessary.
7582         FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
7583                                    CovariantAdjustmentPath);
7584         if (!FD)
7585           return false;
7586       } else {
7587         // Check that the 'this' pointer points to an object of the right type.
7588         // FIXME: If this is an assignment operator call, we may need to change
7589         // the active union member before we check this.
7590         if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
7591           return false;
7592       }
7593     }
7594 
7595     // Destructor calls are different enough that they have their own codepath.
7596     if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
7597       assert(This && "no 'this' pointer for destructor call");
7598       return HandleDestruction(Info, E, *This,
7599                                Info.Ctx.getRecordType(DD->getParent())) &&
7600              CallScope.destroy();
7601     }
7602 
7603     const FunctionDecl *Definition = nullptr;
7604     Stmt *Body = FD->getBody(Definition);
7605 
7606     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
7607         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call,
7608                             Body, Info, Result, ResultSlot))
7609       return false;
7610 
7611     if (!CovariantAdjustmentPath.empty() &&
7612         !HandleCovariantReturnAdjustment(Info, E, Result,
7613                                          CovariantAdjustmentPath))
7614       return false;
7615 
7616     return CallScope.destroy();
7617   }
7618 
7619   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7620     return StmtVisitorTy::Visit(E->getInitializer());
7621   }
7622   bool VisitInitListExpr(const InitListExpr *E) {
7623     if (E->getNumInits() == 0)
7624       return DerivedZeroInitialization(E);
7625     if (E->getNumInits() == 1)
7626       return StmtVisitorTy::Visit(E->getInit(0));
7627     return Error(E);
7628   }
7629   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
7630     return DerivedZeroInitialization(E);
7631   }
7632   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
7633     return DerivedZeroInitialization(E);
7634   }
7635   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
7636     return DerivedZeroInitialization(E);
7637   }
7638 
7639   /// A member expression where the object is a prvalue is itself a prvalue.
7640   bool VisitMemberExpr(const MemberExpr *E) {
7641     assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
7642            "missing temporary materialization conversion");
7643     assert(!E->isArrow() && "missing call to bound member function?");
7644 
7645     APValue Val;
7646     if (!Evaluate(Val, Info, E->getBase()))
7647       return false;
7648 
7649     QualType BaseTy = E->getBase()->getType();
7650 
7651     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
7652     if (!FD) return Error(E);
7653     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
7654     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7655            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7656 
7657     // Note: there is no lvalue base here. But this case should only ever
7658     // happen in C or in C++98, where we cannot be evaluating a constexpr
7659     // constructor, which is the only case the base matters.
7660     CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
7661     SubobjectDesignator Designator(BaseTy);
7662     Designator.addDeclUnchecked(FD);
7663 
7664     APValue Result;
7665     return extractSubobject(Info, E, Obj, Designator, Result) &&
7666            DerivedSuccess(Result, E);
7667   }
7668 
7669   bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
7670     APValue Val;
7671     if (!Evaluate(Val, Info, E->getBase()))
7672       return false;
7673 
7674     if (Val.isVector()) {
7675       SmallVector<uint32_t, 4> Indices;
7676       E->getEncodedElementAccess(Indices);
7677       if (Indices.size() == 1) {
7678         // Return scalar.
7679         return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
7680       } else {
7681         // Construct new APValue vector.
7682         SmallVector<APValue, 4> Elts;
7683         for (unsigned I = 0; I < Indices.size(); ++I) {
7684           Elts.push_back(Val.getVectorElt(Indices[I]));
7685         }
7686         APValue VecResult(Elts.data(), Indices.size());
7687         return DerivedSuccess(VecResult, E);
7688       }
7689     }
7690 
7691     return false;
7692   }
7693 
7694   bool VisitCastExpr(const CastExpr *E) {
7695     switch (E->getCastKind()) {
7696     default:
7697       break;
7698 
7699     case CK_AtomicToNonAtomic: {
7700       APValue AtomicVal;
7701       // This does not need to be done in place even for class/array types:
7702       // atomic-to-non-atomic conversion implies copying the object
7703       // representation.
7704       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
7705         return false;
7706       return DerivedSuccess(AtomicVal, E);
7707     }
7708 
7709     case CK_NoOp:
7710     case CK_UserDefinedConversion:
7711       return StmtVisitorTy::Visit(E->getSubExpr());
7712 
7713     case CK_LValueToRValue: {
7714       LValue LVal;
7715       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
7716         return false;
7717       APValue RVal;
7718       // Note, we use the subexpression's type in order to retain cv-qualifiers.
7719       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7720                                           LVal, RVal))
7721         return false;
7722       return DerivedSuccess(RVal, E);
7723     }
7724     case CK_LValueToRValueBitCast: {
7725       APValue DestValue, SourceValue;
7726       if (!Evaluate(SourceValue, Info, E->getSubExpr()))
7727         return false;
7728       if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
7729         return false;
7730       return DerivedSuccess(DestValue, E);
7731     }
7732 
7733     case CK_AddressSpaceConversion: {
7734       APValue Value;
7735       if (!Evaluate(Value, Info, E->getSubExpr()))
7736         return false;
7737       return DerivedSuccess(Value, E);
7738     }
7739     }
7740 
7741     return Error(E);
7742   }
7743 
7744   bool VisitUnaryPostInc(const UnaryOperator *UO) {
7745     return VisitUnaryPostIncDec(UO);
7746   }
7747   bool VisitUnaryPostDec(const UnaryOperator *UO) {
7748     return VisitUnaryPostIncDec(UO);
7749   }
7750   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
7751     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7752       return Error(UO);
7753 
7754     LValue LVal;
7755     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
7756       return false;
7757     APValue RVal;
7758     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
7759                       UO->isIncrementOp(), &RVal))
7760       return false;
7761     return DerivedSuccess(RVal, UO);
7762   }
7763 
7764   bool VisitStmtExpr(const StmtExpr *E) {
7765     // We will have checked the full-expressions inside the statement expression
7766     // when they were completed, and don't need to check them again now.
7767     if (Info.checkingForUndefinedBehavior())
7768       return Error(E);
7769 
7770     const CompoundStmt *CS = E->getSubStmt();
7771     if (CS->body_empty())
7772       return true;
7773 
7774     BlockScopeRAII Scope(Info);
7775     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
7776                                            BE = CS->body_end();
7777          /**/; ++BI) {
7778       if (BI + 1 == BE) {
7779         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
7780         if (!FinalExpr) {
7781           Info.FFDiag((*BI)->getBeginLoc(),
7782                       diag::note_constexpr_stmt_expr_unsupported);
7783           return false;
7784         }
7785         return this->Visit(FinalExpr) && Scope.destroy();
7786       }
7787 
7788       APValue ReturnValue;
7789       StmtResult Result = { ReturnValue, nullptr };
7790       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
7791       if (ESR != ESR_Succeeded) {
7792         // FIXME: If the statement-expression terminated due to 'return',
7793         // 'break', or 'continue', it would be nice to propagate that to
7794         // the outer statement evaluation rather than bailing out.
7795         if (ESR != ESR_Failed)
7796           Info.FFDiag((*BI)->getBeginLoc(),
7797                       diag::note_constexpr_stmt_expr_unsupported);
7798         return false;
7799       }
7800     }
7801 
7802     llvm_unreachable("Return from function from the loop above.");
7803   }
7804 
7805   /// Visit a value which is evaluated, but whose value is ignored.
7806   void VisitIgnoredValue(const Expr *E) {
7807     EvaluateIgnoredValue(Info, E);
7808   }
7809 
7810   /// Potentially visit a MemberExpr's base expression.
7811   void VisitIgnoredBaseExpression(const Expr *E) {
7812     // While MSVC doesn't evaluate the base expression, it does diagnose the
7813     // presence of side-effecting behavior.
7814     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
7815       return;
7816     VisitIgnoredValue(E);
7817   }
7818 };
7819 
7820 } // namespace
7821 
7822 //===----------------------------------------------------------------------===//
7823 // Common base class for lvalue and temporary evaluation.
7824 //===----------------------------------------------------------------------===//
7825 namespace {
7826 template<class Derived>
7827 class LValueExprEvaluatorBase
7828   : public ExprEvaluatorBase<Derived> {
7829 protected:
7830   LValue &Result;
7831   bool InvalidBaseOK;
7832   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
7833   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
7834 
7835   bool Success(APValue::LValueBase B) {
7836     Result.set(B);
7837     return true;
7838   }
7839 
7840   bool evaluatePointer(const Expr *E, LValue &Result) {
7841     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
7842   }
7843 
7844 public:
7845   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
7846       : ExprEvaluatorBaseTy(Info), Result(Result),
7847         InvalidBaseOK(InvalidBaseOK) {}
7848 
7849   bool Success(const APValue &V, const Expr *E) {
7850     Result.setFrom(this->Info.Ctx, V);
7851     return true;
7852   }
7853 
7854   bool VisitMemberExpr(const MemberExpr *E) {
7855     // Handle non-static data members.
7856     QualType BaseTy;
7857     bool EvalOK;
7858     if (E->isArrow()) {
7859       EvalOK = evaluatePointer(E->getBase(), Result);
7860       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
7861     } else if (E->getBase()->isRValue()) {
7862       assert(E->getBase()->getType()->isRecordType());
7863       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
7864       BaseTy = E->getBase()->getType();
7865     } else {
7866       EvalOK = this->Visit(E->getBase());
7867       BaseTy = E->getBase()->getType();
7868     }
7869     if (!EvalOK) {
7870       if (!InvalidBaseOK)
7871         return false;
7872       Result.setInvalid(E);
7873       return true;
7874     }
7875 
7876     const ValueDecl *MD = E->getMemberDecl();
7877     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
7878       assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7879              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7880       (void)BaseTy;
7881       if (!HandleLValueMember(this->Info, E, Result, FD))
7882         return false;
7883     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
7884       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
7885         return false;
7886     } else
7887       return this->Error(E);
7888 
7889     if (MD->getType()->isReferenceType()) {
7890       APValue RefValue;
7891       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
7892                                           RefValue))
7893         return false;
7894       return Success(RefValue, E);
7895     }
7896     return true;
7897   }
7898 
7899   bool VisitBinaryOperator(const BinaryOperator *E) {
7900     switch (E->getOpcode()) {
7901     default:
7902       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7903 
7904     case BO_PtrMemD:
7905     case BO_PtrMemI:
7906       return HandleMemberPointerAccess(this->Info, E, Result);
7907     }
7908   }
7909 
7910   bool VisitCastExpr(const CastExpr *E) {
7911     switch (E->getCastKind()) {
7912     default:
7913       return ExprEvaluatorBaseTy::VisitCastExpr(E);
7914 
7915     case CK_DerivedToBase:
7916     case CK_UncheckedDerivedToBase:
7917       if (!this->Visit(E->getSubExpr()))
7918         return false;
7919 
7920       // Now figure out the necessary offset to add to the base LV to get from
7921       // the derived class to the base class.
7922       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
7923                                   Result);
7924     }
7925   }
7926 };
7927 }
7928 
7929 //===----------------------------------------------------------------------===//
7930 // LValue Evaluation
7931 //
7932 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
7933 // function designators (in C), decl references to void objects (in C), and
7934 // temporaries (if building with -Wno-address-of-temporary).
7935 //
7936 // LValue evaluation produces values comprising a base expression of one of the
7937 // following types:
7938 // - Declarations
7939 //  * VarDecl
7940 //  * FunctionDecl
7941 // - Literals
7942 //  * CompoundLiteralExpr in C (and in global scope in C++)
7943 //  * StringLiteral
7944 //  * PredefinedExpr
7945 //  * ObjCStringLiteralExpr
7946 //  * ObjCEncodeExpr
7947 //  * AddrLabelExpr
7948 //  * BlockExpr
7949 //  * CallExpr for a MakeStringConstant builtin
7950 // - typeid(T) expressions, as TypeInfoLValues
7951 // - Locals and temporaries
7952 //  * MaterializeTemporaryExpr
7953 //  * Any Expr, with a CallIndex indicating the function in which the temporary
7954 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
7955 //    from the AST (FIXME).
7956 //  * A MaterializeTemporaryExpr that has static storage duration, with no
7957 //    CallIndex, for a lifetime-extended temporary.
7958 //  * The ConstantExpr that is currently being evaluated during evaluation of an
7959 //    immediate invocation.
7960 // plus an offset in bytes.
7961 //===----------------------------------------------------------------------===//
7962 namespace {
7963 class LValueExprEvaluator
7964   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
7965 public:
7966   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
7967     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
7968 
7969   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
7970   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
7971 
7972   bool VisitDeclRefExpr(const DeclRefExpr *E);
7973   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
7974   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
7975   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
7976   bool VisitMemberExpr(const MemberExpr *E);
7977   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
7978   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
7979   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
7980   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
7981   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
7982   bool VisitUnaryDeref(const UnaryOperator *E);
7983   bool VisitUnaryReal(const UnaryOperator *E);
7984   bool VisitUnaryImag(const UnaryOperator *E);
7985   bool VisitUnaryPreInc(const UnaryOperator *UO) {
7986     return VisitUnaryPreIncDec(UO);
7987   }
7988   bool VisitUnaryPreDec(const UnaryOperator *UO) {
7989     return VisitUnaryPreIncDec(UO);
7990   }
7991   bool VisitBinAssign(const BinaryOperator *BO);
7992   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
7993 
7994   bool VisitCastExpr(const CastExpr *E) {
7995     switch (E->getCastKind()) {
7996     default:
7997       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
7998 
7999     case CK_LValueBitCast:
8000       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8001       if (!Visit(E->getSubExpr()))
8002         return false;
8003       Result.Designator.setInvalid();
8004       return true;
8005 
8006     case CK_BaseToDerived:
8007       if (!Visit(E->getSubExpr()))
8008         return false;
8009       return HandleBaseToDerivedCast(Info, E, Result);
8010 
8011     case CK_Dynamic:
8012       if (!Visit(E->getSubExpr()))
8013         return false;
8014       return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8015     }
8016   }
8017 };
8018 } // end anonymous namespace
8019 
8020 /// Evaluate an expression as an lvalue. This can be legitimately called on
8021 /// expressions which are not glvalues, in three cases:
8022 ///  * function designators in C, and
8023 ///  * "extern void" objects
8024 ///  * @selector() expressions in Objective-C
8025 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
8026                            bool InvalidBaseOK) {
8027   assert(E->isGLValue() || E->getType()->isFunctionType() ||
8028          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
8029   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8030 }
8031 
8032 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
8033   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
8034     return Success(FD);
8035   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
8036     return VisitVarDecl(E, VD);
8037   if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
8038     return Visit(BD->getBinding());
8039   if (const MSGuidDecl *GD = dyn_cast<MSGuidDecl>(E->getDecl()))
8040     return Success(GD);
8041   return Error(E);
8042 }
8043 
8044 
8045 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
8046 
8047   // If we are within a lambda's call operator, check whether the 'VD' referred
8048   // to within 'E' actually represents a lambda-capture that maps to a
8049   // data-member/field within the closure object, and if so, evaluate to the
8050   // field or what the field refers to.
8051   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
8052       isa<DeclRefExpr>(E) &&
8053       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
8054     // We don't always have a complete capture-map when checking or inferring if
8055     // the function call operator meets the requirements of a constexpr function
8056     // - but we don't need to evaluate the captures to determine constexprness
8057     // (dcl.constexpr C++17).
8058     if (Info.checkingPotentialConstantExpression())
8059       return false;
8060 
8061     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
8062       // Start with 'Result' referring to the complete closure object...
8063       Result = *Info.CurrentCall->This;
8064       // ... then update it to refer to the field of the closure object
8065       // that represents the capture.
8066       if (!HandleLValueMember(Info, E, Result, FD))
8067         return false;
8068       // And if the field is of reference type, update 'Result' to refer to what
8069       // the field refers to.
8070       if (FD->getType()->isReferenceType()) {
8071         APValue RVal;
8072         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
8073                                             RVal))
8074           return false;
8075         Result.setFrom(Info.Ctx, RVal);
8076       }
8077       return true;
8078     }
8079   }
8080 
8081   CallStackFrame *Frame = nullptr;
8082   unsigned Version = 0;
8083   if (VD->hasLocalStorage()) {
8084     // Only if a local variable was declared in the function currently being
8085     // evaluated, do we expect to be able to find its value in the current
8086     // frame. (Otherwise it was likely declared in an enclosing context and
8087     // could either have a valid evaluatable value (for e.g. a constexpr
8088     // variable) or be ill-formed (and trigger an appropriate evaluation
8089     // diagnostic)).
8090     CallStackFrame *CurrFrame = Info.CurrentCall;
8091     if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
8092       // Function parameters are stored in some caller's frame. (Usually the
8093       // immediate caller, but for an inherited constructor they may be more
8094       // distant.)
8095       if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
8096         if (CurrFrame->Arguments) {
8097           VD = CurrFrame->Arguments.getOrigParam(PVD);
8098           Frame =
8099               Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
8100           Version = CurrFrame->Arguments.Version;
8101         }
8102       } else {
8103         Frame = CurrFrame;
8104         Version = CurrFrame->getCurrentTemporaryVersion(VD);
8105       }
8106     }
8107   }
8108 
8109   if (!VD->getType()->isReferenceType()) {
8110     if (Frame) {
8111       Result.set({VD, Frame->Index, Version});
8112       return true;
8113     }
8114     return Success(VD);
8115   }
8116 
8117   APValue *V;
8118   if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
8119     return false;
8120   if (!V->hasValue()) {
8121     // FIXME: Is it possible for V to be indeterminate here? If so, we should
8122     // adjust the diagnostic to say that.
8123     if (!Info.checkingPotentialConstantExpression())
8124       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
8125     return false;
8126   }
8127   return Success(*V, E);
8128 }
8129 
8130 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
8131     const MaterializeTemporaryExpr *E) {
8132   // Walk through the expression to find the materialized temporary itself.
8133   SmallVector<const Expr *, 2> CommaLHSs;
8134   SmallVector<SubobjectAdjustment, 2> Adjustments;
8135   const Expr *Inner =
8136       E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
8137 
8138   // If we passed any comma operators, evaluate their LHSs.
8139   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
8140     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
8141       return false;
8142 
8143   // A materialized temporary with static storage duration can appear within the
8144   // result of a constant expression evaluation, so we need to preserve its
8145   // value for use outside this evaluation.
8146   APValue *Value;
8147   if (E->getStorageDuration() == SD_Static) {
8148     // FIXME: What about SD_Thread?
8149     Value = E->getOrCreateValue(true);
8150     *Value = APValue();
8151     Result.set(E);
8152   } else {
8153     Value = &Info.CurrentCall->createTemporary(
8154         E, E->getType(),
8155         E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
8156                                                      : ScopeKind::Block,
8157         Result);
8158   }
8159 
8160   QualType Type = Inner->getType();
8161 
8162   // Materialize the temporary itself.
8163   if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
8164     *Value = APValue();
8165     return false;
8166   }
8167 
8168   // Adjust our lvalue to refer to the desired subobject.
8169   for (unsigned I = Adjustments.size(); I != 0; /**/) {
8170     --I;
8171     switch (Adjustments[I].Kind) {
8172     case SubobjectAdjustment::DerivedToBaseAdjustment:
8173       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
8174                                 Type, Result))
8175         return false;
8176       Type = Adjustments[I].DerivedToBase.BasePath->getType();
8177       break;
8178 
8179     case SubobjectAdjustment::FieldAdjustment:
8180       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
8181         return false;
8182       Type = Adjustments[I].Field->getType();
8183       break;
8184 
8185     case SubobjectAdjustment::MemberPointerAdjustment:
8186       if (!HandleMemberPointerAccess(this->Info, Type, Result,
8187                                      Adjustments[I].Ptr.RHS))
8188         return false;
8189       Type = Adjustments[I].Ptr.MPT->getPointeeType();
8190       break;
8191     }
8192   }
8193 
8194   return true;
8195 }
8196 
8197 bool
8198 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8199   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
8200          "lvalue compound literal in c++?");
8201   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
8202   // only see this when folding in C, so there's no standard to follow here.
8203   return Success(E);
8204 }
8205 
8206 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
8207   TypeInfoLValue TypeInfo;
8208 
8209   if (!E->isPotentiallyEvaluated()) {
8210     if (E->isTypeOperand())
8211       TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
8212     else
8213       TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
8214   } else {
8215     if (!Info.Ctx.getLangOpts().CPlusPlus20) {
8216       Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
8217         << E->getExprOperand()->getType()
8218         << E->getExprOperand()->getSourceRange();
8219     }
8220 
8221     if (!Visit(E->getExprOperand()))
8222       return false;
8223 
8224     Optional<DynamicType> DynType =
8225         ComputeDynamicType(Info, E, Result, AK_TypeId);
8226     if (!DynType)
8227       return false;
8228 
8229     TypeInfo =
8230         TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
8231   }
8232 
8233   return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
8234 }
8235 
8236 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
8237   return Success(E->getGuidDecl());
8238 }
8239 
8240 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
8241   // Handle static data members.
8242   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
8243     VisitIgnoredBaseExpression(E->getBase());
8244     return VisitVarDecl(E, VD);
8245   }
8246 
8247   // Handle static member functions.
8248   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
8249     if (MD->isStatic()) {
8250       VisitIgnoredBaseExpression(E->getBase());
8251       return Success(MD);
8252     }
8253   }
8254 
8255   // Handle non-static data members.
8256   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
8257 }
8258 
8259 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
8260   // FIXME: Deal with vectors as array subscript bases.
8261   if (E->getBase()->getType()->isVectorType())
8262     return Error(E);
8263 
8264   APSInt Index;
8265   bool Success = true;
8266 
8267   // C++17's rules require us to evaluate the LHS first, regardless of which
8268   // side is the base.
8269   for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
8270     if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
8271                                 : !EvaluateInteger(SubExpr, Index, Info)) {
8272       if (!Info.noteFailure())
8273         return false;
8274       Success = false;
8275     }
8276   }
8277 
8278   return Success &&
8279          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
8280 }
8281 
8282 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
8283   return evaluatePointer(E->getSubExpr(), Result);
8284 }
8285 
8286 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8287   if (!Visit(E->getSubExpr()))
8288     return false;
8289   // __real is a no-op on scalar lvalues.
8290   if (E->getSubExpr()->getType()->isAnyComplexType())
8291     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
8292   return true;
8293 }
8294 
8295 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8296   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
8297          "lvalue __imag__ on scalar?");
8298   if (!Visit(E->getSubExpr()))
8299     return false;
8300   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
8301   return true;
8302 }
8303 
8304 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
8305   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8306     return Error(UO);
8307 
8308   if (!this->Visit(UO->getSubExpr()))
8309     return false;
8310 
8311   return handleIncDec(
8312       this->Info, UO, Result, UO->getSubExpr()->getType(),
8313       UO->isIncrementOp(), nullptr);
8314 }
8315 
8316 bool LValueExprEvaluator::VisitCompoundAssignOperator(
8317     const CompoundAssignOperator *CAO) {
8318   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8319     return Error(CAO);
8320 
8321   bool Success = true;
8322 
8323   // C++17 onwards require that we evaluate the RHS first.
8324   APValue RHS;
8325   if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
8326     if (!Info.noteFailure())
8327       return false;
8328     Success = false;
8329   }
8330 
8331   // The overall lvalue result is the result of evaluating the LHS.
8332   if (!this->Visit(CAO->getLHS()) || !Success)
8333     return false;
8334 
8335   return handleCompoundAssignment(
8336       this->Info, CAO,
8337       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
8338       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
8339 }
8340 
8341 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
8342   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8343     return Error(E);
8344 
8345   bool Success = true;
8346 
8347   // C++17 onwards require that we evaluate the RHS first.
8348   APValue NewVal;
8349   if (!Evaluate(NewVal, this->Info, E->getRHS())) {
8350     if (!Info.noteFailure())
8351       return false;
8352     Success = false;
8353   }
8354 
8355   if (!this->Visit(E->getLHS()) || !Success)
8356     return false;
8357 
8358   if (Info.getLangOpts().CPlusPlus20 &&
8359       !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
8360     return false;
8361 
8362   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
8363                           NewVal);
8364 }
8365 
8366 //===----------------------------------------------------------------------===//
8367 // Pointer Evaluation
8368 //===----------------------------------------------------------------------===//
8369 
8370 /// Attempts to compute the number of bytes available at the pointer
8371 /// returned by a function with the alloc_size attribute. Returns true if we
8372 /// were successful. Places an unsigned number into `Result`.
8373 ///
8374 /// This expects the given CallExpr to be a call to a function with an
8375 /// alloc_size attribute.
8376 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8377                                             const CallExpr *Call,
8378                                             llvm::APInt &Result) {
8379   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
8380 
8381   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
8382   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
8383   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
8384   if (Call->getNumArgs() <= SizeArgNo)
8385     return false;
8386 
8387   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
8388     Expr::EvalResult ExprResult;
8389     if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
8390       return false;
8391     Into = ExprResult.Val.getInt();
8392     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
8393       return false;
8394     Into = Into.zextOrSelf(BitsInSizeT);
8395     return true;
8396   };
8397 
8398   APSInt SizeOfElem;
8399   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
8400     return false;
8401 
8402   if (!AllocSize->getNumElemsParam().isValid()) {
8403     Result = std::move(SizeOfElem);
8404     return true;
8405   }
8406 
8407   APSInt NumberOfElems;
8408   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
8409   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
8410     return false;
8411 
8412   bool Overflow;
8413   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
8414   if (Overflow)
8415     return false;
8416 
8417   Result = std::move(BytesAvailable);
8418   return true;
8419 }
8420 
8421 /// Convenience function. LVal's base must be a call to an alloc_size
8422 /// function.
8423 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8424                                             const LValue &LVal,
8425                                             llvm::APInt &Result) {
8426   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8427          "Can't get the size of a non alloc_size function");
8428   const auto *Base = LVal.getLValueBase().get<const Expr *>();
8429   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
8430   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
8431 }
8432 
8433 /// Attempts to evaluate the given LValueBase as the result of a call to
8434 /// a function with the alloc_size attribute. If it was possible to do so, this
8435 /// function will return true, make Result's Base point to said function call,
8436 /// and mark Result's Base as invalid.
8437 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
8438                                       LValue &Result) {
8439   if (Base.isNull())
8440     return false;
8441 
8442   // Because we do no form of static analysis, we only support const variables.
8443   //
8444   // Additionally, we can't support parameters, nor can we support static
8445   // variables (in the latter case, use-before-assign isn't UB; in the former,
8446   // we have no clue what they'll be assigned to).
8447   const auto *VD =
8448       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
8449   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
8450     return false;
8451 
8452   const Expr *Init = VD->getAnyInitializer();
8453   if (!Init)
8454     return false;
8455 
8456   const Expr *E = Init->IgnoreParens();
8457   if (!tryUnwrapAllocSizeCall(E))
8458     return false;
8459 
8460   // Store E instead of E unwrapped so that the type of the LValue's base is
8461   // what the user wanted.
8462   Result.setInvalid(E);
8463 
8464   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
8465   Result.addUnsizedArray(Info, E, Pointee);
8466   return true;
8467 }
8468 
8469 namespace {
8470 class PointerExprEvaluator
8471   : public ExprEvaluatorBase<PointerExprEvaluator> {
8472   LValue &Result;
8473   bool InvalidBaseOK;
8474 
8475   bool Success(const Expr *E) {
8476     Result.set(E);
8477     return true;
8478   }
8479 
8480   bool evaluateLValue(const Expr *E, LValue &Result) {
8481     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
8482   }
8483 
8484   bool evaluatePointer(const Expr *E, LValue &Result) {
8485     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
8486   }
8487 
8488   bool visitNonBuiltinCallExpr(const CallExpr *E);
8489 public:
8490 
8491   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
8492       : ExprEvaluatorBaseTy(info), Result(Result),
8493         InvalidBaseOK(InvalidBaseOK) {}
8494 
8495   bool Success(const APValue &V, const Expr *E) {
8496     Result.setFrom(Info.Ctx, V);
8497     return true;
8498   }
8499   bool ZeroInitialization(const Expr *E) {
8500     Result.setNull(Info.Ctx, E->getType());
8501     return true;
8502   }
8503 
8504   bool VisitBinaryOperator(const BinaryOperator *E);
8505   bool VisitCastExpr(const CastExpr* E);
8506   bool VisitUnaryAddrOf(const UnaryOperator *E);
8507   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
8508       { return Success(E); }
8509   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
8510     if (E->isExpressibleAsConstantInitializer())
8511       return Success(E);
8512     if (Info.noteFailure())
8513       EvaluateIgnoredValue(Info, E->getSubExpr());
8514     return Error(E);
8515   }
8516   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
8517       { return Success(E); }
8518   bool VisitCallExpr(const CallExpr *E);
8519   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
8520   bool VisitBlockExpr(const BlockExpr *E) {
8521     if (!E->getBlockDecl()->hasCaptures())
8522       return Success(E);
8523     return Error(E);
8524   }
8525   bool VisitCXXThisExpr(const CXXThisExpr *E) {
8526     // Can't look at 'this' when checking a potential constant expression.
8527     if (Info.checkingPotentialConstantExpression())
8528       return false;
8529     if (!Info.CurrentCall->This) {
8530       if (Info.getLangOpts().CPlusPlus11)
8531         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
8532       else
8533         Info.FFDiag(E);
8534       return false;
8535     }
8536     Result = *Info.CurrentCall->This;
8537     // If we are inside a lambda's call operator, the 'this' expression refers
8538     // to the enclosing '*this' object (either by value or reference) which is
8539     // either copied into the closure object's field that represents the '*this'
8540     // or refers to '*this'.
8541     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
8542       // Ensure we actually have captured 'this'. (an error will have
8543       // been previously reported if not).
8544       if (!Info.CurrentCall->LambdaThisCaptureField)
8545         return false;
8546 
8547       // Update 'Result' to refer to the data member/field of the closure object
8548       // that represents the '*this' capture.
8549       if (!HandleLValueMember(Info, E, Result,
8550                              Info.CurrentCall->LambdaThisCaptureField))
8551         return false;
8552       // If we captured '*this' by reference, replace the field with its referent.
8553       if (Info.CurrentCall->LambdaThisCaptureField->getType()
8554               ->isPointerType()) {
8555         APValue RVal;
8556         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
8557                                             RVal))
8558           return false;
8559 
8560         Result.setFrom(Info.Ctx, RVal);
8561       }
8562     }
8563     return true;
8564   }
8565 
8566   bool VisitCXXNewExpr(const CXXNewExpr *E);
8567 
8568   bool VisitSourceLocExpr(const SourceLocExpr *E) {
8569     assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
8570     APValue LValResult = E->EvaluateInContext(
8571         Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8572     Result.setFrom(Info.Ctx, LValResult);
8573     return true;
8574   }
8575 
8576   // FIXME: Missing: @protocol, @selector
8577 };
8578 } // end anonymous namespace
8579 
8580 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
8581                             bool InvalidBaseOK) {
8582   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
8583   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8584 }
8585 
8586 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8587   if (E->getOpcode() != BO_Add &&
8588       E->getOpcode() != BO_Sub)
8589     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8590 
8591   const Expr *PExp = E->getLHS();
8592   const Expr *IExp = E->getRHS();
8593   if (IExp->getType()->isPointerType())
8594     std::swap(PExp, IExp);
8595 
8596   bool EvalPtrOK = evaluatePointer(PExp, Result);
8597   if (!EvalPtrOK && !Info.noteFailure())
8598     return false;
8599 
8600   llvm::APSInt Offset;
8601   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
8602     return false;
8603 
8604   if (E->getOpcode() == BO_Sub)
8605     negateAsSigned(Offset);
8606 
8607   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
8608   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
8609 }
8610 
8611 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8612   return evaluateLValue(E->getSubExpr(), Result);
8613 }
8614 
8615 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8616   const Expr *SubExpr = E->getSubExpr();
8617 
8618   switch (E->getCastKind()) {
8619   default:
8620     break;
8621   case CK_BitCast:
8622   case CK_CPointerToObjCPointerCast:
8623   case CK_BlockPointerToObjCPointerCast:
8624   case CK_AnyPointerToBlockPointerCast:
8625   case CK_AddressSpaceConversion:
8626     if (!Visit(SubExpr))
8627       return false;
8628     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
8629     // permitted in constant expressions in C++11. Bitcasts from cv void* are
8630     // also static_casts, but we disallow them as a resolution to DR1312.
8631     if (!E->getType()->isVoidPointerType()) {
8632       if (!Result.InvalidBase && !Result.Designator.Invalid &&
8633           !Result.IsNullPtr &&
8634           Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
8635                                           E->getType()->getPointeeType()) &&
8636           Info.getStdAllocatorCaller("allocate")) {
8637         // Inside a call to std::allocator::allocate and friends, we permit
8638         // casting from void* back to cv1 T* for a pointer that points to a
8639         // cv2 T.
8640       } else {
8641         Result.Designator.setInvalid();
8642         if (SubExpr->getType()->isVoidPointerType())
8643           CCEDiag(E, diag::note_constexpr_invalid_cast)
8644             << 3 << SubExpr->getType();
8645         else
8646           CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8647       }
8648     }
8649     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
8650       ZeroInitialization(E);
8651     return true;
8652 
8653   case CK_DerivedToBase:
8654   case CK_UncheckedDerivedToBase:
8655     if (!evaluatePointer(E->getSubExpr(), Result))
8656       return false;
8657     if (!Result.Base && Result.Offset.isZero())
8658       return true;
8659 
8660     // Now figure out the necessary offset to add to the base LV to get from
8661     // the derived class to the base class.
8662     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
8663                                   castAs<PointerType>()->getPointeeType(),
8664                                 Result);
8665 
8666   case CK_BaseToDerived:
8667     if (!Visit(E->getSubExpr()))
8668       return false;
8669     if (!Result.Base && Result.Offset.isZero())
8670       return true;
8671     return HandleBaseToDerivedCast(Info, E, Result);
8672 
8673   case CK_Dynamic:
8674     if (!Visit(E->getSubExpr()))
8675       return false;
8676     return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8677 
8678   case CK_NullToPointer:
8679     VisitIgnoredValue(E->getSubExpr());
8680     return ZeroInitialization(E);
8681 
8682   case CK_IntegralToPointer: {
8683     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8684 
8685     APValue Value;
8686     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
8687       break;
8688 
8689     if (Value.isInt()) {
8690       unsigned Size = Info.Ctx.getTypeSize(E->getType());
8691       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
8692       Result.Base = (Expr*)nullptr;
8693       Result.InvalidBase = false;
8694       Result.Offset = CharUnits::fromQuantity(N);
8695       Result.Designator.setInvalid();
8696       Result.IsNullPtr = false;
8697       return true;
8698     } else {
8699       // Cast is of an lvalue, no need to change value.
8700       Result.setFrom(Info.Ctx, Value);
8701       return true;
8702     }
8703   }
8704 
8705   case CK_ArrayToPointerDecay: {
8706     if (SubExpr->isGLValue()) {
8707       if (!evaluateLValue(SubExpr, Result))
8708         return false;
8709     } else {
8710       APValue &Value = Info.CurrentCall->createTemporary(
8711           SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
8712       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
8713         return false;
8714     }
8715     // The result is a pointer to the first element of the array.
8716     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
8717     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
8718       Result.addArray(Info, E, CAT);
8719     else
8720       Result.addUnsizedArray(Info, E, AT->getElementType());
8721     return true;
8722   }
8723 
8724   case CK_FunctionToPointerDecay:
8725     return evaluateLValue(SubExpr, Result);
8726 
8727   case CK_LValueToRValue: {
8728     LValue LVal;
8729     if (!evaluateLValue(E->getSubExpr(), LVal))
8730       return false;
8731 
8732     APValue RVal;
8733     // Note, we use the subexpression's type in order to retain cv-qualifiers.
8734     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8735                                         LVal, RVal))
8736       return InvalidBaseOK &&
8737              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
8738     return Success(RVal, E);
8739   }
8740   }
8741 
8742   return ExprEvaluatorBaseTy::VisitCastExpr(E);
8743 }
8744 
8745 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
8746                                 UnaryExprOrTypeTrait ExprKind) {
8747   // C++ [expr.alignof]p3:
8748   //     When alignof is applied to a reference type, the result is the
8749   //     alignment of the referenced type.
8750   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
8751     T = Ref->getPointeeType();
8752 
8753   if (T.getQualifiers().hasUnaligned())
8754     return CharUnits::One();
8755 
8756   const bool AlignOfReturnsPreferred =
8757       Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
8758 
8759   // __alignof is defined to return the preferred alignment.
8760   // Before 8, clang returned the preferred alignment for alignof and _Alignof
8761   // as well.
8762   if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
8763     return Info.Ctx.toCharUnitsFromBits(
8764       Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
8765   // alignof and _Alignof are defined to return the ABI alignment.
8766   else if (ExprKind == UETT_AlignOf)
8767     return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
8768   else
8769     llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
8770 }
8771 
8772 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
8773                                 UnaryExprOrTypeTrait ExprKind) {
8774   E = E->IgnoreParens();
8775 
8776   // The kinds of expressions that we have special-case logic here for
8777   // should be kept up to date with the special checks for those
8778   // expressions in Sema.
8779 
8780   // alignof decl is always accepted, even if it doesn't make sense: we default
8781   // to 1 in those cases.
8782   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8783     return Info.Ctx.getDeclAlign(DRE->getDecl(),
8784                                  /*RefAsPointee*/true);
8785 
8786   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
8787     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
8788                                  /*RefAsPointee*/true);
8789 
8790   return GetAlignOfType(Info, E->getType(), ExprKind);
8791 }
8792 
8793 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
8794   if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
8795     return Info.Ctx.getDeclAlign(VD);
8796   if (const auto *E = Value.Base.dyn_cast<const Expr *>())
8797     return GetAlignOfExpr(Info, E, UETT_AlignOf);
8798   return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
8799 }
8800 
8801 /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
8802 /// __builtin_is_aligned and __builtin_assume_aligned.
8803 static bool getAlignmentArgument(const Expr *E, QualType ForType,
8804                                  EvalInfo &Info, APSInt &Alignment) {
8805   if (!EvaluateInteger(E, Alignment, Info))
8806     return false;
8807   if (Alignment < 0 || !Alignment.isPowerOf2()) {
8808     Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
8809     return false;
8810   }
8811   unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
8812   APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
8813   if (APSInt::compareValues(Alignment, MaxValue) > 0) {
8814     Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
8815         << MaxValue << ForType << Alignment;
8816     return false;
8817   }
8818   // Ensure both alignment and source value have the same bit width so that we
8819   // don't assert when computing the resulting value.
8820   APSInt ExtAlignment =
8821       APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
8822   assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
8823          "Alignment should not be changed by ext/trunc");
8824   Alignment = ExtAlignment;
8825   assert(Alignment.getBitWidth() == SrcWidth);
8826   return true;
8827 }
8828 
8829 // To be clear: this happily visits unsupported builtins. Better name welcomed.
8830 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
8831   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
8832     return true;
8833 
8834   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
8835     return false;
8836 
8837   Result.setInvalid(E);
8838   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
8839   Result.addUnsizedArray(Info, E, PointeeTy);
8840   return true;
8841 }
8842 
8843 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
8844   if (IsStringLiteralCall(E))
8845     return Success(E);
8846 
8847   if (unsigned BuiltinOp = E->getBuiltinCallee())
8848     return VisitBuiltinCallExpr(E, BuiltinOp);
8849 
8850   return visitNonBuiltinCallExpr(E);
8851 }
8852 
8853 // Determine if T is a character type for which we guarantee that
8854 // sizeof(T) == 1.
8855 static bool isOneByteCharacterType(QualType T) {
8856   return T->isCharType() || T->isChar8Type();
8857 }
8858 
8859 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8860                                                 unsigned BuiltinOp) {
8861   switch (BuiltinOp) {
8862   case Builtin::BI__builtin_addressof:
8863     return evaluateLValue(E->getArg(0), Result);
8864   case Builtin::BI__builtin_assume_aligned: {
8865     // We need to be very careful here because: if the pointer does not have the
8866     // asserted alignment, then the behavior is undefined, and undefined
8867     // behavior is non-constant.
8868     if (!evaluatePointer(E->getArg(0), Result))
8869       return false;
8870 
8871     LValue OffsetResult(Result);
8872     APSInt Alignment;
8873     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
8874                               Alignment))
8875       return false;
8876     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
8877 
8878     if (E->getNumArgs() > 2) {
8879       APSInt Offset;
8880       if (!EvaluateInteger(E->getArg(2), Offset, Info))
8881         return false;
8882 
8883       int64_t AdditionalOffset = -Offset.getZExtValue();
8884       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
8885     }
8886 
8887     // If there is a base object, then it must have the correct alignment.
8888     if (OffsetResult.Base) {
8889       CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
8890 
8891       if (BaseAlignment < Align) {
8892         Result.Designator.setInvalid();
8893         // FIXME: Add support to Diagnostic for long / long long.
8894         CCEDiag(E->getArg(0),
8895                 diag::note_constexpr_baa_insufficient_alignment) << 0
8896           << (unsigned)BaseAlignment.getQuantity()
8897           << (unsigned)Align.getQuantity();
8898         return false;
8899       }
8900     }
8901 
8902     // The offset must also have the correct alignment.
8903     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
8904       Result.Designator.setInvalid();
8905 
8906       (OffsetResult.Base
8907            ? CCEDiag(E->getArg(0),
8908                      diag::note_constexpr_baa_insufficient_alignment) << 1
8909            : CCEDiag(E->getArg(0),
8910                      diag::note_constexpr_baa_value_insufficient_alignment))
8911         << (int)OffsetResult.Offset.getQuantity()
8912         << (unsigned)Align.getQuantity();
8913       return false;
8914     }
8915 
8916     return true;
8917   }
8918   case Builtin::BI__builtin_align_up:
8919   case Builtin::BI__builtin_align_down: {
8920     if (!evaluatePointer(E->getArg(0), Result))
8921       return false;
8922     APSInt Alignment;
8923     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
8924                               Alignment))
8925       return false;
8926     CharUnits BaseAlignment = getBaseAlignment(Info, Result);
8927     CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
8928     // For align_up/align_down, we can return the same value if the alignment
8929     // is known to be greater or equal to the requested value.
8930     if (PtrAlign.getQuantity() >= Alignment)
8931       return true;
8932 
8933     // The alignment could be greater than the minimum at run-time, so we cannot
8934     // infer much about the resulting pointer value. One case is possible:
8935     // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
8936     // can infer the correct index if the requested alignment is smaller than
8937     // the base alignment so we can perform the computation on the offset.
8938     if (BaseAlignment.getQuantity() >= Alignment) {
8939       assert(Alignment.getBitWidth() <= 64 &&
8940              "Cannot handle > 64-bit address-space");
8941       uint64_t Alignment64 = Alignment.getZExtValue();
8942       CharUnits NewOffset = CharUnits::fromQuantity(
8943           BuiltinOp == Builtin::BI__builtin_align_down
8944               ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
8945               : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
8946       Result.adjustOffset(NewOffset - Result.Offset);
8947       // TODO: diagnose out-of-bounds values/only allow for arrays?
8948       return true;
8949     }
8950     // Otherwise, we cannot constant-evaluate the result.
8951     Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
8952         << Alignment;
8953     return false;
8954   }
8955   case Builtin::BI__builtin_operator_new:
8956     return HandleOperatorNewCall(Info, E, Result);
8957   case Builtin::BI__builtin_launder:
8958     return evaluatePointer(E->getArg(0), Result);
8959   case Builtin::BIstrchr:
8960   case Builtin::BIwcschr:
8961   case Builtin::BImemchr:
8962   case Builtin::BIwmemchr:
8963     if (Info.getLangOpts().CPlusPlus11)
8964       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8965         << /*isConstexpr*/0 << /*isConstructor*/0
8966         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
8967     else
8968       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
8969     LLVM_FALLTHROUGH;
8970   case Builtin::BI__builtin_strchr:
8971   case Builtin::BI__builtin_wcschr:
8972   case Builtin::BI__builtin_memchr:
8973   case Builtin::BI__builtin_char_memchr:
8974   case Builtin::BI__builtin_wmemchr: {
8975     if (!Visit(E->getArg(0)))
8976       return false;
8977     APSInt Desired;
8978     if (!EvaluateInteger(E->getArg(1), Desired, Info))
8979       return false;
8980     uint64_t MaxLength = uint64_t(-1);
8981     if (BuiltinOp != Builtin::BIstrchr &&
8982         BuiltinOp != Builtin::BIwcschr &&
8983         BuiltinOp != Builtin::BI__builtin_strchr &&
8984         BuiltinOp != Builtin::BI__builtin_wcschr) {
8985       APSInt N;
8986       if (!EvaluateInteger(E->getArg(2), N, Info))
8987         return false;
8988       MaxLength = N.getExtValue();
8989     }
8990     // We cannot find the value if there are no candidates to match against.
8991     if (MaxLength == 0u)
8992       return ZeroInitialization(E);
8993     if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
8994         Result.Designator.Invalid)
8995       return false;
8996     QualType CharTy = Result.Designator.getType(Info.Ctx);
8997     bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
8998                      BuiltinOp == Builtin::BI__builtin_memchr;
8999     assert(IsRawByte ||
9000            Info.Ctx.hasSameUnqualifiedType(
9001                CharTy, E->getArg(0)->getType()->getPointeeType()));
9002     // Pointers to const void may point to objects of incomplete type.
9003     if (IsRawByte && CharTy->isIncompleteType()) {
9004       Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
9005       return false;
9006     }
9007     // Give up on byte-oriented matching against multibyte elements.
9008     // FIXME: We can compare the bytes in the correct order.
9009     if (IsRawByte && !isOneByteCharacterType(CharTy)) {
9010       Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
9011           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
9012           << CharTy;
9013       return false;
9014     }
9015     // Figure out what value we're actually looking for (after converting to
9016     // the corresponding unsigned type if necessary).
9017     uint64_t DesiredVal;
9018     bool StopAtNull = false;
9019     switch (BuiltinOp) {
9020     case Builtin::BIstrchr:
9021     case Builtin::BI__builtin_strchr:
9022       // strchr compares directly to the passed integer, and therefore
9023       // always fails if given an int that is not a char.
9024       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
9025                                                   E->getArg(1)->getType(),
9026                                                   Desired),
9027                                Desired))
9028         return ZeroInitialization(E);
9029       StopAtNull = true;
9030       LLVM_FALLTHROUGH;
9031     case Builtin::BImemchr:
9032     case Builtin::BI__builtin_memchr:
9033     case Builtin::BI__builtin_char_memchr:
9034       // memchr compares by converting both sides to unsigned char. That's also
9035       // correct for strchr if we get this far (to cope with plain char being
9036       // unsigned in the strchr case).
9037       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
9038       break;
9039 
9040     case Builtin::BIwcschr:
9041     case Builtin::BI__builtin_wcschr:
9042       StopAtNull = true;
9043       LLVM_FALLTHROUGH;
9044     case Builtin::BIwmemchr:
9045     case Builtin::BI__builtin_wmemchr:
9046       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
9047       DesiredVal = Desired.getZExtValue();
9048       break;
9049     }
9050 
9051     for (; MaxLength; --MaxLength) {
9052       APValue Char;
9053       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
9054           !Char.isInt())
9055         return false;
9056       if (Char.getInt().getZExtValue() == DesiredVal)
9057         return true;
9058       if (StopAtNull && !Char.getInt())
9059         break;
9060       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
9061         return false;
9062     }
9063     // Not found: return nullptr.
9064     return ZeroInitialization(E);
9065   }
9066 
9067   case Builtin::BImemcpy:
9068   case Builtin::BImemmove:
9069   case Builtin::BIwmemcpy:
9070   case Builtin::BIwmemmove:
9071     if (Info.getLangOpts().CPlusPlus11)
9072       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9073         << /*isConstexpr*/0 << /*isConstructor*/0
9074         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9075     else
9076       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9077     LLVM_FALLTHROUGH;
9078   case Builtin::BI__builtin_memcpy:
9079   case Builtin::BI__builtin_memmove:
9080   case Builtin::BI__builtin_wmemcpy:
9081   case Builtin::BI__builtin_wmemmove: {
9082     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
9083                  BuiltinOp == Builtin::BIwmemmove ||
9084                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
9085                  BuiltinOp == Builtin::BI__builtin_wmemmove;
9086     bool Move = BuiltinOp == Builtin::BImemmove ||
9087                 BuiltinOp == Builtin::BIwmemmove ||
9088                 BuiltinOp == Builtin::BI__builtin_memmove ||
9089                 BuiltinOp == Builtin::BI__builtin_wmemmove;
9090 
9091     // The result of mem* is the first argument.
9092     if (!Visit(E->getArg(0)))
9093       return false;
9094     LValue Dest = Result;
9095 
9096     LValue Src;
9097     if (!EvaluatePointer(E->getArg(1), Src, Info))
9098       return false;
9099 
9100     APSInt N;
9101     if (!EvaluateInteger(E->getArg(2), N, Info))
9102       return false;
9103     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
9104 
9105     // If the size is zero, we treat this as always being a valid no-op.
9106     // (Even if one of the src and dest pointers is null.)
9107     if (!N)
9108       return true;
9109 
9110     // Otherwise, if either of the operands is null, we can't proceed. Don't
9111     // try to determine the type of the copied objects, because there aren't
9112     // any.
9113     if (!Src.Base || !Dest.Base) {
9114       APValue Val;
9115       (!Src.Base ? Src : Dest).moveInto(Val);
9116       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
9117           << Move << WChar << !!Src.Base
9118           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
9119       return false;
9120     }
9121     if (Src.Designator.Invalid || Dest.Designator.Invalid)
9122       return false;
9123 
9124     // We require that Src and Dest are both pointers to arrays of
9125     // trivially-copyable type. (For the wide version, the designator will be
9126     // invalid if the designated object is not a wchar_t.)
9127     QualType T = Dest.Designator.getType(Info.Ctx);
9128     QualType SrcT = Src.Designator.getType(Info.Ctx);
9129     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
9130       // FIXME: Consider using our bit_cast implementation to support this.
9131       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
9132       return false;
9133     }
9134     if (T->isIncompleteType()) {
9135       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
9136       return false;
9137     }
9138     if (!T.isTriviallyCopyableType(Info.Ctx)) {
9139       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
9140       return false;
9141     }
9142 
9143     // Figure out how many T's we're copying.
9144     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
9145     if (!WChar) {
9146       uint64_t Remainder;
9147       llvm::APInt OrigN = N;
9148       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
9149       if (Remainder) {
9150         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9151             << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
9152             << (unsigned)TSize;
9153         return false;
9154       }
9155     }
9156 
9157     // Check that the copying will remain within the arrays, just so that we
9158     // can give a more meaningful diagnostic. This implicitly also checks that
9159     // N fits into 64 bits.
9160     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
9161     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
9162     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
9163       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9164           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
9165           << N.toString(10, /*Signed*/false);
9166       return false;
9167     }
9168     uint64_t NElems = N.getZExtValue();
9169     uint64_t NBytes = NElems * TSize;
9170 
9171     // Check for overlap.
9172     int Direction = 1;
9173     if (HasSameBase(Src, Dest)) {
9174       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
9175       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
9176       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
9177         // Dest is inside the source region.
9178         if (!Move) {
9179           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9180           return false;
9181         }
9182         // For memmove and friends, copy backwards.
9183         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
9184             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
9185           return false;
9186         Direction = -1;
9187       } else if (!Move && SrcOffset >= DestOffset &&
9188                  SrcOffset - DestOffset < NBytes) {
9189         // Src is inside the destination region for memcpy: invalid.
9190         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9191         return false;
9192       }
9193     }
9194 
9195     while (true) {
9196       APValue Val;
9197       // FIXME: Set WantObjectRepresentation to true if we're copying a
9198       // char-like type?
9199       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
9200           !handleAssignment(Info, E, Dest, T, Val))
9201         return false;
9202       // Do not iterate past the last element; if we're copying backwards, that
9203       // might take us off the start of the array.
9204       if (--NElems == 0)
9205         return true;
9206       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
9207           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
9208         return false;
9209     }
9210   }
9211 
9212   default:
9213     break;
9214   }
9215 
9216   return visitNonBuiltinCallExpr(E);
9217 }
9218 
9219 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9220                                      APValue &Result, const InitListExpr *ILE,
9221                                      QualType AllocType);
9222 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
9223                                           APValue &Result,
9224                                           const CXXConstructExpr *CCE,
9225                                           QualType AllocType);
9226 
9227 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
9228   if (!Info.getLangOpts().CPlusPlus20)
9229     Info.CCEDiag(E, diag::note_constexpr_new);
9230 
9231   // We cannot speculatively evaluate a delete expression.
9232   if (Info.SpeculativeEvaluationDepth)
9233     return false;
9234 
9235   FunctionDecl *OperatorNew = E->getOperatorNew();
9236 
9237   bool IsNothrow = false;
9238   bool IsPlacement = false;
9239   if (OperatorNew->isReservedGlobalPlacementOperator() &&
9240       Info.CurrentCall->isStdFunction() && !E->isArray()) {
9241     // FIXME Support array placement new.
9242     assert(E->getNumPlacementArgs() == 1);
9243     if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
9244       return false;
9245     if (Result.Designator.Invalid)
9246       return false;
9247     IsPlacement = true;
9248   } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
9249     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
9250         << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
9251     return false;
9252   } else if (E->getNumPlacementArgs()) {
9253     // The only new-placement list we support is of the form (std::nothrow).
9254     //
9255     // FIXME: There is no restriction on this, but it's not clear that any
9256     // other form makes any sense. We get here for cases such as:
9257     //
9258     //   new (std::align_val_t{N}) X(int)
9259     //
9260     // (which should presumably be valid only if N is a multiple of
9261     // alignof(int), and in any case can't be deallocated unless N is
9262     // alignof(X) and X has new-extended alignment).
9263     if (E->getNumPlacementArgs() != 1 ||
9264         !E->getPlacementArg(0)->getType()->isNothrowT())
9265       return Error(E, diag::note_constexpr_new_placement);
9266 
9267     LValue Nothrow;
9268     if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
9269       return false;
9270     IsNothrow = true;
9271   }
9272 
9273   const Expr *Init = E->getInitializer();
9274   const InitListExpr *ResizedArrayILE = nullptr;
9275   const CXXConstructExpr *ResizedArrayCCE = nullptr;
9276   bool ValueInit = false;
9277 
9278   QualType AllocType = E->getAllocatedType();
9279   if (Optional<const Expr*> ArraySize = E->getArraySize()) {
9280     const Expr *Stripped = *ArraySize;
9281     for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
9282          Stripped = ICE->getSubExpr())
9283       if (ICE->getCastKind() != CK_NoOp &&
9284           ICE->getCastKind() != CK_IntegralCast)
9285         break;
9286 
9287     llvm::APSInt ArrayBound;
9288     if (!EvaluateInteger(Stripped, ArrayBound, Info))
9289       return false;
9290 
9291     // C++ [expr.new]p9:
9292     //   The expression is erroneous if:
9293     //   -- [...] its value before converting to size_t [or] applying the
9294     //      second standard conversion sequence is less than zero
9295     if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
9296       if (IsNothrow)
9297         return ZeroInitialization(E);
9298 
9299       Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
9300           << ArrayBound << (*ArraySize)->getSourceRange();
9301       return false;
9302     }
9303 
9304     //   -- its value is such that the size of the allocated object would
9305     //      exceed the implementation-defined limit
9306     if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
9307                                                 ArrayBound) >
9308         ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
9309       if (IsNothrow)
9310         return ZeroInitialization(E);
9311 
9312       Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
9313         << ArrayBound << (*ArraySize)->getSourceRange();
9314       return false;
9315     }
9316 
9317     //   -- the new-initializer is a braced-init-list and the number of
9318     //      array elements for which initializers are provided [...]
9319     //      exceeds the number of elements to initialize
9320     if (!Init) {
9321       // No initialization is performed.
9322     } else if (isa<CXXScalarValueInitExpr>(Init) ||
9323                isa<ImplicitValueInitExpr>(Init)) {
9324       ValueInit = true;
9325     } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
9326       ResizedArrayCCE = CCE;
9327     } else {
9328       auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
9329       assert(CAT && "unexpected type for array initializer");
9330 
9331       unsigned Bits =
9332           std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
9333       llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits);
9334       llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits);
9335       if (InitBound.ugt(AllocBound)) {
9336         if (IsNothrow)
9337           return ZeroInitialization(E);
9338 
9339         Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
9340             << AllocBound.toString(10, /*Signed=*/false)
9341             << InitBound.toString(10, /*Signed=*/false)
9342             << (*ArraySize)->getSourceRange();
9343         return false;
9344       }
9345 
9346       // If the sizes differ, we must have an initializer list, and we need
9347       // special handling for this case when we initialize.
9348       if (InitBound != AllocBound)
9349         ResizedArrayILE = cast<InitListExpr>(Init);
9350     }
9351 
9352     AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
9353                                               ArrayType::Normal, 0);
9354   } else {
9355     assert(!AllocType->isArrayType() &&
9356            "array allocation with non-array new");
9357   }
9358 
9359   APValue *Val;
9360   if (IsPlacement) {
9361     AccessKinds AK = AK_Construct;
9362     struct FindObjectHandler {
9363       EvalInfo &Info;
9364       const Expr *E;
9365       QualType AllocType;
9366       const AccessKinds AccessKind;
9367       APValue *Value;
9368 
9369       typedef bool result_type;
9370       bool failed() { return false; }
9371       bool found(APValue &Subobj, QualType SubobjType) {
9372         // FIXME: Reject the cases where [basic.life]p8 would not permit the
9373         // old name of the object to be used to name the new object.
9374         if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
9375           Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
9376             SubobjType << AllocType;
9377           return false;
9378         }
9379         Value = &Subobj;
9380         return true;
9381       }
9382       bool found(APSInt &Value, QualType SubobjType) {
9383         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9384         return false;
9385       }
9386       bool found(APFloat &Value, QualType SubobjType) {
9387         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9388         return false;
9389       }
9390     } Handler = {Info, E, AllocType, AK, nullptr};
9391 
9392     CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
9393     if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
9394       return false;
9395 
9396     Val = Handler.Value;
9397 
9398     // [basic.life]p1:
9399     //   The lifetime of an object o of type T ends when [...] the storage
9400     //   which the object occupies is [...] reused by an object that is not
9401     //   nested within o (6.6.2).
9402     *Val = APValue();
9403   } else {
9404     // Perform the allocation and obtain a pointer to the resulting object.
9405     Val = Info.createHeapAlloc(E, AllocType, Result);
9406     if (!Val)
9407       return false;
9408   }
9409 
9410   if (ValueInit) {
9411     ImplicitValueInitExpr VIE(AllocType);
9412     if (!EvaluateInPlace(*Val, Info, Result, &VIE))
9413       return false;
9414   } else if (ResizedArrayILE) {
9415     if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
9416                                   AllocType))
9417       return false;
9418   } else if (ResizedArrayCCE) {
9419     if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
9420                                        AllocType))
9421       return false;
9422   } else if (Init) {
9423     if (!EvaluateInPlace(*Val, Info, Result, Init))
9424       return false;
9425   } else if (!getDefaultInitValue(AllocType, *Val)) {
9426     return false;
9427   }
9428 
9429   // Array new returns a pointer to the first element, not a pointer to the
9430   // array.
9431   if (auto *AT = AllocType->getAsArrayTypeUnsafe())
9432     Result.addArray(Info, E, cast<ConstantArrayType>(AT));
9433 
9434   return true;
9435 }
9436 //===----------------------------------------------------------------------===//
9437 // Member Pointer Evaluation
9438 //===----------------------------------------------------------------------===//
9439 
9440 namespace {
9441 class MemberPointerExprEvaluator
9442   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
9443   MemberPtr &Result;
9444 
9445   bool Success(const ValueDecl *D) {
9446     Result = MemberPtr(D);
9447     return true;
9448   }
9449 public:
9450 
9451   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
9452     : ExprEvaluatorBaseTy(Info), Result(Result) {}
9453 
9454   bool Success(const APValue &V, const Expr *E) {
9455     Result.setFrom(V);
9456     return true;
9457   }
9458   bool ZeroInitialization(const Expr *E) {
9459     return Success((const ValueDecl*)nullptr);
9460   }
9461 
9462   bool VisitCastExpr(const CastExpr *E);
9463   bool VisitUnaryAddrOf(const UnaryOperator *E);
9464 };
9465 } // end anonymous namespace
9466 
9467 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
9468                                   EvalInfo &Info) {
9469   assert(E->isRValue() && E->getType()->isMemberPointerType());
9470   return MemberPointerExprEvaluator(Info, Result).Visit(E);
9471 }
9472 
9473 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9474   switch (E->getCastKind()) {
9475   default:
9476     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9477 
9478   case CK_NullToMemberPointer:
9479     VisitIgnoredValue(E->getSubExpr());
9480     return ZeroInitialization(E);
9481 
9482   case CK_BaseToDerivedMemberPointer: {
9483     if (!Visit(E->getSubExpr()))
9484       return false;
9485     if (E->path_empty())
9486       return true;
9487     // Base-to-derived member pointer casts store the path in derived-to-base
9488     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
9489     // the wrong end of the derived->base arc, so stagger the path by one class.
9490     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
9491     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
9492          PathI != PathE; ++PathI) {
9493       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9494       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
9495       if (!Result.castToDerived(Derived))
9496         return Error(E);
9497     }
9498     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
9499     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
9500       return Error(E);
9501     return true;
9502   }
9503 
9504   case CK_DerivedToBaseMemberPointer:
9505     if (!Visit(E->getSubExpr()))
9506       return false;
9507     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9508          PathE = E->path_end(); PathI != PathE; ++PathI) {
9509       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9510       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9511       if (!Result.castToBase(Base))
9512         return Error(E);
9513     }
9514     return true;
9515   }
9516 }
9517 
9518 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9519   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
9520   // member can be formed.
9521   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
9522 }
9523 
9524 //===----------------------------------------------------------------------===//
9525 // Record Evaluation
9526 //===----------------------------------------------------------------------===//
9527 
9528 namespace {
9529   class RecordExprEvaluator
9530   : public ExprEvaluatorBase<RecordExprEvaluator> {
9531     const LValue &This;
9532     APValue &Result;
9533   public:
9534 
9535     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
9536       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
9537 
9538     bool Success(const APValue &V, const Expr *E) {
9539       Result = V;
9540       return true;
9541     }
9542     bool ZeroInitialization(const Expr *E) {
9543       return ZeroInitialization(E, E->getType());
9544     }
9545     bool ZeroInitialization(const Expr *E, QualType T);
9546 
9547     bool VisitCallExpr(const CallExpr *E) {
9548       return handleCallExpr(E, Result, &This);
9549     }
9550     bool VisitCastExpr(const CastExpr *E);
9551     bool VisitInitListExpr(const InitListExpr *E);
9552     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9553       return VisitCXXConstructExpr(E, E->getType());
9554     }
9555     bool VisitLambdaExpr(const LambdaExpr *E);
9556     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
9557     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
9558     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
9559     bool VisitBinCmp(const BinaryOperator *E);
9560   };
9561 }
9562 
9563 /// Perform zero-initialization on an object of non-union class type.
9564 /// C++11 [dcl.init]p5:
9565 ///  To zero-initialize an object or reference of type T means:
9566 ///    [...]
9567 ///    -- if T is a (possibly cv-qualified) non-union class type,
9568 ///       each non-static data member and each base-class subobject is
9569 ///       zero-initialized
9570 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
9571                                           const RecordDecl *RD,
9572                                           const LValue &This, APValue &Result) {
9573   assert(!RD->isUnion() && "Expected non-union class type");
9574   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
9575   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
9576                    std::distance(RD->field_begin(), RD->field_end()));
9577 
9578   if (RD->isInvalidDecl()) return false;
9579   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9580 
9581   if (CD) {
9582     unsigned Index = 0;
9583     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
9584            End = CD->bases_end(); I != End; ++I, ++Index) {
9585       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
9586       LValue Subobject = This;
9587       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
9588         return false;
9589       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
9590                                          Result.getStructBase(Index)))
9591         return false;
9592     }
9593   }
9594 
9595   for (const auto *I : RD->fields()) {
9596     // -- if T is a reference type, no initialization is performed.
9597     if (I->getType()->isReferenceType())
9598       continue;
9599 
9600     LValue Subobject = This;
9601     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
9602       return false;
9603 
9604     ImplicitValueInitExpr VIE(I->getType());
9605     if (!EvaluateInPlace(
9606           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
9607       return false;
9608   }
9609 
9610   return true;
9611 }
9612 
9613 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
9614   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
9615   if (RD->isInvalidDecl()) return false;
9616   if (RD->isUnion()) {
9617     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
9618     // object's first non-static named data member is zero-initialized
9619     RecordDecl::field_iterator I = RD->field_begin();
9620     if (I == RD->field_end()) {
9621       Result = APValue((const FieldDecl*)nullptr);
9622       return true;
9623     }
9624 
9625     LValue Subobject = This;
9626     if (!HandleLValueMember(Info, E, Subobject, *I))
9627       return false;
9628     Result = APValue(*I);
9629     ImplicitValueInitExpr VIE(I->getType());
9630     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
9631   }
9632 
9633   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
9634     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
9635     return false;
9636   }
9637 
9638   return HandleClassZeroInitialization(Info, E, RD, This, Result);
9639 }
9640 
9641 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
9642   switch (E->getCastKind()) {
9643   default:
9644     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9645 
9646   case CK_ConstructorConversion:
9647     return Visit(E->getSubExpr());
9648 
9649   case CK_DerivedToBase:
9650   case CK_UncheckedDerivedToBase: {
9651     APValue DerivedObject;
9652     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
9653       return false;
9654     if (!DerivedObject.isStruct())
9655       return Error(E->getSubExpr());
9656 
9657     // Derived-to-base rvalue conversion: just slice off the derived part.
9658     APValue *Value = &DerivedObject;
9659     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
9660     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9661          PathE = E->path_end(); PathI != PathE; ++PathI) {
9662       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
9663       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9664       Value = &Value->getStructBase(getBaseIndex(RD, Base));
9665       RD = Base;
9666     }
9667     Result = *Value;
9668     return true;
9669   }
9670   }
9671 }
9672 
9673 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9674   if (E->isTransparent())
9675     return Visit(E->getInit(0));
9676 
9677   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
9678   if (RD->isInvalidDecl()) return false;
9679   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9680   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
9681 
9682   EvalInfo::EvaluatingConstructorRAII EvalObj(
9683       Info,
9684       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
9685       CXXRD && CXXRD->getNumBases());
9686 
9687   if (RD->isUnion()) {
9688     const FieldDecl *Field = E->getInitializedFieldInUnion();
9689     Result = APValue(Field);
9690     if (!Field)
9691       return true;
9692 
9693     // If the initializer list for a union does not contain any elements, the
9694     // first element of the union is value-initialized.
9695     // FIXME: The element should be initialized from an initializer list.
9696     //        Is this difference ever observable for initializer lists which
9697     //        we don't build?
9698     ImplicitValueInitExpr VIE(Field->getType());
9699     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
9700 
9701     LValue Subobject = This;
9702     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
9703       return false;
9704 
9705     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9706     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9707                                   isa<CXXDefaultInitExpr>(InitExpr));
9708 
9709     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
9710   }
9711 
9712   if (!Result.hasValue())
9713     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
9714                      std::distance(RD->field_begin(), RD->field_end()));
9715   unsigned ElementNo = 0;
9716   bool Success = true;
9717 
9718   // Initialize base classes.
9719   if (CXXRD && CXXRD->getNumBases()) {
9720     for (const auto &Base : CXXRD->bases()) {
9721       assert(ElementNo < E->getNumInits() && "missing init for base class");
9722       const Expr *Init = E->getInit(ElementNo);
9723 
9724       LValue Subobject = This;
9725       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
9726         return false;
9727 
9728       APValue &FieldVal = Result.getStructBase(ElementNo);
9729       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
9730         if (!Info.noteFailure())
9731           return false;
9732         Success = false;
9733       }
9734       ++ElementNo;
9735     }
9736 
9737     EvalObj.finishedConstructingBases();
9738   }
9739 
9740   // Initialize members.
9741   for (const auto *Field : RD->fields()) {
9742     // Anonymous bit-fields are not considered members of the class for
9743     // purposes of aggregate initialization.
9744     if (Field->isUnnamedBitfield())
9745       continue;
9746 
9747     LValue Subobject = This;
9748 
9749     bool HaveInit = ElementNo < E->getNumInits();
9750 
9751     // FIXME: Diagnostics here should point to the end of the initializer
9752     // list, not the start.
9753     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
9754                             Subobject, Field, &Layout))
9755       return false;
9756 
9757     // Perform an implicit value-initialization for members beyond the end of
9758     // the initializer list.
9759     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
9760     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
9761 
9762     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9763     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9764                                   isa<CXXDefaultInitExpr>(Init));
9765 
9766     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9767     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
9768         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
9769                                                        FieldVal, Field))) {
9770       if (!Info.noteFailure())
9771         return false;
9772       Success = false;
9773     }
9774   }
9775 
9776   EvalObj.finishedConstructingFields();
9777 
9778   return Success;
9779 }
9780 
9781 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
9782                                                 QualType T) {
9783   // Note that E's type is not necessarily the type of our class here; we might
9784   // be initializing an array element instead.
9785   const CXXConstructorDecl *FD = E->getConstructor();
9786   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
9787 
9788   bool ZeroInit = E->requiresZeroInitialization();
9789   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
9790     // If we've already performed zero-initialization, we're already done.
9791     if (Result.hasValue())
9792       return true;
9793 
9794     if (ZeroInit)
9795       return ZeroInitialization(E, T);
9796 
9797     return getDefaultInitValue(T, Result);
9798   }
9799 
9800   const FunctionDecl *Definition = nullptr;
9801   auto Body = FD->getBody(Definition);
9802 
9803   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9804     return false;
9805 
9806   // Avoid materializing a temporary for an elidable copy/move constructor.
9807   if (E->isElidable() && !ZeroInit)
9808     if (const MaterializeTemporaryExpr *ME
9809           = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
9810       return Visit(ME->getSubExpr());
9811 
9812   if (ZeroInit && !ZeroInitialization(E, T))
9813     return false;
9814 
9815   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
9816   return HandleConstructorCall(E, This, Args,
9817                                cast<CXXConstructorDecl>(Definition), Info,
9818                                Result);
9819 }
9820 
9821 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
9822     const CXXInheritedCtorInitExpr *E) {
9823   if (!Info.CurrentCall) {
9824     assert(Info.checkingPotentialConstantExpression());
9825     return false;
9826   }
9827 
9828   const CXXConstructorDecl *FD = E->getConstructor();
9829   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
9830     return false;
9831 
9832   const FunctionDecl *Definition = nullptr;
9833   auto Body = FD->getBody(Definition);
9834 
9835   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9836     return false;
9837 
9838   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
9839                                cast<CXXConstructorDecl>(Definition), Info,
9840                                Result);
9841 }
9842 
9843 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
9844     const CXXStdInitializerListExpr *E) {
9845   const ConstantArrayType *ArrayType =
9846       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
9847 
9848   LValue Array;
9849   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
9850     return false;
9851 
9852   // Get a pointer to the first element of the array.
9853   Array.addArray(Info, E, ArrayType);
9854 
9855   auto InvalidType = [&] {
9856     Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
9857       << E->getType();
9858     return false;
9859   };
9860 
9861   // FIXME: Perform the checks on the field types in SemaInit.
9862   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
9863   RecordDecl::field_iterator Field = Record->field_begin();
9864   if (Field == Record->field_end())
9865     return InvalidType();
9866 
9867   // Start pointer.
9868   if (!Field->getType()->isPointerType() ||
9869       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
9870                             ArrayType->getElementType()))
9871     return InvalidType();
9872 
9873   // FIXME: What if the initializer_list type has base classes, etc?
9874   Result = APValue(APValue::UninitStruct(), 0, 2);
9875   Array.moveInto(Result.getStructField(0));
9876 
9877   if (++Field == Record->field_end())
9878     return InvalidType();
9879 
9880   if (Field->getType()->isPointerType() &&
9881       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
9882                            ArrayType->getElementType())) {
9883     // End pointer.
9884     if (!HandleLValueArrayAdjustment(Info, E, Array,
9885                                      ArrayType->getElementType(),
9886                                      ArrayType->getSize().getZExtValue()))
9887       return false;
9888     Array.moveInto(Result.getStructField(1));
9889   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
9890     // Length.
9891     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
9892   else
9893     return InvalidType();
9894 
9895   if (++Field != Record->field_end())
9896     return InvalidType();
9897 
9898   return true;
9899 }
9900 
9901 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
9902   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
9903   if (ClosureClass->isInvalidDecl())
9904     return false;
9905 
9906   const size_t NumFields =
9907       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
9908 
9909   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
9910                                             E->capture_init_end()) &&
9911          "The number of lambda capture initializers should equal the number of "
9912          "fields within the closure type");
9913 
9914   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
9915   // Iterate through all the lambda's closure object's fields and initialize
9916   // them.
9917   auto *CaptureInitIt = E->capture_init_begin();
9918   const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
9919   bool Success = true;
9920   for (const auto *Field : ClosureClass->fields()) {
9921     assert(CaptureInitIt != E->capture_init_end());
9922     // Get the initializer for this field
9923     Expr *const CurFieldInit = *CaptureInitIt++;
9924 
9925     // If there is no initializer, either this is a VLA or an error has
9926     // occurred.
9927     if (!CurFieldInit)
9928       return Error(E);
9929 
9930     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9931     if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
9932       if (!Info.keepEvaluatingAfterFailure())
9933         return false;
9934       Success = false;
9935     }
9936     ++CaptureIt;
9937   }
9938   return Success;
9939 }
9940 
9941 static bool EvaluateRecord(const Expr *E, const LValue &This,
9942                            APValue &Result, EvalInfo &Info) {
9943   assert(E->isRValue() && E->getType()->isRecordType() &&
9944          "can't evaluate expression as a record rvalue");
9945   return RecordExprEvaluator(Info, This, Result).Visit(E);
9946 }
9947 
9948 //===----------------------------------------------------------------------===//
9949 // Temporary Evaluation
9950 //
9951 // Temporaries are represented in the AST as rvalues, but generally behave like
9952 // lvalues. The full-object of which the temporary is a subobject is implicitly
9953 // materialized so that a reference can bind to it.
9954 //===----------------------------------------------------------------------===//
9955 namespace {
9956 class TemporaryExprEvaluator
9957   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
9958 public:
9959   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
9960     LValueExprEvaluatorBaseTy(Info, Result, false) {}
9961 
9962   /// Visit an expression which constructs the value of this temporary.
9963   bool VisitConstructExpr(const Expr *E) {
9964     APValue &Value = Info.CurrentCall->createTemporary(
9965         E, E->getType(), ScopeKind::FullExpression, Result);
9966     return EvaluateInPlace(Value, Info, Result, E);
9967   }
9968 
9969   bool VisitCastExpr(const CastExpr *E) {
9970     switch (E->getCastKind()) {
9971     default:
9972       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
9973 
9974     case CK_ConstructorConversion:
9975       return VisitConstructExpr(E->getSubExpr());
9976     }
9977   }
9978   bool VisitInitListExpr(const InitListExpr *E) {
9979     return VisitConstructExpr(E);
9980   }
9981   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9982     return VisitConstructExpr(E);
9983   }
9984   bool VisitCallExpr(const CallExpr *E) {
9985     return VisitConstructExpr(E);
9986   }
9987   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
9988     return VisitConstructExpr(E);
9989   }
9990   bool VisitLambdaExpr(const LambdaExpr *E) {
9991     return VisitConstructExpr(E);
9992   }
9993 };
9994 } // end anonymous namespace
9995 
9996 /// Evaluate an expression of record type as a temporary.
9997 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
9998   assert(E->isRValue() && E->getType()->isRecordType());
9999   return TemporaryExprEvaluator(Info, Result).Visit(E);
10000 }
10001 
10002 //===----------------------------------------------------------------------===//
10003 // Vector Evaluation
10004 //===----------------------------------------------------------------------===//
10005 
10006 namespace {
10007   class VectorExprEvaluator
10008   : public ExprEvaluatorBase<VectorExprEvaluator> {
10009     APValue &Result;
10010   public:
10011 
10012     VectorExprEvaluator(EvalInfo &info, APValue &Result)
10013       : ExprEvaluatorBaseTy(info), Result(Result) {}
10014 
10015     bool Success(ArrayRef<APValue> V, const Expr *E) {
10016       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
10017       // FIXME: remove this APValue copy.
10018       Result = APValue(V.data(), V.size());
10019       return true;
10020     }
10021     bool Success(const APValue &V, const Expr *E) {
10022       assert(V.isVector());
10023       Result = V;
10024       return true;
10025     }
10026     bool ZeroInitialization(const Expr *E);
10027 
10028     bool VisitUnaryReal(const UnaryOperator *E)
10029       { return Visit(E->getSubExpr()); }
10030     bool VisitCastExpr(const CastExpr* E);
10031     bool VisitInitListExpr(const InitListExpr *E);
10032     bool VisitUnaryImag(const UnaryOperator *E);
10033     bool VisitBinaryOperator(const BinaryOperator *E);
10034     // FIXME: Missing: unary -, unary ~, conditional operator (for GNU
10035     //                 conditional select), shufflevector, ExtVectorElementExpr
10036   };
10037 } // end anonymous namespace
10038 
10039 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
10040   assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
10041   return VectorExprEvaluator(Info, Result).Visit(E);
10042 }
10043 
10044 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
10045   const VectorType *VTy = E->getType()->castAs<VectorType>();
10046   unsigned NElts = VTy->getNumElements();
10047 
10048   const Expr *SE = E->getSubExpr();
10049   QualType SETy = SE->getType();
10050 
10051   switch (E->getCastKind()) {
10052   case CK_VectorSplat: {
10053     APValue Val = APValue();
10054     if (SETy->isIntegerType()) {
10055       APSInt IntResult;
10056       if (!EvaluateInteger(SE, IntResult, Info))
10057         return false;
10058       Val = APValue(std::move(IntResult));
10059     } else if (SETy->isRealFloatingType()) {
10060       APFloat FloatResult(0.0);
10061       if (!EvaluateFloat(SE, FloatResult, Info))
10062         return false;
10063       Val = APValue(std::move(FloatResult));
10064     } else {
10065       return Error(E);
10066     }
10067 
10068     // Splat and create vector APValue.
10069     SmallVector<APValue, 4> Elts(NElts, Val);
10070     return Success(Elts, E);
10071   }
10072   case CK_BitCast: {
10073     // Evaluate the operand into an APInt we can extract from.
10074     llvm::APInt SValInt;
10075     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
10076       return false;
10077     // Extract the elements
10078     QualType EltTy = VTy->getElementType();
10079     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
10080     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
10081     SmallVector<APValue, 4> Elts;
10082     if (EltTy->isRealFloatingType()) {
10083       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
10084       unsigned FloatEltSize = EltSize;
10085       if (&Sem == &APFloat::x87DoubleExtended())
10086         FloatEltSize = 80;
10087       for (unsigned i = 0; i < NElts; i++) {
10088         llvm::APInt Elt;
10089         if (BigEndian)
10090           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
10091         else
10092           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
10093         Elts.push_back(APValue(APFloat(Sem, Elt)));
10094       }
10095     } else if (EltTy->isIntegerType()) {
10096       for (unsigned i = 0; i < NElts; i++) {
10097         llvm::APInt Elt;
10098         if (BigEndian)
10099           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
10100         else
10101           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
10102         Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
10103       }
10104     } else {
10105       return Error(E);
10106     }
10107     return Success(Elts, E);
10108   }
10109   default:
10110     return ExprEvaluatorBaseTy::VisitCastExpr(E);
10111   }
10112 }
10113 
10114 bool
10115 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10116   const VectorType *VT = E->getType()->castAs<VectorType>();
10117   unsigned NumInits = E->getNumInits();
10118   unsigned NumElements = VT->getNumElements();
10119 
10120   QualType EltTy = VT->getElementType();
10121   SmallVector<APValue, 4> Elements;
10122 
10123   // The number of initializers can be less than the number of
10124   // vector elements. For OpenCL, this can be due to nested vector
10125   // initialization. For GCC compatibility, missing trailing elements
10126   // should be initialized with zeroes.
10127   unsigned CountInits = 0, CountElts = 0;
10128   while (CountElts < NumElements) {
10129     // Handle nested vector initialization.
10130     if (CountInits < NumInits
10131         && E->getInit(CountInits)->getType()->isVectorType()) {
10132       APValue v;
10133       if (!EvaluateVector(E->getInit(CountInits), v, Info))
10134         return Error(E);
10135       unsigned vlen = v.getVectorLength();
10136       for (unsigned j = 0; j < vlen; j++)
10137         Elements.push_back(v.getVectorElt(j));
10138       CountElts += vlen;
10139     } else if (EltTy->isIntegerType()) {
10140       llvm::APSInt sInt(32);
10141       if (CountInits < NumInits) {
10142         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
10143           return false;
10144       } else // trailing integer zero.
10145         sInt = Info.Ctx.MakeIntValue(0, EltTy);
10146       Elements.push_back(APValue(sInt));
10147       CountElts++;
10148     } else {
10149       llvm::APFloat f(0.0);
10150       if (CountInits < NumInits) {
10151         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
10152           return false;
10153       } else // trailing float zero.
10154         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
10155       Elements.push_back(APValue(f));
10156       CountElts++;
10157     }
10158     CountInits++;
10159   }
10160   return Success(Elements, E);
10161 }
10162 
10163 bool
10164 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
10165   const auto *VT = E->getType()->castAs<VectorType>();
10166   QualType EltTy = VT->getElementType();
10167   APValue ZeroElement;
10168   if (EltTy->isIntegerType())
10169     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
10170   else
10171     ZeroElement =
10172         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
10173 
10174   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
10175   return Success(Elements, E);
10176 }
10177 
10178 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
10179   VisitIgnoredValue(E->getSubExpr());
10180   return ZeroInitialization(E);
10181 }
10182 
10183 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10184   BinaryOperatorKind Op = E->getOpcode();
10185   assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
10186          "Operation not supported on vector types");
10187 
10188   if (Op == BO_Comma)
10189     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10190 
10191   Expr *LHS = E->getLHS();
10192   Expr *RHS = E->getRHS();
10193 
10194   assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
10195          "Must both be vector types");
10196   // Checking JUST the types are the same would be fine, except shifts don't
10197   // need to have their types be the same (since you always shift by an int).
10198   assert(LHS->getType()->getAs<VectorType>()->getNumElements() ==
10199              E->getType()->getAs<VectorType>()->getNumElements() &&
10200          RHS->getType()->getAs<VectorType>()->getNumElements() ==
10201              E->getType()->getAs<VectorType>()->getNumElements() &&
10202          "All operands must be the same size.");
10203 
10204   APValue LHSValue;
10205   APValue RHSValue;
10206   bool LHSOK = Evaluate(LHSValue, Info, LHS);
10207   if (!LHSOK && !Info.noteFailure())
10208     return false;
10209   if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
10210     return false;
10211 
10212   if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
10213     return false;
10214 
10215   return Success(LHSValue, E);
10216 }
10217 
10218 //===----------------------------------------------------------------------===//
10219 // Array Evaluation
10220 //===----------------------------------------------------------------------===//
10221 
10222 namespace {
10223   class ArrayExprEvaluator
10224   : public ExprEvaluatorBase<ArrayExprEvaluator> {
10225     const LValue &This;
10226     APValue &Result;
10227   public:
10228 
10229     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
10230       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
10231 
10232     bool Success(const APValue &V, const Expr *E) {
10233       assert(V.isArray() && "expected array");
10234       Result = V;
10235       return true;
10236     }
10237 
10238     bool ZeroInitialization(const Expr *E) {
10239       const ConstantArrayType *CAT =
10240           Info.Ctx.getAsConstantArrayType(E->getType());
10241       if (!CAT) {
10242         if (E->getType()->isIncompleteArrayType()) {
10243           // We can be asked to zero-initialize a flexible array member; this
10244           // is represented as an ImplicitValueInitExpr of incomplete array
10245           // type. In this case, the array has zero elements.
10246           Result = APValue(APValue::UninitArray(), 0, 0);
10247           return true;
10248         }
10249         // FIXME: We could handle VLAs here.
10250         return Error(E);
10251       }
10252 
10253       Result = APValue(APValue::UninitArray(), 0,
10254                        CAT->getSize().getZExtValue());
10255       if (!Result.hasArrayFiller()) return true;
10256 
10257       // Zero-initialize all elements.
10258       LValue Subobject = This;
10259       Subobject.addArray(Info, E, CAT);
10260       ImplicitValueInitExpr VIE(CAT->getElementType());
10261       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
10262     }
10263 
10264     bool VisitCallExpr(const CallExpr *E) {
10265       return handleCallExpr(E, Result, &This);
10266     }
10267     bool VisitInitListExpr(const InitListExpr *E,
10268                            QualType AllocType = QualType());
10269     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
10270     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
10271     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
10272                                const LValue &Subobject,
10273                                APValue *Value, QualType Type);
10274     bool VisitStringLiteral(const StringLiteral *E,
10275                             QualType AllocType = QualType()) {
10276       expandStringLiteral(Info, E, Result, AllocType);
10277       return true;
10278     }
10279   };
10280 } // end anonymous namespace
10281 
10282 static bool EvaluateArray(const Expr *E, const LValue &This,
10283                           APValue &Result, EvalInfo &Info) {
10284   assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
10285   return ArrayExprEvaluator(Info, This, Result).Visit(E);
10286 }
10287 
10288 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10289                                      APValue &Result, const InitListExpr *ILE,
10290                                      QualType AllocType) {
10291   assert(ILE->isRValue() && ILE->getType()->isArrayType() &&
10292          "not an array rvalue");
10293   return ArrayExprEvaluator(Info, This, Result)
10294       .VisitInitListExpr(ILE, AllocType);
10295 }
10296 
10297 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10298                                           APValue &Result,
10299                                           const CXXConstructExpr *CCE,
10300                                           QualType AllocType) {
10301   assert(CCE->isRValue() && CCE->getType()->isArrayType() &&
10302          "not an array rvalue");
10303   return ArrayExprEvaluator(Info, This, Result)
10304       .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
10305 }
10306 
10307 // Return true iff the given array filler may depend on the element index.
10308 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
10309   // For now, just allow non-class value-initialization and initialization
10310   // lists comprised of them.
10311   if (isa<ImplicitValueInitExpr>(FillerExpr))
10312     return false;
10313   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
10314     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
10315       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
10316         return true;
10317     }
10318     return false;
10319   }
10320   return true;
10321 }
10322 
10323 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
10324                                            QualType AllocType) {
10325   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
10326       AllocType.isNull() ? E->getType() : AllocType);
10327   if (!CAT)
10328     return Error(E);
10329 
10330   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
10331   // an appropriately-typed string literal enclosed in braces.
10332   if (E->isStringLiteralInit()) {
10333     auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens());
10334     // FIXME: Support ObjCEncodeExpr here once we support it in
10335     // ArrayExprEvaluator generally.
10336     if (!SL)
10337       return Error(E);
10338     return VisitStringLiteral(SL, AllocType);
10339   }
10340 
10341   bool Success = true;
10342 
10343   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
10344          "zero-initialized array shouldn't have any initialized elts");
10345   APValue Filler;
10346   if (Result.isArray() && Result.hasArrayFiller())
10347     Filler = Result.getArrayFiller();
10348 
10349   unsigned NumEltsToInit = E->getNumInits();
10350   unsigned NumElts = CAT->getSize().getZExtValue();
10351   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
10352 
10353   // If the initializer might depend on the array index, run it for each
10354   // array element.
10355   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
10356     NumEltsToInit = NumElts;
10357 
10358   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
10359                           << NumEltsToInit << ".\n");
10360 
10361   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
10362 
10363   // If the array was previously zero-initialized, preserve the
10364   // zero-initialized values.
10365   if (Filler.hasValue()) {
10366     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
10367       Result.getArrayInitializedElt(I) = Filler;
10368     if (Result.hasArrayFiller())
10369       Result.getArrayFiller() = Filler;
10370   }
10371 
10372   LValue Subobject = This;
10373   Subobject.addArray(Info, E, CAT);
10374   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
10375     const Expr *Init =
10376         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
10377     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10378                          Info, Subobject, Init) ||
10379         !HandleLValueArrayAdjustment(Info, Init, Subobject,
10380                                      CAT->getElementType(), 1)) {
10381       if (!Info.noteFailure())
10382         return false;
10383       Success = false;
10384     }
10385   }
10386 
10387   if (!Result.hasArrayFiller())
10388     return Success;
10389 
10390   // If we get here, we have a trivial filler, which we can just evaluate
10391   // once and splat over the rest of the array elements.
10392   assert(FillerExpr && "no array filler for incomplete init list");
10393   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
10394                          FillerExpr) && Success;
10395 }
10396 
10397 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
10398   LValue CommonLV;
10399   if (E->getCommonExpr() &&
10400       !Evaluate(Info.CurrentCall->createTemporary(
10401                     E->getCommonExpr(),
10402                     getStorageType(Info.Ctx, E->getCommonExpr()),
10403                     ScopeKind::FullExpression, CommonLV),
10404                 Info, E->getCommonExpr()->getSourceExpr()))
10405     return false;
10406 
10407   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
10408 
10409   uint64_t Elements = CAT->getSize().getZExtValue();
10410   Result = APValue(APValue::UninitArray(), Elements, Elements);
10411 
10412   LValue Subobject = This;
10413   Subobject.addArray(Info, E, CAT);
10414 
10415   bool Success = true;
10416   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
10417     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10418                          Info, Subobject, E->getSubExpr()) ||
10419         !HandleLValueArrayAdjustment(Info, E, Subobject,
10420                                      CAT->getElementType(), 1)) {
10421       if (!Info.noteFailure())
10422         return false;
10423       Success = false;
10424     }
10425   }
10426 
10427   return Success;
10428 }
10429 
10430 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
10431   return VisitCXXConstructExpr(E, This, &Result, E->getType());
10432 }
10433 
10434 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10435                                                const LValue &Subobject,
10436                                                APValue *Value,
10437                                                QualType Type) {
10438   bool HadZeroInit = Value->hasValue();
10439 
10440   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
10441     unsigned N = CAT->getSize().getZExtValue();
10442 
10443     // Preserve the array filler if we had prior zero-initialization.
10444     APValue Filler =
10445       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
10446                                              : APValue();
10447 
10448     *Value = APValue(APValue::UninitArray(), N, N);
10449 
10450     if (HadZeroInit)
10451       for (unsigned I = 0; I != N; ++I)
10452         Value->getArrayInitializedElt(I) = Filler;
10453 
10454     // Initialize the elements.
10455     LValue ArrayElt = Subobject;
10456     ArrayElt.addArray(Info, E, CAT);
10457     for (unsigned I = 0; I != N; ++I)
10458       if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
10459                                  CAT->getElementType()) ||
10460           !HandleLValueArrayAdjustment(Info, E, ArrayElt,
10461                                        CAT->getElementType(), 1))
10462         return false;
10463 
10464     return true;
10465   }
10466 
10467   if (!Type->isRecordType())
10468     return Error(E);
10469 
10470   return RecordExprEvaluator(Info, Subobject, *Value)
10471              .VisitCXXConstructExpr(E, Type);
10472 }
10473 
10474 //===----------------------------------------------------------------------===//
10475 // Integer Evaluation
10476 //
10477 // As a GNU extension, we support casting pointers to sufficiently-wide integer
10478 // types and back in constant folding. Integer values are thus represented
10479 // either as an integer-valued APValue, or as an lvalue-valued APValue.
10480 //===----------------------------------------------------------------------===//
10481 
10482 namespace {
10483 class IntExprEvaluator
10484         : public ExprEvaluatorBase<IntExprEvaluator> {
10485   APValue &Result;
10486 public:
10487   IntExprEvaluator(EvalInfo &info, APValue &result)
10488       : ExprEvaluatorBaseTy(info), Result(result) {}
10489 
10490   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
10491     assert(E->getType()->isIntegralOrEnumerationType() &&
10492            "Invalid evaluation result.");
10493     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
10494            "Invalid evaluation result.");
10495     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10496            "Invalid evaluation result.");
10497     Result = APValue(SI);
10498     return true;
10499   }
10500   bool Success(const llvm::APSInt &SI, const Expr *E) {
10501     return Success(SI, E, Result);
10502   }
10503 
10504   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
10505     assert(E->getType()->isIntegralOrEnumerationType() &&
10506            "Invalid evaluation result.");
10507     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10508            "Invalid evaluation result.");
10509     Result = APValue(APSInt(I));
10510     Result.getInt().setIsUnsigned(
10511                             E->getType()->isUnsignedIntegerOrEnumerationType());
10512     return true;
10513   }
10514   bool Success(const llvm::APInt &I, const Expr *E) {
10515     return Success(I, E, Result);
10516   }
10517 
10518   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
10519     assert(E->getType()->isIntegralOrEnumerationType() &&
10520            "Invalid evaluation result.");
10521     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
10522     return true;
10523   }
10524   bool Success(uint64_t Value, const Expr *E) {
10525     return Success(Value, E, Result);
10526   }
10527 
10528   bool Success(CharUnits Size, const Expr *E) {
10529     return Success(Size.getQuantity(), E);
10530   }
10531 
10532   bool Success(const APValue &V, const Expr *E) {
10533     if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
10534       Result = V;
10535       return true;
10536     }
10537     return Success(V.getInt(), E);
10538   }
10539 
10540   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
10541 
10542   //===--------------------------------------------------------------------===//
10543   //                            Visitor Methods
10544   //===--------------------------------------------------------------------===//
10545 
10546   bool VisitIntegerLiteral(const IntegerLiteral *E) {
10547     return Success(E->getValue(), E);
10548   }
10549   bool VisitCharacterLiteral(const CharacterLiteral *E) {
10550     return Success(E->getValue(), E);
10551   }
10552 
10553   bool CheckReferencedDecl(const Expr *E, const Decl *D);
10554   bool VisitDeclRefExpr(const DeclRefExpr *E) {
10555     if (CheckReferencedDecl(E, E->getDecl()))
10556       return true;
10557 
10558     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
10559   }
10560   bool VisitMemberExpr(const MemberExpr *E) {
10561     if (CheckReferencedDecl(E, E->getMemberDecl())) {
10562       VisitIgnoredBaseExpression(E->getBase());
10563       return true;
10564     }
10565 
10566     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
10567   }
10568 
10569   bool VisitCallExpr(const CallExpr *E);
10570   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
10571   bool VisitBinaryOperator(const BinaryOperator *E);
10572   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
10573   bool VisitUnaryOperator(const UnaryOperator *E);
10574 
10575   bool VisitCastExpr(const CastExpr* E);
10576   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
10577 
10578   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
10579     return Success(E->getValue(), E);
10580   }
10581 
10582   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
10583     return Success(E->getValue(), E);
10584   }
10585 
10586   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
10587     if (Info.ArrayInitIndex == uint64_t(-1)) {
10588       // We were asked to evaluate this subexpression independent of the
10589       // enclosing ArrayInitLoopExpr. We can't do that.
10590       Info.FFDiag(E);
10591       return false;
10592     }
10593     return Success(Info.ArrayInitIndex, E);
10594   }
10595 
10596   // Note, GNU defines __null as an integer, not a pointer.
10597   bool VisitGNUNullExpr(const GNUNullExpr *E) {
10598     return ZeroInitialization(E);
10599   }
10600 
10601   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
10602     return Success(E->getValue(), E);
10603   }
10604 
10605   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
10606     return Success(E->getValue(), E);
10607   }
10608 
10609   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
10610     return Success(E->getValue(), E);
10611   }
10612 
10613   bool VisitUnaryReal(const UnaryOperator *E);
10614   bool VisitUnaryImag(const UnaryOperator *E);
10615 
10616   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
10617   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
10618   bool VisitSourceLocExpr(const SourceLocExpr *E);
10619   bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
10620   bool VisitRequiresExpr(const RequiresExpr *E);
10621   // FIXME: Missing: array subscript of vector, member of vector
10622 };
10623 
10624 class FixedPointExprEvaluator
10625     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
10626   APValue &Result;
10627 
10628  public:
10629   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
10630       : ExprEvaluatorBaseTy(info), Result(result) {}
10631 
10632   bool Success(const llvm::APInt &I, const Expr *E) {
10633     return Success(
10634         APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10635   }
10636 
10637   bool Success(uint64_t Value, const Expr *E) {
10638     return Success(
10639         APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10640   }
10641 
10642   bool Success(const APValue &V, const Expr *E) {
10643     return Success(V.getFixedPoint(), E);
10644   }
10645 
10646   bool Success(const APFixedPoint &V, const Expr *E) {
10647     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
10648     assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10649            "Invalid evaluation result.");
10650     Result = APValue(V);
10651     return true;
10652   }
10653 
10654   //===--------------------------------------------------------------------===//
10655   //                            Visitor Methods
10656   //===--------------------------------------------------------------------===//
10657 
10658   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
10659     return Success(E->getValue(), E);
10660   }
10661 
10662   bool VisitCastExpr(const CastExpr *E);
10663   bool VisitUnaryOperator(const UnaryOperator *E);
10664   bool VisitBinaryOperator(const BinaryOperator *E);
10665 };
10666 } // end anonymous namespace
10667 
10668 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
10669 /// produce either the integer value or a pointer.
10670 ///
10671 /// GCC has a heinous extension which folds casts between pointer types and
10672 /// pointer-sized integral types. We support this by allowing the evaluation of
10673 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
10674 /// Some simple arithmetic on such values is supported (they are treated much
10675 /// like char*).
10676 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
10677                                     EvalInfo &Info) {
10678   assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
10679   return IntExprEvaluator(Info, Result).Visit(E);
10680 }
10681 
10682 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
10683   APValue Val;
10684   if (!EvaluateIntegerOrLValue(E, Val, Info))
10685     return false;
10686   if (!Val.isInt()) {
10687     // FIXME: It would be better to produce the diagnostic for casting
10688     //        a pointer to an integer.
10689     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10690     return false;
10691   }
10692   Result = Val.getInt();
10693   return true;
10694 }
10695 
10696 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
10697   APValue Evaluated = E->EvaluateInContext(
10698       Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
10699   return Success(Evaluated, E);
10700 }
10701 
10702 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
10703                                EvalInfo &Info) {
10704   if (E->getType()->isFixedPointType()) {
10705     APValue Val;
10706     if (!FixedPointExprEvaluator(Info, Val).Visit(E))
10707       return false;
10708     if (!Val.isFixedPoint())
10709       return false;
10710 
10711     Result = Val.getFixedPoint();
10712     return true;
10713   }
10714   return false;
10715 }
10716 
10717 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
10718                                         EvalInfo &Info) {
10719   if (E->getType()->isIntegerType()) {
10720     auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
10721     APSInt Val;
10722     if (!EvaluateInteger(E, Val, Info))
10723       return false;
10724     Result = APFixedPoint(Val, FXSema);
10725     return true;
10726   } else if (E->getType()->isFixedPointType()) {
10727     return EvaluateFixedPoint(E, Result, Info);
10728   }
10729   return false;
10730 }
10731 
10732 /// Check whether the given declaration can be directly converted to an integral
10733 /// rvalue. If not, no diagnostic is produced; there are other things we can
10734 /// try.
10735 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
10736   // Enums are integer constant exprs.
10737   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
10738     // Check for signedness/width mismatches between E type and ECD value.
10739     bool SameSign = (ECD->getInitVal().isSigned()
10740                      == E->getType()->isSignedIntegerOrEnumerationType());
10741     bool SameWidth = (ECD->getInitVal().getBitWidth()
10742                       == Info.Ctx.getIntWidth(E->getType()));
10743     if (SameSign && SameWidth)
10744       return Success(ECD->getInitVal(), E);
10745     else {
10746       // Get rid of mismatch (otherwise Success assertions will fail)
10747       // by computing a new value matching the type of E.
10748       llvm::APSInt Val = ECD->getInitVal();
10749       if (!SameSign)
10750         Val.setIsSigned(!ECD->getInitVal().isSigned());
10751       if (!SameWidth)
10752         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
10753       return Success(Val, E);
10754     }
10755   }
10756   return false;
10757 }
10758 
10759 /// Values returned by __builtin_classify_type, chosen to match the values
10760 /// produced by GCC's builtin.
10761 enum class GCCTypeClass {
10762   None = -1,
10763   Void = 0,
10764   Integer = 1,
10765   // GCC reserves 2 for character types, but instead classifies them as
10766   // integers.
10767   Enum = 3,
10768   Bool = 4,
10769   Pointer = 5,
10770   // GCC reserves 6 for references, but appears to never use it (because
10771   // expressions never have reference type, presumably).
10772   PointerToDataMember = 7,
10773   RealFloat = 8,
10774   Complex = 9,
10775   // GCC reserves 10 for functions, but does not use it since GCC version 6 due
10776   // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
10777   // GCC claims to reserve 11 for pointers to member functions, but *actually*
10778   // uses 12 for that purpose, same as for a class or struct. Maybe it
10779   // internally implements a pointer to member as a struct?  Who knows.
10780   PointerToMemberFunction = 12, // Not a bug, see above.
10781   ClassOrStruct = 12,
10782   Union = 13,
10783   // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
10784   // decay to pointer. (Prior to version 6 it was only used in C++ mode).
10785   // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
10786   // literals.
10787 };
10788 
10789 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
10790 /// as GCC.
10791 static GCCTypeClass
10792 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
10793   assert(!T->isDependentType() && "unexpected dependent type");
10794 
10795   QualType CanTy = T.getCanonicalType();
10796   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
10797 
10798   switch (CanTy->getTypeClass()) {
10799 #define TYPE(ID, BASE)
10800 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
10801 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
10802 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
10803 #include "clang/AST/TypeNodes.inc"
10804   case Type::Auto:
10805   case Type::DeducedTemplateSpecialization:
10806       llvm_unreachable("unexpected non-canonical or dependent type");
10807 
10808   case Type::Builtin:
10809     switch (BT->getKind()) {
10810 #define BUILTIN_TYPE(ID, SINGLETON_ID)
10811 #define SIGNED_TYPE(ID, SINGLETON_ID) \
10812     case BuiltinType::ID: return GCCTypeClass::Integer;
10813 #define FLOATING_TYPE(ID, SINGLETON_ID) \
10814     case BuiltinType::ID: return GCCTypeClass::RealFloat;
10815 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
10816     case BuiltinType::ID: break;
10817 #include "clang/AST/BuiltinTypes.def"
10818     case BuiltinType::Void:
10819       return GCCTypeClass::Void;
10820 
10821     case BuiltinType::Bool:
10822       return GCCTypeClass::Bool;
10823 
10824     case BuiltinType::Char_U:
10825     case BuiltinType::UChar:
10826     case BuiltinType::WChar_U:
10827     case BuiltinType::Char8:
10828     case BuiltinType::Char16:
10829     case BuiltinType::Char32:
10830     case BuiltinType::UShort:
10831     case BuiltinType::UInt:
10832     case BuiltinType::ULong:
10833     case BuiltinType::ULongLong:
10834     case BuiltinType::UInt128:
10835       return GCCTypeClass::Integer;
10836 
10837     case BuiltinType::UShortAccum:
10838     case BuiltinType::UAccum:
10839     case BuiltinType::ULongAccum:
10840     case BuiltinType::UShortFract:
10841     case BuiltinType::UFract:
10842     case BuiltinType::ULongFract:
10843     case BuiltinType::SatUShortAccum:
10844     case BuiltinType::SatUAccum:
10845     case BuiltinType::SatULongAccum:
10846     case BuiltinType::SatUShortFract:
10847     case BuiltinType::SatUFract:
10848     case BuiltinType::SatULongFract:
10849       return GCCTypeClass::None;
10850 
10851     case BuiltinType::NullPtr:
10852 
10853     case BuiltinType::ObjCId:
10854     case BuiltinType::ObjCClass:
10855     case BuiltinType::ObjCSel:
10856 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
10857     case BuiltinType::Id:
10858 #include "clang/Basic/OpenCLImageTypes.def"
10859 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
10860     case BuiltinType::Id:
10861 #include "clang/Basic/OpenCLExtensionTypes.def"
10862     case BuiltinType::OCLSampler:
10863     case BuiltinType::OCLEvent:
10864     case BuiltinType::OCLClkEvent:
10865     case BuiltinType::OCLQueue:
10866     case BuiltinType::OCLReserveID:
10867 #define SVE_TYPE(Name, Id, SingletonId) \
10868     case BuiltinType::Id:
10869 #include "clang/Basic/AArch64SVEACLETypes.def"
10870       return GCCTypeClass::None;
10871 
10872     case BuiltinType::Dependent:
10873       llvm_unreachable("unexpected dependent type");
10874     };
10875     llvm_unreachable("unexpected placeholder type");
10876 
10877   case Type::Enum:
10878     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
10879 
10880   case Type::Pointer:
10881   case Type::ConstantArray:
10882   case Type::VariableArray:
10883   case Type::IncompleteArray:
10884   case Type::FunctionNoProto:
10885   case Type::FunctionProto:
10886     return GCCTypeClass::Pointer;
10887 
10888   case Type::MemberPointer:
10889     return CanTy->isMemberDataPointerType()
10890                ? GCCTypeClass::PointerToDataMember
10891                : GCCTypeClass::PointerToMemberFunction;
10892 
10893   case Type::Complex:
10894     return GCCTypeClass::Complex;
10895 
10896   case Type::Record:
10897     return CanTy->isUnionType() ? GCCTypeClass::Union
10898                                 : GCCTypeClass::ClassOrStruct;
10899 
10900   case Type::Atomic:
10901     // GCC classifies _Atomic T the same as T.
10902     return EvaluateBuiltinClassifyType(
10903         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
10904 
10905   case Type::BlockPointer:
10906   case Type::Vector:
10907   case Type::ExtVector:
10908   case Type::ConstantMatrix:
10909   case Type::ObjCObject:
10910   case Type::ObjCInterface:
10911   case Type::ObjCObjectPointer:
10912   case Type::Pipe:
10913   case Type::ExtInt:
10914     // GCC classifies vectors as None. We follow its lead and classify all
10915     // other types that don't fit into the regular classification the same way.
10916     return GCCTypeClass::None;
10917 
10918   case Type::LValueReference:
10919   case Type::RValueReference:
10920     llvm_unreachable("invalid type for expression");
10921   }
10922 
10923   llvm_unreachable("unexpected type class");
10924 }
10925 
10926 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
10927 /// as GCC.
10928 static GCCTypeClass
10929 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
10930   // If no argument was supplied, default to None. This isn't
10931   // ideal, however it is what gcc does.
10932   if (E->getNumArgs() == 0)
10933     return GCCTypeClass::None;
10934 
10935   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
10936   // being an ICE, but still folds it to a constant using the type of the first
10937   // argument.
10938   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
10939 }
10940 
10941 /// EvaluateBuiltinConstantPForLValue - Determine the result of
10942 /// __builtin_constant_p when applied to the given pointer.
10943 ///
10944 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
10945 /// or it points to the first character of a string literal.
10946 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
10947   APValue::LValueBase Base = LV.getLValueBase();
10948   if (Base.isNull()) {
10949     // A null base is acceptable.
10950     return true;
10951   } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
10952     if (!isa<StringLiteral>(E))
10953       return false;
10954     return LV.getLValueOffset().isZero();
10955   } else if (Base.is<TypeInfoLValue>()) {
10956     // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
10957     // evaluate to true.
10958     return true;
10959   } else {
10960     // Any other base is not constant enough for GCC.
10961     return false;
10962   }
10963 }
10964 
10965 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
10966 /// GCC as we can manage.
10967 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
10968   // This evaluation is not permitted to have side-effects, so evaluate it in
10969   // a speculative evaluation context.
10970   SpeculativeEvaluationRAII SpeculativeEval(Info);
10971 
10972   // Constant-folding is always enabled for the operand of __builtin_constant_p
10973   // (even when the enclosing evaluation context otherwise requires a strict
10974   // language-specific constant expression).
10975   FoldConstant Fold(Info, true);
10976 
10977   QualType ArgType = Arg->getType();
10978 
10979   // __builtin_constant_p always has one operand. The rules which gcc follows
10980   // are not precisely documented, but are as follows:
10981   //
10982   //  - If the operand is of integral, floating, complex or enumeration type,
10983   //    and can be folded to a known value of that type, it returns 1.
10984   //  - If the operand can be folded to a pointer to the first character
10985   //    of a string literal (or such a pointer cast to an integral type)
10986   //    or to a null pointer or an integer cast to a pointer, it returns 1.
10987   //
10988   // Otherwise, it returns 0.
10989   //
10990   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
10991   // its support for this did not work prior to GCC 9 and is not yet well
10992   // understood.
10993   if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
10994       ArgType->isAnyComplexType() || ArgType->isPointerType() ||
10995       ArgType->isNullPtrType()) {
10996     APValue V;
10997     if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
10998       Fold.keepDiagnostics();
10999       return false;
11000     }
11001 
11002     // For a pointer (possibly cast to integer), there are special rules.
11003     if (V.getKind() == APValue::LValue)
11004       return EvaluateBuiltinConstantPForLValue(V);
11005 
11006     // Otherwise, any constant value is good enough.
11007     return V.hasValue();
11008   }
11009 
11010   // Anything else isn't considered to be sufficiently constant.
11011   return false;
11012 }
11013 
11014 /// Retrieves the "underlying object type" of the given expression,
11015 /// as used by __builtin_object_size.
11016 static QualType getObjectType(APValue::LValueBase B) {
11017   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
11018     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
11019       return VD->getType();
11020   } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
11021     if (isa<CompoundLiteralExpr>(E))
11022       return E->getType();
11023   } else if (B.is<TypeInfoLValue>()) {
11024     return B.getTypeInfoType();
11025   } else if (B.is<DynamicAllocLValue>()) {
11026     return B.getDynamicAllocType();
11027   }
11028 
11029   return QualType();
11030 }
11031 
11032 /// A more selective version of E->IgnoreParenCasts for
11033 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
11034 /// to change the type of E.
11035 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
11036 ///
11037 /// Always returns an RValue with a pointer representation.
11038 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
11039   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
11040 
11041   auto *NoParens = E->IgnoreParens();
11042   auto *Cast = dyn_cast<CastExpr>(NoParens);
11043   if (Cast == nullptr)
11044     return NoParens;
11045 
11046   // We only conservatively allow a few kinds of casts, because this code is
11047   // inherently a simple solution that seeks to support the common case.
11048   auto CastKind = Cast->getCastKind();
11049   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
11050       CastKind != CK_AddressSpaceConversion)
11051     return NoParens;
11052 
11053   auto *SubExpr = Cast->getSubExpr();
11054   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
11055     return NoParens;
11056   return ignorePointerCastsAndParens(SubExpr);
11057 }
11058 
11059 /// Checks to see if the given LValue's Designator is at the end of the LValue's
11060 /// record layout. e.g.
11061 ///   struct { struct { int a, b; } fst, snd; } obj;
11062 ///   obj.fst   // no
11063 ///   obj.snd   // yes
11064 ///   obj.fst.a // no
11065 ///   obj.fst.b // no
11066 ///   obj.snd.a // no
11067 ///   obj.snd.b // yes
11068 ///
11069 /// Please note: this function is specialized for how __builtin_object_size
11070 /// views "objects".
11071 ///
11072 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
11073 /// correct result, it will always return true.
11074 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
11075   assert(!LVal.Designator.Invalid);
11076 
11077   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
11078     const RecordDecl *Parent = FD->getParent();
11079     Invalid = Parent->isInvalidDecl();
11080     if (Invalid || Parent->isUnion())
11081       return true;
11082     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
11083     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
11084   };
11085 
11086   auto &Base = LVal.getLValueBase();
11087   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
11088     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
11089       bool Invalid;
11090       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11091         return Invalid;
11092     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
11093       for (auto *FD : IFD->chain()) {
11094         bool Invalid;
11095         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
11096           return Invalid;
11097       }
11098     }
11099   }
11100 
11101   unsigned I = 0;
11102   QualType BaseType = getType(Base);
11103   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
11104     // If we don't know the array bound, conservatively assume we're looking at
11105     // the final array element.
11106     ++I;
11107     if (BaseType->isIncompleteArrayType())
11108       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
11109     else
11110       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
11111   }
11112 
11113   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
11114     const auto &Entry = LVal.Designator.Entries[I];
11115     if (BaseType->isArrayType()) {
11116       // Because __builtin_object_size treats arrays as objects, we can ignore
11117       // the index iff this is the last array in the Designator.
11118       if (I + 1 == E)
11119         return true;
11120       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
11121       uint64_t Index = Entry.getAsArrayIndex();
11122       if (Index + 1 != CAT->getSize())
11123         return false;
11124       BaseType = CAT->getElementType();
11125     } else if (BaseType->isAnyComplexType()) {
11126       const auto *CT = BaseType->castAs<ComplexType>();
11127       uint64_t Index = Entry.getAsArrayIndex();
11128       if (Index != 1)
11129         return false;
11130       BaseType = CT->getElementType();
11131     } else if (auto *FD = getAsField(Entry)) {
11132       bool Invalid;
11133       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11134         return Invalid;
11135       BaseType = FD->getType();
11136     } else {
11137       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
11138       return false;
11139     }
11140   }
11141   return true;
11142 }
11143 
11144 /// Tests to see if the LValue has a user-specified designator (that isn't
11145 /// necessarily valid). Note that this always returns 'true' if the LValue has
11146 /// an unsized array as its first designator entry, because there's currently no
11147 /// way to tell if the user typed *foo or foo[0].
11148 static bool refersToCompleteObject(const LValue &LVal) {
11149   if (LVal.Designator.Invalid)
11150     return false;
11151 
11152   if (!LVal.Designator.Entries.empty())
11153     return LVal.Designator.isMostDerivedAnUnsizedArray();
11154 
11155   if (!LVal.InvalidBase)
11156     return true;
11157 
11158   // If `E` is a MemberExpr, then the first part of the designator is hiding in
11159   // the LValueBase.
11160   const auto *E = LVal.Base.dyn_cast<const Expr *>();
11161   return !E || !isa<MemberExpr>(E);
11162 }
11163 
11164 /// Attempts to detect a user writing into a piece of memory that's impossible
11165 /// to figure out the size of by just using types.
11166 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
11167   const SubobjectDesignator &Designator = LVal.Designator;
11168   // Notes:
11169   // - Users can only write off of the end when we have an invalid base. Invalid
11170   //   bases imply we don't know where the memory came from.
11171   // - We used to be a bit more aggressive here; we'd only be conservative if
11172   //   the array at the end was flexible, or if it had 0 or 1 elements. This
11173   //   broke some common standard library extensions (PR30346), but was
11174   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
11175   //   with some sort of list. OTOH, it seems that GCC is always
11176   //   conservative with the last element in structs (if it's an array), so our
11177   //   current behavior is more compatible than an explicit list approach would
11178   //   be.
11179   return LVal.InvalidBase &&
11180          Designator.Entries.size() == Designator.MostDerivedPathLength &&
11181          Designator.MostDerivedIsArrayElement &&
11182          isDesignatorAtObjectEnd(Ctx, LVal);
11183 }
11184 
11185 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
11186 /// Fails if the conversion would cause loss of precision.
11187 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
11188                                             CharUnits &Result) {
11189   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
11190   if (Int.ugt(CharUnitsMax))
11191     return false;
11192   Result = CharUnits::fromQuantity(Int.getZExtValue());
11193   return true;
11194 }
11195 
11196 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
11197 /// determine how many bytes exist from the beginning of the object to either
11198 /// the end of the current subobject, or the end of the object itself, depending
11199 /// on what the LValue looks like + the value of Type.
11200 ///
11201 /// If this returns false, the value of Result is undefined.
11202 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
11203                                unsigned Type, const LValue &LVal,
11204                                CharUnits &EndOffset) {
11205   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
11206 
11207   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
11208     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
11209       return false;
11210     return HandleSizeof(Info, ExprLoc, Ty, Result);
11211   };
11212 
11213   // We want to evaluate the size of the entire object. This is a valid fallback
11214   // for when Type=1 and the designator is invalid, because we're asked for an
11215   // upper-bound.
11216   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
11217     // Type=3 wants a lower bound, so we can't fall back to this.
11218     if (Type == 3 && !DetermineForCompleteObject)
11219       return false;
11220 
11221     llvm::APInt APEndOffset;
11222     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11223         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11224       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11225 
11226     if (LVal.InvalidBase)
11227       return false;
11228 
11229     QualType BaseTy = getObjectType(LVal.getLValueBase());
11230     return CheckedHandleSizeof(BaseTy, EndOffset);
11231   }
11232 
11233   // We want to evaluate the size of a subobject.
11234   const SubobjectDesignator &Designator = LVal.Designator;
11235 
11236   // The following is a moderately common idiom in C:
11237   //
11238   // struct Foo { int a; char c[1]; };
11239   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
11240   // strcpy(&F->c[0], Bar);
11241   //
11242   // In order to not break too much legacy code, we need to support it.
11243   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
11244     // If we can resolve this to an alloc_size call, we can hand that back,
11245     // because we know for certain how many bytes there are to write to.
11246     llvm::APInt APEndOffset;
11247     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11248         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11249       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11250 
11251     // If we cannot determine the size of the initial allocation, then we can't
11252     // given an accurate upper-bound. However, we are still able to give
11253     // conservative lower-bounds for Type=3.
11254     if (Type == 1)
11255       return false;
11256   }
11257 
11258   CharUnits BytesPerElem;
11259   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
11260     return false;
11261 
11262   // According to the GCC documentation, we want the size of the subobject
11263   // denoted by the pointer. But that's not quite right -- what we actually
11264   // want is the size of the immediately-enclosing array, if there is one.
11265   int64_t ElemsRemaining;
11266   if (Designator.MostDerivedIsArrayElement &&
11267       Designator.Entries.size() == Designator.MostDerivedPathLength) {
11268     uint64_t ArraySize = Designator.getMostDerivedArraySize();
11269     uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
11270     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
11271   } else {
11272     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
11273   }
11274 
11275   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
11276   return true;
11277 }
11278 
11279 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
11280 /// returns true and stores the result in @p Size.
11281 ///
11282 /// If @p WasError is non-null, this will report whether the failure to evaluate
11283 /// is to be treated as an Error in IntExprEvaluator.
11284 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
11285                                          EvalInfo &Info, uint64_t &Size) {
11286   // Determine the denoted object.
11287   LValue LVal;
11288   {
11289     // The operand of __builtin_object_size is never evaluated for side-effects.
11290     // If there are any, but we can determine the pointed-to object anyway, then
11291     // ignore the side-effects.
11292     SpeculativeEvaluationRAII SpeculativeEval(Info);
11293     IgnoreSideEffectsRAII Fold(Info);
11294 
11295     if (E->isGLValue()) {
11296       // It's possible for us to be given GLValues if we're called via
11297       // Expr::tryEvaluateObjectSize.
11298       APValue RVal;
11299       if (!EvaluateAsRValue(Info, E, RVal))
11300         return false;
11301       LVal.setFrom(Info.Ctx, RVal);
11302     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
11303                                 /*InvalidBaseOK=*/true))
11304       return false;
11305   }
11306 
11307   // If we point to before the start of the object, there are no accessible
11308   // bytes.
11309   if (LVal.getLValueOffset().isNegative()) {
11310     Size = 0;
11311     return true;
11312   }
11313 
11314   CharUnits EndOffset;
11315   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
11316     return false;
11317 
11318   // If we've fallen outside of the end offset, just pretend there's nothing to
11319   // write to/read from.
11320   if (EndOffset <= LVal.getLValueOffset())
11321     Size = 0;
11322   else
11323     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
11324   return true;
11325 }
11326 
11327 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
11328   if (unsigned BuiltinOp = E->getBuiltinCallee())
11329     return VisitBuiltinCallExpr(E, BuiltinOp);
11330 
11331   return ExprEvaluatorBaseTy::VisitCallExpr(E);
11332 }
11333 
11334 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
11335                                      APValue &Val, APSInt &Alignment) {
11336   QualType SrcTy = E->getArg(0)->getType();
11337   if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
11338     return false;
11339   // Even though we are evaluating integer expressions we could get a pointer
11340   // argument for the __builtin_is_aligned() case.
11341   if (SrcTy->isPointerType()) {
11342     LValue Ptr;
11343     if (!EvaluatePointer(E->getArg(0), Ptr, Info))
11344       return false;
11345     Ptr.moveInto(Val);
11346   } else if (!SrcTy->isIntegralOrEnumerationType()) {
11347     Info.FFDiag(E->getArg(0));
11348     return false;
11349   } else {
11350     APSInt SrcInt;
11351     if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
11352       return false;
11353     assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
11354            "Bit widths must be the same");
11355     Val = APValue(SrcInt);
11356   }
11357   assert(Val.hasValue());
11358   return true;
11359 }
11360 
11361 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
11362                                             unsigned BuiltinOp) {
11363   switch (BuiltinOp) {
11364   default:
11365     return ExprEvaluatorBaseTy::VisitCallExpr(E);
11366 
11367   case Builtin::BI__builtin_dynamic_object_size:
11368   case Builtin::BI__builtin_object_size: {
11369     // The type was checked when we built the expression.
11370     unsigned Type =
11371         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11372     assert(Type <= 3 && "unexpected type");
11373 
11374     uint64_t Size;
11375     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
11376       return Success(Size, E);
11377 
11378     if (E->getArg(0)->HasSideEffects(Info.Ctx))
11379       return Success((Type & 2) ? 0 : -1, E);
11380 
11381     // Expression had no side effects, but we couldn't statically determine the
11382     // size of the referenced object.
11383     switch (Info.EvalMode) {
11384     case EvalInfo::EM_ConstantExpression:
11385     case EvalInfo::EM_ConstantFold:
11386     case EvalInfo::EM_IgnoreSideEffects:
11387       // Leave it to IR generation.
11388       return Error(E);
11389     case EvalInfo::EM_ConstantExpressionUnevaluated:
11390       // Reduce it to a constant now.
11391       return Success((Type & 2) ? 0 : -1, E);
11392     }
11393 
11394     llvm_unreachable("unexpected EvalMode");
11395   }
11396 
11397   case Builtin::BI__builtin_os_log_format_buffer_size: {
11398     analyze_os_log::OSLogBufferLayout Layout;
11399     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
11400     return Success(Layout.size().getQuantity(), E);
11401   }
11402 
11403   case Builtin::BI__builtin_is_aligned: {
11404     APValue Src;
11405     APSInt Alignment;
11406     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11407       return false;
11408     if (Src.isLValue()) {
11409       // If we evaluated a pointer, check the minimum known alignment.
11410       LValue Ptr;
11411       Ptr.setFrom(Info.Ctx, Src);
11412       CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
11413       CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
11414       // We can return true if the known alignment at the computed offset is
11415       // greater than the requested alignment.
11416       assert(PtrAlign.isPowerOfTwo());
11417       assert(Alignment.isPowerOf2());
11418       if (PtrAlign.getQuantity() >= Alignment)
11419         return Success(1, E);
11420       // If the alignment is not known to be sufficient, some cases could still
11421       // be aligned at run time. However, if the requested alignment is less or
11422       // equal to the base alignment and the offset is not aligned, we know that
11423       // the run-time value can never be aligned.
11424       if (BaseAlignment.getQuantity() >= Alignment &&
11425           PtrAlign.getQuantity() < Alignment)
11426         return Success(0, E);
11427       // Otherwise we can't infer whether the value is sufficiently aligned.
11428       // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
11429       //  in cases where we can't fully evaluate the pointer.
11430       Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
11431           << Alignment;
11432       return false;
11433     }
11434     assert(Src.isInt());
11435     return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
11436   }
11437   case Builtin::BI__builtin_align_up: {
11438     APValue Src;
11439     APSInt Alignment;
11440     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11441       return false;
11442     if (!Src.isInt())
11443       return Error(E);
11444     APSInt AlignedVal =
11445         APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
11446                Src.getInt().isUnsigned());
11447     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11448     return Success(AlignedVal, E);
11449   }
11450   case Builtin::BI__builtin_align_down: {
11451     APValue Src;
11452     APSInt Alignment;
11453     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11454       return false;
11455     if (!Src.isInt())
11456       return Error(E);
11457     APSInt AlignedVal =
11458         APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
11459     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11460     return Success(AlignedVal, E);
11461   }
11462 
11463   case Builtin::BI__builtin_bitreverse8:
11464   case Builtin::BI__builtin_bitreverse16:
11465   case Builtin::BI__builtin_bitreverse32:
11466   case Builtin::BI__builtin_bitreverse64: {
11467     APSInt Val;
11468     if (!EvaluateInteger(E->getArg(0), Val, Info))
11469       return false;
11470 
11471     return Success(Val.reverseBits(), E);
11472   }
11473 
11474   case Builtin::BI__builtin_bswap16:
11475   case Builtin::BI__builtin_bswap32:
11476   case Builtin::BI__builtin_bswap64: {
11477     APSInt Val;
11478     if (!EvaluateInteger(E->getArg(0), Val, Info))
11479       return false;
11480 
11481     return Success(Val.byteSwap(), E);
11482   }
11483 
11484   case Builtin::BI__builtin_classify_type:
11485     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
11486 
11487   case Builtin::BI__builtin_clrsb:
11488   case Builtin::BI__builtin_clrsbl:
11489   case Builtin::BI__builtin_clrsbll: {
11490     APSInt Val;
11491     if (!EvaluateInteger(E->getArg(0), Val, Info))
11492       return false;
11493 
11494     return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
11495   }
11496 
11497   case Builtin::BI__builtin_clz:
11498   case Builtin::BI__builtin_clzl:
11499   case Builtin::BI__builtin_clzll:
11500   case Builtin::BI__builtin_clzs: {
11501     APSInt Val;
11502     if (!EvaluateInteger(E->getArg(0), Val, Info))
11503       return false;
11504     if (!Val)
11505       return Error(E);
11506 
11507     return Success(Val.countLeadingZeros(), E);
11508   }
11509 
11510   case Builtin::BI__builtin_constant_p: {
11511     const Expr *Arg = E->getArg(0);
11512     if (EvaluateBuiltinConstantP(Info, Arg))
11513       return Success(true, E);
11514     if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
11515       // Outside a constant context, eagerly evaluate to false in the presence
11516       // of side-effects in order to avoid -Wunsequenced false-positives in
11517       // a branch on __builtin_constant_p(expr).
11518       return Success(false, E);
11519     }
11520     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11521     return false;
11522   }
11523 
11524   case Builtin::BI__builtin_is_constant_evaluated: {
11525     const auto *Callee = Info.CurrentCall->getCallee();
11526     if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
11527         (Info.CallStackDepth == 1 ||
11528          (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
11529           Callee->getIdentifier() &&
11530           Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
11531       // FIXME: Find a better way to avoid duplicated diagnostics.
11532       if (Info.EvalStatus.Diag)
11533         Info.report((Info.CallStackDepth == 1) ? E->getExprLoc()
11534                                                : Info.CurrentCall->CallLoc,
11535                     diag::warn_is_constant_evaluated_always_true_constexpr)
11536             << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
11537                                          : "std::is_constant_evaluated");
11538     }
11539 
11540     return Success(Info.InConstantContext, E);
11541   }
11542 
11543   case Builtin::BI__builtin_ctz:
11544   case Builtin::BI__builtin_ctzl:
11545   case Builtin::BI__builtin_ctzll:
11546   case Builtin::BI__builtin_ctzs: {
11547     APSInt Val;
11548     if (!EvaluateInteger(E->getArg(0), Val, Info))
11549       return false;
11550     if (!Val)
11551       return Error(E);
11552 
11553     return Success(Val.countTrailingZeros(), E);
11554   }
11555 
11556   case Builtin::BI__builtin_eh_return_data_regno: {
11557     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11558     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
11559     return Success(Operand, E);
11560   }
11561 
11562   case Builtin::BI__builtin_expect:
11563   case Builtin::BI__builtin_expect_with_probability:
11564     return Visit(E->getArg(0));
11565 
11566   case Builtin::BI__builtin_ffs:
11567   case Builtin::BI__builtin_ffsl:
11568   case Builtin::BI__builtin_ffsll: {
11569     APSInt Val;
11570     if (!EvaluateInteger(E->getArg(0), Val, Info))
11571       return false;
11572 
11573     unsigned N = Val.countTrailingZeros();
11574     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
11575   }
11576 
11577   case Builtin::BI__builtin_fpclassify: {
11578     APFloat Val(0.0);
11579     if (!EvaluateFloat(E->getArg(5), Val, Info))
11580       return false;
11581     unsigned Arg;
11582     switch (Val.getCategory()) {
11583     case APFloat::fcNaN: Arg = 0; break;
11584     case APFloat::fcInfinity: Arg = 1; break;
11585     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
11586     case APFloat::fcZero: Arg = 4; break;
11587     }
11588     return Visit(E->getArg(Arg));
11589   }
11590 
11591   case Builtin::BI__builtin_isinf_sign: {
11592     APFloat Val(0.0);
11593     return EvaluateFloat(E->getArg(0), Val, Info) &&
11594            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
11595   }
11596 
11597   case Builtin::BI__builtin_isinf: {
11598     APFloat Val(0.0);
11599     return EvaluateFloat(E->getArg(0), Val, Info) &&
11600            Success(Val.isInfinity() ? 1 : 0, E);
11601   }
11602 
11603   case Builtin::BI__builtin_isfinite: {
11604     APFloat Val(0.0);
11605     return EvaluateFloat(E->getArg(0), Val, Info) &&
11606            Success(Val.isFinite() ? 1 : 0, E);
11607   }
11608 
11609   case Builtin::BI__builtin_isnan: {
11610     APFloat Val(0.0);
11611     return EvaluateFloat(E->getArg(0), Val, Info) &&
11612            Success(Val.isNaN() ? 1 : 0, E);
11613   }
11614 
11615   case Builtin::BI__builtin_isnormal: {
11616     APFloat Val(0.0);
11617     return EvaluateFloat(E->getArg(0), Val, Info) &&
11618            Success(Val.isNormal() ? 1 : 0, E);
11619   }
11620 
11621   case Builtin::BI__builtin_parity:
11622   case Builtin::BI__builtin_parityl:
11623   case Builtin::BI__builtin_parityll: {
11624     APSInt Val;
11625     if (!EvaluateInteger(E->getArg(0), Val, Info))
11626       return false;
11627 
11628     return Success(Val.countPopulation() % 2, E);
11629   }
11630 
11631   case Builtin::BI__builtin_popcount:
11632   case Builtin::BI__builtin_popcountl:
11633   case Builtin::BI__builtin_popcountll: {
11634     APSInt Val;
11635     if (!EvaluateInteger(E->getArg(0), Val, Info))
11636       return false;
11637 
11638     return Success(Val.countPopulation(), E);
11639   }
11640 
11641   case Builtin::BI__builtin_rotateleft8:
11642   case Builtin::BI__builtin_rotateleft16:
11643   case Builtin::BI__builtin_rotateleft32:
11644   case Builtin::BI__builtin_rotateleft64:
11645   case Builtin::BI_rotl8: // Microsoft variants of rotate right
11646   case Builtin::BI_rotl16:
11647   case Builtin::BI_rotl:
11648   case Builtin::BI_lrotl:
11649   case Builtin::BI_rotl64: {
11650     APSInt Val, Amt;
11651     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
11652         !EvaluateInteger(E->getArg(1), Amt, Info))
11653       return false;
11654 
11655     return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
11656   }
11657 
11658   case Builtin::BI__builtin_rotateright8:
11659   case Builtin::BI__builtin_rotateright16:
11660   case Builtin::BI__builtin_rotateright32:
11661   case Builtin::BI__builtin_rotateright64:
11662   case Builtin::BI_rotr8: // Microsoft variants of rotate right
11663   case Builtin::BI_rotr16:
11664   case Builtin::BI_rotr:
11665   case Builtin::BI_lrotr:
11666   case Builtin::BI_rotr64: {
11667     APSInt Val, Amt;
11668     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
11669         !EvaluateInteger(E->getArg(1), Amt, Info))
11670       return false;
11671 
11672     return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
11673   }
11674 
11675   case Builtin::BIstrlen:
11676   case Builtin::BIwcslen:
11677     // A call to strlen is not a constant expression.
11678     if (Info.getLangOpts().CPlusPlus11)
11679       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11680         << /*isConstexpr*/0 << /*isConstructor*/0
11681         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11682     else
11683       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11684     LLVM_FALLTHROUGH;
11685   case Builtin::BI__builtin_strlen:
11686   case Builtin::BI__builtin_wcslen: {
11687     // As an extension, we support __builtin_strlen() as a constant expression,
11688     // and support folding strlen() to a constant.
11689     LValue String;
11690     if (!EvaluatePointer(E->getArg(0), String, Info))
11691       return false;
11692 
11693     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
11694 
11695     // Fast path: if it's a string literal, search the string value.
11696     if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
11697             String.getLValueBase().dyn_cast<const Expr *>())) {
11698       // The string literal may have embedded null characters. Find the first
11699       // one and truncate there.
11700       StringRef Str = S->getBytes();
11701       int64_t Off = String.Offset.getQuantity();
11702       if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
11703           S->getCharByteWidth() == 1 &&
11704           // FIXME: Add fast-path for wchar_t too.
11705           Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
11706         Str = Str.substr(Off);
11707 
11708         StringRef::size_type Pos = Str.find(0);
11709         if (Pos != StringRef::npos)
11710           Str = Str.substr(0, Pos);
11711 
11712         return Success(Str.size(), E);
11713       }
11714 
11715       // Fall through to slow path to issue appropriate diagnostic.
11716     }
11717 
11718     // Slow path: scan the bytes of the string looking for the terminating 0.
11719     for (uint64_t Strlen = 0; /**/; ++Strlen) {
11720       APValue Char;
11721       if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
11722           !Char.isInt())
11723         return false;
11724       if (!Char.getInt())
11725         return Success(Strlen, E);
11726       if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
11727         return false;
11728     }
11729   }
11730 
11731   case Builtin::BIstrcmp:
11732   case Builtin::BIwcscmp:
11733   case Builtin::BIstrncmp:
11734   case Builtin::BIwcsncmp:
11735   case Builtin::BImemcmp:
11736   case Builtin::BIbcmp:
11737   case Builtin::BIwmemcmp:
11738     // A call to strlen is not a constant expression.
11739     if (Info.getLangOpts().CPlusPlus11)
11740       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11741         << /*isConstexpr*/0 << /*isConstructor*/0
11742         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11743     else
11744       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11745     LLVM_FALLTHROUGH;
11746   case Builtin::BI__builtin_strcmp:
11747   case Builtin::BI__builtin_wcscmp:
11748   case Builtin::BI__builtin_strncmp:
11749   case Builtin::BI__builtin_wcsncmp:
11750   case Builtin::BI__builtin_memcmp:
11751   case Builtin::BI__builtin_bcmp:
11752   case Builtin::BI__builtin_wmemcmp: {
11753     LValue String1, String2;
11754     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
11755         !EvaluatePointer(E->getArg(1), String2, Info))
11756       return false;
11757 
11758     uint64_t MaxLength = uint64_t(-1);
11759     if (BuiltinOp != Builtin::BIstrcmp &&
11760         BuiltinOp != Builtin::BIwcscmp &&
11761         BuiltinOp != Builtin::BI__builtin_strcmp &&
11762         BuiltinOp != Builtin::BI__builtin_wcscmp) {
11763       APSInt N;
11764       if (!EvaluateInteger(E->getArg(2), N, Info))
11765         return false;
11766       MaxLength = N.getExtValue();
11767     }
11768 
11769     // Empty substrings compare equal by definition.
11770     if (MaxLength == 0u)
11771       return Success(0, E);
11772 
11773     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11774         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11775         String1.Designator.Invalid || String2.Designator.Invalid)
11776       return false;
11777 
11778     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
11779     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
11780 
11781     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
11782                      BuiltinOp == Builtin::BIbcmp ||
11783                      BuiltinOp == Builtin::BI__builtin_memcmp ||
11784                      BuiltinOp == Builtin::BI__builtin_bcmp;
11785 
11786     assert(IsRawByte ||
11787            (Info.Ctx.hasSameUnqualifiedType(
11788                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
11789             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
11790 
11791     // For memcmp, allow comparing any arrays of '[[un]signed] char' or
11792     // 'char8_t', but no other types.
11793     if (IsRawByte &&
11794         !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
11795       // FIXME: Consider using our bit_cast implementation to support this.
11796       Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
11797           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
11798           << CharTy1 << CharTy2;
11799       return false;
11800     }
11801 
11802     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
11803       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
11804              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
11805              Char1.isInt() && Char2.isInt();
11806     };
11807     const auto &AdvanceElems = [&] {
11808       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
11809              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
11810     };
11811 
11812     bool StopAtNull =
11813         (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
11814          BuiltinOp != Builtin::BIwmemcmp &&
11815          BuiltinOp != Builtin::BI__builtin_memcmp &&
11816          BuiltinOp != Builtin::BI__builtin_bcmp &&
11817          BuiltinOp != Builtin::BI__builtin_wmemcmp);
11818     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
11819                   BuiltinOp == Builtin::BIwcsncmp ||
11820                   BuiltinOp == Builtin::BIwmemcmp ||
11821                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
11822                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
11823                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
11824 
11825     for (; MaxLength; --MaxLength) {
11826       APValue Char1, Char2;
11827       if (!ReadCurElems(Char1, Char2))
11828         return false;
11829       if (Char1.getInt().ne(Char2.getInt())) {
11830         if (IsWide) // wmemcmp compares with wchar_t signedness.
11831           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
11832         // memcmp always compares unsigned chars.
11833         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
11834       }
11835       if (StopAtNull && !Char1.getInt())
11836         return Success(0, E);
11837       assert(!(StopAtNull && !Char2.getInt()));
11838       if (!AdvanceElems())
11839         return false;
11840     }
11841     // We hit the strncmp / memcmp limit.
11842     return Success(0, E);
11843   }
11844 
11845   case Builtin::BI__atomic_always_lock_free:
11846   case Builtin::BI__atomic_is_lock_free:
11847   case Builtin::BI__c11_atomic_is_lock_free: {
11848     APSInt SizeVal;
11849     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
11850       return false;
11851 
11852     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
11853     // of two less than or equal to the maximum inline atomic width, we know it
11854     // is lock-free.  If the size isn't a power of two, or greater than the
11855     // maximum alignment where we promote atomics, we know it is not lock-free
11856     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
11857     // the answer can only be determined at runtime; for example, 16-byte
11858     // atomics have lock-free implementations on some, but not all,
11859     // x86-64 processors.
11860 
11861     // Check power-of-two.
11862     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
11863     if (Size.isPowerOfTwo()) {
11864       // Check against inlining width.
11865       unsigned InlineWidthBits =
11866           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
11867       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
11868         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
11869             Size == CharUnits::One() ||
11870             E->getArg(1)->isNullPointerConstant(Info.Ctx,
11871                                                 Expr::NPC_NeverValueDependent))
11872           // OK, we will inline appropriately-aligned operations of this size,
11873           // and _Atomic(T) is appropriately-aligned.
11874           return Success(1, E);
11875 
11876         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
11877           castAs<PointerType>()->getPointeeType();
11878         if (!PointeeType->isIncompleteType() &&
11879             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
11880           // OK, we will inline operations on this object.
11881           return Success(1, E);
11882         }
11883       }
11884     }
11885 
11886     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
11887         Success(0, E) : Error(E);
11888   }
11889   case Builtin::BIomp_is_initial_device:
11890     // We can decide statically which value the runtime would return if called.
11891     return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
11892   case Builtin::BI__builtin_add_overflow:
11893   case Builtin::BI__builtin_sub_overflow:
11894   case Builtin::BI__builtin_mul_overflow:
11895   case Builtin::BI__builtin_sadd_overflow:
11896   case Builtin::BI__builtin_uadd_overflow:
11897   case Builtin::BI__builtin_uaddl_overflow:
11898   case Builtin::BI__builtin_uaddll_overflow:
11899   case Builtin::BI__builtin_usub_overflow:
11900   case Builtin::BI__builtin_usubl_overflow:
11901   case Builtin::BI__builtin_usubll_overflow:
11902   case Builtin::BI__builtin_umul_overflow:
11903   case Builtin::BI__builtin_umull_overflow:
11904   case Builtin::BI__builtin_umulll_overflow:
11905   case Builtin::BI__builtin_saddl_overflow:
11906   case Builtin::BI__builtin_saddll_overflow:
11907   case Builtin::BI__builtin_ssub_overflow:
11908   case Builtin::BI__builtin_ssubl_overflow:
11909   case Builtin::BI__builtin_ssubll_overflow:
11910   case Builtin::BI__builtin_smul_overflow:
11911   case Builtin::BI__builtin_smull_overflow:
11912   case Builtin::BI__builtin_smulll_overflow: {
11913     LValue ResultLValue;
11914     APSInt LHS, RHS;
11915 
11916     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
11917     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
11918         !EvaluateInteger(E->getArg(1), RHS, Info) ||
11919         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
11920       return false;
11921 
11922     APSInt Result;
11923     bool DidOverflow = false;
11924 
11925     // If the types don't have to match, enlarge all 3 to the largest of them.
11926     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
11927         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
11928         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
11929       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
11930                       ResultType->isSignedIntegerOrEnumerationType();
11931       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
11932                       ResultType->isSignedIntegerOrEnumerationType();
11933       uint64_t LHSSize = LHS.getBitWidth();
11934       uint64_t RHSSize = RHS.getBitWidth();
11935       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
11936       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
11937 
11938       // Add an additional bit if the signedness isn't uniformly agreed to. We
11939       // could do this ONLY if there is a signed and an unsigned that both have
11940       // MaxBits, but the code to check that is pretty nasty.  The issue will be
11941       // caught in the shrink-to-result later anyway.
11942       if (IsSigned && !AllSigned)
11943         ++MaxBits;
11944 
11945       LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
11946       RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
11947       Result = APSInt(MaxBits, !IsSigned);
11948     }
11949 
11950     // Find largest int.
11951     switch (BuiltinOp) {
11952     default:
11953       llvm_unreachable("Invalid value for BuiltinOp");
11954     case Builtin::BI__builtin_add_overflow:
11955     case Builtin::BI__builtin_sadd_overflow:
11956     case Builtin::BI__builtin_saddl_overflow:
11957     case Builtin::BI__builtin_saddll_overflow:
11958     case Builtin::BI__builtin_uadd_overflow:
11959     case Builtin::BI__builtin_uaddl_overflow:
11960     case Builtin::BI__builtin_uaddll_overflow:
11961       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
11962                               : LHS.uadd_ov(RHS, DidOverflow);
11963       break;
11964     case Builtin::BI__builtin_sub_overflow:
11965     case Builtin::BI__builtin_ssub_overflow:
11966     case Builtin::BI__builtin_ssubl_overflow:
11967     case Builtin::BI__builtin_ssubll_overflow:
11968     case Builtin::BI__builtin_usub_overflow:
11969     case Builtin::BI__builtin_usubl_overflow:
11970     case Builtin::BI__builtin_usubll_overflow:
11971       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
11972                               : LHS.usub_ov(RHS, DidOverflow);
11973       break;
11974     case Builtin::BI__builtin_mul_overflow:
11975     case Builtin::BI__builtin_smul_overflow:
11976     case Builtin::BI__builtin_smull_overflow:
11977     case Builtin::BI__builtin_smulll_overflow:
11978     case Builtin::BI__builtin_umul_overflow:
11979     case Builtin::BI__builtin_umull_overflow:
11980     case Builtin::BI__builtin_umulll_overflow:
11981       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
11982                               : LHS.umul_ov(RHS, DidOverflow);
11983       break;
11984     }
11985 
11986     // In the case where multiple sizes are allowed, truncate and see if
11987     // the values are the same.
11988     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
11989         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
11990         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
11991       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
11992       // since it will give us the behavior of a TruncOrSelf in the case where
11993       // its parameter <= its size.  We previously set Result to be at least the
11994       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
11995       // will work exactly like TruncOrSelf.
11996       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
11997       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
11998 
11999       if (!APSInt::isSameValue(Temp, Result))
12000         DidOverflow = true;
12001       Result = Temp;
12002     }
12003 
12004     APValue APV{Result};
12005     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
12006       return false;
12007     return Success(DidOverflow, E);
12008   }
12009   }
12010 }
12011 
12012 /// Determine whether this is a pointer past the end of the complete
12013 /// object referred to by the lvalue.
12014 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
12015                                             const LValue &LV) {
12016   // A null pointer can be viewed as being "past the end" but we don't
12017   // choose to look at it that way here.
12018   if (!LV.getLValueBase())
12019     return false;
12020 
12021   // If the designator is valid and refers to a subobject, we're not pointing
12022   // past the end.
12023   if (!LV.getLValueDesignator().Invalid &&
12024       !LV.getLValueDesignator().isOnePastTheEnd())
12025     return false;
12026 
12027   // A pointer to an incomplete type might be past-the-end if the type's size is
12028   // zero.  We cannot tell because the type is incomplete.
12029   QualType Ty = getType(LV.getLValueBase());
12030   if (Ty->isIncompleteType())
12031     return true;
12032 
12033   // We're a past-the-end pointer if we point to the byte after the object,
12034   // no matter what our type or path is.
12035   auto Size = Ctx.getTypeSizeInChars(Ty);
12036   return LV.getLValueOffset() == Size;
12037 }
12038 
12039 namespace {
12040 
12041 /// Data recursive integer evaluator of certain binary operators.
12042 ///
12043 /// We use a data recursive algorithm for binary operators so that we are able
12044 /// to handle extreme cases of chained binary operators without causing stack
12045 /// overflow.
12046 class DataRecursiveIntBinOpEvaluator {
12047   struct EvalResult {
12048     APValue Val;
12049     bool Failed;
12050 
12051     EvalResult() : Failed(false) { }
12052 
12053     void swap(EvalResult &RHS) {
12054       Val.swap(RHS.Val);
12055       Failed = RHS.Failed;
12056       RHS.Failed = false;
12057     }
12058   };
12059 
12060   struct Job {
12061     const Expr *E;
12062     EvalResult LHSResult; // meaningful only for binary operator expression.
12063     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
12064 
12065     Job() = default;
12066     Job(Job &&) = default;
12067 
12068     void startSpeculativeEval(EvalInfo &Info) {
12069       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
12070     }
12071 
12072   private:
12073     SpeculativeEvaluationRAII SpecEvalRAII;
12074   };
12075 
12076   SmallVector<Job, 16> Queue;
12077 
12078   IntExprEvaluator &IntEval;
12079   EvalInfo &Info;
12080   APValue &FinalResult;
12081 
12082 public:
12083   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
12084     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
12085 
12086   /// True if \param E is a binary operator that we are going to handle
12087   /// data recursively.
12088   /// We handle binary operators that are comma, logical, or that have operands
12089   /// with integral or enumeration type.
12090   static bool shouldEnqueue(const BinaryOperator *E) {
12091     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
12092            (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
12093             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12094             E->getRHS()->getType()->isIntegralOrEnumerationType());
12095   }
12096 
12097   bool Traverse(const BinaryOperator *E) {
12098     enqueue(E);
12099     EvalResult PrevResult;
12100     while (!Queue.empty())
12101       process(PrevResult);
12102 
12103     if (PrevResult.Failed) return false;
12104 
12105     FinalResult.swap(PrevResult.Val);
12106     return true;
12107   }
12108 
12109 private:
12110   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
12111     return IntEval.Success(Value, E, Result);
12112   }
12113   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
12114     return IntEval.Success(Value, E, Result);
12115   }
12116   bool Error(const Expr *E) {
12117     return IntEval.Error(E);
12118   }
12119   bool Error(const Expr *E, diag::kind D) {
12120     return IntEval.Error(E, D);
12121   }
12122 
12123   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
12124     return Info.CCEDiag(E, D);
12125   }
12126 
12127   // Returns true if visiting the RHS is necessary, false otherwise.
12128   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12129                          bool &SuppressRHSDiags);
12130 
12131   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12132                   const BinaryOperator *E, APValue &Result);
12133 
12134   void EvaluateExpr(const Expr *E, EvalResult &Result) {
12135     Result.Failed = !Evaluate(Result.Val, Info, E);
12136     if (Result.Failed)
12137       Result.Val = APValue();
12138   }
12139 
12140   void process(EvalResult &Result);
12141 
12142   void enqueue(const Expr *E) {
12143     E = E->IgnoreParens();
12144     Queue.resize(Queue.size()+1);
12145     Queue.back().E = E;
12146     Queue.back().Kind = Job::AnyExprKind;
12147   }
12148 };
12149 
12150 }
12151 
12152 bool DataRecursiveIntBinOpEvaluator::
12153        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12154                          bool &SuppressRHSDiags) {
12155   if (E->getOpcode() == BO_Comma) {
12156     // Ignore LHS but note if we could not evaluate it.
12157     if (LHSResult.Failed)
12158       return Info.noteSideEffect();
12159     return true;
12160   }
12161 
12162   if (E->isLogicalOp()) {
12163     bool LHSAsBool;
12164     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
12165       // We were able to evaluate the LHS, see if we can get away with not
12166       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
12167       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
12168         Success(LHSAsBool, E, LHSResult.Val);
12169         return false; // Ignore RHS
12170       }
12171     } else {
12172       LHSResult.Failed = true;
12173 
12174       // Since we weren't able to evaluate the left hand side, it
12175       // might have had side effects.
12176       if (!Info.noteSideEffect())
12177         return false;
12178 
12179       // We can't evaluate the LHS; however, sometimes the result
12180       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12181       // Don't ignore RHS and suppress diagnostics from this arm.
12182       SuppressRHSDiags = true;
12183     }
12184 
12185     return true;
12186   }
12187 
12188   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12189          E->getRHS()->getType()->isIntegralOrEnumerationType());
12190 
12191   if (LHSResult.Failed && !Info.noteFailure())
12192     return false; // Ignore RHS;
12193 
12194   return true;
12195 }
12196 
12197 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
12198                                     bool IsSub) {
12199   // Compute the new offset in the appropriate width, wrapping at 64 bits.
12200   // FIXME: When compiling for a 32-bit target, we should use 32-bit
12201   // offsets.
12202   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
12203   CharUnits &Offset = LVal.getLValueOffset();
12204   uint64_t Offset64 = Offset.getQuantity();
12205   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
12206   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
12207                                          : Offset64 + Index64);
12208 }
12209 
12210 bool DataRecursiveIntBinOpEvaluator::
12211        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12212                   const BinaryOperator *E, APValue &Result) {
12213   if (E->getOpcode() == BO_Comma) {
12214     if (RHSResult.Failed)
12215       return false;
12216     Result = RHSResult.Val;
12217     return true;
12218   }
12219 
12220   if (E->isLogicalOp()) {
12221     bool lhsResult, rhsResult;
12222     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
12223     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
12224 
12225     if (LHSIsOK) {
12226       if (RHSIsOK) {
12227         if (E->getOpcode() == BO_LOr)
12228           return Success(lhsResult || rhsResult, E, Result);
12229         else
12230           return Success(lhsResult && rhsResult, E, Result);
12231       }
12232     } else {
12233       if (RHSIsOK) {
12234         // We can't evaluate the LHS; however, sometimes the result
12235         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12236         if (rhsResult == (E->getOpcode() == BO_LOr))
12237           return Success(rhsResult, E, Result);
12238       }
12239     }
12240 
12241     return false;
12242   }
12243 
12244   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12245          E->getRHS()->getType()->isIntegralOrEnumerationType());
12246 
12247   if (LHSResult.Failed || RHSResult.Failed)
12248     return false;
12249 
12250   const APValue &LHSVal = LHSResult.Val;
12251   const APValue &RHSVal = RHSResult.Val;
12252 
12253   // Handle cases like (unsigned long)&a + 4.
12254   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
12255     Result = LHSVal;
12256     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
12257     return true;
12258   }
12259 
12260   // Handle cases like 4 + (unsigned long)&a
12261   if (E->getOpcode() == BO_Add &&
12262       RHSVal.isLValue() && LHSVal.isInt()) {
12263     Result = RHSVal;
12264     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
12265     return true;
12266   }
12267 
12268   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
12269     // Handle (intptr_t)&&A - (intptr_t)&&B.
12270     if (!LHSVal.getLValueOffset().isZero() ||
12271         !RHSVal.getLValueOffset().isZero())
12272       return false;
12273     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
12274     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
12275     if (!LHSExpr || !RHSExpr)
12276       return false;
12277     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12278     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12279     if (!LHSAddrExpr || !RHSAddrExpr)
12280       return false;
12281     // Make sure both labels come from the same function.
12282     if (LHSAddrExpr->getLabel()->getDeclContext() !=
12283         RHSAddrExpr->getLabel()->getDeclContext())
12284       return false;
12285     Result = APValue(LHSAddrExpr, RHSAddrExpr);
12286     return true;
12287   }
12288 
12289   // All the remaining cases expect both operands to be an integer
12290   if (!LHSVal.isInt() || !RHSVal.isInt())
12291     return Error(E);
12292 
12293   // Set up the width and signedness manually, in case it can't be deduced
12294   // from the operation we're performing.
12295   // FIXME: Don't do this in the cases where we can deduce it.
12296   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
12297                E->getType()->isUnsignedIntegerOrEnumerationType());
12298   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
12299                          RHSVal.getInt(), Value))
12300     return false;
12301   return Success(Value, E, Result);
12302 }
12303 
12304 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
12305   Job &job = Queue.back();
12306 
12307   switch (job.Kind) {
12308     case Job::AnyExprKind: {
12309       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
12310         if (shouldEnqueue(Bop)) {
12311           job.Kind = Job::BinOpKind;
12312           enqueue(Bop->getLHS());
12313           return;
12314         }
12315       }
12316 
12317       EvaluateExpr(job.E, Result);
12318       Queue.pop_back();
12319       return;
12320     }
12321 
12322     case Job::BinOpKind: {
12323       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12324       bool SuppressRHSDiags = false;
12325       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
12326         Queue.pop_back();
12327         return;
12328       }
12329       if (SuppressRHSDiags)
12330         job.startSpeculativeEval(Info);
12331       job.LHSResult.swap(Result);
12332       job.Kind = Job::BinOpVisitedLHSKind;
12333       enqueue(Bop->getRHS());
12334       return;
12335     }
12336 
12337     case Job::BinOpVisitedLHSKind: {
12338       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12339       EvalResult RHS;
12340       RHS.swap(Result);
12341       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
12342       Queue.pop_back();
12343       return;
12344     }
12345   }
12346 
12347   llvm_unreachable("Invalid Job::Kind!");
12348 }
12349 
12350 namespace {
12351 /// Used when we determine that we should fail, but can keep evaluating prior to
12352 /// noting that we had a failure.
12353 class DelayedNoteFailureRAII {
12354   EvalInfo &Info;
12355   bool NoteFailure;
12356 
12357 public:
12358   DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
12359       : Info(Info), NoteFailure(NoteFailure) {}
12360   ~DelayedNoteFailureRAII() {
12361     if (NoteFailure) {
12362       bool ContinueAfterFailure = Info.noteFailure();
12363       (void)ContinueAfterFailure;
12364       assert(ContinueAfterFailure &&
12365              "Shouldn't have kept evaluating on failure.");
12366     }
12367   }
12368 };
12369 
12370 enum class CmpResult {
12371   Unequal,
12372   Less,
12373   Equal,
12374   Greater,
12375   Unordered,
12376 };
12377 }
12378 
12379 template <class SuccessCB, class AfterCB>
12380 static bool
12381 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
12382                                  SuccessCB &&Success, AfterCB &&DoAfter) {
12383   assert(E->isComparisonOp() && "expected comparison operator");
12384   assert((E->getOpcode() == BO_Cmp ||
12385           E->getType()->isIntegralOrEnumerationType()) &&
12386          "unsupported binary expression evaluation");
12387   auto Error = [&](const Expr *E) {
12388     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12389     return false;
12390   };
12391 
12392   bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
12393   bool IsEquality = E->isEqualityOp();
12394 
12395   QualType LHSTy = E->getLHS()->getType();
12396   QualType RHSTy = E->getRHS()->getType();
12397 
12398   if (LHSTy->isIntegralOrEnumerationType() &&
12399       RHSTy->isIntegralOrEnumerationType()) {
12400     APSInt LHS, RHS;
12401     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
12402     if (!LHSOK && !Info.noteFailure())
12403       return false;
12404     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
12405       return false;
12406     if (LHS < RHS)
12407       return Success(CmpResult::Less, E);
12408     if (LHS > RHS)
12409       return Success(CmpResult::Greater, E);
12410     return Success(CmpResult::Equal, E);
12411   }
12412 
12413   if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
12414     APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
12415     APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
12416 
12417     bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
12418     if (!LHSOK && !Info.noteFailure())
12419       return false;
12420     if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
12421       return false;
12422     if (LHSFX < RHSFX)
12423       return Success(CmpResult::Less, E);
12424     if (LHSFX > RHSFX)
12425       return Success(CmpResult::Greater, E);
12426     return Success(CmpResult::Equal, E);
12427   }
12428 
12429   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
12430     ComplexValue LHS, RHS;
12431     bool LHSOK;
12432     if (E->isAssignmentOp()) {
12433       LValue LV;
12434       EvaluateLValue(E->getLHS(), LV, Info);
12435       LHSOK = false;
12436     } else if (LHSTy->isRealFloatingType()) {
12437       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
12438       if (LHSOK) {
12439         LHS.makeComplexFloat();
12440         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
12441       }
12442     } else {
12443       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
12444     }
12445     if (!LHSOK && !Info.noteFailure())
12446       return false;
12447 
12448     if (E->getRHS()->getType()->isRealFloatingType()) {
12449       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
12450         return false;
12451       RHS.makeComplexFloat();
12452       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
12453     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
12454       return false;
12455 
12456     if (LHS.isComplexFloat()) {
12457       APFloat::cmpResult CR_r =
12458         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
12459       APFloat::cmpResult CR_i =
12460         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
12461       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
12462       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12463     } else {
12464       assert(IsEquality && "invalid complex comparison");
12465       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
12466                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
12467       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12468     }
12469   }
12470 
12471   if (LHSTy->isRealFloatingType() &&
12472       RHSTy->isRealFloatingType()) {
12473     APFloat RHS(0.0), LHS(0.0);
12474 
12475     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
12476     if (!LHSOK && !Info.noteFailure())
12477       return false;
12478 
12479     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
12480       return false;
12481 
12482     assert(E->isComparisonOp() && "Invalid binary operator!");
12483     auto GetCmpRes = [&]() {
12484       switch (LHS.compare(RHS)) {
12485       case APFloat::cmpEqual:
12486         return CmpResult::Equal;
12487       case APFloat::cmpLessThan:
12488         return CmpResult::Less;
12489       case APFloat::cmpGreaterThan:
12490         return CmpResult::Greater;
12491       case APFloat::cmpUnordered:
12492         return CmpResult::Unordered;
12493       }
12494       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
12495     };
12496     return Success(GetCmpRes(), E);
12497   }
12498 
12499   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
12500     LValue LHSValue, RHSValue;
12501 
12502     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12503     if (!LHSOK && !Info.noteFailure())
12504       return false;
12505 
12506     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12507       return false;
12508 
12509     // Reject differing bases from the normal codepath; we special-case
12510     // comparisons to null.
12511     if (!HasSameBase(LHSValue, RHSValue)) {
12512       // Inequalities and subtractions between unrelated pointers have
12513       // unspecified or undefined behavior.
12514       if (!IsEquality) {
12515         Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified);
12516         return false;
12517       }
12518       // A constant address may compare equal to the address of a symbol.
12519       // The one exception is that address of an object cannot compare equal
12520       // to a null pointer constant.
12521       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
12522           (!RHSValue.Base && !RHSValue.Offset.isZero()))
12523         return Error(E);
12524       // It's implementation-defined whether distinct literals will have
12525       // distinct addresses. In clang, the result of such a comparison is
12526       // unspecified, so it is not a constant expression. However, we do know
12527       // that the address of a literal will be non-null.
12528       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
12529           LHSValue.Base && RHSValue.Base)
12530         return Error(E);
12531       // We can't tell whether weak symbols will end up pointing to the same
12532       // object.
12533       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
12534         return Error(E);
12535       // We can't compare the address of the start of one object with the
12536       // past-the-end address of another object, per C++ DR1652.
12537       if ((LHSValue.Base && LHSValue.Offset.isZero() &&
12538            isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
12539           (RHSValue.Base && RHSValue.Offset.isZero() &&
12540            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
12541         return Error(E);
12542       // We can't tell whether an object is at the same address as another
12543       // zero sized object.
12544       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
12545           (LHSValue.Base && isZeroSized(RHSValue)))
12546         return Error(E);
12547       return Success(CmpResult::Unequal, E);
12548     }
12549 
12550     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12551     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12552 
12553     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12554     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12555 
12556     // C++11 [expr.rel]p3:
12557     //   Pointers to void (after pointer conversions) can be compared, with a
12558     //   result defined as follows: If both pointers represent the same
12559     //   address or are both the null pointer value, the result is true if the
12560     //   operator is <= or >= and false otherwise; otherwise the result is
12561     //   unspecified.
12562     // We interpret this as applying to pointers to *cv* void.
12563     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
12564       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
12565 
12566     // C++11 [expr.rel]p2:
12567     // - If two pointers point to non-static data members of the same object,
12568     //   or to subobjects or array elements fo such members, recursively, the
12569     //   pointer to the later declared member compares greater provided the
12570     //   two members have the same access control and provided their class is
12571     //   not a union.
12572     //   [...]
12573     // - Otherwise pointer comparisons are unspecified.
12574     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
12575       bool WasArrayIndex;
12576       unsigned Mismatch = FindDesignatorMismatch(
12577           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
12578       // At the point where the designators diverge, the comparison has a
12579       // specified value if:
12580       //  - we are comparing array indices
12581       //  - we are comparing fields of a union, or fields with the same access
12582       // Otherwise, the result is unspecified and thus the comparison is not a
12583       // constant expression.
12584       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
12585           Mismatch < RHSDesignator.Entries.size()) {
12586         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
12587         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
12588         if (!LF && !RF)
12589           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
12590         else if (!LF)
12591           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12592               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
12593               << RF->getParent() << RF;
12594         else if (!RF)
12595           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12596               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
12597               << LF->getParent() << LF;
12598         else if (!LF->getParent()->isUnion() &&
12599                  LF->getAccess() != RF->getAccess())
12600           Info.CCEDiag(E,
12601                        diag::note_constexpr_pointer_comparison_differing_access)
12602               << LF << LF->getAccess() << RF << RF->getAccess()
12603               << LF->getParent();
12604       }
12605     }
12606 
12607     // The comparison here must be unsigned, and performed with the same
12608     // width as the pointer.
12609     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
12610     uint64_t CompareLHS = LHSOffset.getQuantity();
12611     uint64_t CompareRHS = RHSOffset.getQuantity();
12612     assert(PtrSize <= 64 && "Unexpected pointer width");
12613     uint64_t Mask = ~0ULL >> (64 - PtrSize);
12614     CompareLHS &= Mask;
12615     CompareRHS &= Mask;
12616 
12617     // If there is a base and this is a relational operator, we can only
12618     // compare pointers within the object in question; otherwise, the result
12619     // depends on where the object is located in memory.
12620     if (!LHSValue.Base.isNull() && IsRelational) {
12621       QualType BaseTy = getType(LHSValue.Base);
12622       if (BaseTy->isIncompleteType())
12623         return Error(E);
12624       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
12625       uint64_t OffsetLimit = Size.getQuantity();
12626       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
12627         return Error(E);
12628     }
12629 
12630     if (CompareLHS < CompareRHS)
12631       return Success(CmpResult::Less, E);
12632     if (CompareLHS > CompareRHS)
12633       return Success(CmpResult::Greater, E);
12634     return Success(CmpResult::Equal, E);
12635   }
12636 
12637   if (LHSTy->isMemberPointerType()) {
12638     assert(IsEquality && "unexpected member pointer operation");
12639     assert(RHSTy->isMemberPointerType() && "invalid comparison");
12640 
12641     MemberPtr LHSValue, RHSValue;
12642 
12643     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
12644     if (!LHSOK && !Info.noteFailure())
12645       return false;
12646 
12647     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12648       return false;
12649 
12650     // C++11 [expr.eq]p2:
12651     //   If both operands are null, they compare equal. Otherwise if only one is
12652     //   null, they compare unequal.
12653     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
12654       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
12655       return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12656     }
12657 
12658     //   Otherwise if either is a pointer to a virtual member function, the
12659     //   result is unspecified.
12660     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
12661       if (MD->isVirtual())
12662         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12663     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
12664       if (MD->isVirtual())
12665         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12666 
12667     //   Otherwise they compare equal if and only if they would refer to the
12668     //   same member of the same most derived object or the same subobject if
12669     //   they were dereferenced with a hypothetical object of the associated
12670     //   class type.
12671     bool Equal = LHSValue == RHSValue;
12672     return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12673   }
12674 
12675   if (LHSTy->isNullPtrType()) {
12676     assert(E->isComparisonOp() && "unexpected nullptr operation");
12677     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
12678     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
12679     // are compared, the result is true of the operator is <=, >= or ==, and
12680     // false otherwise.
12681     return Success(CmpResult::Equal, E);
12682   }
12683 
12684   return DoAfter();
12685 }
12686 
12687 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
12688   if (!CheckLiteralType(Info, E))
12689     return false;
12690 
12691   auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12692     ComparisonCategoryResult CCR;
12693     switch (CR) {
12694     case CmpResult::Unequal:
12695       llvm_unreachable("should never produce Unequal for three-way comparison");
12696     case CmpResult::Less:
12697       CCR = ComparisonCategoryResult::Less;
12698       break;
12699     case CmpResult::Equal:
12700       CCR = ComparisonCategoryResult::Equal;
12701       break;
12702     case CmpResult::Greater:
12703       CCR = ComparisonCategoryResult::Greater;
12704       break;
12705     case CmpResult::Unordered:
12706       CCR = ComparisonCategoryResult::Unordered;
12707       break;
12708     }
12709     // Evaluation succeeded. Lookup the information for the comparison category
12710     // type and fetch the VarDecl for the result.
12711     const ComparisonCategoryInfo &CmpInfo =
12712         Info.Ctx.CompCategories.getInfoForType(E->getType());
12713     const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
12714     // Check and evaluate the result as a constant expression.
12715     LValue LV;
12716     LV.set(VD);
12717     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
12718       return false;
12719     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
12720   };
12721   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12722     return ExprEvaluatorBaseTy::VisitBinCmp(E);
12723   });
12724 }
12725 
12726 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12727   // We don't call noteFailure immediately because the assignment happens after
12728   // we evaluate LHS and RHS.
12729   if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
12730     return Error(E);
12731 
12732   DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
12733   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
12734     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
12735 
12736   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
12737           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
12738          "DataRecursiveIntBinOpEvaluator should have handled integral types");
12739 
12740   if (E->isComparisonOp()) {
12741     // Evaluate builtin binary comparisons by evaluating them as three-way
12742     // comparisons and then translating the result.
12743     auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12744       assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
12745              "should only produce Unequal for equality comparisons");
12746       bool IsEqual   = CR == CmpResult::Equal,
12747            IsLess    = CR == CmpResult::Less,
12748            IsGreater = CR == CmpResult::Greater;
12749       auto Op = E->getOpcode();
12750       switch (Op) {
12751       default:
12752         llvm_unreachable("unsupported binary operator");
12753       case BO_EQ:
12754       case BO_NE:
12755         return Success(IsEqual == (Op == BO_EQ), E);
12756       case BO_LT:
12757         return Success(IsLess, E);
12758       case BO_GT:
12759         return Success(IsGreater, E);
12760       case BO_LE:
12761         return Success(IsEqual || IsLess, E);
12762       case BO_GE:
12763         return Success(IsEqual || IsGreater, E);
12764       }
12765     };
12766     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12767       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12768     });
12769   }
12770 
12771   QualType LHSTy = E->getLHS()->getType();
12772   QualType RHSTy = E->getRHS()->getType();
12773 
12774   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
12775       E->getOpcode() == BO_Sub) {
12776     LValue LHSValue, RHSValue;
12777 
12778     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12779     if (!LHSOK && !Info.noteFailure())
12780       return false;
12781 
12782     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12783       return false;
12784 
12785     // Reject differing bases from the normal codepath; we special-case
12786     // comparisons to null.
12787     if (!HasSameBase(LHSValue, RHSValue)) {
12788       // Handle &&A - &&B.
12789       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
12790         return Error(E);
12791       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
12792       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
12793       if (!LHSExpr || !RHSExpr)
12794         return Error(E);
12795       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12796       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12797       if (!LHSAddrExpr || !RHSAddrExpr)
12798         return Error(E);
12799       // Make sure both labels come from the same function.
12800       if (LHSAddrExpr->getLabel()->getDeclContext() !=
12801           RHSAddrExpr->getLabel()->getDeclContext())
12802         return Error(E);
12803       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
12804     }
12805     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12806     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12807 
12808     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12809     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12810 
12811     // C++11 [expr.add]p6:
12812     //   Unless both pointers point to elements of the same array object, or
12813     //   one past the last element of the array object, the behavior is
12814     //   undefined.
12815     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
12816         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
12817                                 RHSDesignator))
12818       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
12819 
12820     QualType Type = E->getLHS()->getType();
12821     QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
12822 
12823     CharUnits ElementSize;
12824     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
12825       return false;
12826 
12827     // As an extension, a type may have zero size (empty struct or union in
12828     // C, array of zero length). Pointer subtraction in such cases has
12829     // undefined behavior, so is not constant.
12830     if (ElementSize.isZero()) {
12831       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
12832           << ElementType;
12833       return false;
12834     }
12835 
12836     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
12837     // and produce incorrect results when it overflows. Such behavior
12838     // appears to be non-conforming, but is common, so perhaps we should
12839     // assume the standard intended for such cases to be undefined behavior
12840     // and check for them.
12841 
12842     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
12843     // overflow in the final conversion to ptrdiff_t.
12844     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
12845     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
12846     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
12847                     false);
12848     APSInt TrueResult = (LHS - RHS) / ElemSize;
12849     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
12850 
12851     if (Result.extend(65) != TrueResult &&
12852         !HandleOverflow(Info, E, TrueResult, E->getType()))
12853       return false;
12854     return Success(Result, E);
12855   }
12856 
12857   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12858 }
12859 
12860 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
12861 /// a result as the expression's type.
12862 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
12863                                     const UnaryExprOrTypeTraitExpr *E) {
12864   switch(E->getKind()) {
12865   case UETT_PreferredAlignOf:
12866   case UETT_AlignOf: {
12867     if (E->isArgumentType())
12868       return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
12869                      E);
12870     else
12871       return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
12872                      E);
12873   }
12874 
12875   case UETT_VecStep: {
12876     QualType Ty = E->getTypeOfArgument();
12877 
12878     if (Ty->isVectorType()) {
12879       unsigned n = Ty->castAs<VectorType>()->getNumElements();
12880 
12881       // The vec_step built-in functions that take a 3-component
12882       // vector return 4. (OpenCL 1.1 spec 6.11.12)
12883       if (n == 3)
12884         n = 4;
12885 
12886       return Success(n, E);
12887     } else
12888       return Success(1, E);
12889   }
12890 
12891   case UETT_SizeOf: {
12892     QualType SrcTy = E->getTypeOfArgument();
12893     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
12894     //   the result is the size of the referenced type."
12895     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
12896       SrcTy = Ref->getPointeeType();
12897 
12898     CharUnits Sizeof;
12899     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
12900       return false;
12901     return Success(Sizeof, E);
12902   }
12903   case UETT_OpenMPRequiredSimdAlign:
12904     assert(E->isArgumentType());
12905     return Success(
12906         Info.Ctx.toCharUnitsFromBits(
12907                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
12908             .getQuantity(),
12909         E);
12910   }
12911 
12912   llvm_unreachable("unknown expr/type trait");
12913 }
12914 
12915 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
12916   CharUnits Result;
12917   unsigned n = OOE->getNumComponents();
12918   if (n == 0)
12919     return Error(OOE);
12920   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
12921   for (unsigned i = 0; i != n; ++i) {
12922     OffsetOfNode ON = OOE->getComponent(i);
12923     switch (ON.getKind()) {
12924     case OffsetOfNode::Array: {
12925       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
12926       APSInt IdxResult;
12927       if (!EvaluateInteger(Idx, IdxResult, Info))
12928         return false;
12929       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
12930       if (!AT)
12931         return Error(OOE);
12932       CurrentType = AT->getElementType();
12933       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
12934       Result += IdxResult.getSExtValue() * ElementSize;
12935       break;
12936     }
12937 
12938     case OffsetOfNode::Field: {
12939       FieldDecl *MemberDecl = ON.getField();
12940       const RecordType *RT = CurrentType->getAs<RecordType>();
12941       if (!RT)
12942         return Error(OOE);
12943       RecordDecl *RD = RT->getDecl();
12944       if (RD->isInvalidDecl()) return false;
12945       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
12946       unsigned i = MemberDecl->getFieldIndex();
12947       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
12948       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
12949       CurrentType = MemberDecl->getType().getNonReferenceType();
12950       break;
12951     }
12952 
12953     case OffsetOfNode::Identifier:
12954       llvm_unreachable("dependent __builtin_offsetof");
12955 
12956     case OffsetOfNode::Base: {
12957       CXXBaseSpecifier *BaseSpec = ON.getBase();
12958       if (BaseSpec->isVirtual())
12959         return Error(OOE);
12960 
12961       // Find the layout of the class whose base we are looking into.
12962       const RecordType *RT = CurrentType->getAs<RecordType>();
12963       if (!RT)
12964         return Error(OOE);
12965       RecordDecl *RD = RT->getDecl();
12966       if (RD->isInvalidDecl()) return false;
12967       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
12968 
12969       // Find the base class itself.
12970       CurrentType = BaseSpec->getType();
12971       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
12972       if (!BaseRT)
12973         return Error(OOE);
12974 
12975       // Add the offset to the base.
12976       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
12977       break;
12978     }
12979     }
12980   }
12981   return Success(Result, OOE);
12982 }
12983 
12984 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12985   switch (E->getOpcode()) {
12986   default:
12987     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
12988     // See C99 6.6p3.
12989     return Error(E);
12990   case UO_Extension:
12991     // FIXME: Should extension allow i-c-e extension expressions in its scope?
12992     // If so, we could clear the diagnostic ID.
12993     return Visit(E->getSubExpr());
12994   case UO_Plus:
12995     // The result is just the value.
12996     return Visit(E->getSubExpr());
12997   case UO_Minus: {
12998     if (!Visit(E->getSubExpr()))
12999       return false;
13000     if (!Result.isInt()) return Error(E);
13001     const APSInt &Value = Result.getInt();
13002     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
13003         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
13004                         E->getType()))
13005       return false;
13006     return Success(-Value, E);
13007   }
13008   case UO_Not: {
13009     if (!Visit(E->getSubExpr()))
13010       return false;
13011     if (!Result.isInt()) return Error(E);
13012     return Success(~Result.getInt(), E);
13013   }
13014   case UO_LNot: {
13015     bool bres;
13016     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13017       return false;
13018     return Success(!bres, E);
13019   }
13020   }
13021 }
13022 
13023 /// HandleCast - This is used to evaluate implicit or explicit casts where the
13024 /// result type is integer.
13025 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
13026   const Expr *SubExpr = E->getSubExpr();
13027   QualType DestType = E->getType();
13028   QualType SrcType = SubExpr->getType();
13029 
13030   switch (E->getCastKind()) {
13031   case CK_BaseToDerived:
13032   case CK_DerivedToBase:
13033   case CK_UncheckedDerivedToBase:
13034   case CK_Dynamic:
13035   case CK_ToUnion:
13036   case CK_ArrayToPointerDecay:
13037   case CK_FunctionToPointerDecay:
13038   case CK_NullToPointer:
13039   case CK_NullToMemberPointer:
13040   case CK_BaseToDerivedMemberPointer:
13041   case CK_DerivedToBaseMemberPointer:
13042   case CK_ReinterpretMemberPointer:
13043   case CK_ConstructorConversion:
13044   case CK_IntegralToPointer:
13045   case CK_ToVoid:
13046   case CK_VectorSplat:
13047   case CK_IntegralToFloating:
13048   case CK_FloatingCast:
13049   case CK_CPointerToObjCPointerCast:
13050   case CK_BlockPointerToObjCPointerCast:
13051   case CK_AnyPointerToBlockPointerCast:
13052   case CK_ObjCObjectLValueCast:
13053   case CK_FloatingRealToComplex:
13054   case CK_FloatingComplexToReal:
13055   case CK_FloatingComplexCast:
13056   case CK_FloatingComplexToIntegralComplex:
13057   case CK_IntegralRealToComplex:
13058   case CK_IntegralComplexCast:
13059   case CK_IntegralComplexToFloatingComplex:
13060   case CK_BuiltinFnToFnPtr:
13061   case CK_ZeroToOCLOpaqueType:
13062   case CK_NonAtomicToAtomic:
13063   case CK_AddressSpaceConversion:
13064   case CK_IntToOCLSampler:
13065   case CK_FloatingToFixedPoint:
13066   case CK_FixedPointToFloating:
13067   case CK_FixedPointCast:
13068   case CK_IntegralToFixedPoint:
13069     llvm_unreachable("invalid cast kind for integral value");
13070 
13071   case CK_BitCast:
13072   case CK_Dependent:
13073   case CK_LValueBitCast:
13074   case CK_ARCProduceObject:
13075   case CK_ARCConsumeObject:
13076   case CK_ARCReclaimReturnedObject:
13077   case CK_ARCExtendBlockObject:
13078   case CK_CopyAndAutoreleaseBlockObject:
13079     return Error(E);
13080 
13081   case CK_UserDefinedConversion:
13082   case CK_LValueToRValue:
13083   case CK_AtomicToNonAtomic:
13084   case CK_NoOp:
13085   case CK_LValueToRValueBitCast:
13086     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13087 
13088   case CK_MemberPointerToBoolean:
13089   case CK_PointerToBoolean:
13090   case CK_IntegralToBoolean:
13091   case CK_FloatingToBoolean:
13092   case CK_BooleanToSignedIntegral:
13093   case CK_FloatingComplexToBoolean:
13094   case CK_IntegralComplexToBoolean: {
13095     bool BoolResult;
13096     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
13097       return false;
13098     uint64_t IntResult = BoolResult;
13099     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
13100       IntResult = (uint64_t)-1;
13101     return Success(IntResult, E);
13102   }
13103 
13104   case CK_FixedPointToIntegral: {
13105     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
13106     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13107       return false;
13108     bool Overflowed;
13109     llvm::APSInt Result = Src.convertToInt(
13110         Info.Ctx.getIntWidth(DestType),
13111         DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
13112     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
13113       return false;
13114     return Success(Result, E);
13115   }
13116 
13117   case CK_FixedPointToBoolean: {
13118     // Unsigned padding does not affect this.
13119     APValue Val;
13120     if (!Evaluate(Val, Info, SubExpr))
13121       return false;
13122     return Success(Val.getFixedPoint().getBoolValue(), E);
13123   }
13124 
13125   case CK_IntegralCast: {
13126     if (!Visit(SubExpr))
13127       return false;
13128 
13129     if (!Result.isInt()) {
13130       // Allow casts of address-of-label differences if they are no-ops
13131       // or narrowing.  (The narrowing case isn't actually guaranteed to
13132       // be constant-evaluatable except in some narrow cases which are hard
13133       // to detect here.  We let it through on the assumption the user knows
13134       // what they are doing.)
13135       if (Result.isAddrLabelDiff())
13136         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
13137       // Only allow casts of lvalues if they are lossless.
13138       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
13139     }
13140 
13141     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
13142                                       Result.getInt()), E);
13143   }
13144 
13145   case CK_PointerToIntegral: {
13146     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
13147 
13148     LValue LV;
13149     if (!EvaluatePointer(SubExpr, LV, Info))
13150       return false;
13151 
13152     if (LV.getLValueBase()) {
13153       // Only allow based lvalue casts if they are lossless.
13154       // FIXME: Allow a larger integer size than the pointer size, and allow
13155       // narrowing back down to pointer width in subsequent integral casts.
13156       // FIXME: Check integer type's active bits, not its type size.
13157       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
13158         return Error(E);
13159 
13160       LV.Designator.setInvalid();
13161       LV.moveInto(Result);
13162       return true;
13163     }
13164 
13165     APSInt AsInt;
13166     APValue V;
13167     LV.moveInto(V);
13168     if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
13169       llvm_unreachable("Can't cast this!");
13170 
13171     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
13172   }
13173 
13174   case CK_IntegralComplexToReal: {
13175     ComplexValue C;
13176     if (!EvaluateComplex(SubExpr, C, Info))
13177       return false;
13178     return Success(C.getComplexIntReal(), E);
13179   }
13180 
13181   case CK_FloatingToIntegral: {
13182     APFloat F(0.0);
13183     if (!EvaluateFloat(SubExpr, F, Info))
13184       return false;
13185 
13186     APSInt Value;
13187     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
13188       return false;
13189     return Success(Value, E);
13190   }
13191   }
13192 
13193   llvm_unreachable("unknown cast resulting in integral value");
13194 }
13195 
13196 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13197   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13198     ComplexValue LV;
13199     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13200       return false;
13201     if (!LV.isComplexInt())
13202       return Error(E);
13203     return Success(LV.getComplexIntReal(), E);
13204   }
13205 
13206   return Visit(E->getSubExpr());
13207 }
13208 
13209 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13210   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
13211     ComplexValue LV;
13212     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13213       return false;
13214     if (!LV.isComplexInt())
13215       return Error(E);
13216     return Success(LV.getComplexIntImag(), E);
13217   }
13218 
13219   VisitIgnoredValue(E->getSubExpr());
13220   return Success(0, E);
13221 }
13222 
13223 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
13224   return Success(E->getPackLength(), E);
13225 }
13226 
13227 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
13228   return Success(E->getValue(), E);
13229 }
13230 
13231 bool IntExprEvaluator::VisitConceptSpecializationExpr(
13232        const ConceptSpecializationExpr *E) {
13233   return Success(E->isSatisfied(), E);
13234 }
13235 
13236 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
13237   return Success(E->isSatisfied(), E);
13238 }
13239 
13240 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13241   switch (E->getOpcode()) {
13242     default:
13243       // Invalid unary operators
13244       return Error(E);
13245     case UO_Plus:
13246       // The result is just the value.
13247       return Visit(E->getSubExpr());
13248     case UO_Minus: {
13249       if (!Visit(E->getSubExpr())) return false;
13250       if (!Result.isFixedPoint())
13251         return Error(E);
13252       bool Overflowed;
13253       APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
13254       if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
13255         return false;
13256       return Success(Negated, E);
13257     }
13258     case UO_LNot: {
13259       bool bres;
13260       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13261         return false;
13262       return Success(!bres, E);
13263     }
13264   }
13265 }
13266 
13267 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
13268   const Expr *SubExpr = E->getSubExpr();
13269   QualType DestType = E->getType();
13270   assert(DestType->isFixedPointType() &&
13271          "Expected destination type to be a fixed point type");
13272   auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
13273 
13274   switch (E->getCastKind()) {
13275   case CK_FixedPointCast: {
13276     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13277     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13278       return false;
13279     bool Overflowed;
13280     APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
13281     if (Overflowed) {
13282       if (Info.checkingForUndefinedBehavior())
13283         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13284                                          diag::warn_fixedpoint_constant_overflow)
13285           << Result.toString() << E->getType();
13286       else if (!HandleOverflow(Info, E, Result, E->getType()))
13287         return false;
13288     }
13289     return Success(Result, E);
13290   }
13291   case CK_IntegralToFixedPoint: {
13292     APSInt Src;
13293     if (!EvaluateInteger(SubExpr, Src, Info))
13294       return false;
13295 
13296     bool Overflowed;
13297     APFixedPoint IntResult = APFixedPoint::getFromIntValue(
13298         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13299 
13300     if (Overflowed) {
13301       if (Info.checkingForUndefinedBehavior())
13302         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13303                                          diag::warn_fixedpoint_constant_overflow)
13304           << IntResult.toString() << E->getType();
13305       else if (!HandleOverflow(Info, E, IntResult, E->getType()))
13306         return false;
13307     }
13308 
13309     return Success(IntResult, E);
13310   }
13311   case CK_FloatingToFixedPoint: {
13312     APFloat Src(0.0);
13313     if (!EvaluateFloat(SubExpr, Src, Info))
13314       return false;
13315 
13316     bool Overflowed;
13317     APFixedPoint Result = APFixedPoint::getFromFloatValue(
13318         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13319 
13320     if (Overflowed) {
13321       if (Info.checkingForUndefinedBehavior())
13322         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13323                                          diag::warn_fixedpoint_constant_overflow)
13324           << Result.toString() << E->getType();
13325       else if (!HandleOverflow(Info, E, Result, E->getType()))
13326         return false;
13327     }
13328 
13329     return Success(Result, E);
13330   }
13331   case CK_NoOp:
13332   case CK_LValueToRValue:
13333     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13334   default:
13335     return Error(E);
13336   }
13337 }
13338 
13339 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13340   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13341     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13342 
13343   const Expr *LHS = E->getLHS();
13344   const Expr *RHS = E->getRHS();
13345   FixedPointSemantics ResultFXSema =
13346       Info.Ctx.getFixedPointSemantics(E->getType());
13347 
13348   APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
13349   if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
13350     return false;
13351   APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
13352   if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
13353     return false;
13354 
13355   bool OpOverflow = false, ConversionOverflow = false;
13356   APFixedPoint Result(LHSFX.getSemantics());
13357   switch (E->getOpcode()) {
13358   case BO_Add: {
13359     Result = LHSFX.add(RHSFX, &OpOverflow)
13360                   .convert(ResultFXSema, &ConversionOverflow);
13361     break;
13362   }
13363   case BO_Sub: {
13364     Result = LHSFX.sub(RHSFX, &OpOverflow)
13365                   .convert(ResultFXSema, &ConversionOverflow);
13366     break;
13367   }
13368   case BO_Mul: {
13369     Result = LHSFX.mul(RHSFX, &OpOverflow)
13370                   .convert(ResultFXSema, &ConversionOverflow);
13371     break;
13372   }
13373   case BO_Div: {
13374     if (RHSFX.getValue() == 0) {
13375       Info.FFDiag(E, diag::note_expr_divide_by_zero);
13376       return false;
13377     }
13378     Result = LHSFX.div(RHSFX, &OpOverflow)
13379                   .convert(ResultFXSema, &ConversionOverflow);
13380     break;
13381   }
13382   case BO_Shl:
13383   case BO_Shr: {
13384     FixedPointSemantics LHSSema = LHSFX.getSemantics();
13385     llvm::APSInt RHSVal = RHSFX.getValue();
13386 
13387     unsigned ShiftBW =
13388         LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
13389     unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
13390     // Embedded-C 4.1.6.2.2:
13391     //   The right operand must be nonnegative and less than the total number
13392     //   of (nonpadding) bits of the fixed-point operand ...
13393     if (RHSVal.isNegative())
13394       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
13395     else if (Amt != RHSVal)
13396       Info.CCEDiag(E, diag::note_constexpr_large_shift)
13397           << RHSVal << E->getType() << ShiftBW;
13398 
13399     if (E->getOpcode() == BO_Shl)
13400       Result = LHSFX.shl(Amt, &OpOverflow);
13401     else
13402       Result = LHSFX.shr(Amt, &OpOverflow);
13403     break;
13404   }
13405   default:
13406     return false;
13407   }
13408   if (OpOverflow || ConversionOverflow) {
13409     if (Info.checkingForUndefinedBehavior())
13410       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13411                                        diag::warn_fixedpoint_constant_overflow)
13412         << Result.toString() << E->getType();
13413     else if (!HandleOverflow(Info, E, Result, E->getType()))
13414       return false;
13415   }
13416   return Success(Result, E);
13417 }
13418 
13419 //===----------------------------------------------------------------------===//
13420 // Float Evaluation
13421 //===----------------------------------------------------------------------===//
13422 
13423 namespace {
13424 class FloatExprEvaluator
13425   : public ExprEvaluatorBase<FloatExprEvaluator> {
13426   APFloat &Result;
13427 public:
13428   FloatExprEvaluator(EvalInfo &info, APFloat &result)
13429     : ExprEvaluatorBaseTy(info), Result(result) {}
13430 
13431   bool Success(const APValue &V, const Expr *e) {
13432     Result = V.getFloat();
13433     return true;
13434   }
13435 
13436   bool ZeroInitialization(const Expr *E) {
13437     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
13438     return true;
13439   }
13440 
13441   bool VisitCallExpr(const CallExpr *E);
13442 
13443   bool VisitUnaryOperator(const UnaryOperator *E);
13444   bool VisitBinaryOperator(const BinaryOperator *E);
13445   bool VisitFloatingLiteral(const FloatingLiteral *E);
13446   bool VisitCastExpr(const CastExpr *E);
13447 
13448   bool VisitUnaryReal(const UnaryOperator *E);
13449   bool VisitUnaryImag(const UnaryOperator *E);
13450 
13451   // FIXME: Missing: array subscript of vector, member of vector
13452 };
13453 } // end anonymous namespace
13454 
13455 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
13456   assert(E->isRValue() && E->getType()->isRealFloatingType());
13457   return FloatExprEvaluator(Info, Result).Visit(E);
13458 }
13459 
13460 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
13461                                   QualType ResultTy,
13462                                   const Expr *Arg,
13463                                   bool SNaN,
13464                                   llvm::APFloat &Result) {
13465   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
13466   if (!S) return false;
13467 
13468   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
13469 
13470   llvm::APInt fill;
13471 
13472   // Treat empty strings as if they were zero.
13473   if (S->getString().empty())
13474     fill = llvm::APInt(32, 0);
13475   else if (S->getString().getAsInteger(0, fill))
13476     return false;
13477 
13478   if (Context.getTargetInfo().isNan2008()) {
13479     if (SNaN)
13480       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13481     else
13482       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13483   } else {
13484     // Prior to IEEE 754-2008, architectures were allowed to choose whether
13485     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
13486     // a different encoding to what became a standard in 2008, and for pre-
13487     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
13488     // sNaN. This is now known as "legacy NaN" encoding.
13489     if (SNaN)
13490       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13491     else
13492       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13493   }
13494 
13495   return true;
13496 }
13497 
13498 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
13499   switch (E->getBuiltinCallee()) {
13500   default:
13501     return ExprEvaluatorBaseTy::VisitCallExpr(E);
13502 
13503   case Builtin::BI__builtin_huge_val:
13504   case Builtin::BI__builtin_huge_valf:
13505   case Builtin::BI__builtin_huge_vall:
13506   case Builtin::BI__builtin_huge_valf128:
13507   case Builtin::BI__builtin_inf:
13508   case Builtin::BI__builtin_inff:
13509   case Builtin::BI__builtin_infl:
13510   case Builtin::BI__builtin_inff128: {
13511     const llvm::fltSemantics &Sem =
13512       Info.Ctx.getFloatTypeSemantics(E->getType());
13513     Result = llvm::APFloat::getInf(Sem);
13514     return true;
13515   }
13516 
13517   case Builtin::BI__builtin_nans:
13518   case Builtin::BI__builtin_nansf:
13519   case Builtin::BI__builtin_nansl:
13520   case Builtin::BI__builtin_nansf128:
13521     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13522                                true, Result))
13523       return Error(E);
13524     return true;
13525 
13526   case Builtin::BI__builtin_nan:
13527   case Builtin::BI__builtin_nanf:
13528   case Builtin::BI__builtin_nanl:
13529   case Builtin::BI__builtin_nanf128:
13530     // If this is __builtin_nan() turn this into a nan, otherwise we
13531     // can't constant fold it.
13532     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13533                                false, Result))
13534       return Error(E);
13535     return true;
13536 
13537   case Builtin::BI__builtin_fabs:
13538   case Builtin::BI__builtin_fabsf:
13539   case Builtin::BI__builtin_fabsl:
13540   case Builtin::BI__builtin_fabsf128:
13541     if (!EvaluateFloat(E->getArg(0), Result, Info))
13542       return false;
13543 
13544     if (Result.isNegative())
13545       Result.changeSign();
13546     return true;
13547 
13548   // FIXME: Builtin::BI__builtin_powi
13549   // FIXME: Builtin::BI__builtin_powif
13550   // FIXME: Builtin::BI__builtin_powil
13551 
13552   case Builtin::BI__builtin_copysign:
13553   case Builtin::BI__builtin_copysignf:
13554   case Builtin::BI__builtin_copysignl:
13555   case Builtin::BI__builtin_copysignf128: {
13556     APFloat RHS(0.);
13557     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
13558         !EvaluateFloat(E->getArg(1), RHS, Info))
13559       return false;
13560     Result.copySign(RHS);
13561     return true;
13562   }
13563   }
13564 }
13565 
13566 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13567   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13568     ComplexValue CV;
13569     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13570       return false;
13571     Result = CV.FloatReal;
13572     return true;
13573   }
13574 
13575   return Visit(E->getSubExpr());
13576 }
13577 
13578 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13579   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13580     ComplexValue CV;
13581     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13582       return false;
13583     Result = CV.FloatImag;
13584     return true;
13585   }
13586 
13587   VisitIgnoredValue(E->getSubExpr());
13588   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
13589   Result = llvm::APFloat::getZero(Sem);
13590   return true;
13591 }
13592 
13593 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13594   switch (E->getOpcode()) {
13595   default: return Error(E);
13596   case UO_Plus:
13597     return EvaluateFloat(E->getSubExpr(), Result, Info);
13598   case UO_Minus:
13599     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
13600       return false;
13601     Result.changeSign();
13602     return true;
13603   }
13604 }
13605 
13606 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13607   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13608     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13609 
13610   APFloat RHS(0.0);
13611   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
13612   if (!LHSOK && !Info.noteFailure())
13613     return false;
13614   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
13615          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
13616 }
13617 
13618 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
13619   Result = E->getValue();
13620   return true;
13621 }
13622 
13623 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
13624   const Expr* SubExpr = E->getSubExpr();
13625 
13626   switch (E->getCastKind()) {
13627   default:
13628     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13629 
13630   case CK_IntegralToFloating: {
13631     APSInt IntResult;
13632     return EvaluateInteger(SubExpr, IntResult, Info) &&
13633            HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
13634                                 E->getType(), Result);
13635   }
13636 
13637   case CK_FixedPointToFloating: {
13638     APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13639     if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
13640       return false;
13641     Result =
13642         FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
13643     return true;
13644   }
13645 
13646   case CK_FloatingCast: {
13647     if (!Visit(SubExpr))
13648       return false;
13649     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
13650                                   Result);
13651   }
13652 
13653   case CK_FloatingComplexToReal: {
13654     ComplexValue V;
13655     if (!EvaluateComplex(SubExpr, V, Info))
13656       return false;
13657     Result = V.getComplexFloatReal();
13658     return true;
13659   }
13660   }
13661 }
13662 
13663 //===----------------------------------------------------------------------===//
13664 // Complex Evaluation (for float and integer)
13665 //===----------------------------------------------------------------------===//
13666 
13667 namespace {
13668 class ComplexExprEvaluator
13669   : public ExprEvaluatorBase<ComplexExprEvaluator> {
13670   ComplexValue &Result;
13671 
13672 public:
13673   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
13674     : ExprEvaluatorBaseTy(info), Result(Result) {}
13675 
13676   bool Success(const APValue &V, const Expr *e) {
13677     Result.setFrom(V);
13678     return true;
13679   }
13680 
13681   bool ZeroInitialization(const Expr *E);
13682 
13683   //===--------------------------------------------------------------------===//
13684   //                            Visitor Methods
13685   //===--------------------------------------------------------------------===//
13686 
13687   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
13688   bool VisitCastExpr(const CastExpr *E);
13689   bool VisitBinaryOperator(const BinaryOperator *E);
13690   bool VisitUnaryOperator(const UnaryOperator *E);
13691   bool VisitInitListExpr(const InitListExpr *E);
13692   bool VisitCallExpr(const CallExpr *E);
13693 };
13694 } // end anonymous namespace
13695 
13696 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
13697                             EvalInfo &Info) {
13698   assert(E->isRValue() && E->getType()->isAnyComplexType());
13699   return ComplexExprEvaluator(Info, Result).Visit(E);
13700 }
13701 
13702 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
13703   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
13704   if (ElemTy->isRealFloatingType()) {
13705     Result.makeComplexFloat();
13706     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
13707     Result.FloatReal = Zero;
13708     Result.FloatImag = Zero;
13709   } else {
13710     Result.makeComplexInt();
13711     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
13712     Result.IntReal = Zero;
13713     Result.IntImag = Zero;
13714   }
13715   return true;
13716 }
13717 
13718 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
13719   const Expr* SubExpr = E->getSubExpr();
13720 
13721   if (SubExpr->getType()->isRealFloatingType()) {
13722     Result.makeComplexFloat();
13723     APFloat &Imag = Result.FloatImag;
13724     if (!EvaluateFloat(SubExpr, Imag, Info))
13725       return false;
13726 
13727     Result.FloatReal = APFloat(Imag.getSemantics());
13728     return true;
13729   } else {
13730     assert(SubExpr->getType()->isIntegerType() &&
13731            "Unexpected imaginary literal.");
13732 
13733     Result.makeComplexInt();
13734     APSInt &Imag = Result.IntImag;
13735     if (!EvaluateInteger(SubExpr, Imag, Info))
13736       return false;
13737 
13738     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
13739     return true;
13740   }
13741 }
13742 
13743 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
13744 
13745   switch (E->getCastKind()) {
13746   case CK_BitCast:
13747   case CK_BaseToDerived:
13748   case CK_DerivedToBase:
13749   case CK_UncheckedDerivedToBase:
13750   case CK_Dynamic:
13751   case CK_ToUnion:
13752   case CK_ArrayToPointerDecay:
13753   case CK_FunctionToPointerDecay:
13754   case CK_NullToPointer:
13755   case CK_NullToMemberPointer:
13756   case CK_BaseToDerivedMemberPointer:
13757   case CK_DerivedToBaseMemberPointer:
13758   case CK_MemberPointerToBoolean:
13759   case CK_ReinterpretMemberPointer:
13760   case CK_ConstructorConversion:
13761   case CK_IntegralToPointer:
13762   case CK_PointerToIntegral:
13763   case CK_PointerToBoolean:
13764   case CK_ToVoid:
13765   case CK_VectorSplat:
13766   case CK_IntegralCast:
13767   case CK_BooleanToSignedIntegral:
13768   case CK_IntegralToBoolean:
13769   case CK_IntegralToFloating:
13770   case CK_FloatingToIntegral:
13771   case CK_FloatingToBoolean:
13772   case CK_FloatingCast:
13773   case CK_CPointerToObjCPointerCast:
13774   case CK_BlockPointerToObjCPointerCast:
13775   case CK_AnyPointerToBlockPointerCast:
13776   case CK_ObjCObjectLValueCast:
13777   case CK_FloatingComplexToReal:
13778   case CK_FloatingComplexToBoolean:
13779   case CK_IntegralComplexToReal:
13780   case CK_IntegralComplexToBoolean:
13781   case CK_ARCProduceObject:
13782   case CK_ARCConsumeObject:
13783   case CK_ARCReclaimReturnedObject:
13784   case CK_ARCExtendBlockObject:
13785   case CK_CopyAndAutoreleaseBlockObject:
13786   case CK_BuiltinFnToFnPtr:
13787   case CK_ZeroToOCLOpaqueType:
13788   case CK_NonAtomicToAtomic:
13789   case CK_AddressSpaceConversion:
13790   case CK_IntToOCLSampler:
13791   case CK_FloatingToFixedPoint:
13792   case CK_FixedPointToFloating:
13793   case CK_FixedPointCast:
13794   case CK_FixedPointToBoolean:
13795   case CK_FixedPointToIntegral:
13796   case CK_IntegralToFixedPoint:
13797     llvm_unreachable("invalid cast kind for complex value");
13798 
13799   case CK_LValueToRValue:
13800   case CK_AtomicToNonAtomic:
13801   case CK_NoOp:
13802   case CK_LValueToRValueBitCast:
13803     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13804 
13805   case CK_Dependent:
13806   case CK_LValueBitCast:
13807   case CK_UserDefinedConversion:
13808     return Error(E);
13809 
13810   case CK_FloatingRealToComplex: {
13811     APFloat &Real = Result.FloatReal;
13812     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
13813       return false;
13814 
13815     Result.makeComplexFloat();
13816     Result.FloatImag = APFloat(Real.getSemantics());
13817     return true;
13818   }
13819 
13820   case CK_FloatingComplexCast: {
13821     if (!Visit(E->getSubExpr()))
13822       return false;
13823 
13824     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13825     QualType From
13826       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13827 
13828     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
13829            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
13830   }
13831 
13832   case CK_FloatingComplexToIntegralComplex: {
13833     if (!Visit(E->getSubExpr()))
13834       return false;
13835 
13836     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13837     QualType From
13838       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13839     Result.makeComplexInt();
13840     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
13841                                 To, Result.IntReal) &&
13842            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
13843                                 To, Result.IntImag);
13844   }
13845 
13846   case CK_IntegralRealToComplex: {
13847     APSInt &Real = Result.IntReal;
13848     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
13849       return false;
13850 
13851     Result.makeComplexInt();
13852     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
13853     return true;
13854   }
13855 
13856   case CK_IntegralComplexCast: {
13857     if (!Visit(E->getSubExpr()))
13858       return false;
13859 
13860     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13861     QualType From
13862       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13863 
13864     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
13865     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
13866     return true;
13867   }
13868 
13869   case CK_IntegralComplexToFloatingComplex: {
13870     if (!Visit(E->getSubExpr()))
13871       return false;
13872 
13873     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13874     QualType From
13875       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13876     Result.makeComplexFloat();
13877     return HandleIntToFloatCast(Info, E, From, Result.IntReal,
13878                                 To, Result.FloatReal) &&
13879            HandleIntToFloatCast(Info, E, From, Result.IntImag,
13880                                 To, Result.FloatImag);
13881   }
13882   }
13883 
13884   llvm_unreachable("unknown cast resulting in complex value");
13885 }
13886 
13887 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13888   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13889     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13890 
13891   // Track whether the LHS or RHS is real at the type system level. When this is
13892   // the case we can simplify our evaluation strategy.
13893   bool LHSReal = false, RHSReal = false;
13894 
13895   bool LHSOK;
13896   if (E->getLHS()->getType()->isRealFloatingType()) {
13897     LHSReal = true;
13898     APFloat &Real = Result.FloatReal;
13899     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
13900     if (LHSOK) {
13901       Result.makeComplexFloat();
13902       Result.FloatImag = APFloat(Real.getSemantics());
13903     }
13904   } else {
13905     LHSOK = Visit(E->getLHS());
13906   }
13907   if (!LHSOK && !Info.noteFailure())
13908     return false;
13909 
13910   ComplexValue RHS;
13911   if (E->getRHS()->getType()->isRealFloatingType()) {
13912     RHSReal = true;
13913     APFloat &Real = RHS.FloatReal;
13914     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
13915       return false;
13916     RHS.makeComplexFloat();
13917     RHS.FloatImag = APFloat(Real.getSemantics());
13918   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
13919     return false;
13920 
13921   assert(!(LHSReal && RHSReal) &&
13922          "Cannot have both operands of a complex operation be real.");
13923   switch (E->getOpcode()) {
13924   default: return Error(E);
13925   case BO_Add:
13926     if (Result.isComplexFloat()) {
13927       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
13928                                        APFloat::rmNearestTiesToEven);
13929       if (LHSReal)
13930         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
13931       else if (!RHSReal)
13932         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
13933                                          APFloat::rmNearestTiesToEven);
13934     } else {
13935       Result.getComplexIntReal() += RHS.getComplexIntReal();
13936       Result.getComplexIntImag() += RHS.getComplexIntImag();
13937     }
13938     break;
13939   case BO_Sub:
13940     if (Result.isComplexFloat()) {
13941       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
13942                                             APFloat::rmNearestTiesToEven);
13943       if (LHSReal) {
13944         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
13945         Result.getComplexFloatImag().changeSign();
13946       } else if (!RHSReal) {
13947         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
13948                                               APFloat::rmNearestTiesToEven);
13949       }
13950     } else {
13951       Result.getComplexIntReal() -= RHS.getComplexIntReal();
13952       Result.getComplexIntImag() -= RHS.getComplexIntImag();
13953     }
13954     break;
13955   case BO_Mul:
13956     if (Result.isComplexFloat()) {
13957       // This is an implementation of complex multiplication according to the
13958       // constraints laid out in C11 Annex G. The implementation uses the
13959       // following naming scheme:
13960       //   (a + ib) * (c + id)
13961       ComplexValue LHS = Result;
13962       APFloat &A = LHS.getComplexFloatReal();
13963       APFloat &B = LHS.getComplexFloatImag();
13964       APFloat &C = RHS.getComplexFloatReal();
13965       APFloat &D = RHS.getComplexFloatImag();
13966       APFloat &ResR = Result.getComplexFloatReal();
13967       APFloat &ResI = Result.getComplexFloatImag();
13968       if (LHSReal) {
13969         assert(!RHSReal && "Cannot have two real operands for a complex op!");
13970         ResR = A * C;
13971         ResI = A * D;
13972       } else if (RHSReal) {
13973         ResR = C * A;
13974         ResI = C * B;
13975       } else {
13976         // In the fully general case, we need to handle NaNs and infinities
13977         // robustly.
13978         APFloat AC = A * C;
13979         APFloat BD = B * D;
13980         APFloat AD = A * D;
13981         APFloat BC = B * C;
13982         ResR = AC - BD;
13983         ResI = AD + BC;
13984         if (ResR.isNaN() && ResI.isNaN()) {
13985           bool Recalc = false;
13986           if (A.isInfinity() || B.isInfinity()) {
13987             A = APFloat::copySign(
13988                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
13989             B = APFloat::copySign(
13990                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
13991             if (C.isNaN())
13992               C = APFloat::copySign(APFloat(C.getSemantics()), C);
13993             if (D.isNaN())
13994               D = APFloat::copySign(APFloat(D.getSemantics()), D);
13995             Recalc = true;
13996           }
13997           if (C.isInfinity() || D.isInfinity()) {
13998             C = APFloat::copySign(
13999                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14000             D = APFloat::copySign(
14001                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14002             if (A.isNaN())
14003               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14004             if (B.isNaN())
14005               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14006             Recalc = true;
14007           }
14008           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
14009                           AD.isInfinity() || BC.isInfinity())) {
14010             if (A.isNaN())
14011               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14012             if (B.isNaN())
14013               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14014             if (C.isNaN())
14015               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14016             if (D.isNaN())
14017               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14018             Recalc = true;
14019           }
14020           if (Recalc) {
14021             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
14022             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
14023           }
14024         }
14025       }
14026     } else {
14027       ComplexValue LHS = Result;
14028       Result.getComplexIntReal() =
14029         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
14030          LHS.getComplexIntImag() * RHS.getComplexIntImag());
14031       Result.getComplexIntImag() =
14032         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
14033          LHS.getComplexIntImag() * RHS.getComplexIntReal());
14034     }
14035     break;
14036   case BO_Div:
14037     if (Result.isComplexFloat()) {
14038       // This is an implementation of complex division according to the
14039       // constraints laid out in C11 Annex G. The implementation uses the
14040       // following naming scheme:
14041       //   (a + ib) / (c + id)
14042       ComplexValue LHS = Result;
14043       APFloat &A = LHS.getComplexFloatReal();
14044       APFloat &B = LHS.getComplexFloatImag();
14045       APFloat &C = RHS.getComplexFloatReal();
14046       APFloat &D = RHS.getComplexFloatImag();
14047       APFloat &ResR = Result.getComplexFloatReal();
14048       APFloat &ResI = Result.getComplexFloatImag();
14049       if (RHSReal) {
14050         ResR = A / C;
14051         ResI = B / C;
14052       } else {
14053         if (LHSReal) {
14054           // No real optimizations we can do here, stub out with zero.
14055           B = APFloat::getZero(A.getSemantics());
14056         }
14057         int DenomLogB = 0;
14058         APFloat MaxCD = maxnum(abs(C), abs(D));
14059         if (MaxCD.isFinite()) {
14060           DenomLogB = ilogb(MaxCD);
14061           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
14062           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
14063         }
14064         APFloat Denom = C * C + D * D;
14065         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
14066                       APFloat::rmNearestTiesToEven);
14067         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
14068                       APFloat::rmNearestTiesToEven);
14069         if (ResR.isNaN() && ResI.isNaN()) {
14070           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
14071             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
14072             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
14073           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
14074                      D.isFinite()) {
14075             A = APFloat::copySign(
14076                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14077             B = APFloat::copySign(
14078                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14079             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
14080             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
14081           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
14082             C = APFloat::copySign(
14083                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14084             D = APFloat::copySign(
14085                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14086             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
14087             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
14088           }
14089         }
14090       }
14091     } else {
14092       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
14093         return Error(E, diag::note_expr_divide_by_zero);
14094 
14095       ComplexValue LHS = Result;
14096       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
14097         RHS.getComplexIntImag() * RHS.getComplexIntImag();
14098       Result.getComplexIntReal() =
14099         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
14100          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
14101       Result.getComplexIntImag() =
14102         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
14103          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
14104     }
14105     break;
14106   }
14107 
14108   return true;
14109 }
14110 
14111 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14112   // Get the operand value into 'Result'.
14113   if (!Visit(E->getSubExpr()))
14114     return false;
14115 
14116   switch (E->getOpcode()) {
14117   default:
14118     return Error(E);
14119   case UO_Extension:
14120     return true;
14121   case UO_Plus:
14122     // The result is always just the subexpr.
14123     return true;
14124   case UO_Minus:
14125     if (Result.isComplexFloat()) {
14126       Result.getComplexFloatReal().changeSign();
14127       Result.getComplexFloatImag().changeSign();
14128     }
14129     else {
14130       Result.getComplexIntReal() = -Result.getComplexIntReal();
14131       Result.getComplexIntImag() = -Result.getComplexIntImag();
14132     }
14133     return true;
14134   case UO_Not:
14135     if (Result.isComplexFloat())
14136       Result.getComplexFloatImag().changeSign();
14137     else
14138       Result.getComplexIntImag() = -Result.getComplexIntImag();
14139     return true;
14140   }
14141 }
14142 
14143 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
14144   if (E->getNumInits() == 2) {
14145     if (E->getType()->isComplexType()) {
14146       Result.makeComplexFloat();
14147       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
14148         return false;
14149       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
14150         return false;
14151     } else {
14152       Result.makeComplexInt();
14153       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
14154         return false;
14155       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
14156         return false;
14157     }
14158     return true;
14159   }
14160   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
14161 }
14162 
14163 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
14164   switch (E->getBuiltinCallee()) {
14165   case Builtin::BI__builtin_complex:
14166     Result.makeComplexFloat();
14167     if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
14168       return false;
14169     if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
14170       return false;
14171     return true;
14172 
14173   default:
14174     break;
14175   }
14176 
14177   return ExprEvaluatorBaseTy::VisitCallExpr(E);
14178 }
14179 
14180 //===----------------------------------------------------------------------===//
14181 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
14182 // implicit conversion.
14183 //===----------------------------------------------------------------------===//
14184 
14185 namespace {
14186 class AtomicExprEvaluator :
14187     public ExprEvaluatorBase<AtomicExprEvaluator> {
14188   const LValue *This;
14189   APValue &Result;
14190 public:
14191   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
14192       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
14193 
14194   bool Success(const APValue &V, const Expr *E) {
14195     Result = V;
14196     return true;
14197   }
14198 
14199   bool ZeroInitialization(const Expr *E) {
14200     ImplicitValueInitExpr VIE(
14201         E->getType()->castAs<AtomicType>()->getValueType());
14202     // For atomic-qualified class (and array) types in C++, initialize the
14203     // _Atomic-wrapped subobject directly, in-place.
14204     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
14205                 : Evaluate(Result, Info, &VIE);
14206   }
14207 
14208   bool VisitCastExpr(const CastExpr *E) {
14209     switch (E->getCastKind()) {
14210     default:
14211       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14212     case CK_NonAtomicToAtomic:
14213       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
14214                   : Evaluate(Result, Info, E->getSubExpr());
14215     }
14216   }
14217 };
14218 } // end anonymous namespace
14219 
14220 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
14221                            EvalInfo &Info) {
14222   assert(E->isRValue() && E->getType()->isAtomicType());
14223   return AtomicExprEvaluator(Info, This, Result).Visit(E);
14224 }
14225 
14226 //===----------------------------------------------------------------------===//
14227 // Void expression evaluation, primarily for a cast to void on the LHS of a
14228 // comma operator
14229 //===----------------------------------------------------------------------===//
14230 
14231 namespace {
14232 class VoidExprEvaluator
14233   : public ExprEvaluatorBase<VoidExprEvaluator> {
14234 public:
14235   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
14236 
14237   bool Success(const APValue &V, const Expr *e) { return true; }
14238 
14239   bool ZeroInitialization(const Expr *E) { return true; }
14240 
14241   bool VisitCastExpr(const CastExpr *E) {
14242     switch (E->getCastKind()) {
14243     default:
14244       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14245     case CK_ToVoid:
14246       VisitIgnoredValue(E->getSubExpr());
14247       return true;
14248     }
14249   }
14250 
14251   bool VisitCallExpr(const CallExpr *E) {
14252     switch (E->getBuiltinCallee()) {
14253     case Builtin::BI__assume:
14254     case Builtin::BI__builtin_assume:
14255       // The argument is not evaluated!
14256       return true;
14257 
14258     case Builtin::BI__builtin_operator_delete:
14259       return HandleOperatorDeleteCall(Info, E);
14260 
14261     default:
14262       break;
14263     }
14264 
14265     return ExprEvaluatorBaseTy::VisitCallExpr(E);
14266   }
14267 
14268   bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
14269 };
14270 } // end anonymous namespace
14271 
14272 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
14273   // We cannot speculatively evaluate a delete expression.
14274   if (Info.SpeculativeEvaluationDepth)
14275     return false;
14276 
14277   FunctionDecl *OperatorDelete = E->getOperatorDelete();
14278   if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
14279     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14280         << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
14281     return false;
14282   }
14283 
14284   const Expr *Arg = E->getArgument();
14285 
14286   LValue Pointer;
14287   if (!EvaluatePointer(Arg, Pointer, Info))
14288     return false;
14289   if (Pointer.Designator.Invalid)
14290     return false;
14291 
14292   // Deleting a null pointer has no effect.
14293   if (Pointer.isNullPointer()) {
14294     // This is the only case where we need to produce an extension warning:
14295     // the only other way we can succeed is if we find a dynamic allocation,
14296     // and we will have warned when we allocated it in that case.
14297     if (!Info.getLangOpts().CPlusPlus20)
14298       Info.CCEDiag(E, diag::note_constexpr_new);
14299     return true;
14300   }
14301 
14302   Optional<DynAlloc *> Alloc = CheckDeleteKind(
14303       Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
14304   if (!Alloc)
14305     return false;
14306   QualType AllocType = Pointer.Base.getDynamicAllocType();
14307 
14308   // For the non-array case, the designator must be empty if the static type
14309   // does not have a virtual destructor.
14310   if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
14311       !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
14312     Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
14313         << Arg->getType()->getPointeeType() << AllocType;
14314     return false;
14315   }
14316 
14317   // For a class type with a virtual destructor, the selected operator delete
14318   // is the one looked up when building the destructor.
14319   if (!E->isArrayForm() && !E->isGlobalDelete()) {
14320     const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
14321     if (VirtualDelete &&
14322         !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
14323       Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14324           << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
14325       return false;
14326     }
14327   }
14328 
14329   if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
14330                          (*Alloc)->Value, AllocType))
14331     return false;
14332 
14333   if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
14334     // The element was already erased. This means the destructor call also
14335     // deleted the object.
14336     // FIXME: This probably results in undefined behavior before we get this
14337     // far, and should be diagnosed elsewhere first.
14338     Info.FFDiag(E, diag::note_constexpr_double_delete);
14339     return false;
14340   }
14341 
14342   return true;
14343 }
14344 
14345 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
14346   assert(E->isRValue() && E->getType()->isVoidType());
14347   return VoidExprEvaluator(Info).Visit(E);
14348 }
14349 
14350 //===----------------------------------------------------------------------===//
14351 // Top level Expr::EvaluateAsRValue method.
14352 //===----------------------------------------------------------------------===//
14353 
14354 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
14355   // In C, function designators are not lvalues, but we evaluate them as if they
14356   // are.
14357   QualType T = E->getType();
14358   if (E->isGLValue() || T->isFunctionType()) {
14359     LValue LV;
14360     if (!EvaluateLValue(E, LV, Info))
14361       return false;
14362     LV.moveInto(Result);
14363   } else if (T->isVectorType()) {
14364     if (!EvaluateVector(E, Result, Info))
14365       return false;
14366   } else if (T->isIntegralOrEnumerationType()) {
14367     if (!IntExprEvaluator(Info, Result).Visit(E))
14368       return false;
14369   } else if (T->hasPointerRepresentation()) {
14370     LValue LV;
14371     if (!EvaluatePointer(E, LV, Info))
14372       return false;
14373     LV.moveInto(Result);
14374   } else if (T->isRealFloatingType()) {
14375     llvm::APFloat F(0.0);
14376     if (!EvaluateFloat(E, F, Info))
14377       return false;
14378     Result = APValue(F);
14379   } else if (T->isAnyComplexType()) {
14380     ComplexValue C;
14381     if (!EvaluateComplex(E, C, Info))
14382       return false;
14383     C.moveInto(Result);
14384   } else if (T->isFixedPointType()) {
14385     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
14386   } else if (T->isMemberPointerType()) {
14387     MemberPtr P;
14388     if (!EvaluateMemberPointer(E, P, Info))
14389       return false;
14390     P.moveInto(Result);
14391     return true;
14392   } else if (T->isArrayType()) {
14393     LValue LV;
14394     APValue &Value =
14395         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14396     if (!EvaluateArray(E, LV, Value, Info))
14397       return false;
14398     Result = Value;
14399   } else if (T->isRecordType()) {
14400     LValue LV;
14401     APValue &Value =
14402         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14403     if (!EvaluateRecord(E, LV, Value, Info))
14404       return false;
14405     Result = Value;
14406   } else if (T->isVoidType()) {
14407     if (!Info.getLangOpts().CPlusPlus11)
14408       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
14409         << E->getType();
14410     if (!EvaluateVoid(E, Info))
14411       return false;
14412   } else if (T->isAtomicType()) {
14413     QualType Unqual = T.getAtomicUnqualifiedType();
14414     if (Unqual->isArrayType() || Unqual->isRecordType()) {
14415       LValue LV;
14416       APValue &Value = Info.CurrentCall->createTemporary(
14417           E, Unqual, ScopeKind::FullExpression, LV);
14418       if (!EvaluateAtomic(E, &LV, Value, Info))
14419         return false;
14420     } else {
14421       if (!EvaluateAtomic(E, nullptr, Result, Info))
14422         return false;
14423     }
14424   } else if (Info.getLangOpts().CPlusPlus11) {
14425     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
14426     return false;
14427   } else {
14428     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
14429     return false;
14430   }
14431 
14432   return true;
14433 }
14434 
14435 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
14436 /// cases, the in-place evaluation is essential, since later initializers for
14437 /// an object can indirectly refer to subobjects which were initialized earlier.
14438 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
14439                             const Expr *E, bool AllowNonLiteralTypes) {
14440   assert(!E->isValueDependent());
14441 
14442   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
14443     return false;
14444 
14445   if (E->isRValue()) {
14446     // Evaluate arrays and record types in-place, so that later initializers can
14447     // refer to earlier-initialized members of the object.
14448     QualType T = E->getType();
14449     if (T->isArrayType())
14450       return EvaluateArray(E, This, Result, Info);
14451     else if (T->isRecordType())
14452       return EvaluateRecord(E, This, Result, Info);
14453     else if (T->isAtomicType()) {
14454       QualType Unqual = T.getAtomicUnqualifiedType();
14455       if (Unqual->isArrayType() || Unqual->isRecordType())
14456         return EvaluateAtomic(E, &This, Result, Info);
14457     }
14458   }
14459 
14460   // For any other type, in-place evaluation is unimportant.
14461   return Evaluate(Result, Info, E);
14462 }
14463 
14464 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
14465 /// lvalue-to-rvalue cast if it is an lvalue.
14466 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
14467   if (Info.EnableNewConstInterp) {
14468     if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
14469       return false;
14470   } else {
14471     if (E->getType().isNull())
14472       return false;
14473 
14474     if (!CheckLiteralType(Info, E))
14475       return false;
14476 
14477     if (!::Evaluate(Result, Info, E))
14478       return false;
14479 
14480     if (E->isGLValue()) {
14481       LValue LV;
14482       LV.setFrom(Info.Ctx, Result);
14483       if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
14484         return false;
14485     }
14486   }
14487 
14488   // Check this core constant expression is a constant expression.
14489   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result) &&
14490          CheckMemoryLeaks(Info);
14491 }
14492 
14493 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
14494                                  const ASTContext &Ctx, bool &IsConst) {
14495   // Fast-path evaluations of integer literals, since we sometimes see files
14496   // containing vast quantities of these.
14497   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
14498     Result.Val = APValue(APSInt(L->getValue(),
14499                                 L->getType()->isUnsignedIntegerType()));
14500     IsConst = true;
14501     return true;
14502   }
14503 
14504   // This case should be rare, but we need to check it before we check on
14505   // the type below.
14506   if (Exp->getType().isNull()) {
14507     IsConst = false;
14508     return true;
14509   }
14510 
14511   // FIXME: Evaluating values of large array and record types can cause
14512   // performance problems. Only do so in C++11 for now.
14513   if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
14514                           Exp->getType()->isRecordType()) &&
14515       !Ctx.getLangOpts().CPlusPlus11) {
14516     IsConst = false;
14517     return true;
14518   }
14519   return false;
14520 }
14521 
14522 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
14523                                       Expr::SideEffectsKind SEK) {
14524   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
14525          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
14526 }
14527 
14528 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
14529                              const ASTContext &Ctx, EvalInfo &Info) {
14530   bool IsConst;
14531   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
14532     return IsConst;
14533 
14534   return EvaluateAsRValue(Info, E, Result.Val);
14535 }
14536 
14537 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
14538                           const ASTContext &Ctx,
14539                           Expr::SideEffectsKind AllowSideEffects,
14540                           EvalInfo &Info) {
14541   if (!E->getType()->isIntegralOrEnumerationType())
14542     return false;
14543 
14544   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
14545       !ExprResult.Val.isInt() ||
14546       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14547     return false;
14548 
14549   return true;
14550 }
14551 
14552 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
14553                                  const ASTContext &Ctx,
14554                                  Expr::SideEffectsKind AllowSideEffects,
14555                                  EvalInfo &Info) {
14556   if (!E->getType()->isFixedPointType())
14557     return false;
14558 
14559   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
14560     return false;
14561 
14562   if (!ExprResult.Val.isFixedPoint() ||
14563       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14564     return false;
14565 
14566   return true;
14567 }
14568 
14569 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
14570 /// any crazy technique (that has nothing to do with language standards) that
14571 /// we want to.  If this function returns true, it returns the folded constant
14572 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
14573 /// will be applied to the result.
14574 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
14575                             bool InConstantContext) const {
14576   assert(!isValueDependent() &&
14577          "Expression evaluator can't be called on a dependent expression.");
14578   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14579   Info.InConstantContext = InConstantContext;
14580   return ::EvaluateAsRValue(this, Result, Ctx, Info);
14581 }
14582 
14583 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
14584                                       bool InConstantContext) const {
14585   assert(!isValueDependent() &&
14586          "Expression evaluator can't be called on a dependent expression.");
14587   EvalResult Scratch;
14588   return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
14589          HandleConversionToBool(Scratch.Val, Result);
14590 }
14591 
14592 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
14593                          SideEffectsKind AllowSideEffects,
14594                          bool InConstantContext) const {
14595   assert(!isValueDependent() &&
14596          "Expression evaluator can't be called on a dependent expression.");
14597   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14598   Info.InConstantContext = InConstantContext;
14599   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
14600 }
14601 
14602 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
14603                                 SideEffectsKind AllowSideEffects,
14604                                 bool InConstantContext) const {
14605   assert(!isValueDependent() &&
14606          "Expression evaluator can't be called on a dependent expression.");
14607   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14608   Info.InConstantContext = InConstantContext;
14609   return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
14610 }
14611 
14612 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
14613                            SideEffectsKind AllowSideEffects,
14614                            bool InConstantContext) const {
14615   assert(!isValueDependent() &&
14616          "Expression evaluator can't be called on a dependent expression.");
14617 
14618   if (!getType()->isRealFloatingType())
14619     return false;
14620 
14621   EvalResult ExprResult;
14622   if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
14623       !ExprResult.Val.isFloat() ||
14624       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14625     return false;
14626 
14627   Result = ExprResult.Val.getFloat();
14628   return true;
14629 }
14630 
14631 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
14632                             bool InConstantContext) const {
14633   assert(!isValueDependent() &&
14634          "Expression evaluator can't be called on a dependent expression.");
14635 
14636   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
14637   Info.InConstantContext = InConstantContext;
14638   LValue LV;
14639   CheckedTemporaries CheckedTemps;
14640   if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
14641       Result.HasSideEffects ||
14642       !CheckLValueConstantExpression(Info, getExprLoc(),
14643                                      Ctx.getLValueReferenceType(getType()), LV,
14644                                      Expr::EvaluateForCodeGen, CheckedTemps))
14645     return false;
14646 
14647   LV.moveInto(Result.Val);
14648   return true;
14649 }
14650 
14651 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
14652                                   const ASTContext &Ctx, bool InPlace) const {
14653   assert(!isValueDependent() &&
14654          "Expression evaluator can't be called on a dependent expression.");
14655 
14656   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
14657   EvalInfo Info(Ctx, Result, EM);
14658   Info.InConstantContext = true;
14659 
14660   if (InPlace) {
14661     Info.setEvaluatingDecl(this, Result.Val);
14662     LValue LVal;
14663     LVal.set(this);
14664     if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
14665         Result.HasSideEffects)
14666       return false;
14667   } else if (!::Evaluate(Result.Val, Info, this) || Result.HasSideEffects)
14668     return false;
14669 
14670   if (!Info.discardCleanups())
14671     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14672 
14673   return CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
14674                                  Result.Val, Usage) &&
14675          CheckMemoryLeaks(Info);
14676 }
14677 
14678 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
14679                                  const VarDecl *VD,
14680                             SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
14681   assert(!isValueDependent() &&
14682          "Expression evaluator can't be called on a dependent expression.");
14683 
14684   // FIXME: Evaluating initializers for large array and record types can cause
14685   // performance problems. Only do so in C++11 for now.
14686   if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
14687       !Ctx.getLangOpts().CPlusPlus11)
14688     return false;
14689 
14690   Expr::EvalStatus EStatus;
14691   EStatus.Diag = &Notes;
14692 
14693   EvalInfo Info(Ctx, EStatus, VD->isConstexpr()
14694                                       ? EvalInfo::EM_ConstantExpression
14695                                       : EvalInfo::EM_ConstantFold);
14696   Info.setEvaluatingDecl(VD, Value);
14697   Info.InConstantContext = true;
14698 
14699   SourceLocation DeclLoc = VD->getLocation();
14700   QualType DeclTy = VD->getType();
14701 
14702   if (Info.EnableNewConstInterp) {
14703     auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
14704     if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
14705       return false;
14706   } else {
14707     LValue LVal;
14708     LVal.set(VD);
14709 
14710     if (!EvaluateInPlace(Value, Info, LVal, this,
14711                          /*AllowNonLiteralTypes=*/true) ||
14712         EStatus.HasSideEffects)
14713       return false;
14714 
14715     // At this point, any lifetime-extended temporaries are completely
14716     // initialized.
14717     Info.performLifetimeExtension();
14718 
14719     if (!Info.discardCleanups())
14720       llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14721   }
14722   return CheckConstantExpression(Info, DeclLoc, DeclTy, Value) &&
14723          CheckMemoryLeaks(Info);
14724 }
14725 
14726 bool VarDecl::evaluateDestruction(
14727     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
14728   Expr::EvalStatus EStatus;
14729   EStatus.Diag = &Notes;
14730 
14731   // Make a copy of the value for the destructor to mutate, if we know it.
14732   // Otherwise, treat the value as default-initialized; if the destructor works
14733   // anyway, then the destruction is constant (and must be essentially empty).
14734   APValue DestroyedValue;
14735   if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
14736     DestroyedValue = *getEvaluatedValue();
14737   else if (!getDefaultInitValue(getType(), DestroyedValue))
14738     return false;
14739 
14740   EvalInfo Info(getASTContext(), EStatus, EvalInfo::EM_ConstantExpression);
14741   Info.setEvaluatingDecl(this, DestroyedValue,
14742                          EvalInfo::EvaluatingDeclKind::Dtor);
14743   Info.InConstantContext = true;
14744 
14745   SourceLocation DeclLoc = getLocation();
14746   QualType DeclTy = getType();
14747 
14748   LValue LVal;
14749   LVal.set(this);
14750 
14751   if (!HandleDestruction(Info, DeclLoc, LVal.Base, DestroyedValue, DeclTy) ||
14752       EStatus.HasSideEffects)
14753     return false;
14754 
14755   if (!Info.discardCleanups())
14756     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14757 
14758   ensureEvaluatedStmt()->HasConstantDestruction = true;
14759   return true;
14760 }
14761 
14762 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
14763 /// constant folded, but discard the result.
14764 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
14765   assert(!isValueDependent() &&
14766          "Expression evaluator can't be called on a dependent expression.");
14767 
14768   EvalResult Result;
14769   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
14770          !hasUnacceptableSideEffect(Result, SEK);
14771 }
14772 
14773 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
14774                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
14775   assert(!isValueDependent() &&
14776          "Expression evaluator can't be called on a dependent expression.");
14777 
14778   EvalResult EVResult;
14779   EVResult.Diag = Diag;
14780   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14781   Info.InConstantContext = true;
14782 
14783   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
14784   (void)Result;
14785   assert(Result && "Could not evaluate expression");
14786   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
14787 
14788   return EVResult.Val.getInt();
14789 }
14790 
14791 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
14792     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
14793   assert(!isValueDependent() &&
14794          "Expression evaluator can't be called on a dependent expression.");
14795 
14796   EvalResult EVResult;
14797   EVResult.Diag = Diag;
14798   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14799   Info.InConstantContext = true;
14800   Info.CheckingForUndefinedBehavior = true;
14801 
14802   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
14803   (void)Result;
14804   assert(Result && "Could not evaluate expression");
14805   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
14806 
14807   return EVResult.Val.getInt();
14808 }
14809 
14810 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
14811   assert(!isValueDependent() &&
14812          "Expression evaluator can't be called on a dependent expression.");
14813 
14814   bool IsConst;
14815   EvalResult EVResult;
14816   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
14817     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14818     Info.CheckingForUndefinedBehavior = true;
14819     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
14820   }
14821 }
14822 
14823 bool Expr::EvalResult::isGlobalLValue() const {
14824   assert(Val.isLValue());
14825   return IsGlobalLValue(Val.getLValueBase());
14826 }
14827 
14828 
14829 /// isIntegerConstantExpr - this recursive routine will test if an expression is
14830 /// an integer constant expression.
14831 
14832 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
14833 /// comma, etc
14834 
14835 // CheckICE - This function does the fundamental ICE checking: the returned
14836 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
14837 // and a (possibly null) SourceLocation indicating the location of the problem.
14838 //
14839 // Note that to reduce code duplication, this helper does no evaluation
14840 // itself; the caller checks whether the expression is evaluatable, and
14841 // in the rare cases where CheckICE actually cares about the evaluated
14842 // value, it calls into Evaluate.
14843 
14844 namespace {
14845 
14846 enum ICEKind {
14847   /// This expression is an ICE.
14848   IK_ICE,
14849   /// This expression is not an ICE, but if it isn't evaluated, it's
14850   /// a legal subexpression for an ICE. This return value is used to handle
14851   /// the comma operator in C99 mode, and non-constant subexpressions.
14852   IK_ICEIfUnevaluated,
14853   /// This expression is not an ICE, and is not a legal subexpression for one.
14854   IK_NotICE
14855 };
14856 
14857 struct ICEDiag {
14858   ICEKind Kind;
14859   SourceLocation Loc;
14860 
14861   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
14862 };
14863 
14864 }
14865 
14866 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
14867 
14868 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
14869 
14870 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
14871   Expr::EvalResult EVResult;
14872   Expr::EvalStatus Status;
14873   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
14874 
14875   Info.InConstantContext = true;
14876   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
14877       !EVResult.Val.isInt())
14878     return ICEDiag(IK_NotICE, E->getBeginLoc());
14879 
14880   return NoDiag();
14881 }
14882 
14883 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
14884   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
14885   if (!E->getType()->isIntegralOrEnumerationType())
14886     return ICEDiag(IK_NotICE, E->getBeginLoc());
14887 
14888   switch (E->getStmtClass()) {
14889 #define ABSTRACT_STMT(Node)
14890 #define STMT(Node, Base) case Expr::Node##Class:
14891 #define EXPR(Node, Base)
14892 #include "clang/AST/StmtNodes.inc"
14893   case Expr::PredefinedExprClass:
14894   case Expr::FloatingLiteralClass:
14895   case Expr::ImaginaryLiteralClass:
14896   case Expr::StringLiteralClass:
14897   case Expr::ArraySubscriptExprClass:
14898   case Expr::MatrixSubscriptExprClass:
14899   case Expr::OMPArraySectionExprClass:
14900   case Expr::OMPArrayShapingExprClass:
14901   case Expr::OMPIteratorExprClass:
14902   case Expr::MemberExprClass:
14903   case Expr::CompoundAssignOperatorClass:
14904   case Expr::CompoundLiteralExprClass:
14905   case Expr::ExtVectorElementExprClass:
14906   case Expr::DesignatedInitExprClass:
14907   case Expr::ArrayInitLoopExprClass:
14908   case Expr::ArrayInitIndexExprClass:
14909   case Expr::NoInitExprClass:
14910   case Expr::DesignatedInitUpdateExprClass:
14911   case Expr::ImplicitValueInitExprClass:
14912   case Expr::ParenListExprClass:
14913   case Expr::VAArgExprClass:
14914   case Expr::AddrLabelExprClass:
14915   case Expr::StmtExprClass:
14916   case Expr::CXXMemberCallExprClass:
14917   case Expr::CUDAKernelCallExprClass:
14918   case Expr::CXXAddrspaceCastExprClass:
14919   case Expr::CXXDynamicCastExprClass:
14920   case Expr::CXXTypeidExprClass:
14921   case Expr::CXXUuidofExprClass:
14922   case Expr::MSPropertyRefExprClass:
14923   case Expr::MSPropertySubscriptExprClass:
14924   case Expr::CXXNullPtrLiteralExprClass:
14925   case Expr::UserDefinedLiteralClass:
14926   case Expr::CXXThisExprClass:
14927   case Expr::CXXThrowExprClass:
14928   case Expr::CXXNewExprClass:
14929   case Expr::CXXDeleteExprClass:
14930   case Expr::CXXPseudoDestructorExprClass:
14931   case Expr::UnresolvedLookupExprClass:
14932   case Expr::TypoExprClass:
14933   case Expr::RecoveryExprClass:
14934   case Expr::DependentScopeDeclRefExprClass:
14935   case Expr::CXXConstructExprClass:
14936   case Expr::CXXInheritedCtorInitExprClass:
14937   case Expr::CXXStdInitializerListExprClass:
14938   case Expr::CXXBindTemporaryExprClass:
14939   case Expr::ExprWithCleanupsClass:
14940   case Expr::CXXTemporaryObjectExprClass:
14941   case Expr::CXXUnresolvedConstructExprClass:
14942   case Expr::CXXDependentScopeMemberExprClass:
14943   case Expr::UnresolvedMemberExprClass:
14944   case Expr::ObjCStringLiteralClass:
14945   case Expr::ObjCBoxedExprClass:
14946   case Expr::ObjCArrayLiteralClass:
14947   case Expr::ObjCDictionaryLiteralClass:
14948   case Expr::ObjCEncodeExprClass:
14949   case Expr::ObjCMessageExprClass:
14950   case Expr::ObjCSelectorExprClass:
14951   case Expr::ObjCProtocolExprClass:
14952   case Expr::ObjCIvarRefExprClass:
14953   case Expr::ObjCPropertyRefExprClass:
14954   case Expr::ObjCSubscriptRefExprClass:
14955   case Expr::ObjCIsaExprClass:
14956   case Expr::ObjCAvailabilityCheckExprClass:
14957   case Expr::ShuffleVectorExprClass:
14958   case Expr::ConvertVectorExprClass:
14959   case Expr::BlockExprClass:
14960   case Expr::NoStmtClass:
14961   case Expr::OpaqueValueExprClass:
14962   case Expr::PackExpansionExprClass:
14963   case Expr::SubstNonTypeTemplateParmPackExprClass:
14964   case Expr::FunctionParmPackExprClass:
14965   case Expr::AsTypeExprClass:
14966   case Expr::ObjCIndirectCopyRestoreExprClass:
14967   case Expr::MaterializeTemporaryExprClass:
14968   case Expr::PseudoObjectExprClass:
14969   case Expr::AtomicExprClass:
14970   case Expr::LambdaExprClass:
14971   case Expr::CXXFoldExprClass:
14972   case Expr::CoawaitExprClass:
14973   case Expr::DependentCoawaitExprClass:
14974   case Expr::CoyieldExprClass:
14975     return ICEDiag(IK_NotICE, E->getBeginLoc());
14976 
14977   case Expr::InitListExprClass: {
14978     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
14979     // form "T x = { a };" is equivalent to "T x = a;".
14980     // Unless we're initializing a reference, T is a scalar as it is known to be
14981     // of integral or enumeration type.
14982     if (E->isRValue())
14983       if (cast<InitListExpr>(E)->getNumInits() == 1)
14984         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
14985     return ICEDiag(IK_NotICE, E->getBeginLoc());
14986   }
14987 
14988   case Expr::SizeOfPackExprClass:
14989   case Expr::GNUNullExprClass:
14990   case Expr::SourceLocExprClass:
14991     return NoDiag();
14992 
14993   case Expr::SubstNonTypeTemplateParmExprClass:
14994     return
14995       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
14996 
14997   case Expr::ConstantExprClass:
14998     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
14999 
15000   case Expr::ParenExprClass:
15001     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
15002   case Expr::GenericSelectionExprClass:
15003     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
15004   case Expr::IntegerLiteralClass:
15005   case Expr::FixedPointLiteralClass:
15006   case Expr::CharacterLiteralClass:
15007   case Expr::ObjCBoolLiteralExprClass:
15008   case Expr::CXXBoolLiteralExprClass:
15009   case Expr::CXXScalarValueInitExprClass:
15010   case Expr::TypeTraitExprClass:
15011   case Expr::ConceptSpecializationExprClass:
15012   case Expr::RequiresExprClass:
15013   case Expr::ArrayTypeTraitExprClass:
15014   case Expr::ExpressionTraitExprClass:
15015   case Expr::CXXNoexceptExprClass:
15016     return NoDiag();
15017   case Expr::CallExprClass:
15018   case Expr::CXXOperatorCallExprClass: {
15019     // C99 6.6/3 allows function calls within unevaluated subexpressions of
15020     // constant expressions, but they can never be ICEs because an ICE cannot
15021     // contain an operand of (pointer to) function type.
15022     const CallExpr *CE = cast<CallExpr>(E);
15023     if (CE->getBuiltinCallee())
15024       return CheckEvalInICE(E, Ctx);
15025     return ICEDiag(IK_NotICE, E->getBeginLoc());
15026   }
15027   case Expr::CXXRewrittenBinaryOperatorClass:
15028     return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
15029                     Ctx);
15030   case Expr::DeclRefExprClass: {
15031     if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
15032       return NoDiag();
15033     const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
15034     if (Ctx.getLangOpts().CPlusPlus &&
15035         D && IsConstNonVolatile(D->getType())) {
15036       // Parameter variables are never constants.  Without this check,
15037       // getAnyInitializer() can find a default argument, which leads
15038       // to chaos.
15039       if (isa<ParmVarDecl>(D))
15040         return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
15041 
15042       // C++ 7.1.5.1p2
15043       //   A variable of non-volatile const-qualified integral or enumeration
15044       //   type initialized by an ICE can be used in ICEs.
15045       if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
15046         if (!Dcl->getType()->isIntegralOrEnumerationType())
15047           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
15048 
15049         const VarDecl *VD;
15050         // Look for a declaration of this variable that has an initializer, and
15051         // check whether it is an ICE.
15052         if (Dcl->getAnyInitializer(VD) && !VD->isWeak() && VD->checkInitIsICE())
15053           return NoDiag();
15054         else
15055           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
15056       }
15057     }
15058     return ICEDiag(IK_NotICE, E->getBeginLoc());
15059   }
15060   case Expr::UnaryOperatorClass: {
15061     const UnaryOperator *Exp = cast<UnaryOperator>(E);
15062     switch (Exp->getOpcode()) {
15063     case UO_PostInc:
15064     case UO_PostDec:
15065     case UO_PreInc:
15066     case UO_PreDec:
15067     case UO_AddrOf:
15068     case UO_Deref:
15069     case UO_Coawait:
15070       // C99 6.6/3 allows increment and decrement within unevaluated
15071       // subexpressions of constant expressions, but they can never be ICEs
15072       // because an ICE cannot contain an lvalue operand.
15073       return ICEDiag(IK_NotICE, E->getBeginLoc());
15074     case UO_Extension:
15075     case UO_LNot:
15076     case UO_Plus:
15077     case UO_Minus:
15078     case UO_Not:
15079     case UO_Real:
15080     case UO_Imag:
15081       return CheckICE(Exp->getSubExpr(), Ctx);
15082     }
15083     llvm_unreachable("invalid unary operator class");
15084   }
15085   case Expr::OffsetOfExprClass: {
15086     // Note that per C99, offsetof must be an ICE. And AFAIK, using
15087     // EvaluateAsRValue matches the proposed gcc behavior for cases like
15088     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
15089     // compliance: we should warn earlier for offsetof expressions with
15090     // array subscripts that aren't ICEs, and if the array subscripts
15091     // are ICEs, the value of the offsetof must be an integer constant.
15092     return CheckEvalInICE(E, Ctx);
15093   }
15094   case Expr::UnaryExprOrTypeTraitExprClass: {
15095     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
15096     if ((Exp->getKind() ==  UETT_SizeOf) &&
15097         Exp->getTypeOfArgument()->isVariableArrayType())
15098       return ICEDiag(IK_NotICE, E->getBeginLoc());
15099     return NoDiag();
15100   }
15101   case Expr::BinaryOperatorClass: {
15102     const BinaryOperator *Exp = cast<BinaryOperator>(E);
15103     switch (Exp->getOpcode()) {
15104     case BO_PtrMemD:
15105     case BO_PtrMemI:
15106     case BO_Assign:
15107     case BO_MulAssign:
15108     case BO_DivAssign:
15109     case BO_RemAssign:
15110     case BO_AddAssign:
15111     case BO_SubAssign:
15112     case BO_ShlAssign:
15113     case BO_ShrAssign:
15114     case BO_AndAssign:
15115     case BO_XorAssign:
15116     case BO_OrAssign:
15117       // C99 6.6/3 allows assignments within unevaluated subexpressions of
15118       // constant expressions, but they can never be ICEs because an ICE cannot
15119       // contain an lvalue operand.
15120       return ICEDiag(IK_NotICE, E->getBeginLoc());
15121 
15122     case BO_Mul:
15123     case BO_Div:
15124     case BO_Rem:
15125     case BO_Add:
15126     case BO_Sub:
15127     case BO_Shl:
15128     case BO_Shr:
15129     case BO_LT:
15130     case BO_GT:
15131     case BO_LE:
15132     case BO_GE:
15133     case BO_EQ:
15134     case BO_NE:
15135     case BO_And:
15136     case BO_Xor:
15137     case BO_Or:
15138     case BO_Comma:
15139     case BO_Cmp: {
15140       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15141       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15142       if (Exp->getOpcode() == BO_Div ||
15143           Exp->getOpcode() == BO_Rem) {
15144         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
15145         // we don't evaluate one.
15146         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
15147           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
15148           if (REval == 0)
15149             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15150           if (REval.isSigned() && REval.isAllOnesValue()) {
15151             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
15152             if (LEval.isMinSignedValue())
15153               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15154           }
15155         }
15156       }
15157       if (Exp->getOpcode() == BO_Comma) {
15158         if (Ctx.getLangOpts().C99) {
15159           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
15160           // if it isn't evaluated.
15161           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
15162             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15163         } else {
15164           // In both C89 and C++, commas in ICEs are illegal.
15165           return ICEDiag(IK_NotICE, E->getBeginLoc());
15166         }
15167       }
15168       return Worst(LHSResult, RHSResult);
15169     }
15170     case BO_LAnd:
15171     case BO_LOr: {
15172       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15173       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15174       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
15175         // Rare case where the RHS has a comma "side-effect"; we need
15176         // to actually check the condition to see whether the side
15177         // with the comma is evaluated.
15178         if ((Exp->getOpcode() == BO_LAnd) !=
15179             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
15180           return RHSResult;
15181         return NoDiag();
15182       }
15183 
15184       return Worst(LHSResult, RHSResult);
15185     }
15186     }
15187     llvm_unreachable("invalid binary operator kind");
15188   }
15189   case Expr::ImplicitCastExprClass:
15190   case Expr::CStyleCastExprClass:
15191   case Expr::CXXFunctionalCastExprClass:
15192   case Expr::CXXStaticCastExprClass:
15193   case Expr::CXXReinterpretCastExprClass:
15194   case Expr::CXXConstCastExprClass:
15195   case Expr::ObjCBridgedCastExprClass: {
15196     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
15197     if (isa<ExplicitCastExpr>(E)) {
15198       if (const FloatingLiteral *FL
15199             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
15200         unsigned DestWidth = Ctx.getIntWidth(E->getType());
15201         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
15202         APSInt IgnoredVal(DestWidth, !DestSigned);
15203         bool Ignored;
15204         // If the value does not fit in the destination type, the behavior is
15205         // undefined, so we are not required to treat it as a constant
15206         // expression.
15207         if (FL->getValue().convertToInteger(IgnoredVal,
15208                                             llvm::APFloat::rmTowardZero,
15209                                             &Ignored) & APFloat::opInvalidOp)
15210           return ICEDiag(IK_NotICE, E->getBeginLoc());
15211         return NoDiag();
15212       }
15213     }
15214     switch (cast<CastExpr>(E)->getCastKind()) {
15215     case CK_LValueToRValue:
15216     case CK_AtomicToNonAtomic:
15217     case CK_NonAtomicToAtomic:
15218     case CK_NoOp:
15219     case CK_IntegralToBoolean:
15220     case CK_IntegralCast:
15221       return CheckICE(SubExpr, Ctx);
15222     default:
15223       return ICEDiag(IK_NotICE, E->getBeginLoc());
15224     }
15225   }
15226   case Expr::BinaryConditionalOperatorClass: {
15227     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
15228     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
15229     if (CommonResult.Kind == IK_NotICE) return CommonResult;
15230     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15231     if (FalseResult.Kind == IK_NotICE) return FalseResult;
15232     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
15233     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
15234         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
15235     return FalseResult;
15236   }
15237   case Expr::ConditionalOperatorClass: {
15238     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
15239     // If the condition (ignoring parens) is a __builtin_constant_p call,
15240     // then only the true side is actually considered in an integer constant
15241     // expression, and it is fully evaluated.  This is an important GNU
15242     // extension.  See GCC PR38377 for discussion.
15243     if (const CallExpr *CallCE
15244         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
15245       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
15246         return CheckEvalInICE(E, Ctx);
15247     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
15248     if (CondResult.Kind == IK_NotICE)
15249       return CondResult;
15250 
15251     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
15252     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15253 
15254     if (TrueResult.Kind == IK_NotICE)
15255       return TrueResult;
15256     if (FalseResult.Kind == IK_NotICE)
15257       return FalseResult;
15258     if (CondResult.Kind == IK_ICEIfUnevaluated)
15259       return CondResult;
15260     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
15261       return NoDiag();
15262     // Rare case where the diagnostics depend on which side is evaluated
15263     // Note that if we get here, CondResult is 0, and at least one of
15264     // TrueResult and FalseResult is non-zero.
15265     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
15266       return FalseResult;
15267     return TrueResult;
15268   }
15269   case Expr::CXXDefaultArgExprClass:
15270     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
15271   case Expr::CXXDefaultInitExprClass:
15272     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
15273   case Expr::ChooseExprClass: {
15274     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
15275   }
15276   case Expr::BuiltinBitCastExprClass: {
15277     if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
15278       return ICEDiag(IK_NotICE, E->getBeginLoc());
15279     return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
15280   }
15281   }
15282 
15283   llvm_unreachable("Invalid StmtClass!");
15284 }
15285 
15286 /// Evaluate an expression as a C++11 integral constant expression.
15287 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
15288                                                     const Expr *E,
15289                                                     llvm::APSInt *Value,
15290                                                     SourceLocation *Loc) {
15291   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15292     if (Loc) *Loc = E->getExprLoc();
15293     return false;
15294   }
15295 
15296   APValue Result;
15297   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
15298     return false;
15299 
15300   if (!Result.isInt()) {
15301     if (Loc) *Loc = E->getExprLoc();
15302     return false;
15303   }
15304 
15305   if (Value) *Value = Result.getInt();
15306   return true;
15307 }
15308 
15309 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
15310                                  SourceLocation *Loc) const {
15311   assert(!isValueDependent() &&
15312          "Expression evaluator can't be called on a dependent expression.");
15313 
15314   if (Ctx.getLangOpts().CPlusPlus11)
15315     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
15316 
15317   ICEDiag D = CheckICE(this, Ctx);
15318   if (D.Kind != IK_ICE) {
15319     if (Loc) *Loc = D.Loc;
15320     return false;
15321   }
15322   return true;
15323 }
15324 
15325 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx,
15326                                                     SourceLocation *Loc,
15327                                                     bool isEvaluated) const {
15328   assert(!isValueDependent() &&
15329          "Expression evaluator can't be called on a dependent expression.");
15330 
15331   APSInt Value;
15332 
15333   if (Ctx.getLangOpts().CPlusPlus11) {
15334     if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc))
15335       return Value;
15336     return None;
15337   }
15338 
15339   if (!isIntegerConstantExpr(Ctx, Loc))
15340     return None;
15341 
15342   // The only possible side-effects here are due to UB discovered in the
15343   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
15344   // required to treat the expression as an ICE, so we produce the folded
15345   // value.
15346   EvalResult ExprResult;
15347   Expr::EvalStatus Status;
15348   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
15349   Info.InConstantContext = true;
15350 
15351   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
15352     llvm_unreachable("ICE cannot be evaluated!");
15353 
15354   return ExprResult.Val.getInt();
15355 }
15356 
15357 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
15358   assert(!isValueDependent() &&
15359          "Expression evaluator can't be called on a dependent expression.");
15360 
15361   return CheckICE(this, Ctx).Kind == IK_ICE;
15362 }
15363 
15364 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
15365                                SourceLocation *Loc) const {
15366   assert(!isValueDependent() &&
15367          "Expression evaluator can't be called on a dependent expression.");
15368 
15369   // We support this checking in C++98 mode in order to diagnose compatibility
15370   // issues.
15371   assert(Ctx.getLangOpts().CPlusPlus);
15372 
15373   // Build evaluation settings.
15374   Expr::EvalStatus Status;
15375   SmallVector<PartialDiagnosticAt, 8> Diags;
15376   Status.Diag = &Diags;
15377   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15378 
15379   APValue Scratch;
15380   bool IsConstExpr =
15381       ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
15382       // FIXME: We don't produce a diagnostic for this, but the callers that
15383       // call us on arbitrary full-expressions should generally not care.
15384       Info.discardCleanups() && !Status.HasSideEffects;
15385 
15386   if (!Diags.empty()) {
15387     IsConstExpr = false;
15388     if (Loc) *Loc = Diags[0].first;
15389   } else if (!IsConstExpr) {
15390     // FIXME: This shouldn't happen.
15391     if (Loc) *Loc = getExprLoc();
15392   }
15393 
15394   return IsConstExpr;
15395 }
15396 
15397 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
15398                                     const FunctionDecl *Callee,
15399                                     ArrayRef<const Expr*> Args,
15400                                     const Expr *This) const {
15401   assert(!isValueDependent() &&
15402          "Expression evaluator can't be called on a dependent expression.");
15403 
15404   Expr::EvalStatus Status;
15405   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
15406   Info.InConstantContext = true;
15407 
15408   LValue ThisVal;
15409   const LValue *ThisPtr = nullptr;
15410   if (This) {
15411 #ifndef NDEBUG
15412     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
15413     assert(MD && "Don't provide `this` for non-methods.");
15414     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
15415 #endif
15416     if (!This->isValueDependent() &&
15417         EvaluateObjectArgument(Info, This, ThisVal) &&
15418         !Info.EvalStatus.HasSideEffects)
15419       ThisPtr = &ThisVal;
15420 
15421     // Ignore any side-effects from a failed evaluation. This is safe because
15422     // they can't interfere with any other argument evaluation.
15423     Info.EvalStatus.HasSideEffects = false;
15424   }
15425 
15426   CallRef Call = Info.CurrentCall->createCall(Callee);
15427   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
15428        I != E; ++I) {
15429     unsigned Idx = I - Args.begin();
15430     if (Idx >= Callee->getNumParams())
15431       break;
15432     const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
15433     if ((*I)->isValueDependent() ||
15434         !EvaluateCallArg(PVD, *I, Call, Info) ||
15435         Info.EvalStatus.HasSideEffects) {
15436       // If evaluation fails, throw away the argument entirely.
15437       if (APValue *Slot = Info.getParamSlot(Call, PVD))
15438         *Slot = APValue();
15439     }
15440 
15441     // Ignore any side-effects from a failed evaluation. This is safe because
15442     // they can't interfere with any other argument evaluation.
15443     Info.EvalStatus.HasSideEffects = false;
15444   }
15445 
15446   // Parameter cleanups happen in the caller and are not part of this
15447   // evaluation.
15448   Info.discardCleanups();
15449   Info.EvalStatus.HasSideEffects = false;
15450 
15451   // Build fake call to Callee.
15452   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call);
15453   // FIXME: Missing ExprWithCleanups in enable_if conditions?
15454   FullExpressionRAII Scope(Info);
15455   return Evaluate(Value, Info, this) && Scope.destroy() &&
15456          !Info.EvalStatus.HasSideEffects;
15457 }
15458 
15459 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
15460                                    SmallVectorImpl<
15461                                      PartialDiagnosticAt> &Diags) {
15462   // FIXME: It would be useful to check constexpr function templates, but at the
15463   // moment the constant expression evaluator cannot cope with the non-rigorous
15464   // ASTs which we build for dependent expressions.
15465   if (FD->isDependentContext())
15466     return true;
15467 
15468   // Bail out if a constexpr constructor has an initializer that contains an
15469   // error. We deliberately don't produce a diagnostic, as we have produced a
15470   // relevant diagnostic when parsing the error initializer.
15471   if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
15472     for (const auto *InitExpr : Ctor->inits()) {
15473       if (InitExpr->getInit() && InitExpr->getInit()->containsErrors())
15474         return false;
15475     }
15476   }
15477   Expr::EvalStatus Status;
15478   Status.Diag = &Diags;
15479 
15480   EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
15481   Info.InConstantContext = true;
15482   Info.CheckingPotentialConstantExpression = true;
15483 
15484   // The constexpr VM attempts to compile all methods to bytecode here.
15485   if (Info.EnableNewConstInterp) {
15486     Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
15487     return Diags.empty();
15488   }
15489 
15490   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
15491   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
15492 
15493   // Fabricate an arbitrary expression on the stack and pretend that it
15494   // is a temporary being used as the 'this' pointer.
15495   LValue This;
15496   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
15497   This.set({&VIE, Info.CurrentCall->Index});
15498 
15499   ArrayRef<const Expr*> Args;
15500 
15501   APValue Scratch;
15502   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
15503     // Evaluate the call as a constant initializer, to allow the construction
15504     // of objects of non-literal types.
15505     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
15506     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
15507   } else {
15508     SourceLocation Loc = FD->getLocation();
15509     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
15510                        Args, CallRef(), FD->getBody(), Info, Scratch, nullptr);
15511   }
15512 
15513   return Diags.empty();
15514 }
15515 
15516 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
15517                                               const FunctionDecl *FD,
15518                                               SmallVectorImpl<
15519                                                 PartialDiagnosticAt> &Diags) {
15520   assert(!E->isValueDependent() &&
15521          "Expression evaluator can't be called on a dependent expression.");
15522 
15523   Expr::EvalStatus Status;
15524   Status.Diag = &Diags;
15525 
15526   EvalInfo Info(FD->getASTContext(), Status,
15527                 EvalInfo::EM_ConstantExpressionUnevaluated);
15528   Info.InConstantContext = true;
15529   Info.CheckingPotentialConstantExpression = true;
15530 
15531   // Fabricate a call stack frame to give the arguments a plausible cover story.
15532   CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef());
15533 
15534   APValue ResultScratch;
15535   Evaluate(ResultScratch, Info, E);
15536   return Diags.empty();
15537 }
15538 
15539 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
15540                                  unsigned Type) const {
15541   if (!getType()->isPointerType())
15542     return false;
15543 
15544   Expr::EvalStatus Status;
15545   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
15546   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
15547 }
15548