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   /// Determines whether the given kind of constant expression is only ever
187   /// used for name mangling. If so, it's permitted to reference things that we
188   /// can't generate code for (in particular, dllimported functions).
189   static bool isForManglingOnly(ConstantExprKind Kind) {
190     switch (Kind) {
191     case ConstantExprKind::Normal:
192     case ConstantExprKind::ClassTemplateArgument:
193     case ConstantExprKind::ImmediateInvocation:
194       // Note that non-type template arguments of class type are emitted as
195       // template parameter objects.
196       return false;
197 
198     case ConstantExprKind::NonClassTemplateArgument:
199       return true;
200     }
201     llvm_unreachable("unknown ConstantExprKind");
202   }
203 
204   static bool isTemplateArgument(ConstantExprKind Kind) {
205     switch (Kind) {
206     case ConstantExprKind::Normal:
207     case ConstantExprKind::ImmediateInvocation:
208       return false;
209 
210     case ConstantExprKind::ClassTemplateArgument:
211     case ConstantExprKind::NonClassTemplateArgument:
212       return true;
213     }
214     llvm_unreachable("unknown ConstantExprKind");
215   }
216 
217   /// The bound to claim that an array of unknown bound has.
218   /// The value in MostDerivedArraySize is undefined in this case. So, set it
219   /// to an arbitrary value that's likely to loudly break things if it's used.
220   static const uint64_t AssumedSizeForUnsizedArray =
221       std::numeric_limits<uint64_t>::max() / 2;
222 
223   /// Determines if an LValue with the given LValueBase will have an unsized
224   /// array in its designator.
225   /// Find the path length and type of the most-derived subobject in the given
226   /// path, and find the size of the containing array, if any.
227   static unsigned
228   findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
229                            ArrayRef<APValue::LValuePathEntry> Path,
230                            uint64_t &ArraySize, QualType &Type, bool &IsArray,
231                            bool &FirstEntryIsUnsizedArray) {
232     // This only accepts LValueBases from APValues, and APValues don't support
233     // arrays that lack size info.
234     assert(!isBaseAnAllocSizeCall(Base) &&
235            "Unsized arrays shouldn't appear here");
236     unsigned MostDerivedLength = 0;
237     Type = getType(Base);
238 
239     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
240       if (Type->isArrayType()) {
241         const ArrayType *AT = Ctx.getAsArrayType(Type);
242         Type = AT->getElementType();
243         MostDerivedLength = I + 1;
244         IsArray = true;
245 
246         if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
247           ArraySize = CAT->getSize().getZExtValue();
248         } else {
249           assert(I == 0 && "unexpected unsized array designator");
250           FirstEntryIsUnsizedArray = true;
251           ArraySize = AssumedSizeForUnsizedArray;
252         }
253       } else if (Type->isAnyComplexType()) {
254         const ComplexType *CT = Type->castAs<ComplexType>();
255         Type = CT->getElementType();
256         ArraySize = 2;
257         MostDerivedLength = I + 1;
258         IsArray = true;
259       } else if (const FieldDecl *FD = getAsField(Path[I])) {
260         Type = FD->getType();
261         ArraySize = 0;
262         MostDerivedLength = I + 1;
263         IsArray = false;
264       } else {
265         // Path[I] describes a base class.
266         ArraySize = 0;
267         IsArray = false;
268       }
269     }
270     return MostDerivedLength;
271   }
272 
273   /// A path from a glvalue to a subobject of that glvalue.
274   struct SubobjectDesignator {
275     /// True if the subobject was named in a manner not supported by C++11. Such
276     /// lvalues can still be folded, but they are not core constant expressions
277     /// and we cannot perform lvalue-to-rvalue conversions on them.
278     unsigned Invalid : 1;
279 
280     /// Is this a pointer one past the end of an object?
281     unsigned IsOnePastTheEnd : 1;
282 
283     /// Indicator of whether the first entry is an unsized array.
284     unsigned FirstEntryIsAnUnsizedArray : 1;
285 
286     /// Indicator of whether the most-derived object is an array element.
287     unsigned MostDerivedIsArrayElement : 1;
288 
289     /// The length of the path to the most-derived object of which this is a
290     /// subobject.
291     unsigned MostDerivedPathLength : 28;
292 
293     /// The size of the array of which the most-derived object is an element.
294     /// This will always be 0 if the most-derived object is not an array
295     /// element. 0 is not an indicator of whether or not the most-derived object
296     /// is an array, however, because 0-length arrays are allowed.
297     ///
298     /// If the current array is an unsized array, the value of this is
299     /// undefined.
300     uint64_t MostDerivedArraySize;
301 
302     /// The type of the most derived object referred to by this address.
303     QualType MostDerivedType;
304 
305     typedef APValue::LValuePathEntry PathEntry;
306 
307     /// The entries on the path from the glvalue to the designated subobject.
308     SmallVector<PathEntry, 8> Entries;
309 
310     SubobjectDesignator() : Invalid(true) {}
311 
312     explicit SubobjectDesignator(QualType T)
313         : Invalid(false), IsOnePastTheEnd(false),
314           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
315           MostDerivedPathLength(0), MostDerivedArraySize(0),
316           MostDerivedType(T) {}
317 
318     SubobjectDesignator(ASTContext &Ctx, const APValue &V)
319         : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
320           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
321           MostDerivedPathLength(0), MostDerivedArraySize(0) {
322       assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
323       if (!Invalid) {
324         IsOnePastTheEnd = V.isLValueOnePastTheEnd();
325         ArrayRef<PathEntry> VEntries = V.getLValuePath();
326         Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
327         if (V.getLValueBase()) {
328           bool IsArray = false;
329           bool FirstIsUnsizedArray = false;
330           MostDerivedPathLength = findMostDerivedSubobject(
331               Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
332               MostDerivedType, IsArray, FirstIsUnsizedArray);
333           MostDerivedIsArrayElement = IsArray;
334           FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
335         }
336       }
337     }
338 
339     void truncate(ASTContext &Ctx, APValue::LValueBase Base,
340                   unsigned NewLength) {
341       if (Invalid)
342         return;
343 
344       assert(Base && "cannot truncate path for null pointer");
345       assert(NewLength <= Entries.size() && "not a truncation");
346 
347       if (NewLength == Entries.size())
348         return;
349       Entries.resize(NewLength);
350 
351       bool IsArray = false;
352       bool FirstIsUnsizedArray = false;
353       MostDerivedPathLength = findMostDerivedSubobject(
354           Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
355           FirstIsUnsizedArray);
356       MostDerivedIsArrayElement = IsArray;
357       FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
358     }
359 
360     void setInvalid() {
361       Invalid = true;
362       Entries.clear();
363     }
364 
365     /// Determine whether the most derived subobject is an array without a
366     /// known bound.
367     bool isMostDerivedAnUnsizedArray() const {
368       assert(!Invalid && "Calling this makes no sense on invalid designators");
369       return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
370     }
371 
372     /// Determine what the most derived array's size is. Results in an assertion
373     /// failure if the most derived array lacks a size.
374     uint64_t getMostDerivedArraySize() const {
375       assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
376       return MostDerivedArraySize;
377     }
378 
379     /// Determine whether this is a one-past-the-end pointer.
380     bool isOnePastTheEnd() const {
381       assert(!Invalid);
382       if (IsOnePastTheEnd)
383         return true;
384       if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
385           Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
386               MostDerivedArraySize)
387         return true;
388       return false;
389     }
390 
391     /// Get the range of valid index adjustments in the form
392     ///   {maximum value that can be subtracted from this pointer,
393     ///    maximum value that can be added to this pointer}
394     std::pair<uint64_t, uint64_t> validIndexAdjustments() {
395       if (Invalid || isMostDerivedAnUnsizedArray())
396         return {0, 0};
397 
398       // [expr.add]p4: For the purposes of these operators, a pointer to a
399       // nonarray object behaves the same as a pointer to the first element of
400       // an array of length one with the type of the object as its element type.
401       bool IsArray = MostDerivedPathLength == Entries.size() &&
402                      MostDerivedIsArrayElement;
403       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
404                                     : (uint64_t)IsOnePastTheEnd;
405       uint64_t ArraySize =
406           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
407       return {ArrayIndex, ArraySize - ArrayIndex};
408     }
409 
410     /// Check that this refers to a valid subobject.
411     bool isValidSubobject() const {
412       if (Invalid)
413         return false;
414       return !isOnePastTheEnd();
415     }
416     /// Check that this refers to a valid subobject, and if not, produce a
417     /// relevant diagnostic and set the designator as invalid.
418     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
419 
420     /// Get the type of the designated object.
421     QualType getType(ASTContext &Ctx) const {
422       assert(!Invalid && "invalid designator has no subobject type");
423       return MostDerivedPathLength == Entries.size()
424                  ? MostDerivedType
425                  : Ctx.getRecordType(getAsBaseClass(Entries.back()));
426     }
427 
428     /// Update this designator to refer to the first element within this array.
429     void addArrayUnchecked(const ConstantArrayType *CAT) {
430       Entries.push_back(PathEntry::ArrayIndex(0));
431 
432       // This is a most-derived object.
433       MostDerivedType = CAT->getElementType();
434       MostDerivedIsArrayElement = true;
435       MostDerivedArraySize = CAT->getSize().getZExtValue();
436       MostDerivedPathLength = Entries.size();
437     }
438     /// Update this designator to refer to the first element within the array of
439     /// elements of type T. This is an array of unknown size.
440     void addUnsizedArrayUnchecked(QualType ElemTy) {
441       Entries.push_back(PathEntry::ArrayIndex(0));
442 
443       MostDerivedType = ElemTy;
444       MostDerivedIsArrayElement = true;
445       // The value in MostDerivedArraySize is undefined in this case. So, set it
446       // to an arbitrary value that's likely to loudly break things if it's
447       // used.
448       MostDerivedArraySize = AssumedSizeForUnsizedArray;
449       MostDerivedPathLength = Entries.size();
450     }
451     /// Update this designator to refer to the given base or member of this
452     /// object.
453     void addDeclUnchecked(const Decl *D, bool Virtual = false) {
454       Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
455 
456       // If this isn't a base class, it's a new most-derived object.
457       if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
458         MostDerivedType = FD->getType();
459         MostDerivedIsArrayElement = false;
460         MostDerivedArraySize = 0;
461         MostDerivedPathLength = Entries.size();
462       }
463     }
464     /// Update this designator to refer to the given complex component.
465     void addComplexUnchecked(QualType EltTy, bool Imag) {
466       Entries.push_back(PathEntry::ArrayIndex(Imag));
467 
468       // This is technically a most-derived object, though in practice this
469       // is unlikely to matter.
470       MostDerivedType = EltTy;
471       MostDerivedIsArrayElement = true;
472       MostDerivedArraySize = 2;
473       MostDerivedPathLength = Entries.size();
474     }
475     void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
476     void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
477                                    const APSInt &N);
478     /// Add N to the address of this subobject.
479     void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
480       if (Invalid || !N) return;
481       uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
482       if (isMostDerivedAnUnsizedArray()) {
483         diagnoseUnsizedArrayPointerArithmetic(Info, E);
484         // Can't verify -- trust that the user is doing the right thing (or if
485         // not, trust that the caller will catch the bad behavior).
486         // FIXME: Should we reject if this overflows, at least?
487         Entries.back() = PathEntry::ArrayIndex(
488             Entries.back().getAsArrayIndex() + TruncatedN);
489         return;
490       }
491 
492       // [expr.add]p4: For the purposes of these operators, a pointer to a
493       // nonarray object behaves the same as a pointer to the first element of
494       // an array of length one with the type of the object as its element type.
495       bool IsArray = MostDerivedPathLength == Entries.size() &&
496                      MostDerivedIsArrayElement;
497       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
498                                     : (uint64_t)IsOnePastTheEnd;
499       uint64_t ArraySize =
500           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
501 
502       if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
503         // Calculate the actual index in a wide enough type, so we can include
504         // it in the note.
505         N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
506         (llvm::APInt&)N += ArrayIndex;
507         assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
508         diagnosePointerArithmetic(Info, E, N);
509         setInvalid();
510         return;
511       }
512 
513       ArrayIndex += TruncatedN;
514       assert(ArrayIndex <= ArraySize &&
515              "bounds check succeeded for out-of-bounds index");
516 
517       if (IsArray)
518         Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
519       else
520         IsOnePastTheEnd = (ArrayIndex != 0);
521     }
522   };
523 
524   /// A scope at the end of which an object can need to be destroyed.
525   enum class ScopeKind {
526     Block,
527     FullExpression,
528     Call
529   };
530 
531   /// A reference to a particular call and its arguments.
532   struct CallRef {
533     CallRef() : OrigCallee(), CallIndex(0), Version() {}
534     CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
535         : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
536 
537     explicit operator bool() const { return OrigCallee; }
538 
539     /// Get the parameter that the caller initialized, corresponding to the
540     /// given parameter in the callee.
541     const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
542       return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
543                         : PVD;
544     }
545 
546     /// The callee at the point where the arguments were evaluated. This might
547     /// be different from the actual callee (a different redeclaration, or a
548     /// virtual override), but this function's parameters are the ones that
549     /// appear in the parameter map.
550     const FunctionDecl *OrigCallee;
551     /// The call index of the frame that holds the argument values.
552     unsigned CallIndex;
553     /// The version of the parameters corresponding to this call.
554     unsigned Version;
555   };
556 
557   /// A stack frame in the constexpr call stack.
558   class CallStackFrame : public interp::Frame {
559   public:
560     EvalInfo &Info;
561 
562     /// Parent - The caller of this stack frame.
563     CallStackFrame *Caller;
564 
565     /// Callee - The function which was called.
566     const FunctionDecl *Callee;
567 
568     /// This - The binding for the this pointer in this call, if any.
569     const LValue *This;
570 
571     /// Information on how to find the arguments to this call. Our arguments
572     /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
573     /// key and this value as the version.
574     CallRef Arguments;
575 
576     /// Source location information about the default argument or default
577     /// initializer expression we're evaluating, if any.
578     CurrentSourceLocExprScope CurSourceLocExprScope;
579 
580     // Note that we intentionally use std::map here so that references to
581     // values are stable.
582     typedef std::pair<const void *, unsigned> MapKeyTy;
583     typedef std::map<MapKeyTy, APValue> MapTy;
584     /// Temporaries - Temporary lvalues materialized within this stack frame.
585     MapTy Temporaries;
586 
587     /// CallLoc - The location of the call expression for this call.
588     SourceLocation CallLoc;
589 
590     /// Index - The call index of this call.
591     unsigned Index;
592 
593     /// The stack of integers for tracking version numbers for temporaries.
594     SmallVector<unsigned, 2> TempVersionStack = {1};
595     unsigned CurTempVersion = TempVersionStack.back();
596 
597     unsigned getTempVersion() const { return TempVersionStack.back(); }
598 
599     void pushTempVersion() {
600       TempVersionStack.push_back(++CurTempVersion);
601     }
602 
603     void popTempVersion() {
604       TempVersionStack.pop_back();
605     }
606 
607     CallRef createCall(const FunctionDecl *Callee) {
608       return {Callee, Index, ++CurTempVersion};
609     }
610 
611     // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
612     // on the overall stack usage of deeply-recursing constexpr evaluations.
613     // (We should cache this map rather than recomputing it repeatedly.)
614     // But let's try this and see how it goes; we can look into caching the map
615     // as a later change.
616 
617     /// LambdaCaptureFields - Mapping from captured variables/this to
618     /// corresponding data members in the closure class.
619     llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
620     FieldDecl *LambdaThisCaptureField;
621 
622     CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
623                    const FunctionDecl *Callee, const LValue *This,
624                    CallRef Arguments);
625     ~CallStackFrame();
626 
627     // Return the temporary for Key whose version number is Version.
628     APValue *getTemporary(const void *Key, unsigned Version) {
629       MapKeyTy KV(Key, Version);
630       auto LB = Temporaries.lower_bound(KV);
631       if (LB != Temporaries.end() && LB->first == KV)
632         return &LB->second;
633       // Pair (Key,Version) wasn't found in the map. Check that no elements
634       // in the map have 'Key' as their key.
635       assert((LB == Temporaries.end() || LB->first.first != Key) &&
636              (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
637              "Element with key 'Key' found in map");
638       return nullptr;
639     }
640 
641     // Return the current temporary for Key in the map.
642     APValue *getCurrentTemporary(const void *Key) {
643       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
644       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
645         return &std::prev(UB)->second;
646       return nullptr;
647     }
648 
649     // Return the version number of the current temporary for Key.
650     unsigned getCurrentTemporaryVersion(const void *Key) const {
651       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
652       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
653         return std::prev(UB)->first.second;
654       return 0;
655     }
656 
657     /// Allocate storage for an object of type T in this stack frame.
658     /// Populates LV with a handle to the created object. Key identifies
659     /// the temporary within the stack frame, and must not be reused without
660     /// bumping the temporary version number.
661     template<typename KeyT>
662     APValue &createTemporary(const KeyT *Key, QualType T,
663                              ScopeKind Scope, LValue &LV);
664 
665     /// Allocate storage for a parameter of a function call made in this frame.
666     APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
667 
668     void describe(llvm::raw_ostream &OS) override;
669 
670     Frame *getCaller() const override { return Caller; }
671     SourceLocation getCallLocation() const override { return CallLoc; }
672     const FunctionDecl *getCallee() const override { return Callee; }
673 
674     bool isStdFunction() const {
675       for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
676         if (DC->isStdNamespace())
677           return true;
678       return false;
679     }
680 
681   private:
682     APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
683                          ScopeKind Scope);
684   };
685 
686   /// Temporarily override 'this'.
687   class ThisOverrideRAII {
688   public:
689     ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
690         : Frame(Frame), OldThis(Frame.This) {
691       if (Enable)
692         Frame.This = NewThis;
693     }
694     ~ThisOverrideRAII() {
695       Frame.This = OldThis;
696     }
697   private:
698     CallStackFrame &Frame;
699     const LValue *OldThis;
700   };
701 }
702 
703 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
704                               const LValue &This, QualType ThisType);
705 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
706                               APValue::LValueBase LVBase, APValue &Value,
707                               QualType T);
708 
709 namespace {
710   /// A cleanup, and a flag indicating whether it is lifetime-extended.
711   class Cleanup {
712     llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
713     APValue::LValueBase Base;
714     QualType T;
715 
716   public:
717     Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
718             ScopeKind Scope)
719         : Value(Val, Scope), Base(Base), T(T) {}
720 
721     /// Determine whether this cleanup should be performed at the end of the
722     /// given kind of scope.
723     bool isDestroyedAtEndOf(ScopeKind K) const {
724       return (int)Value.getInt() >= (int)K;
725     }
726     bool endLifetime(EvalInfo &Info, bool RunDestructors) {
727       if (RunDestructors) {
728         SourceLocation Loc;
729         if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
730           Loc = VD->getLocation();
731         else if (const Expr *E = Base.dyn_cast<const Expr*>())
732           Loc = E->getExprLoc();
733         return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
734       }
735       *Value.getPointer() = APValue();
736       return true;
737     }
738 
739     bool hasSideEffect() {
740       return T.isDestructedType();
741     }
742   };
743 
744   /// A reference to an object whose construction we are currently evaluating.
745   struct ObjectUnderConstruction {
746     APValue::LValueBase Base;
747     ArrayRef<APValue::LValuePathEntry> Path;
748     friend bool operator==(const ObjectUnderConstruction &LHS,
749                            const ObjectUnderConstruction &RHS) {
750       return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
751     }
752     friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
753       return llvm::hash_combine(Obj.Base, Obj.Path);
754     }
755   };
756   enum class ConstructionPhase {
757     None,
758     Bases,
759     AfterBases,
760     AfterFields,
761     Destroying,
762     DestroyingBases
763   };
764 }
765 
766 namespace llvm {
767 template<> struct DenseMapInfo<ObjectUnderConstruction> {
768   using Base = DenseMapInfo<APValue::LValueBase>;
769   static ObjectUnderConstruction getEmptyKey() {
770     return {Base::getEmptyKey(), {}}; }
771   static ObjectUnderConstruction getTombstoneKey() {
772     return {Base::getTombstoneKey(), {}};
773   }
774   static unsigned getHashValue(const ObjectUnderConstruction &Object) {
775     return hash_value(Object);
776   }
777   static bool isEqual(const ObjectUnderConstruction &LHS,
778                       const ObjectUnderConstruction &RHS) {
779     return LHS == RHS;
780   }
781 };
782 }
783 
784 namespace {
785   /// A dynamically-allocated heap object.
786   struct DynAlloc {
787     /// The value of this heap-allocated object.
788     APValue Value;
789     /// The allocating expression; used for diagnostics. Either a CXXNewExpr
790     /// or a CallExpr (the latter is for direct calls to operator new inside
791     /// std::allocator<T>::allocate).
792     const Expr *AllocExpr = nullptr;
793 
794     enum Kind {
795       New,
796       ArrayNew,
797       StdAllocator
798     };
799 
800     /// Get the kind of the allocation. This must match between allocation
801     /// and deallocation.
802     Kind getKind() const {
803       if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
804         return NE->isArray() ? ArrayNew : New;
805       assert(isa<CallExpr>(AllocExpr));
806       return StdAllocator;
807     }
808   };
809 
810   struct DynAllocOrder {
811     bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
812       return L.getIndex() < R.getIndex();
813     }
814   };
815 
816   /// EvalInfo - This is a private struct used by the evaluator to capture
817   /// information about a subexpression as it is folded.  It retains information
818   /// about the AST context, but also maintains information about the folded
819   /// expression.
820   ///
821   /// If an expression could be evaluated, it is still possible it is not a C
822   /// "integer constant expression" or constant expression.  If not, this struct
823   /// captures information about how and why not.
824   ///
825   /// One bit of information passed *into* the request for constant folding
826   /// indicates whether the subexpression is "evaluated" or not according to C
827   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
828   /// evaluate the expression regardless of what the RHS is, but C only allows
829   /// certain things in certain situations.
830   class EvalInfo : public interp::State {
831   public:
832     ASTContext &Ctx;
833 
834     /// EvalStatus - Contains information about the evaluation.
835     Expr::EvalStatus &EvalStatus;
836 
837     /// CurrentCall - The top of the constexpr call stack.
838     CallStackFrame *CurrentCall;
839 
840     /// CallStackDepth - The number of calls in the call stack right now.
841     unsigned CallStackDepth;
842 
843     /// NextCallIndex - The next call index to assign.
844     unsigned NextCallIndex;
845 
846     /// StepsLeft - The remaining number of evaluation steps we're permitted
847     /// to perform. This is essentially a limit for the number of statements
848     /// we will evaluate.
849     unsigned StepsLeft;
850 
851     /// Enable the experimental new constant interpreter. If an expression is
852     /// not supported by the interpreter, an error is triggered.
853     bool EnableNewConstInterp;
854 
855     /// BottomFrame - The frame in which evaluation started. This must be
856     /// initialized after CurrentCall and CallStackDepth.
857     CallStackFrame BottomFrame;
858 
859     /// A stack of values whose lifetimes end at the end of some surrounding
860     /// evaluation frame.
861     llvm::SmallVector<Cleanup, 16> CleanupStack;
862 
863     /// EvaluatingDecl - This is the declaration whose initializer is being
864     /// evaluated, if any.
865     APValue::LValueBase EvaluatingDecl;
866 
867     enum class EvaluatingDeclKind {
868       None,
869       /// We're evaluating the construction of EvaluatingDecl.
870       Ctor,
871       /// We're evaluating the destruction of EvaluatingDecl.
872       Dtor,
873     };
874     EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
875 
876     /// EvaluatingDeclValue - This is the value being constructed for the
877     /// declaration whose initializer is being evaluated, if any.
878     APValue *EvaluatingDeclValue;
879 
880     /// Set of objects that are currently being constructed.
881     llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
882         ObjectsUnderConstruction;
883 
884     /// Current heap allocations, along with the location where each was
885     /// allocated. We use std::map here because we need stable addresses
886     /// for the stored APValues.
887     std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
888 
889     /// The number of heap allocations performed so far in this evaluation.
890     unsigned NumHeapAllocs = 0;
891 
892     struct EvaluatingConstructorRAII {
893       EvalInfo &EI;
894       ObjectUnderConstruction Object;
895       bool DidInsert;
896       EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
897                                 bool HasBases)
898           : EI(EI), Object(Object) {
899         DidInsert =
900             EI.ObjectsUnderConstruction
901                 .insert({Object, HasBases ? ConstructionPhase::Bases
902                                           : ConstructionPhase::AfterBases})
903                 .second;
904       }
905       void finishedConstructingBases() {
906         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
907       }
908       void finishedConstructingFields() {
909         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
910       }
911       ~EvaluatingConstructorRAII() {
912         if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
913       }
914     };
915 
916     struct EvaluatingDestructorRAII {
917       EvalInfo &EI;
918       ObjectUnderConstruction Object;
919       bool DidInsert;
920       EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
921           : EI(EI), Object(Object) {
922         DidInsert = EI.ObjectsUnderConstruction
923                         .insert({Object, ConstructionPhase::Destroying})
924                         .second;
925       }
926       void startedDestroyingBases() {
927         EI.ObjectsUnderConstruction[Object] =
928             ConstructionPhase::DestroyingBases;
929       }
930       ~EvaluatingDestructorRAII() {
931         if (DidInsert)
932           EI.ObjectsUnderConstruction.erase(Object);
933       }
934     };
935 
936     ConstructionPhase
937     isEvaluatingCtorDtor(APValue::LValueBase Base,
938                          ArrayRef<APValue::LValuePathEntry> Path) {
939       return ObjectsUnderConstruction.lookup({Base, Path});
940     }
941 
942     /// If we're currently speculatively evaluating, the outermost call stack
943     /// depth at which we can mutate state, otherwise 0.
944     unsigned SpeculativeEvaluationDepth = 0;
945 
946     /// The current array initialization index, if we're performing array
947     /// initialization.
948     uint64_t ArrayInitIndex = -1;
949 
950     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
951     /// notes attached to it will also be stored, otherwise they will not be.
952     bool HasActiveDiagnostic;
953 
954     /// Have we emitted a diagnostic explaining why we couldn't constant
955     /// fold (not just why it's not strictly a constant expression)?
956     bool HasFoldFailureDiagnostic;
957 
958     /// Whether or not we're in a context where the front end requires a
959     /// constant value.
960     bool InConstantContext;
961 
962     /// Whether we're checking that an expression is a potential constant
963     /// expression. If so, do not fail on constructs that could become constant
964     /// later on (such as a use of an undefined global).
965     bool CheckingPotentialConstantExpression = false;
966 
967     /// Whether we're checking for an expression that has undefined behavior.
968     /// If so, we will produce warnings if we encounter an operation that is
969     /// always undefined.
970     bool CheckingForUndefinedBehavior = false;
971 
972     enum EvaluationMode {
973       /// Evaluate as a constant expression. Stop if we find that the expression
974       /// is not a constant expression.
975       EM_ConstantExpression,
976 
977       /// Evaluate as a constant expression. Stop if we find that the expression
978       /// is not a constant expression. Some expressions can be retried in the
979       /// optimizer if we don't constant fold them here, but in an unevaluated
980       /// context we try to fold them immediately since the optimizer never
981       /// gets a chance to look at it.
982       EM_ConstantExpressionUnevaluated,
983 
984       /// Fold the expression to a constant. Stop if we hit a side-effect that
985       /// we can't model.
986       EM_ConstantFold,
987 
988       /// Evaluate in any way we know how. Don't worry about side-effects that
989       /// can't be modeled.
990       EM_IgnoreSideEffects,
991     } EvalMode;
992 
993     /// Are we checking whether the expression is a potential constant
994     /// expression?
995     bool checkingPotentialConstantExpression() const override  {
996       return CheckingPotentialConstantExpression;
997     }
998 
999     /// Are we checking an expression for overflow?
1000     // FIXME: We should check for any kind of undefined or suspicious behavior
1001     // in such constructs, not just overflow.
1002     bool checkingForUndefinedBehavior() const override {
1003       return CheckingForUndefinedBehavior;
1004     }
1005 
1006     EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
1007         : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
1008           CallStackDepth(0), NextCallIndex(1),
1009           StepsLeft(C.getLangOpts().ConstexprStepLimit),
1010           EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
1011           BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()),
1012           EvaluatingDecl((const ValueDecl *)nullptr),
1013           EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
1014           HasFoldFailureDiagnostic(false), InConstantContext(false),
1015           EvalMode(Mode) {}
1016 
1017     ~EvalInfo() {
1018       discardCleanups();
1019     }
1020 
1021     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
1022                            EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
1023       EvaluatingDecl = Base;
1024       IsEvaluatingDecl = EDK;
1025       EvaluatingDeclValue = &Value;
1026     }
1027 
1028     bool CheckCallLimit(SourceLocation Loc) {
1029       // Don't perform any constexpr calls (other than the call we're checking)
1030       // when checking a potential constant expression.
1031       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
1032         return false;
1033       if (NextCallIndex == 0) {
1034         // NextCallIndex has wrapped around.
1035         FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
1036         return false;
1037       }
1038       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
1039         return true;
1040       FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
1041         << getLangOpts().ConstexprCallDepth;
1042       return false;
1043     }
1044 
1045     std::pair<CallStackFrame *, unsigned>
1046     getCallFrameAndDepth(unsigned CallIndex) {
1047       assert(CallIndex && "no call index in getCallFrameAndDepth");
1048       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1049       // be null in this loop.
1050       unsigned Depth = CallStackDepth;
1051       CallStackFrame *Frame = CurrentCall;
1052       while (Frame->Index > CallIndex) {
1053         Frame = Frame->Caller;
1054         --Depth;
1055       }
1056       if (Frame->Index == CallIndex)
1057         return {Frame, Depth};
1058       return {nullptr, 0};
1059     }
1060 
1061     bool nextStep(const Stmt *S) {
1062       if (!StepsLeft) {
1063         FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1064         return false;
1065       }
1066       --StepsLeft;
1067       return true;
1068     }
1069 
1070     APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1071 
1072     Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) {
1073       Optional<DynAlloc*> Result;
1074       auto It = HeapAllocs.find(DA);
1075       if (It != HeapAllocs.end())
1076         Result = &It->second;
1077       return Result;
1078     }
1079 
1080     /// Get the allocated storage for the given parameter of the given call.
1081     APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1082       CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1083       return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1084                    : nullptr;
1085     }
1086 
1087     /// Information about a stack frame for std::allocator<T>::[de]allocate.
1088     struct StdAllocatorCaller {
1089       unsigned FrameIndex;
1090       QualType ElemType;
1091       explicit operator bool() const { return FrameIndex != 0; };
1092     };
1093 
1094     StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1095       for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1096            Call = Call->Caller) {
1097         const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1098         if (!MD)
1099           continue;
1100         const IdentifierInfo *FnII = MD->getIdentifier();
1101         if (!FnII || !FnII->isStr(FnName))
1102           continue;
1103 
1104         const auto *CTSD =
1105             dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1106         if (!CTSD)
1107           continue;
1108 
1109         const IdentifierInfo *ClassII = CTSD->getIdentifier();
1110         const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1111         if (CTSD->isInStdNamespace() && ClassII &&
1112             ClassII->isStr("allocator") && TAL.size() >= 1 &&
1113             TAL[0].getKind() == TemplateArgument::Type)
1114           return {Call->Index, TAL[0].getAsType()};
1115       }
1116 
1117       return {};
1118     }
1119 
1120     void performLifetimeExtension() {
1121       // Disable the cleanups for lifetime-extended temporaries.
1122       CleanupStack.erase(std::remove_if(CleanupStack.begin(),
1123                                         CleanupStack.end(),
1124                                         [](Cleanup &C) {
1125                                           return !C.isDestroyedAtEndOf(
1126                                               ScopeKind::FullExpression);
1127                                         }),
1128                          CleanupStack.end());
1129      }
1130 
1131     /// Throw away any remaining cleanups at the end of evaluation. If any
1132     /// cleanups would have had a side-effect, note that as an unmodeled
1133     /// side-effect and return false. Otherwise, return true.
1134     bool discardCleanups() {
1135       for (Cleanup &C : CleanupStack) {
1136         if (C.hasSideEffect() && !noteSideEffect()) {
1137           CleanupStack.clear();
1138           return false;
1139         }
1140       }
1141       CleanupStack.clear();
1142       return true;
1143     }
1144 
1145   private:
1146     interp::Frame *getCurrentFrame() override { return CurrentCall; }
1147     const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1148 
1149     bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1150     void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1151 
1152     void setFoldFailureDiagnostic(bool Flag) override {
1153       HasFoldFailureDiagnostic = Flag;
1154     }
1155 
1156     Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1157 
1158     ASTContext &getCtx() const override { return Ctx; }
1159 
1160     // If we have a prior diagnostic, it will be noting that the expression
1161     // isn't a constant expression. This diagnostic is more important,
1162     // unless we require this evaluation to produce a constant expression.
1163     //
1164     // FIXME: We might want to show both diagnostics to the user in
1165     // EM_ConstantFold mode.
1166     bool hasPriorDiagnostic() override {
1167       if (!EvalStatus.Diag->empty()) {
1168         switch (EvalMode) {
1169         case EM_ConstantFold:
1170         case EM_IgnoreSideEffects:
1171           if (!HasFoldFailureDiagnostic)
1172             break;
1173           // We've already failed to fold something. Keep that diagnostic.
1174           LLVM_FALLTHROUGH;
1175         case EM_ConstantExpression:
1176         case EM_ConstantExpressionUnevaluated:
1177           setActiveDiagnostic(false);
1178           return true;
1179         }
1180       }
1181       return false;
1182     }
1183 
1184     unsigned getCallStackDepth() override { return CallStackDepth; }
1185 
1186   public:
1187     /// Should we continue evaluation after encountering a side-effect that we
1188     /// couldn't model?
1189     bool keepEvaluatingAfterSideEffect() {
1190       switch (EvalMode) {
1191       case EM_IgnoreSideEffects:
1192         return true;
1193 
1194       case EM_ConstantExpression:
1195       case EM_ConstantExpressionUnevaluated:
1196       case EM_ConstantFold:
1197         // By default, assume any side effect might be valid in some other
1198         // evaluation of this expression from a different context.
1199         return checkingPotentialConstantExpression() ||
1200                checkingForUndefinedBehavior();
1201       }
1202       llvm_unreachable("Missed EvalMode case");
1203     }
1204 
1205     /// Note that we have had a side-effect, and determine whether we should
1206     /// keep evaluating.
1207     bool noteSideEffect() {
1208       EvalStatus.HasSideEffects = true;
1209       return keepEvaluatingAfterSideEffect();
1210     }
1211 
1212     /// Should we continue evaluation after encountering undefined behavior?
1213     bool keepEvaluatingAfterUndefinedBehavior() {
1214       switch (EvalMode) {
1215       case EM_IgnoreSideEffects:
1216       case EM_ConstantFold:
1217         return true;
1218 
1219       case EM_ConstantExpression:
1220       case EM_ConstantExpressionUnevaluated:
1221         return checkingForUndefinedBehavior();
1222       }
1223       llvm_unreachable("Missed EvalMode case");
1224     }
1225 
1226     /// Note that we hit something that was technically undefined behavior, but
1227     /// that we can evaluate past it (such as signed overflow or floating-point
1228     /// division by zero.)
1229     bool noteUndefinedBehavior() override {
1230       EvalStatus.HasUndefinedBehavior = true;
1231       return keepEvaluatingAfterUndefinedBehavior();
1232     }
1233 
1234     /// Should we continue evaluation as much as possible after encountering a
1235     /// construct which can't be reduced to a value?
1236     bool keepEvaluatingAfterFailure() const override {
1237       if (!StepsLeft)
1238         return false;
1239 
1240       switch (EvalMode) {
1241       case EM_ConstantExpression:
1242       case EM_ConstantExpressionUnevaluated:
1243       case EM_ConstantFold:
1244       case EM_IgnoreSideEffects:
1245         return checkingPotentialConstantExpression() ||
1246                checkingForUndefinedBehavior();
1247       }
1248       llvm_unreachable("Missed EvalMode case");
1249     }
1250 
1251     /// Notes that we failed to evaluate an expression that other expressions
1252     /// directly depend on, and determine if we should keep evaluating. This
1253     /// should only be called if we actually intend to keep evaluating.
1254     ///
1255     /// Call noteSideEffect() instead if we may be able to ignore the value that
1256     /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1257     ///
1258     /// (Foo(), 1)      // use noteSideEffect
1259     /// (Foo() || true) // use noteSideEffect
1260     /// Foo() + 1       // use noteFailure
1261     LLVM_NODISCARD bool noteFailure() {
1262       // Failure when evaluating some expression often means there is some
1263       // subexpression whose evaluation was skipped. Therefore, (because we
1264       // don't track whether we skipped an expression when unwinding after an
1265       // evaluation failure) every evaluation failure that bubbles up from a
1266       // subexpression implies that a side-effect has potentially happened. We
1267       // skip setting the HasSideEffects flag to true until we decide to
1268       // continue evaluating after that point, which happens here.
1269       bool KeepGoing = keepEvaluatingAfterFailure();
1270       EvalStatus.HasSideEffects |= KeepGoing;
1271       return KeepGoing;
1272     }
1273 
1274     class ArrayInitLoopIndex {
1275       EvalInfo &Info;
1276       uint64_t OuterIndex;
1277 
1278     public:
1279       ArrayInitLoopIndex(EvalInfo &Info)
1280           : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1281         Info.ArrayInitIndex = 0;
1282       }
1283       ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1284 
1285       operator uint64_t&() { return Info.ArrayInitIndex; }
1286     };
1287   };
1288 
1289   /// Object used to treat all foldable expressions as constant expressions.
1290   struct FoldConstant {
1291     EvalInfo &Info;
1292     bool Enabled;
1293     bool HadNoPriorDiags;
1294     EvalInfo::EvaluationMode OldMode;
1295 
1296     explicit FoldConstant(EvalInfo &Info, bool Enabled)
1297       : Info(Info),
1298         Enabled(Enabled),
1299         HadNoPriorDiags(Info.EvalStatus.Diag &&
1300                         Info.EvalStatus.Diag->empty() &&
1301                         !Info.EvalStatus.HasSideEffects),
1302         OldMode(Info.EvalMode) {
1303       if (Enabled)
1304         Info.EvalMode = EvalInfo::EM_ConstantFold;
1305     }
1306     void keepDiagnostics() { Enabled = false; }
1307     ~FoldConstant() {
1308       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1309           !Info.EvalStatus.HasSideEffects)
1310         Info.EvalStatus.Diag->clear();
1311       Info.EvalMode = OldMode;
1312     }
1313   };
1314 
1315   /// RAII object used to set the current evaluation mode to ignore
1316   /// side-effects.
1317   struct IgnoreSideEffectsRAII {
1318     EvalInfo &Info;
1319     EvalInfo::EvaluationMode OldMode;
1320     explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1321         : Info(Info), OldMode(Info.EvalMode) {
1322       Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1323     }
1324 
1325     ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1326   };
1327 
1328   /// RAII object used to optionally suppress diagnostics and side-effects from
1329   /// a speculative evaluation.
1330   class SpeculativeEvaluationRAII {
1331     EvalInfo *Info = nullptr;
1332     Expr::EvalStatus OldStatus;
1333     unsigned OldSpeculativeEvaluationDepth;
1334 
1335     void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1336       Info = Other.Info;
1337       OldStatus = Other.OldStatus;
1338       OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1339       Other.Info = nullptr;
1340     }
1341 
1342     void maybeRestoreState() {
1343       if (!Info)
1344         return;
1345 
1346       Info->EvalStatus = OldStatus;
1347       Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1348     }
1349 
1350   public:
1351     SpeculativeEvaluationRAII() = default;
1352 
1353     SpeculativeEvaluationRAII(
1354         EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1355         : Info(&Info), OldStatus(Info.EvalStatus),
1356           OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1357       Info.EvalStatus.Diag = NewDiag;
1358       Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1359     }
1360 
1361     SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1362     SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1363       moveFromAndCancel(std::move(Other));
1364     }
1365 
1366     SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1367       maybeRestoreState();
1368       moveFromAndCancel(std::move(Other));
1369       return *this;
1370     }
1371 
1372     ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1373   };
1374 
1375   /// RAII object wrapping a full-expression or block scope, and handling
1376   /// the ending of the lifetime of temporaries created within it.
1377   template<ScopeKind Kind>
1378   class ScopeRAII {
1379     EvalInfo &Info;
1380     unsigned OldStackSize;
1381   public:
1382     ScopeRAII(EvalInfo &Info)
1383         : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1384       // Push a new temporary version. This is needed to distinguish between
1385       // temporaries created in different iterations of a loop.
1386       Info.CurrentCall->pushTempVersion();
1387     }
1388     bool destroy(bool RunDestructors = true) {
1389       bool OK = cleanup(Info, RunDestructors, OldStackSize);
1390       OldStackSize = -1U;
1391       return OK;
1392     }
1393     ~ScopeRAII() {
1394       if (OldStackSize != -1U)
1395         destroy(false);
1396       // Body moved to a static method to encourage the compiler to inline away
1397       // instances of this class.
1398       Info.CurrentCall->popTempVersion();
1399     }
1400   private:
1401     static bool cleanup(EvalInfo &Info, bool RunDestructors,
1402                         unsigned OldStackSize) {
1403       assert(OldStackSize <= Info.CleanupStack.size() &&
1404              "running cleanups out of order?");
1405 
1406       // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1407       // for a full-expression scope.
1408       bool Success = true;
1409       for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1410         if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1411           if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1412             Success = false;
1413             break;
1414           }
1415         }
1416       }
1417 
1418       // Compact any retained cleanups.
1419       auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1420       if (Kind != ScopeKind::Block)
1421         NewEnd =
1422             std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1423               return C.isDestroyedAtEndOf(Kind);
1424             });
1425       Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1426       return Success;
1427     }
1428   };
1429   typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1430   typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1431   typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1432 }
1433 
1434 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1435                                          CheckSubobjectKind CSK) {
1436   if (Invalid)
1437     return false;
1438   if (isOnePastTheEnd()) {
1439     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1440       << CSK;
1441     setInvalid();
1442     return false;
1443   }
1444   // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1445   // must actually be at least one array element; even a VLA cannot have a
1446   // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1447   return true;
1448 }
1449 
1450 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1451                                                                 const Expr *E) {
1452   Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1453   // Do not set the designator as invalid: we can represent this situation,
1454   // and correct handling of __builtin_object_size requires us to do so.
1455 }
1456 
1457 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1458                                                     const Expr *E,
1459                                                     const APSInt &N) {
1460   // If we're complaining, we must be able to statically determine the size of
1461   // the most derived array.
1462   if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1463     Info.CCEDiag(E, diag::note_constexpr_array_index)
1464       << N << /*array*/ 0
1465       << static_cast<unsigned>(getMostDerivedArraySize());
1466   else
1467     Info.CCEDiag(E, diag::note_constexpr_array_index)
1468       << N << /*non-array*/ 1;
1469   setInvalid();
1470 }
1471 
1472 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1473                                const FunctionDecl *Callee, const LValue *This,
1474                                CallRef Call)
1475     : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1476       Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1477   Info.CurrentCall = this;
1478   ++Info.CallStackDepth;
1479 }
1480 
1481 CallStackFrame::~CallStackFrame() {
1482   assert(Info.CurrentCall == this && "calls retired out of order");
1483   --Info.CallStackDepth;
1484   Info.CurrentCall = Caller;
1485 }
1486 
1487 static bool isRead(AccessKinds AK) {
1488   return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1489 }
1490 
1491 static bool isModification(AccessKinds AK) {
1492   switch (AK) {
1493   case AK_Read:
1494   case AK_ReadObjectRepresentation:
1495   case AK_MemberCall:
1496   case AK_DynamicCast:
1497   case AK_TypeId:
1498     return false;
1499   case AK_Assign:
1500   case AK_Increment:
1501   case AK_Decrement:
1502   case AK_Construct:
1503   case AK_Destroy:
1504     return true;
1505   }
1506   llvm_unreachable("unknown access kind");
1507 }
1508 
1509 static bool isAnyAccess(AccessKinds AK) {
1510   return isRead(AK) || isModification(AK);
1511 }
1512 
1513 /// Is this an access per the C++ definition?
1514 static bool isFormalAccess(AccessKinds AK) {
1515   return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
1516 }
1517 
1518 /// Is this kind of axcess valid on an indeterminate object value?
1519 static bool isValidIndeterminateAccess(AccessKinds AK) {
1520   switch (AK) {
1521   case AK_Read:
1522   case AK_Increment:
1523   case AK_Decrement:
1524     // These need the object's value.
1525     return false;
1526 
1527   case AK_ReadObjectRepresentation:
1528   case AK_Assign:
1529   case AK_Construct:
1530   case AK_Destroy:
1531     // Construction and destruction don't need the value.
1532     return true;
1533 
1534   case AK_MemberCall:
1535   case AK_DynamicCast:
1536   case AK_TypeId:
1537     // These aren't really meaningful on scalars.
1538     return true;
1539   }
1540   llvm_unreachable("unknown access kind");
1541 }
1542 
1543 namespace {
1544   struct ComplexValue {
1545   private:
1546     bool IsInt;
1547 
1548   public:
1549     APSInt IntReal, IntImag;
1550     APFloat FloatReal, FloatImag;
1551 
1552     ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1553 
1554     void makeComplexFloat() { IsInt = false; }
1555     bool isComplexFloat() const { return !IsInt; }
1556     APFloat &getComplexFloatReal() { return FloatReal; }
1557     APFloat &getComplexFloatImag() { return FloatImag; }
1558 
1559     void makeComplexInt() { IsInt = true; }
1560     bool isComplexInt() const { return IsInt; }
1561     APSInt &getComplexIntReal() { return IntReal; }
1562     APSInt &getComplexIntImag() { return IntImag; }
1563 
1564     void moveInto(APValue &v) const {
1565       if (isComplexFloat())
1566         v = APValue(FloatReal, FloatImag);
1567       else
1568         v = APValue(IntReal, IntImag);
1569     }
1570     void setFrom(const APValue &v) {
1571       assert(v.isComplexFloat() || v.isComplexInt());
1572       if (v.isComplexFloat()) {
1573         makeComplexFloat();
1574         FloatReal = v.getComplexFloatReal();
1575         FloatImag = v.getComplexFloatImag();
1576       } else {
1577         makeComplexInt();
1578         IntReal = v.getComplexIntReal();
1579         IntImag = v.getComplexIntImag();
1580       }
1581     }
1582   };
1583 
1584   struct LValue {
1585     APValue::LValueBase Base;
1586     CharUnits Offset;
1587     SubobjectDesignator Designator;
1588     bool IsNullPtr : 1;
1589     bool InvalidBase : 1;
1590 
1591     const APValue::LValueBase getLValueBase() const { return Base; }
1592     CharUnits &getLValueOffset() { return Offset; }
1593     const CharUnits &getLValueOffset() const { return Offset; }
1594     SubobjectDesignator &getLValueDesignator() { return Designator; }
1595     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1596     bool isNullPointer() const { return IsNullPtr;}
1597 
1598     unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1599     unsigned getLValueVersion() const { return Base.getVersion(); }
1600 
1601     void moveInto(APValue &V) const {
1602       if (Designator.Invalid)
1603         V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1604       else {
1605         assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1606         V = APValue(Base, Offset, Designator.Entries,
1607                     Designator.IsOnePastTheEnd, IsNullPtr);
1608       }
1609     }
1610     void setFrom(ASTContext &Ctx, const APValue &V) {
1611       assert(V.isLValue() && "Setting LValue from a non-LValue?");
1612       Base = V.getLValueBase();
1613       Offset = V.getLValueOffset();
1614       InvalidBase = false;
1615       Designator = SubobjectDesignator(Ctx, V);
1616       IsNullPtr = V.isNullPointer();
1617     }
1618 
1619     void set(APValue::LValueBase B, bool BInvalid = false) {
1620 #ifndef NDEBUG
1621       // We only allow a few types of invalid bases. Enforce that here.
1622       if (BInvalid) {
1623         const auto *E = B.get<const Expr *>();
1624         assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1625                "Unexpected type of invalid base");
1626       }
1627 #endif
1628 
1629       Base = B;
1630       Offset = CharUnits::fromQuantity(0);
1631       InvalidBase = BInvalid;
1632       Designator = SubobjectDesignator(getType(B));
1633       IsNullPtr = false;
1634     }
1635 
1636     void setNull(ASTContext &Ctx, QualType PointerTy) {
1637       Base = (const ValueDecl *)nullptr;
1638       Offset =
1639           CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
1640       InvalidBase = false;
1641       Designator = SubobjectDesignator(PointerTy->getPointeeType());
1642       IsNullPtr = true;
1643     }
1644 
1645     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1646       set(B, true);
1647     }
1648 
1649     std::string toString(ASTContext &Ctx, QualType T) const {
1650       APValue Printable;
1651       moveInto(Printable);
1652       return Printable.getAsString(Ctx, T);
1653     }
1654 
1655   private:
1656     // Check that this LValue is not based on a null pointer. If it is, produce
1657     // a diagnostic and mark the designator as invalid.
1658     template <typename GenDiagType>
1659     bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1660       if (Designator.Invalid)
1661         return false;
1662       if (IsNullPtr) {
1663         GenDiag();
1664         Designator.setInvalid();
1665         return false;
1666       }
1667       return true;
1668     }
1669 
1670   public:
1671     bool checkNullPointer(EvalInfo &Info, const Expr *E,
1672                           CheckSubobjectKind CSK) {
1673       return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1674         Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1675       });
1676     }
1677 
1678     bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1679                                        AccessKinds AK) {
1680       return checkNullPointerDiagnosingWith([&Info, E, AK] {
1681         Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1682       });
1683     }
1684 
1685     // Check this LValue refers to an object. If not, set the designator to be
1686     // invalid and emit a diagnostic.
1687     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1688       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1689              Designator.checkSubobject(Info, E, CSK);
1690     }
1691 
1692     void addDecl(EvalInfo &Info, const Expr *E,
1693                  const Decl *D, bool Virtual = false) {
1694       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1695         Designator.addDeclUnchecked(D, Virtual);
1696     }
1697     void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1698       if (!Designator.Entries.empty()) {
1699         Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1700         Designator.setInvalid();
1701         return;
1702       }
1703       if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1704         assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1705         Designator.FirstEntryIsAnUnsizedArray = true;
1706         Designator.addUnsizedArrayUnchecked(ElemTy);
1707       }
1708     }
1709     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1710       if (checkSubobject(Info, E, CSK_ArrayToPointer))
1711         Designator.addArrayUnchecked(CAT);
1712     }
1713     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1714       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1715         Designator.addComplexUnchecked(EltTy, Imag);
1716     }
1717     void clearIsNullPointer() {
1718       IsNullPtr = false;
1719     }
1720     void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1721                               const APSInt &Index, CharUnits ElementSize) {
1722       // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1723       // but we're not required to diagnose it and it's valid in C++.)
1724       if (!Index)
1725         return;
1726 
1727       // Compute the new offset in the appropriate width, wrapping at 64 bits.
1728       // FIXME: When compiling for a 32-bit target, we should use 32-bit
1729       // offsets.
1730       uint64_t Offset64 = Offset.getQuantity();
1731       uint64_t ElemSize64 = ElementSize.getQuantity();
1732       uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1733       Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1734 
1735       if (checkNullPointer(Info, E, CSK_ArrayIndex))
1736         Designator.adjustIndex(Info, E, Index);
1737       clearIsNullPointer();
1738     }
1739     void adjustOffset(CharUnits N) {
1740       Offset += N;
1741       if (N.getQuantity())
1742         clearIsNullPointer();
1743     }
1744   };
1745 
1746   struct MemberPtr {
1747     MemberPtr() {}
1748     explicit MemberPtr(const ValueDecl *Decl) :
1749       DeclAndIsDerivedMember(Decl, false), Path() {}
1750 
1751     /// The member or (direct or indirect) field referred to by this member
1752     /// pointer, or 0 if this is a null member pointer.
1753     const ValueDecl *getDecl() const {
1754       return DeclAndIsDerivedMember.getPointer();
1755     }
1756     /// Is this actually a member of some type derived from the relevant class?
1757     bool isDerivedMember() const {
1758       return DeclAndIsDerivedMember.getInt();
1759     }
1760     /// Get the class which the declaration actually lives in.
1761     const CXXRecordDecl *getContainingRecord() const {
1762       return cast<CXXRecordDecl>(
1763           DeclAndIsDerivedMember.getPointer()->getDeclContext());
1764     }
1765 
1766     void moveInto(APValue &V) const {
1767       V = APValue(getDecl(), isDerivedMember(), Path);
1768     }
1769     void setFrom(const APValue &V) {
1770       assert(V.isMemberPointer());
1771       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1772       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1773       Path.clear();
1774       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1775       Path.insert(Path.end(), P.begin(), P.end());
1776     }
1777 
1778     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1779     /// whether the member is a member of some class derived from the class type
1780     /// of the member pointer.
1781     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1782     /// Path - The path of base/derived classes from the member declaration's
1783     /// class (exclusive) to the class type of the member pointer (inclusive).
1784     SmallVector<const CXXRecordDecl*, 4> Path;
1785 
1786     /// Perform a cast towards the class of the Decl (either up or down the
1787     /// hierarchy).
1788     bool castBack(const CXXRecordDecl *Class) {
1789       assert(!Path.empty());
1790       const CXXRecordDecl *Expected;
1791       if (Path.size() >= 2)
1792         Expected = Path[Path.size() - 2];
1793       else
1794         Expected = getContainingRecord();
1795       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1796         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1797         // if B does not contain the original member and is not a base or
1798         // derived class of the class containing the original member, the result
1799         // of the cast is undefined.
1800         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1801         // (D::*). We consider that to be a language defect.
1802         return false;
1803       }
1804       Path.pop_back();
1805       return true;
1806     }
1807     /// Perform a base-to-derived member pointer cast.
1808     bool castToDerived(const CXXRecordDecl *Derived) {
1809       if (!getDecl())
1810         return true;
1811       if (!isDerivedMember()) {
1812         Path.push_back(Derived);
1813         return true;
1814       }
1815       if (!castBack(Derived))
1816         return false;
1817       if (Path.empty())
1818         DeclAndIsDerivedMember.setInt(false);
1819       return true;
1820     }
1821     /// Perform a derived-to-base member pointer cast.
1822     bool castToBase(const CXXRecordDecl *Base) {
1823       if (!getDecl())
1824         return true;
1825       if (Path.empty())
1826         DeclAndIsDerivedMember.setInt(true);
1827       if (isDerivedMember()) {
1828         Path.push_back(Base);
1829         return true;
1830       }
1831       return castBack(Base);
1832     }
1833   };
1834 
1835   /// Compare two member pointers, which are assumed to be of the same type.
1836   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1837     if (!LHS.getDecl() || !RHS.getDecl())
1838       return !LHS.getDecl() && !RHS.getDecl();
1839     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1840       return false;
1841     return LHS.Path == RHS.Path;
1842   }
1843 }
1844 
1845 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1846 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1847                             const LValue &This, const Expr *E,
1848                             bool AllowNonLiteralTypes = false);
1849 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1850                            bool InvalidBaseOK = false);
1851 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1852                             bool InvalidBaseOK = false);
1853 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1854                                   EvalInfo &Info);
1855 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1856 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1857 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1858                                     EvalInfo &Info);
1859 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1860 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1861 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1862                            EvalInfo &Info);
1863 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1864 
1865 /// Evaluate an integer or fixed point expression into an APResult.
1866 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1867                                         EvalInfo &Info);
1868 
1869 /// Evaluate only a fixed point expression into an APResult.
1870 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1871                                EvalInfo &Info);
1872 
1873 //===----------------------------------------------------------------------===//
1874 // Misc utilities
1875 //===----------------------------------------------------------------------===//
1876 
1877 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1878 /// preserving its value (by extending by up to one bit as needed).
1879 static void negateAsSigned(APSInt &Int) {
1880   if (Int.isUnsigned() || Int.isMinSignedValue()) {
1881     Int = Int.extend(Int.getBitWidth() + 1);
1882     Int.setIsSigned(true);
1883   }
1884   Int = -Int;
1885 }
1886 
1887 template<typename KeyT>
1888 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1889                                          ScopeKind Scope, LValue &LV) {
1890   unsigned Version = getTempVersion();
1891   APValue::LValueBase Base(Key, Index, Version);
1892   LV.set(Base);
1893   return createLocal(Base, Key, T, Scope);
1894 }
1895 
1896 /// Allocate storage for a parameter of a function call made in this frame.
1897 APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1898                                      LValue &LV) {
1899   assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1900   APValue::LValueBase Base(PVD, Index, Args.Version);
1901   LV.set(Base);
1902   // We always destroy parameters at the end of the call, even if we'd allow
1903   // them to live to the end of the full-expression at runtime, in order to
1904   // give portable results and match other compilers.
1905   return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1906 }
1907 
1908 APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1909                                      QualType T, ScopeKind Scope) {
1910   assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1911   unsigned Version = Base.getVersion();
1912   APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1913   assert(Result.isAbsent() && "local created multiple times");
1914 
1915   // If we're creating a local immediately in the operand of a speculative
1916   // evaluation, don't register a cleanup to be run outside the speculative
1917   // evaluation context, since we won't actually be able to initialize this
1918   // object.
1919   if (Index <= Info.SpeculativeEvaluationDepth) {
1920     if (T.isDestructedType())
1921       Info.noteSideEffect();
1922   } else {
1923     Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1924   }
1925   return Result;
1926 }
1927 
1928 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1929   if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1930     FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1931     return nullptr;
1932   }
1933 
1934   DynamicAllocLValue DA(NumHeapAllocs++);
1935   LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1936   auto Result = HeapAllocs.emplace(std::piecewise_construct,
1937                                    std::forward_as_tuple(DA), std::tuple<>());
1938   assert(Result.second && "reused a heap alloc index?");
1939   Result.first->second.AllocExpr = E;
1940   return &Result.first->second.Value;
1941 }
1942 
1943 /// Produce a string describing the given constexpr call.
1944 void CallStackFrame::describe(raw_ostream &Out) {
1945   unsigned ArgIndex = 0;
1946   bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1947                       !isa<CXXConstructorDecl>(Callee) &&
1948                       cast<CXXMethodDecl>(Callee)->isInstance();
1949 
1950   if (!IsMemberCall)
1951     Out << *Callee << '(';
1952 
1953   if (This && IsMemberCall) {
1954     APValue Val;
1955     This->moveInto(Val);
1956     Val.printPretty(Out, Info.Ctx,
1957                     This->Designator.MostDerivedType);
1958     // FIXME: Add parens around Val if needed.
1959     Out << "->" << *Callee << '(';
1960     IsMemberCall = false;
1961   }
1962 
1963   for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1964        E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
1965     if (ArgIndex > (unsigned)IsMemberCall)
1966       Out << ", ";
1967 
1968     const ParmVarDecl *Param = *I;
1969     APValue *V = Info.getParamSlot(Arguments, Param);
1970     if (V)
1971       V->printPretty(Out, Info.Ctx, Param->getType());
1972     else
1973       Out << "<...>";
1974 
1975     if (ArgIndex == 0 && IsMemberCall)
1976       Out << "->" << *Callee << '(';
1977   }
1978 
1979   Out << ')';
1980 }
1981 
1982 /// Evaluate an expression to see if it had side-effects, and discard its
1983 /// result.
1984 /// \return \c true if the caller should keep evaluating.
1985 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1986   APValue Scratch;
1987   if (!Evaluate(Scratch, Info, E))
1988     // We don't need the value, but we might have skipped a side effect here.
1989     return Info.noteSideEffect();
1990   return true;
1991 }
1992 
1993 /// Should this call expression be treated as a string literal?
1994 static bool IsStringLiteralCall(const CallExpr *E) {
1995   unsigned Builtin = E->getBuiltinCallee();
1996   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1997           Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1998 }
1999 
2000 static bool IsGlobalLValue(APValue::LValueBase B) {
2001   // C++11 [expr.const]p3 An address constant expression is a prvalue core
2002   // constant expression of pointer type that evaluates to...
2003 
2004   // ... a null pointer value, or a prvalue core constant expression of type
2005   // std::nullptr_t.
2006   if (!B) return true;
2007 
2008   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
2009     // ... the address of an object with static storage duration,
2010     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
2011       return VD->hasGlobalStorage();
2012     if (isa<TemplateParamObjectDecl>(D))
2013       return true;
2014     // ... the address of a function,
2015     // ... the address of a GUID [MS extension],
2016     return isa<FunctionDecl>(D) || isa<MSGuidDecl>(D);
2017   }
2018 
2019   if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
2020     return true;
2021 
2022   const Expr *E = B.get<const Expr*>();
2023   switch (E->getStmtClass()) {
2024   default:
2025     return false;
2026   case Expr::CompoundLiteralExprClass: {
2027     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
2028     return CLE->isFileScope() && CLE->isLValue();
2029   }
2030   case Expr::MaterializeTemporaryExprClass:
2031     // A materialized temporary might have been lifetime-extended to static
2032     // storage duration.
2033     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
2034   // A string literal has static storage duration.
2035   case Expr::StringLiteralClass:
2036   case Expr::PredefinedExprClass:
2037   case Expr::ObjCStringLiteralClass:
2038   case Expr::ObjCEncodeExprClass:
2039     return true;
2040   case Expr::ObjCBoxedExprClass:
2041     return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2042   case Expr::CallExprClass:
2043     return IsStringLiteralCall(cast<CallExpr>(E));
2044   // For GCC compatibility, &&label has static storage duration.
2045   case Expr::AddrLabelExprClass:
2046     return true;
2047   // A Block literal expression may be used as the initialization value for
2048   // Block variables at global or local static scope.
2049   case Expr::BlockExprClass:
2050     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2051   case Expr::ImplicitValueInitExprClass:
2052     // FIXME:
2053     // We can never form an lvalue with an implicit value initialization as its
2054     // base through expression evaluation, so these only appear in one case: the
2055     // implicit variable declaration we invent when checking whether a constexpr
2056     // constructor can produce a constant expression. We must assume that such
2057     // an expression might be a global lvalue.
2058     return true;
2059   }
2060 }
2061 
2062 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2063   return LVal.Base.dyn_cast<const ValueDecl*>();
2064 }
2065 
2066 static bool IsLiteralLValue(const LValue &Value) {
2067   if (Value.getLValueCallIndex())
2068     return false;
2069   const Expr *E = Value.Base.dyn_cast<const Expr*>();
2070   return E && !isa<MaterializeTemporaryExpr>(E);
2071 }
2072 
2073 static bool IsWeakLValue(const LValue &Value) {
2074   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2075   return Decl && Decl->isWeak();
2076 }
2077 
2078 static bool isZeroSized(const LValue &Value) {
2079   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2080   if (Decl && isa<VarDecl>(Decl)) {
2081     QualType Ty = Decl->getType();
2082     if (Ty->isArrayType())
2083       return Ty->isIncompleteType() ||
2084              Decl->getASTContext().getTypeSize(Ty) == 0;
2085   }
2086   return false;
2087 }
2088 
2089 static bool HasSameBase(const LValue &A, const LValue &B) {
2090   if (!A.getLValueBase())
2091     return !B.getLValueBase();
2092   if (!B.getLValueBase())
2093     return false;
2094 
2095   if (A.getLValueBase().getOpaqueValue() !=
2096       B.getLValueBase().getOpaqueValue())
2097     return false;
2098 
2099   return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2100          A.getLValueVersion() == B.getLValueVersion();
2101 }
2102 
2103 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2104   assert(Base && "no location for a null lvalue");
2105   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2106 
2107   // For a parameter, find the corresponding call stack frame (if it still
2108   // exists), and point at the parameter of the function definition we actually
2109   // invoked.
2110   if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2111     unsigned Idx = PVD->getFunctionScopeIndex();
2112     for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2113       if (F->Arguments.CallIndex == Base.getCallIndex() &&
2114           F->Arguments.Version == Base.getVersion() && F->Callee &&
2115           Idx < F->Callee->getNumParams()) {
2116         VD = F->Callee->getParamDecl(Idx);
2117         break;
2118       }
2119     }
2120   }
2121 
2122   if (VD)
2123     Info.Note(VD->getLocation(), diag::note_declared_at);
2124   else if (const Expr *E = Base.dyn_cast<const Expr*>())
2125     Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2126   else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2127     // FIXME: Produce a note for dangling pointers too.
2128     if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA))
2129       Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2130                 diag::note_constexpr_dynamic_alloc_here);
2131   }
2132   // We have no information to show for a typeid(T) object.
2133 }
2134 
2135 enum class CheckEvaluationResultKind {
2136   ConstantExpression,
2137   FullyInitialized,
2138 };
2139 
2140 /// Materialized temporaries that we've already checked to determine if they're
2141 /// initializsed by a constant expression.
2142 using CheckedTemporaries =
2143     llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
2144 
2145 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2146                                   EvalInfo &Info, SourceLocation DiagLoc,
2147                                   QualType Type, const APValue &Value,
2148                                   ConstantExprKind Kind,
2149                                   SourceLocation SubobjectLoc,
2150                                   CheckedTemporaries &CheckedTemps);
2151 
2152 /// Check that this reference or pointer core constant expression is a valid
2153 /// value for an address or reference constant expression. Return true if we
2154 /// can fold this expression, whether or not it's a constant expression.
2155 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2156                                           QualType Type, const LValue &LVal,
2157                                           ConstantExprKind Kind,
2158                                           CheckedTemporaries &CheckedTemps) {
2159   bool IsReferenceType = Type->isReferenceType();
2160 
2161   APValue::LValueBase Base = LVal.getLValueBase();
2162   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2163 
2164   const Expr *BaseE = Base.dyn_cast<const Expr *>();
2165   const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2166 
2167   // Additional restrictions apply in a template argument. We only enforce the
2168   // C++20 restrictions here; additional syntactic and semantic restrictions
2169   // are applied elsewhere.
2170   if (isTemplateArgument(Kind)) {
2171     int InvalidBaseKind = -1;
2172     StringRef Ident;
2173     if (Base.is<TypeInfoLValue>())
2174       InvalidBaseKind = 0;
2175     else if (isa_and_nonnull<StringLiteral>(BaseE))
2176       InvalidBaseKind = 1;
2177     else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2178              isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2179       InvalidBaseKind = 2;
2180     else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2181       InvalidBaseKind = 3;
2182       Ident = PE->getIdentKindName();
2183     }
2184 
2185     if (InvalidBaseKind != -1) {
2186       Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2187           << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2188           << Ident;
2189       return false;
2190     }
2191   }
2192 
2193   if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD)) {
2194     if (FD->isConsteval()) {
2195       Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2196           << !Type->isAnyPointerType();
2197       Info.Note(FD->getLocation(), diag::note_declared_at);
2198       return false;
2199     }
2200   }
2201 
2202   // Check that the object is a global. Note that the fake 'this' object we
2203   // manufacture when checking potential constant expressions is conservatively
2204   // assumed to be global here.
2205   if (!IsGlobalLValue(Base)) {
2206     if (Info.getLangOpts().CPlusPlus11) {
2207       const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2208       Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2209         << IsReferenceType << !Designator.Entries.empty()
2210         << !!VD << VD;
2211 
2212       auto *VarD = dyn_cast_or_null<VarDecl>(VD);
2213       if (VarD && VarD->isConstexpr()) {
2214         // Non-static local constexpr variables have unintuitive semantics:
2215         //   constexpr int a = 1;
2216         //   constexpr const int *p = &a;
2217         // ... is invalid because the address of 'a' is not constant. Suggest
2218         // adding a 'static' in this case.
2219         Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2220             << VarD
2221             << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2222       } else {
2223         NoteLValueLocation(Info, Base);
2224       }
2225     } else {
2226       Info.FFDiag(Loc);
2227     }
2228     // Don't allow references to temporaries to escape.
2229     return false;
2230   }
2231   assert((Info.checkingPotentialConstantExpression() ||
2232           LVal.getLValueCallIndex() == 0) &&
2233          "have call index for global lvalue");
2234 
2235   if (Base.is<DynamicAllocLValue>()) {
2236     Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2237         << IsReferenceType << !Designator.Entries.empty();
2238     NoteLValueLocation(Info, Base);
2239     return false;
2240   }
2241 
2242   if (BaseVD) {
2243     if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2244       // Check if this is a thread-local variable.
2245       if (Var->getTLSKind())
2246         // FIXME: Diagnostic!
2247         return false;
2248 
2249       // A dllimport variable never acts like a constant, unless we're
2250       // evaluating a value for use only in name mangling.
2251       if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2252         // FIXME: Diagnostic!
2253         return false;
2254     }
2255     if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2256       // __declspec(dllimport) must be handled very carefully:
2257       // We must never initialize an expression with the thunk in C++.
2258       // Doing otherwise would allow the same id-expression to yield
2259       // different addresses for the same function in different translation
2260       // units.  However, this means that we must dynamically initialize the
2261       // expression with the contents of the import address table at runtime.
2262       //
2263       // The C language has no notion of ODR; furthermore, it has no notion of
2264       // dynamic initialization.  This means that we are permitted to
2265       // perform initialization with the address of the thunk.
2266       if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2267           FD->hasAttr<DLLImportAttr>())
2268         // FIXME: Diagnostic!
2269         return false;
2270     }
2271   } else if (const auto *MTE =
2272                  dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2273     if (CheckedTemps.insert(MTE).second) {
2274       QualType TempType = getType(Base);
2275       if (TempType.isDestructedType()) {
2276         Info.FFDiag(MTE->getExprLoc(),
2277                     diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2278             << TempType;
2279         return false;
2280       }
2281 
2282       APValue *V = MTE->getOrCreateValue(false);
2283       assert(V && "evasluation result refers to uninitialised temporary");
2284       if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2285                                  Info, MTE->getExprLoc(), TempType, *V,
2286                                  Kind, SourceLocation(), CheckedTemps))
2287         return false;
2288     }
2289   }
2290 
2291   // Allow address constant expressions to be past-the-end pointers. This is
2292   // an extension: the standard requires them to point to an object.
2293   if (!IsReferenceType)
2294     return true;
2295 
2296   // A reference constant expression must refer to an object.
2297   if (!Base) {
2298     // FIXME: diagnostic
2299     Info.CCEDiag(Loc);
2300     return true;
2301   }
2302 
2303   // Does this refer one past the end of some object?
2304   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2305     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2306       << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2307     NoteLValueLocation(Info, Base);
2308   }
2309 
2310   return true;
2311 }
2312 
2313 /// Member pointers are constant expressions unless they point to a
2314 /// non-virtual dllimport member function.
2315 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2316                                                  SourceLocation Loc,
2317                                                  QualType Type,
2318                                                  const APValue &Value,
2319                                                  ConstantExprKind Kind) {
2320   const ValueDecl *Member = Value.getMemberPointerDecl();
2321   const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2322   if (!FD)
2323     return true;
2324   if (FD->isConsteval()) {
2325     Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2326     Info.Note(FD->getLocation(), diag::note_declared_at);
2327     return false;
2328   }
2329   return isForManglingOnly(Kind) || FD->isVirtual() ||
2330          !FD->hasAttr<DLLImportAttr>();
2331 }
2332 
2333 /// Check that this core constant expression is of literal type, and if not,
2334 /// produce an appropriate diagnostic.
2335 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2336                              const LValue *This = nullptr) {
2337   if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
2338     return true;
2339 
2340   // C++1y: A constant initializer for an object o [...] may also invoke
2341   // constexpr constructors for o and its subobjects even if those objects
2342   // are of non-literal class types.
2343   //
2344   // C++11 missed this detail for aggregates, so classes like this:
2345   //   struct foo_t { union { int i; volatile int j; } u; };
2346   // are not (obviously) initializable like so:
2347   //   __attribute__((__require_constant_initialization__))
2348   //   static const foo_t x = {{0}};
2349   // because "i" is a subobject with non-literal initialization (due to the
2350   // volatile member of the union). See:
2351   //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2352   // Therefore, we use the C++1y behavior.
2353   if (This && Info.EvaluatingDecl == This->getLValueBase())
2354     return true;
2355 
2356   // Prvalue constant expressions must be of literal types.
2357   if (Info.getLangOpts().CPlusPlus11)
2358     Info.FFDiag(E, diag::note_constexpr_nonliteral)
2359       << E->getType();
2360   else
2361     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2362   return false;
2363 }
2364 
2365 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2366                                   EvalInfo &Info, SourceLocation DiagLoc,
2367                                   QualType Type, const APValue &Value,
2368                                   ConstantExprKind Kind,
2369                                   SourceLocation SubobjectLoc,
2370                                   CheckedTemporaries &CheckedTemps) {
2371   if (!Value.hasValue()) {
2372     Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2373       << true << Type;
2374     if (SubobjectLoc.isValid())
2375       Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2376     return false;
2377   }
2378 
2379   // We allow _Atomic(T) to be initialized from anything that T can be
2380   // initialized from.
2381   if (const AtomicType *AT = Type->getAs<AtomicType>())
2382     Type = AT->getValueType();
2383 
2384   // Core issue 1454: For a literal constant expression of array or class type,
2385   // each subobject of its value shall have been initialized by a constant
2386   // expression.
2387   if (Value.isArray()) {
2388     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2389     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2390       if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2391                                  Value.getArrayInitializedElt(I), Kind,
2392                                  SubobjectLoc, CheckedTemps))
2393         return false;
2394     }
2395     if (!Value.hasArrayFiller())
2396       return true;
2397     return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2398                                  Value.getArrayFiller(), Kind, SubobjectLoc,
2399                                  CheckedTemps);
2400   }
2401   if (Value.isUnion() && Value.getUnionField()) {
2402     return CheckEvaluationResult(
2403         CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2404         Value.getUnionValue(), Kind, Value.getUnionField()->getLocation(),
2405         CheckedTemps);
2406   }
2407   if (Value.isStruct()) {
2408     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2409     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2410       unsigned BaseIndex = 0;
2411       for (const CXXBaseSpecifier &BS : CD->bases()) {
2412         if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2413                                    Value.getStructBase(BaseIndex), Kind,
2414                                    BS.getBeginLoc(), CheckedTemps))
2415           return false;
2416         ++BaseIndex;
2417       }
2418     }
2419     for (const auto *I : RD->fields()) {
2420       if (I->isUnnamedBitfield())
2421         continue;
2422 
2423       if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2424                                  Value.getStructField(I->getFieldIndex()),
2425                                  Kind, I->getLocation(), CheckedTemps))
2426         return false;
2427     }
2428   }
2429 
2430   if (Value.isLValue() &&
2431       CERK == CheckEvaluationResultKind::ConstantExpression) {
2432     LValue LVal;
2433     LVal.setFrom(Info.Ctx, Value);
2434     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2435                                          CheckedTemps);
2436   }
2437 
2438   if (Value.isMemberPointer() &&
2439       CERK == CheckEvaluationResultKind::ConstantExpression)
2440     return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2441 
2442   // Everything else is fine.
2443   return true;
2444 }
2445 
2446 /// Check that this core constant expression value is a valid value for a
2447 /// constant expression. If not, report an appropriate diagnostic. Does not
2448 /// check that the expression is of literal type.
2449 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2450                                     QualType Type, const APValue &Value,
2451                                     ConstantExprKind Kind) {
2452   // Nothing to check for a constant expression of type 'cv void'.
2453   if (Type->isVoidType())
2454     return true;
2455 
2456   CheckedTemporaries CheckedTemps;
2457   return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2458                                Info, DiagLoc, Type, Value, Kind,
2459                                SourceLocation(), CheckedTemps);
2460 }
2461 
2462 /// Check that this evaluated value is fully-initialized and can be loaded by
2463 /// an lvalue-to-rvalue conversion.
2464 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2465                                   QualType Type, const APValue &Value) {
2466   CheckedTemporaries CheckedTemps;
2467   return CheckEvaluationResult(
2468       CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2469       ConstantExprKind::Normal, SourceLocation(), CheckedTemps);
2470 }
2471 
2472 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2473 /// "the allocated storage is deallocated within the evaluation".
2474 static bool CheckMemoryLeaks(EvalInfo &Info) {
2475   if (!Info.HeapAllocs.empty()) {
2476     // We can still fold to a constant despite a compile-time memory leak,
2477     // so long as the heap allocation isn't referenced in the result (we check
2478     // that in CheckConstantExpression).
2479     Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2480                  diag::note_constexpr_memory_leak)
2481         << unsigned(Info.HeapAllocs.size() - 1);
2482   }
2483   return true;
2484 }
2485 
2486 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2487   // A null base expression indicates a null pointer.  These are always
2488   // evaluatable, and they are false unless the offset is zero.
2489   if (!Value.getLValueBase()) {
2490     Result = !Value.getLValueOffset().isZero();
2491     return true;
2492   }
2493 
2494   // We have a non-null base.  These are generally known to be true, but if it's
2495   // a weak declaration it can be null at runtime.
2496   Result = true;
2497   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2498   return !Decl || !Decl->isWeak();
2499 }
2500 
2501 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2502   switch (Val.getKind()) {
2503   case APValue::None:
2504   case APValue::Indeterminate:
2505     return false;
2506   case APValue::Int:
2507     Result = Val.getInt().getBoolValue();
2508     return true;
2509   case APValue::FixedPoint:
2510     Result = Val.getFixedPoint().getBoolValue();
2511     return true;
2512   case APValue::Float:
2513     Result = !Val.getFloat().isZero();
2514     return true;
2515   case APValue::ComplexInt:
2516     Result = Val.getComplexIntReal().getBoolValue() ||
2517              Val.getComplexIntImag().getBoolValue();
2518     return true;
2519   case APValue::ComplexFloat:
2520     Result = !Val.getComplexFloatReal().isZero() ||
2521              !Val.getComplexFloatImag().isZero();
2522     return true;
2523   case APValue::LValue:
2524     return EvalPointerValueAsBool(Val, Result);
2525   case APValue::MemberPointer:
2526     Result = Val.getMemberPointerDecl();
2527     return true;
2528   case APValue::Vector:
2529   case APValue::Array:
2530   case APValue::Struct:
2531   case APValue::Union:
2532   case APValue::AddrLabelDiff:
2533     return false;
2534   }
2535 
2536   llvm_unreachable("unknown APValue kind");
2537 }
2538 
2539 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2540                                        EvalInfo &Info) {
2541   assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
2542   APValue Val;
2543   if (!Evaluate(Val, Info, E))
2544     return false;
2545   return HandleConversionToBool(Val, Result);
2546 }
2547 
2548 template<typename T>
2549 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2550                            const T &SrcValue, QualType DestType) {
2551   Info.CCEDiag(E, diag::note_constexpr_overflow)
2552     << SrcValue << DestType;
2553   return Info.noteUndefinedBehavior();
2554 }
2555 
2556 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2557                                  QualType SrcType, const APFloat &Value,
2558                                  QualType DestType, APSInt &Result) {
2559   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2560   // Determine whether we are converting to unsigned or signed.
2561   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2562 
2563   Result = APSInt(DestWidth, !DestSigned);
2564   bool ignored;
2565   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2566       & APFloat::opInvalidOp)
2567     return HandleOverflow(Info, E, Value, DestType);
2568   return true;
2569 }
2570 
2571 /// Get rounding mode used for evaluation of the specified expression.
2572 /// \param[out] DynamicRM Is set to true is the requested rounding mode is
2573 ///                       dynamic.
2574 /// If rounding mode is unknown at compile time, still try to evaluate the
2575 /// expression. If the result is exact, it does not depend on rounding mode.
2576 /// So return "tonearest" mode instead of "dynamic".
2577 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E,
2578                                                 bool &DynamicRM) {
2579   llvm::RoundingMode RM =
2580       E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2581   DynamicRM = (RM == llvm::RoundingMode::Dynamic);
2582   if (DynamicRM)
2583     RM = llvm::RoundingMode::NearestTiesToEven;
2584   return RM;
2585 }
2586 
2587 /// Check if the given evaluation result is allowed for constant evaluation.
2588 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2589                                      APFloat::opStatus St) {
2590   // In a constant context, assume that any dynamic rounding mode or FP
2591   // exception state matches the default floating-point environment.
2592   if (Info.InConstantContext)
2593     return true;
2594 
2595   FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2596   if ((St & APFloat::opInexact) &&
2597       FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2598     // Inexact result means that it depends on rounding mode. If the requested
2599     // mode is dynamic, the evaluation cannot be made in compile time.
2600     Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2601     return false;
2602   }
2603 
2604   if ((St != APFloat::opOK) &&
2605       (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2606        FPO.getFPExceptionMode() != LangOptions::FPE_Ignore ||
2607        FPO.getAllowFEnvAccess())) {
2608     Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2609     return false;
2610   }
2611 
2612   if ((St & APFloat::opStatus::opInvalidOp) &&
2613       FPO.getFPExceptionMode() != LangOptions::FPE_Ignore) {
2614     // There is no usefully definable result.
2615     Info.FFDiag(E);
2616     return false;
2617   }
2618 
2619   // FIXME: if:
2620   // - evaluation triggered other FP exception, and
2621   // - exception mode is not "ignore", and
2622   // - the expression being evaluated is not a part of global variable
2623   //   initializer,
2624   // the evaluation probably need to be rejected.
2625   return true;
2626 }
2627 
2628 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2629                                    QualType SrcType, QualType DestType,
2630                                    APFloat &Result) {
2631   assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E));
2632   bool DynamicRM;
2633   llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM);
2634   APFloat::opStatus St;
2635   APFloat Value = Result;
2636   bool ignored;
2637   St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2638   return checkFloatingPointResult(Info, E, St);
2639 }
2640 
2641 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2642                                  QualType DestType, QualType SrcType,
2643                                  const APSInt &Value) {
2644   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2645   // Figure out if this is a truncate, extend or noop cast.
2646   // If the input is signed, do a sign extend, noop, or truncate.
2647   APSInt Result = Value.extOrTrunc(DestWidth);
2648   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2649   if (DestType->isBooleanType())
2650     Result = Value.getBoolValue();
2651   return Result;
2652 }
2653 
2654 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2655                                  const FPOptions FPO,
2656                                  QualType SrcType, const APSInt &Value,
2657                                  QualType DestType, APFloat &Result) {
2658   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2659   APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(),
2660        APFloat::rmNearestTiesToEven);
2661   if (!Info.InConstantContext && St != llvm::APFloatBase::opOK &&
2662       FPO.isFPConstrained()) {
2663     Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2664     return false;
2665   }
2666   return true;
2667 }
2668 
2669 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2670                                   APValue &Value, const FieldDecl *FD) {
2671   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2672 
2673   if (!Value.isInt()) {
2674     // Trying to store a pointer-cast-to-integer into a bitfield.
2675     // FIXME: In this case, we should provide the diagnostic for casting
2676     // a pointer to an integer.
2677     assert(Value.isLValue() && "integral value neither int nor lvalue?");
2678     Info.FFDiag(E);
2679     return false;
2680   }
2681 
2682   APSInt &Int = Value.getInt();
2683   unsigned OldBitWidth = Int.getBitWidth();
2684   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2685   if (NewBitWidth < OldBitWidth)
2686     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2687   return true;
2688 }
2689 
2690 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2691                                   llvm::APInt &Res) {
2692   APValue SVal;
2693   if (!Evaluate(SVal, Info, E))
2694     return false;
2695   if (SVal.isInt()) {
2696     Res = SVal.getInt();
2697     return true;
2698   }
2699   if (SVal.isFloat()) {
2700     Res = SVal.getFloat().bitcastToAPInt();
2701     return true;
2702   }
2703   if (SVal.isVector()) {
2704     QualType VecTy = E->getType();
2705     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2706     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2707     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2708     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2709     Res = llvm::APInt::getNullValue(VecSize);
2710     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2711       APValue &Elt = SVal.getVectorElt(i);
2712       llvm::APInt EltAsInt;
2713       if (Elt.isInt()) {
2714         EltAsInt = Elt.getInt();
2715       } else if (Elt.isFloat()) {
2716         EltAsInt = Elt.getFloat().bitcastToAPInt();
2717       } else {
2718         // Don't try to handle vectors of anything other than int or float
2719         // (not sure if it's possible to hit this case).
2720         Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2721         return false;
2722       }
2723       unsigned BaseEltSize = EltAsInt.getBitWidth();
2724       if (BigEndian)
2725         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2726       else
2727         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2728     }
2729     return true;
2730   }
2731   // Give up if the input isn't an int, float, or vector.  For example, we
2732   // reject "(v4i16)(intptr_t)&a".
2733   Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2734   return false;
2735 }
2736 
2737 /// Perform the given integer operation, which is known to need at most BitWidth
2738 /// bits, and check for overflow in the original type (if that type was not an
2739 /// unsigned type).
2740 template<typename Operation>
2741 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2742                                  const APSInt &LHS, const APSInt &RHS,
2743                                  unsigned BitWidth, Operation Op,
2744                                  APSInt &Result) {
2745   if (LHS.isUnsigned()) {
2746     Result = Op(LHS, RHS);
2747     return true;
2748   }
2749 
2750   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2751   Result = Value.trunc(LHS.getBitWidth());
2752   if (Result.extend(BitWidth) != Value) {
2753     if (Info.checkingForUndefinedBehavior())
2754       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2755                                        diag::warn_integer_constant_overflow)
2756           << Result.toString(10) << E->getType();
2757     else
2758       return HandleOverflow(Info, E, Value, E->getType());
2759   }
2760   return true;
2761 }
2762 
2763 /// Perform the given binary integer operation.
2764 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2765                               BinaryOperatorKind Opcode, APSInt RHS,
2766                               APSInt &Result) {
2767   switch (Opcode) {
2768   default:
2769     Info.FFDiag(E);
2770     return false;
2771   case BO_Mul:
2772     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2773                                 std::multiplies<APSInt>(), Result);
2774   case BO_Add:
2775     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2776                                 std::plus<APSInt>(), Result);
2777   case BO_Sub:
2778     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2779                                 std::minus<APSInt>(), Result);
2780   case BO_And: Result = LHS & RHS; return true;
2781   case BO_Xor: Result = LHS ^ RHS; return true;
2782   case BO_Or:  Result = LHS | RHS; return true;
2783   case BO_Div:
2784   case BO_Rem:
2785     if (RHS == 0) {
2786       Info.FFDiag(E, diag::note_expr_divide_by_zero);
2787       return false;
2788     }
2789     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2790     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2791     // this operation and gives the two's complement result.
2792     if (RHS.isNegative() && RHS.isAllOnesValue() &&
2793         LHS.isSigned() && LHS.isMinSignedValue())
2794       return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2795                             E->getType());
2796     return true;
2797   case BO_Shl: {
2798     if (Info.getLangOpts().OpenCL)
2799       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2800       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2801                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2802                     RHS.isUnsigned());
2803     else if (RHS.isSigned() && RHS.isNegative()) {
2804       // During constant-folding, a negative shift is an opposite shift. Such
2805       // a shift is not a constant expression.
2806       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2807       RHS = -RHS;
2808       goto shift_right;
2809     }
2810   shift_left:
2811     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2812     // the shifted type.
2813     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2814     if (SA != RHS) {
2815       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2816         << RHS << E->getType() << LHS.getBitWidth();
2817     } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2818       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2819       // operand, and must not overflow the corresponding unsigned type.
2820       // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2821       // E1 x 2^E2 module 2^N.
2822       if (LHS.isNegative())
2823         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2824       else if (LHS.countLeadingZeros() < SA)
2825         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2826     }
2827     Result = LHS << SA;
2828     return true;
2829   }
2830   case BO_Shr: {
2831     if (Info.getLangOpts().OpenCL)
2832       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2833       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2834                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2835                     RHS.isUnsigned());
2836     else if (RHS.isSigned() && RHS.isNegative()) {
2837       // During constant-folding, a negative shift is an opposite shift. Such a
2838       // shift is not a constant expression.
2839       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2840       RHS = -RHS;
2841       goto shift_left;
2842     }
2843   shift_right:
2844     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2845     // shifted type.
2846     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2847     if (SA != RHS)
2848       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2849         << RHS << E->getType() << LHS.getBitWidth();
2850     Result = LHS >> SA;
2851     return true;
2852   }
2853 
2854   case BO_LT: Result = LHS < RHS; return true;
2855   case BO_GT: Result = LHS > RHS; return true;
2856   case BO_LE: Result = LHS <= RHS; return true;
2857   case BO_GE: Result = LHS >= RHS; return true;
2858   case BO_EQ: Result = LHS == RHS; return true;
2859   case BO_NE: Result = LHS != RHS; return true;
2860   case BO_Cmp:
2861     llvm_unreachable("BO_Cmp should be handled elsewhere");
2862   }
2863 }
2864 
2865 /// Perform the given binary floating-point operation, in-place, on LHS.
2866 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2867                                   APFloat &LHS, BinaryOperatorKind Opcode,
2868                                   const APFloat &RHS) {
2869   bool DynamicRM;
2870   llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM);
2871   APFloat::opStatus St;
2872   switch (Opcode) {
2873   default:
2874     Info.FFDiag(E);
2875     return false;
2876   case BO_Mul:
2877     St = LHS.multiply(RHS, RM);
2878     break;
2879   case BO_Add:
2880     St = LHS.add(RHS, RM);
2881     break;
2882   case BO_Sub:
2883     St = LHS.subtract(RHS, RM);
2884     break;
2885   case BO_Div:
2886     // [expr.mul]p4:
2887     //   If the second operand of / or % is zero the behavior is undefined.
2888     if (RHS.isZero())
2889       Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2890     St = LHS.divide(RHS, RM);
2891     break;
2892   }
2893 
2894   // [expr.pre]p4:
2895   //   If during the evaluation of an expression, the result is not
2896   //   mathematically defined [...], the behavior is undefined.
2897   // FIXME: C++ rules require us to not conform to IEEE 754 here.
2898   if (LHS.isNaN()) {
2899     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2900     return Info.noteUndefinedBehavior();
2901   }
2902 
2903   return checkFloatingPointResult(Info, E, St);
2904 }
2905 
2906 static bool handleLogicalOpForVector(const APInt &LHSValue,
2907                                      BinaryOperatorKind Opcode,
2908                                      const APInt &RHSValue, APInt &Result) {
2909   bool LHS = (LHSValue != 0);
2910   bool RHS = (RHSValue != 0);
2911 
2912   if (Opcode == BO_LAnd)
2913     Result = LHS && RHS;
2914   else
2915     Result = LHS || RHS;
2916   return true;
2917 }
2918 static bool handleLogicalOpForVector(const APFloat &LHSValue,
2919                                      BinaryOperatorKind Opcode,
2920                                      const APFloat &RHSValue, APInt &Result) {
2921   bool LHS = !LHSValue.isZero();
2922   bool RHS = !RHSValue.isZero();
2923 
2924   if (Opcode == BO_LAnd)
2925     Result = LHS && RHS;
2926   else
2927     Result = LHS || RHS;
2928   return true;
2929 }
2930 
2931 static bool handleLogicalOpForVector(const APValue &LHSValue,
2932                                      BinaryOperatorKind Opcode,
2933                                      const APValue &RHSValue, APInt &Result) {
2934   // The result is always an int type, however operands match the first.
2935   if (LHSValue.getKind() == APValue::Int)
2936     return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2937                                     RHSValue.getInt(), Result);
2938   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2939   return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2940                                   RHSValue.getFloat(), Result);
2941 }
2942 
2943 template <typename APTy>
2944 static bool
2945 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
2946                                const APTy &RHSValue, APInt &Result) {
2947   switch (Opcode) {
2948   default:
2949     llvm_unreachable("unsupported binary operator");
2950   case BO_EQ:
2951     Result = (LHSValue == RHSValue);
2952     break;
2953   case BO_NE:
2954     Result = (LHSValue != RHSValue);
2955     break;
2956   case BO_LT:
2957     Result = (LHSValue < RHSValue);
2958     break;
2959   case BO_GT:
2960     Result = (LHSValue > RHSValue);
2961     break;
2962   case BO_LE:
2963     Result = (LHSValue <= RHSValue);
2964     break;
2965   case BO_GE:
2966     Result = (LHSValue >= RHSValue);
2967     break;
2968   }
2969 
2970   return true;
2971 }
2972 
2973 static bool handleCompareOpForVector(const APValue &LHSValue,
2974                                      BinaryOperatorKind Opcode,
2975                                      const APValue &RHSValue, APInt &Result) {
2976   // The result is always an int type, however operands match the first.
2977   if (LHSValue.getKind() == APValue::Int)
2978     return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
2979                                           RHSValue.getInt(), Result);
2980   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2981   return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
2982                                         RHSValue.getFloat(), Result);
2983 }
2984 
2985 // Perform binary operations for vector types, in place on the LHS.
2986 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
2987                                     BinaryOperatorKind Opcode,
2988                                     APValue &LHSValue,
2989                                     const APValue &RHSValue) {
2990   assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
2991          "Operation not supported on vector types");
2992 
2993   const auto *VT = E->getType()->castAs<VectorType>();
2994   unsigned NumElements = VT->getNumElements();
2995   QualType EltTy = VT->getElementType();
2996 
2997   // In the cases (typically C as I've observed) where we aren't evaluating
2998   // constexpr but are checking for cases where the LHS isn't yet evaluatable,
2999   // just give up.
3000   if (!LHSValue.isVector()) {
3001     assert(LHSValue.isLValue() &&
3002            "A vector result that isn't a vector OR uncalculated LValue");
3003     Info.FFDiag(E);
3004     return false;
3005   }
3006 
3007   assert(LHSValue.getVectorLength() == NumElements &&
3008          RHSValue.getVectorLength() == NumElements && "Different vector sizes");
3009 
3010   SmallVector<APValue, 4> ResultElements;
3011 
3012   for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
3013     APValue LHSElt = LHSValue.getVectorElt(EltNum);
3014     APValue RHSElt = RHSValue.getVectorElt(EltNum);
3015 
3016     if (EltTy->isIntegerType()) {
3017       APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3018                        EltTy->isUnsignedIntegerType()};
3019       bool Success = true;
3020 
3021       if (BinaryOperator::isLogicalOp(Opcode))
3022         Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3023       else if (BinaryOperator::isComparisonOp(Opcode))
3024         Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3025       else
3026         Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3027                                     RHSElt.getInt(), EltResult);
3028 
3029       if (!Success) {
3030         Info.FFDiag(E);
3031         return false;
3032       }
3033       ResultElements.emplace_back(EltResult);
3034 
3035     } else if (EltTy->isFloatingType()) {
3036       assert(LHSElt.getKind() == APValue::Float &&
3037              RHSElt.getKind() == APValue::Float &&
3038              "Mismatched LHS/RHS/Result Type");
3039       APFloat LHSFloat = LHSElt.getFloat();
3040 
3041       if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3042                                  RHSElt.getFloat())) {
3043         Info.FFDiag(E);
3044         return false;
3045       }
3046 
3047       ResultElements.emplace_back(LHSFloat);
3048     }
3049   }
3050 
3051   LHSValue = APValue(ResultElements.data(), ResultElements.size());
3052   return true;
3053 }
3054 
3055 /// Cast an lvalue referring to a base subobject to a derived class, by
3056 /// truncating the lvalue's path to the given length.
3057 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3058                                const RecordDecl *TruncatedType,
3059                                unsigned TruncatedElements) {
3060   SubobjectDesignator &D = Result.Designator;
3061 
3062   // Check we actually point to a derived class object.
3063   if (TruncatedElements == D.Entries.size())
3064     return true;
3065   assert(TruncatedElements >= D.MostDerivedPathLength &&
3066          "not casting to a derived class");
3067   if (!Result.checkSubobject(Info, E, CSK_Derived))
3068     return false;
3069 
3070   // Truncate the path to the subobject, and remove any derived-to-base offsets.
3071   const RecordDecl *RD = TruncatedType;
3072   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3073     if (RD->isInvalidDecl()) return false;
3074     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3075     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3076     if (isVirtualBaseClass(D.Entries[I]))
3077       Result.Offset -= Layout.getVBaseClassOffset(Base);
3078     else
3079       Result.Offset -= Layout.getBaseClassOffset(Base);
3080     RD = Base;
3081   }
3082   D.Entries.resize(TruncatedElements);
3083   return true;
3084 }
3085 
3086 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3087                                    const CXXRecordDecl *Derived,
3088                                    const CXXRecordDecl *Base,
3089                                    const ASTRecordLayout *RL = nullptr) {
3090   if (!RL) {
3091     if (Derived->isInvalidDecl()) return false;
3092     RL = &Info.Ctx.getASTRecordLayout(Derived);
3093   }
3094 
3095   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3096   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3097   return true;
3098 }
3099 
3100 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3101                              const CXXRecordDecl *DerivedDecl,
3102                              const CXXBaseSpecifier *Base) {
3103   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3104 
3105   if (!Base->isVirtual())
3106     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3107 
3108   SubobjectDesignator &D = Obj.Designator;
3109   if (D.Invalid)
3110     return false;
3111 
3112   // Extract most-derived object and corresponding type.
3113   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3114   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3115     return false;
3116 
3117   // Find the virtual base class.
3118   if (DerivedDecl->isInvalidDecl()) return false;
3119   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3120   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3121   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3122   return true;
3123 }
3124 
3125 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3126                                  QualType Type, LValue &Result) {
3127   for (CastExpr::path_const_iterator PathI = E->path_begin(),
3128                                      PathE = E->path_end();
3129        PathI != PathE; ++PathI) {
3130     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3131                           *PathI))
3132       return false;
3133     Type = (*PathI)->getType();
3134   }
3135   return true;
3136 }
3137 
3138 /// Cast an lvalue referring to a derived class to a known base subobject.
3139 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3140                             const CXXRecordDecl *DerivedRD,
3141                             const CXXRecordDecl *BaseRD) {
3142   CXXBasePaths Paths(/*FindAmbiguities=*/false,
3143                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
3144   if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3145     llvm_unreachable("Class must be derived from the passed in base class!");
3146 
3147   for (CXXBasePathElement &Elem : Paths.front())
3148     if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3149       return false;
3150   return true;
3151 }
3152 
3153 /// Update LVal to refer to the given field, which must be a member of the type
3154 /// currently described by LVal.
3155 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3156                                const FieldDecl *FD,
3157                                const ASTRecordLayout *RL = nullptr) {
3158   if (!RL) {
3159     if (FD->getParent()->isInvalidDecl()) return false;
3160     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3161   }
3162 
3163   unsigned I = FD->getFieldIndex();
3164   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3165   LVal.addDecl(Info, E, FD);
3166   return true;
3167 }
3168 
3169 /// Update LVal to refer to the given indirect field.
3170 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3171                                        LValue &LVal,
3172                                        const IndirectFieldDecl *IFD) {
3173   for (const auto *C : IFD->chain())
3174     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3175       return false;
3176   return true;
3177 }
3178 
3179 /// Get the size of the given type in char units.
3180 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
3181                          QualType Type, CharUnits &Size) {
3182   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3183   // extension.
3184   if (Type->isVoidType() || Type->isFunctionType()) {
3185     Size = CharUnits::One();
3186     return true;
3187   }
3188 
3189   if (Type->isDependentType()) {
3190     Info.FFDiag(Loc);
3191     return false;
3192   }
3193 
3194   if (!Type->isConstantSizeType()) {
3195     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3196     // FIXME: Better diagnostic.
3197     Info.FFDiag(Loc);
3198     return false;
3199   }
3200 
3201   Size = Info.Ctx.getTypeSizeInChars(Type);
3202   return true;
3203 }
3204 
3205 /// Update a pointer value to model pointer arithmetic.
3206 /// \param Info - Information about the ongoing evaluation.
3207 /// \param E - The expression being evaluated, for diagnostic purposes.
3208 /// \param LVal - The pointer value to be updated.
3209 /// \param EltTy - The pointee type represented by LVal.
3210 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3211 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3212                                         LValue &LVal, QualType EltTy,
3213                                         APSInt Adjustment) {
3214   CharUnits SizeOfPointee;
3215   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3216     return false;
3217 
3218   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3219   return true;
3220 }
3221 
3222 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3223                                         LValue &LVal, QualType EltTy,
3224                                         int64_t Adjustment) {
3225   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3226                                      APSInt::get(Adjustment));
3227 }
3228 
3229 /// Update an lvalue to refer to a component of a complex number.
3230 /// \param Info - Information about the ongoing evaluation.
3231 /// \param LVal - The lvalue to be updated.
3232 /// \param EltTy - The complex number's component type.
3233 /// \param Imag - False for the real component, true for the imaginary.
3234 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3235                                        LValue &LVal, QualType EltTy,
3236                                        bool Imag) {
3237   if (Imag) {
3238     CharUnits SizeOfComponent;
3239     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3240       return false;
3241     LVal.Offset += SizeOfComponent;
3242   }
3243   LVal.addComplex(Info, E, EltTy, Imag);
3244   return true;
3245 }
3246 
3247 /// Try to evaluate the initializer for a variable declaration.
3248 ///
3249 /// \param Info   Information about the ongoing evaluation.
3250 /// \param E      An expression to be used when printing diagnostics.
3251 /// \param VD     The variable whose initializer should be obtained.
3252 /// \param Version The version of the variable within the frame.
3253 /// \param Frame  The frame in which the variable was created. Must be null
3254 ///               if this variable is not local to the evaluation.
3255 /// \param Result Filled in with a pointer to the value of the variable.
3256 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3257                                 const VarDecl *VD, CallStackFrame *Frame,
3258                                 unsigned Version, APValue *&Result) {
3259   APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3260 
3261   // If this is a local variable, dig out its value.
3262   if (Frame) {
3263     Result = Frame->getTemporary(VD, Version);
3264     if (Result)
3265       return true;
3266 
3267     if (!isa<ParmVarDecl>(VD)) {
3268       // Assume variables referenced within a lambda's call operator that were
3269       // not declared within the call operator are captures and during checking
3270       // of a potential constant expression, assume they are unknown constant
3271       // expressions.
3272       assert(isLambdaCallOperator(Frame->Callee) &&
3273              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3274              "missing value for local variable");
3275       if (Info.checkingPotentialConstantExpression())
3276         return false;
3277       // FIXME: This diagnostic is bogus; we do support captures. Is this code
3278       // still reachable at all?
3279       Info.FFDiag(E->getBeginLoc(),
3280                   diag::note_unimplemented_constexpr_lambda_feature_ast)
3281           << "captures not currently allowed";
3282       return false;
3283     }
3284   }
3285 
3286   // If we're currently evaluating the initializer of this declaration, use that
3287   // in-flight value.
3288   if (Info.EvaluatingDecl == Base) {
3289     Result = Info.EvaluatingDeclValue;
3290     return true;
3291   }
3292 
3293   if (isa<ParmVarDecl>(VD)) {
3294     // Assume parameters of a potential constant expression are usable in
3295     // constant expressions.
3296     if (!Info.checkingPotentialConstantExpression() ||
3297         !Info.CurrentCall->Callee ||
3298         !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3299       if (Info.getLangOpts().CPlusPlus11) {
3300         Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3301             << VD;
3302         NoteLValueLocation(Info, Base);
3303       } else {
3304         Info.FFDiag(E);
3305       }
3306     }
3307     return false;
3308   }
3309 
3310   // Dig out the initializer, and use the declaration which it's attached to.
3311   // FIXME: We should eventually check whether the variable has a reachable
3312   // initializing declaration.
3313   const Expr *Init = VD->getAnyInitializer(VD);
3314   if (!Init) {
3315     // Don't diagnose during potential constant expression checking; an
3316     // initializer might be added later.
3317     if (!Info.checkingPotentialConstantExpression()) {
3318       Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3319         << VD;
3320       NoteLValueLocation(Info, Base);
3321     }
3322     return false;
3323   }
3324 
3325   if (Init->isValueDependent()) {
3326     // The DeclRefExpr is not value-dependent, but the variable it refers to
3327     // has a value-dependent initializer. This should only happen in
3328     // constant-folding cases, where the variable is not actually of a suitable
3329     // type for use in a constant expression (otherwise the DeclRefExpr would
3330     // have been value-dependent too), so diagnose that.
3331     assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3332     if (!Info.checkingPotentialConstantExpression()) {
3333       Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3334                          ? diag::note_constexpr_ltor_non_constexpr
3335                          : diag::note_constexpr_ltor_non_integral, 1)
3336           << VD << VD->getType();
3337       NoteLValueLocation(Info, Base);
3338     }
3339     return false;
3340   }
3341 
3342   // Check that we can fold the initializer. In C++, we will have already done
3343   // this in the cases where it matters for conformance.
3344   if (!VD->evaluateValue()) {
3345     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3346     NoteLValueLocation(Info, Base);
3347     return false;
3348   }
3349 
3350   // Check that the variable is actually usable in constant expressions. For a
3351   // const integral variable or a reference, we might have a non-constant
3352   // initializer that we can nonetheless evaluate the initializer for. Such
3353   // variables are not usable in constant expressions. In C++98, the
3354   // initializer also syntactically needs to be an ICE.
3355   //
3356   // FIXME: We don't diagnose cases that aren't potentially usable in constant
3357   // expressions here; doing so would regress diagnostics for things like
3358   // reading from a volatile constexpr variable.
3359   if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3360        VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||
3361       ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3362        !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3363     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3364     NoteLValueLocation(Info, Base);
3365   }
3366 
3367   // Never use the initializer of a weak variable, not even for constant
3368   // folding. We can't be sure that this is the definition that will be used.
3369   if (VD->isWeak()) {
3370     Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3371     NoteLValueLocation(Info, Base);
3372     return false;
3373   }
3374 
3375   Result = VD->getEvaluatedValue();
3376   return true;
3377 }
3378 
3379 /// Get the base index of the given base class within an APValue representing
3380 /// the given derived class.
3381 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3382                              const CXXRecordDecl *Base) {
3383   Base = Base->getCanonicalDecl();
3384   unsigned Index = 0;
3385   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3386          E = Derived->bases_end(); I != E; ++I, ++Index) {
3387     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3388       return Index;
3389   }
3390 
3391   llvm_unreachable("base class missing from derived class's bases list");
3392 }
3393 
3394 /// Extract the value of a character from a string literal.
3395 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3396                                             uint64_t Index) {
3397   assert(!isa<SourceLocExpr>(Lit) &&
3398          "SourceLocExpr should have already been converted to a StringLiteral");
3399 
3400   // FIXME: Support MakeStringConstant
3401   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3402     std::string Str;
3403     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3404     assert(Index <= Str.size() && "Index too large");
3405     return APSInt::getUnsigned(Str.c_str()[Index]);
3406   }
3407 
3408   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3409     Lit = PE->getFunctionName();
3410   const StringLiteral *S = cast<StringLiteral>(Lit);
3411   const ConstantArrayType *CAT =
3412       Info.Ctx.getAsConstantArrayType(S->getType());
3413   assert(CAT && "string literal isn't an array");
3414   QualType CharType = CAT->getElementType();
3415   assert(CharType->isIntegerType() && "unexpected character type");
3416 
3417   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3418                CharType->isUnsignedIntegerType());
3419   if (Index < S->getLength())
3420     Value = S->getCodeUnit(Index);
3421   return Value;
3422 }
3423 
3424 // Expand a string literal into an array of characters.
3425 //
3426 // FIXME: This is inefficient; we should probably introduce something similar
3427 // to the LLVM ConstantDataArray to make this cheaper.
3428 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3429                                 APValue &Result,
3430                                 QualType AllocType = QualType()) {
3431   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3432       AllocType.isNull() ? S->getType() : AllocType);
3433   assert(CAT && "string literal isn't an array");
3434   QualType CharType = CAT->getElementType();
3435   assert(CharType->isIntegerType() && "unexpected character type");
3436 
3437   unsigned Elts = CAT->getSize().getZExtValue();
3438   Result = APValue(APValue::UninitArray(),
3439                    std::min(S->getLength(), Elts), Elts);
3440   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3441                CharType->isUnsignedIntegerType());
3442   if (Result.hasArrayFiller())
3443     Result.getArrayFiller() = APValue(Value);
3444   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3445     Value = S->getCodeUnit(I);
3446     Result.getArrayInitializedElt(I) = APValue(Value);
3447   }
3448 }
3449 
3450 // Expand an array so that it has more than Index filled elements.
3451 static void expandArray(APValue &Array, unsigned Index) {
3452   unsigned Size = Array.getArraySize();
3453   assert(Index < Size);
3454 
3455   // Always at least double the number of elements for which we store a value.
3456   unsigned OldElts = Array.getArrayInitializedElts();
3457   unsigned NewElts = std::max(Index+1, OldElts * 2);
3458   NewElts = std::min(Size, std::max(NewElts, 8u));
3459 
3460   // Copy the data across.
3461   APValue NewValue(APValue::UninitArray(), NewElts, Size);
3462   for (unsigned I = 0; I != OldElts; ++I)
3463     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3464   for (unsigned I = OldElts; I != NewElts; ++I)
3465     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3466   if (NewValue.hasArrayFiller())
3467     NewValue.getArrayFiller() = Array.getArrayFiller();
3468   Array.swap(NewValue);
3469 }
3470 
3471 /// Determine whether a type would actually be read by an lvalue-to-rvalue
3472 /// conversion. If it's of class type, we may assume that the copy operation
3473 /// is trivial. Note that this is never true for a union type with fields
3474 /// (because the copy always "reads" the active member) and always true for
3475 /// a non-class type.
3476 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3477 static bool isReadByLvalueToRvalueConversion(QualType T) {
3478   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3479   return !RD || isReadByLvalueToRvalueConversion(RD);
3480 }
3481 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3482   // FIXME: A trivial copy of a union copies the object representation, even if
3483   // the union is empty.
3484   if (RD->isUnion())
3485     return !RD->field_empty();
3486   if (RD->isEmpty())
3487     return false;
3488 
3489   for (auto *Field : RD->fields())
3490     if (!Field->isUnnamedBitfield() &&
3491         isReadByLvalueToRvalueConversion(Field->getType()))
3492       return true;
3493 
3494   for (auto &BaseSpec : RD->bases())
3495     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3496       return true;
3497 
3498   return false;
3499 }
3500 
3501 /// Diagnose an attempt to read from any unreadable field within the specified
3502 /// type, which might be a class type.
3503 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3504                                   QualType T) {
3505   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3506   if (!RD)
3507     return false;
3508 
3509   if (!RD->hasMutableFields())
3510     return false;
3511 
3512   for (auto *Field : RD->fields()) {
3513     // If we're actually going to read this field in some way, then it can't
3514     // be mutable. If we're in a union, then assigning to a mutable field
3515     // (even an empty one) can change the active member, so that's not OK.
3516     // FIXME: Add core issue number for the union case.
3517     if (Field->isMutable() &&
3518         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3519       Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3520       Info.Note(Field->getLocation(), diag::note_declared_at);
3521       return true;
3522     }
3523 
3524     if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3525       return true;
3526   }
3527 
3528   for (auto &BaseSpec : RD->bases())
3529     if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3530       return true;
3531 
3532   // All mutable fields were empty, and thus not actually read.
3533   return false;
3534 }
3535 
3536 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3537                                         APValue::LValueBase Base,
3538                                         bool MutableSubobject = false) {
3539   // A temporary we created.
3540   if (Base.getCallIndex())
3541     return true;
3542 
3543   switch (Info.IsEvaluatingDecl) {
3544   case EvalInfo::EvaluatingDeclKind::None:
3545     return false;
3546 
3547   case EvalInfo::EvaluatingDeclKind::Ctor:
3548     // The variable whose initializer we're evaluating.
3549     if (Info.EvaluatingDecl == Base)
3550       return true;
3551 
3552     // A temporary lifetime-extended by the variable whose initializer we're
3553     // evaluating.
3554     if (auto *BaseE = Base.dyn_cast<const Expr *>())
3555       if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3556         return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3557     return false;
3558 
3559   case EvalInfo::EvaluatingDeclKind::Dtor:
3560     // C++2a [expr.const]p6:
3561     //   [during constant destruction] the lifetime of a and its non-mutable
3562     //   subobjects (but not its mutable subobjects) [are] considered to start
3563     //   within e.
3564     if (MutableSubobject || Base != Info.EvaluatingDecl)
3565       return false;
3566     // FIXME: We can meaningfully extend this to cover non-const objects, but
3567     // we will need special handling: we should be able to access only
3568     // subobjects of such objects that are themselves declared const.
3569     QualType T = getType(Base);
3570     return T.isConstQualified() || T->isReferenceType();
3571   }
3572 
3573   llvm_unreachable("unknown evaluating decl kind");
3574 }
3575 
3576 namespace {
3577 /// A handle to a complete object (an object that is not a subobject of
3578 /// another object).
3579 struct CompleteObject {
3580   /// The identity of the object.
3581   APValue::LValueBase Base;
3582   /// The value of the complete object.
3583   APValue *Value;
3584   /// The type of the complete object.
3585   QualType Type;
3586 
3587   CompleteObject() : Value(nullptr) {}
3588   CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3589       : Base(Base), Value(Value), Type(Type) {}
3590 
3591   bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3592     // If this isn't a "real" access (eg, if it's just accessing the type
3593     // info), allow it. We assume the type doesn't change dynamically for
3594     // subobjects of constexpr objects (even though we'd hit UB here if it
3595     // did). FIXME: Is this right?
3596     if (!isAnyAccess(AK))
3597       return true;
3598 
3599     // In C++14 onwards, it is permitted to read a mutable member whose
3600     // lifetime began within the evaluation.
3601     // FIXME: Should we also allow this in C++11?
3602     if (!Info.getLangOpts().CPlusPlus14)
3603       return false;
3604     return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3605   }
3606 
3607   explicit operator bool() const { return !Type.isNull(); }
3608 };
3609 } // end anonymous namespace
3610 
3611 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3612                                  bool IsMutable = false) {
3613   // C++ [basic.type.qualifier]p1:
3614   // - A const object is an object of type const T or a non-mutable subobject
3615   //   of a const object.
3616   if (ObjType.isConstQualified() && !IsMutable)
3617     SubobjType.addConst();
3618   // - A volatile object is an object of type const T or a subobject of a
3619   //   volatile object.
3620   if (ObjType.isVolatileQualified())
3621     SubobjType.addVolatile();
3622   return SubobjType;
3623 }
3624 
3625 /// Find the designated sub-object of an rvalue.
3626 template<typename SubobjectHandler>
3627 typename SubobjectHandler::result_type
3628 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3629               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3630   if (Sub.Invalid)
3631     // A diagnostic will have already been produced.
3632     return handler.failed();
3633   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3634     if (Info.getLangOpts().CPlusPlus11)
3635       Info.FFDiag(E, Sub.isOnePastTheEnd()
3636                          ? diag::note_constexpr_access_past_end
3637                          : diag::note_constexpr_access_unsized_array)
3638           << handler.AccessKind;
3639     else
3640       Info.FFDiag(E);
3641     return handler.failed();
3642   }
3643 
3644   APValue *O = Obj.Value;
3645   QualType ObjType = Obj.Type;
3646   const FieldDecl *LastField = nullptr;
3647   const FieldDecl *VolatileField = nullptr;
3648 
3649   // Walk the designator's path to find the subobject.
3650   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3651     // Reading an indeterminate value is undefined, but assigning over one is OK.
3652     if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3653         (O->isIndeterminate() &&
3654          !isValidIndeterminateAccess(handler.AccessKind))) {
3655       if (!Info.checkingPotentialConstantExpression())
3656         Info.FFDiag(E, diag::note_constexpr_access_uninit)
3657             << handler.AccessKind << O->isIndeterminate();
3658       return handler.failed();
3659     }
3660 
3661     // C++ [class.ctor]p5, C++ [class.dtor]p5:
3662     //    const and volatile semantics are not applied on an object under
3663     //    {con,de}struction.
3664     if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3665         ObjType->isRecordType() &&
3666         Info.isEvaluatingCtorDtor(
3667             Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3668                                          Sub.Entries.begin() + I)) !=
3669                           ConstructionPhase::None) {
3670       ObjType = Info.Ctx.getCanonicalType(ObjType);
3671       ObjType.removeLocalConst();
3672       ObjType.removeLocalVolatile();
3673     }
3674 
3675     // If this is our last pass, check that the final object type is OK.
3676     if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3677       // Accesses to volatile objects are prohibited.
3678       if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3679         if (Info.getLangOpts().CPlusPlus) {
3680           int DiagKind;
3681           SourceLocation Loc;
3682           const NamedDecl *Decl = nullptr;
3683           if (VolatileField) {
3684             DiagKind = 2;
3685             Loc = VolatileField->getLocation();
3686             Decl = VolatileField;
3687           } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3688             DiagKind = 1;
3689             Loc = VD->getLocation();
3690             Decl = VD;
3691           } else {
3692             DiagKind = 0;
3693             if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3694               Loc = E->getExprLoc();
3695           }
3696           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3697               << handler.AccessKind << DiagKind << Decl;
3698           Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3699         } else {
3700           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3701         }
3702         return handler.failed();
3703       }
3704 
3705       // If we are reading an object of class type, there may still be more
3706       // things we need to check: if there are any mutable subobjects, we
3707       // cannot perform this read. (This only happens when performing a trivial
3708       // copy or assignment.)
3709       if (ObjType->isRecordType() &&
3710           !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3711           diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3712         return handler.failed();
3713     }
3714 
3715     if (I == N) {
3716       if (!handler.found(*O, ObjType))
3717         return false;
3718 
3719       // If we modified a bit-field, truncate it to the right width.
3720       if (isModification(handler.AccessKind) &&
3721           LastField && LastField->isBitField() &&
3722           !truncateBitfieldValue(Info, E, *O, LastField))
3723         return false;
3724 
3725       return true;
3726     }
3727 
3728     LastField = nullptr;
3729     if (ObjType->isArrayType()) {
3730       // Next subobject is an array element.
3731       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3732       assert(CAT && "vla in literal type?");
3733       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3734       if (CAT->getSize().ule(Index)) {
3735         // Note, it should not be possible to form a pointer with a valid
3736         // designator which points more than one past the end of the array.
3737         if (Info.getLangOpts().CPlusPlus11)
3738           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3739             << handler.AccessKind;
3740         else
3741           Info.FFDiag(E);
3742         return handler.failed();
3743       }
3744 
3745       ObjType = CAT->getElementType();
3746 
3747       if (O->getArrayInitializedElts() > Index)
3748         O = &O->getArrayInitializedElt(Index);
3749       else if (!isRead(handler.AccessKind)) {
3750         expandArray(*O, Index);
3751         O = &O->getArrayInitializedElt(Index);
3752       } else
3753         O = &O->getArrayFiller();
3754     } else if (ObjType->isAnyComplexType()) {
3755       // Next subobject is a complex number.
3756       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3757       if (Index > 1) {
3758         if (Info.getLangOpts().CPlusPlus11)
3759           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3760             << handler.AccessKind;
3761         else
3762           Info.FFDiag(E);
3763         return handler.failed();
3764       }
3765 
3766       ObjType = getSubobjectType(
3767           ObjType, ObjType->castAs<ComplexType>()->getElementType());
3768 
3769       assert(I == N - 1 && "extracting subobject of scalar?");
3770       if (O->isComplexInt()) {
3771         return handler.found(Index ? O->getComplexIntImag()
3772                                    : O->getComplexIntReal(), ObjType);
3773       } else {
3774         assert(O->isComplexFloat());
3775         return handler.found(Index ? O->getComplexFloatImag()
3776                                    : O->getComplexFloatReal(), ObjType);
3777       }
3778     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3779       if (Field->isMutable() &&
3780           !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3781         Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3782           << handler.AccessKind << Field;
3783         Info.Note(Field->getLocation(), diag::note_declared_at);
3784         return handler.failed();
3785       }
3786 
3787       // Next subobject is a class, struct or union field.
3788       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3789       if (RD->isUnion()) {
3790         const FieldDecl *UnionField = O->getUnionField();
3791         if (!UnionField ||
3792             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3793           if (I == N - 1 && handler.AccessKind == AK_Construct) {
3794             // Placement new onto an inactive union member makes it active.
3795             O->setUnion(Field, APValue());
3796           } else {
3797             // FIXME: If O->getUnionValue() is absent, report that there's no
3798             // active union member rather than reporting the prior active union
3799             // member. We'll need to fix nullptr_t to not use APValue() as its
3800             // representation first.
3801             Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3802                 << handler.AccessKind << Field << !UnionField << UnionField;
3803             return handler.failed();
3804           }
3805         }
3806         O = &O->getUnionValue();
3807       } else
3808         O = &O->getStructField(Field->getFieldIndex());
3809 
3810       ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3811       LastField = Field;
3812       if (Field->getType().isVolatileQualified())
3813         VolatileField = Field;
3814     } else {
3815       // Next subobject is a base class.
3816       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3817       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3818       O = &O->getStructBase(getBaseIndex(Derived, Base));
3819 
3820       ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3821     }
3822   }
3823 }
3824 
3825 namespace {
3826 struct ExtractSubobjectHandler {
3827   EvalInfo &Info;
3828   const Expr *E;
3829   APValue &Result;
3830   const AccessKinds AccessKind;
3831 
3832   typedef bool result_type;
3833   bool failed() { return false; }
3834   bool found(APValue &Subobj, QualType SubobjType) {
3835     Result = Subobj;
3836     if (AccessKind == AK_ReadObjectRepresentation)
3837       return true;
3838     return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3839   }
3840   bool found(APSInt &Value, QualType SubobjType) {
3841     Result = APValue(Value);
3842     return true;
3843   }
3844   bool found(APFloat &Value, QualType SubobjType) {
3845     Result = APValue(Value);
3846     return true;
3847   }
3848 };
3849 } // end anonymous namespace
3850 
3851 /// Extract the designated sub-object of an rvalue.
3852 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3853                              const CompleteObject &Obj,
3854                              const SubobjectDesignator &Sub, APValue &Result,
3855                              AccessKinds AK = AK_Read) {
3856   assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3857   ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3858   return findSubobject(Info, E, Obj, Sub, Handler);
3859 }
3860 
3861 namespace {
3862 struct ModifySubobjectHandler {
3863   EvalInfo &Info;
3864   APValue &NewVal;
3865   const Expr *E;
3866 
3867   typedef bool result_type;
3868   static const AccessKinds AccessKind = AK_Assign;
3869 
3870   bool checkConst(QualType QT) {
3871     // Assigning to a const object has undefined behavior.
3872     if (QT.isConstQualified()) {
3873       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3874       return false;
3875     }
3876     return true;
3877   }
3878 
3879   bool failed() { return false; }
3880   bool found(APValue &Subobj, QualType SubobjType) {
3881     if (!checkConst(SubobjType))
3882       return false;
3883     // We've been given ownership of NewVal, so just swap it in.
3884     Subobj.swap(NewVal);
3885     return true;
3886   }
3887   bool found(APSInt &Value, QualType SubobjType) {
3888     if (!checkConst(SubobjType))
3889       return false;
3890     if (!NewVal.isInt()) {
3891       // Maybe trying to write a cast pointer value into a complex?
3892       Info.FFDiag(E);
3893       return false;
3894     }
3895     Value = NewVal.getInt();
3896     return true;
3897   }
3898   bool found(APFloat &Value, QualType SubobjType) {
3899     if (!checkConst(SubobjType))
3900       return false;
3901     Value = NewVal.getFloat();
3902     return true;
3903   }
3904 };
3905 } // end anonymous namespace
3906 
3907 const AccessKinds ModifySubobjectHandler::AccessKind;
3908 
3909 /// Update the designated sub-object of an rvalue to the given value.
3910 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3911                             const CompleteObject &Obj,
3912                             const SubobjectDesignator &Sub,
3913                             APValue &NewVal) {
3914   ModifySubobjectHandler Handler = { Info, NewVal, E };
3915   return findSubobject(Info, E, Obj, Sub, Handler);
3916 }
3917 
3918 /// Find the position where two subobject designators diverge, or equivalently
3919 /// the length of the common initial subsequence.
3920 static unsigned FindDesignatorMismatch(QualType ObjType,
3921                                        const SubobjectDesignator &A,
3922                                        const SubobjectDesignator &B,
3923                                        bool &WasArrayIndex) {
3924   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3925   for (/**/; I != N; ++I) {
3926     if (!ObjType.isNull() &&
3927         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3928       // Next subobject is an array element.
3929       if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3930         WasArrayIndex = true;
3931         return I;
3932       }
3933       if (ObjType->isAnyComplexType())
3934         ObjType = ObjType->castAs<ComplexType>()->getElementType();
3935       else
3936         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3937     } else {
3938       if (A.Entries[I].getAsBaseOrMember() !=
3939           B.Entries[I].getAsBaseOrMember()) {
3940         WasArrayIndex = false;
3941         return I;
3942       }
3943       if (const FieldDecl *FD = getAsField(A.Entries[I]))
3944         // Next subobject is a field.
3945         ObjType = FD->getType();
3946       else
3947         // Next subobject is a base class.
3948         ObjType = QualType();
3949     }
3950   }
3951   WasArrayIndex = false;
3952   return I;
3953 }
3954 
3955 /// Determine whether the given subobject designators refer to elements of the
3956 /// same array object.
3957 static bool AreElementsOfSameArray(QualType ObjType,
3958                                    const SubobjectDesignator &A,
3959                                    const SubobjectDesignator &B) {
3960   if (A.Entries.size() != B.Entries.size())
3961     return false;
3962 
3963   bool IsArray = A.MostDerivedIsArrayElement;
3964   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3965     // A is a subobject of the array element.
3966     return false;
3967 
3968   // If A (and B) designates an array element, the last entry will be the array
3969   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3970   // of length 1' case, and the entire path must match.
3971   bool WasArrayIndex;
3972   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3973   return CommonLength >= A.Entries.size() - IsArray;
3974 }
3975 
3976 /// Find the complete object to which an LValue refers.
3977 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3978                                          AccessKinds AK, const LValue &LVal,
3979                                          QualType LValType) {
3980   if (LVal.InvalidBase) {
3981     Info.FFDiag(E);
3982     return CompleteObject();
3983   }
3984 
3985   if (!LVal.Base) {
3986     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3987     return CompleteObject();
3988   }
3989 
3990   CallStackFrame *Frame = nullptr;
3991   unsigned Depth = 0;
3992   if (LVal.getLValueCallIndex()) {
3993     std::tie(Frame, Depth) =
3994         Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3995     if (!Frame) {
3996       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3997         << AK << LVal.Base.is<const ValueDecl*>();
3998       NoteLValueLocation(Info, LVal.Base);
3999       return CompleteObject();
4000     }
4001   }
4002 
4003   bool IsAccess = isAnyAccess(AK);
4004 
4005   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
4006   // is not a constant expression (even if the object is non-volatile). We also
4007   // apply this rule to C++98, in order to conform to the expected 'volatile'
4008   // semantics.
4009   if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
4010     if (Info.getLangOpts().CPlusPlus)
4011       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
4012         << AK << LValType;
4013     else
4014       Info.FFDiag(E);
4015     return CompleteObject();
4016   }
4017 
4018   // Compute value storage location and type of base object.
4019   APValue *BaseVal = nullptr;
4020   QualType BaseType = getType(LVal.Base);
4021 
4022   if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4023       lifetimeStartedInEvaluation(Info, LVal.Base)) {
4024     // This is the object whose initializer we're evaluating, so its lifetime
4025     // started in the current evaluation.
4026     BaseVal = Info.EvaluatingDeclValue;
4027   } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4028     // Allow reading from a GUID declaration.
4029     if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4030       if (isModification(AK)) {
4031         // All the remaining cases do not permit modification of the object.
4032         Info.FFDiag(E, diag::note_constexpr_modify_global);
4033         return CompleteObject();
4034       }
4035       APValue &V = GD->getAsAPValue();
4036       if (V.isAbsent()) {
4037         Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4038             << GD->getType();
4039         return CompleteObject();
4040       }
4041       return CompleteObject(LVal.Base, &V, GD->getType());
4042     }
4043 
4044     // Allow reading from template parameter objects.
4045     if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4046       if (isModification(AK)) {
4047         Info.FFDiag(E, diag::note_constexpr_modify_global);
4048         return CompleteObject();
4049       }
4050       return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4051                             TPO->getType());
4052     }
4053 
4054     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4055     // In C++11, constexpr, non-volatile variables initialized with constant
4056     // expressions are constant expressions too. Inside constexpr functions,
4057     // parameters are constant expressions even if they're non-const.
4058     // In C++1y, objects local to a constant expression (those with a Frame) are
4059     // both readable and writable inside constant expressions.
4060     // In C, such things can also be folded, although they are not ICEs.
4061     const VarDecl *VD = dyn_cast<VarDecl>(D);
4062     if (VD) {
4063       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4064         VD = VDef;
4065     }
4066     if (!VD || VD->isInvalidDecl()) {
4067       Info.FFDiag(E);
4068       return CompleteObject();
4069     }
4070 
4071     bool IsConstant = BaseType.isConstant(Info.Ctx);
4072 
4073     // Unless we're looking at a local variable or argument in a constexpr call,
4074     // the variable we're reading must be const.
4075     if (!Frame) {
4076       if (IsAccess && isa<ParmVarDecl>(VD)) {
4077         // Access of a parameter that's not associated with a frame isn't going
4078         // to work out, but we can leave it to evaluateVarDeclInit to provide a
4079         // suitable diagnostic.
4080       } else if (Info.getLangOpts().CPlusPlus14 &&
4081                  lifetimeStartedInEvaluation(Info, LVal.Base)) {
4082         // OK, we can read and modify an object if we're in the process of
4083         // evaluating its initializer, because its lifetime began in this
4084         // evaluation.
4085       } else if (isModification(AK)) {
4086         // All the remaining cases do not permit modification of the object.
4087         Info.FFDiag(E, diag::note_constexpr_modify_global);
4088         return CompleteObject();
4089       } else if (VD->isConstexpr()) {
4090         // OK, we can read this variable.
4091       } else if (BaseType->isIntegralOrEnumerationType()) {
4092         if (!IsConstant) {
4093           if (!IsAccess)
4094             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4095           if (Info.getLangOpts().CPlusPlus) {
4096             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4097             Info.Note(VD->getLocation(), diag::note_declared_at);
4098           } else {
4099             Info.FFDiag(E);
4100           }
4101           return CompleteObject();
4102         }
4103       } else if (!IsAccess) {
4104         return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4105       } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
4106                  BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4107         // This variable might end up being constexpr. Don't diagnose it yet.
4108       } else if (IsConstant) {
4109         // Keep evaluating to see what we can do. In particular, we support
4110         // folding of const floating-point types, in order to make static const
4111         // data members of such types (supported as an extension) more useful.
4112         if (Info.getLangOpts().CPlusPlus) {
4113           Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4114                               ? diag::note_constexpr_ltor_non_constexpr
4115                               : diag::note_constexpr_ltor_non_integral, 1)
4116               << VD << BaseType;
4117           Info.Note(VD->getLocation(), diag::note_declared_at);
4118         } else {
4119           Info.CCEDiag(E);
4120         }
4121       } else {
4122         // Never allow reading a non-const value.
4123         if (Info.getLangOpts().CPlusPlus) {
4124           Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4125                              ? diag::note_constexpr_ltor_non_constexpr
4126                              : diag::note_constexpr_ltor_non_integral, 1)
4127               << VD << BaseType;
4128           Info.Note(VD->getLocation(), diag::note_declared_at);
4129         } else {
4130           Info.FFDiag(E);
4131         }
4132         return CompleteObject();
4133       }
4134     }
4135 
4136     if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
4137       return CompleteObject();
4138   } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4139     Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
4140     if (!Alloc) {
4141       Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4142       return CompleteObject();
4143     }
4144     return CompleteObject(LVal.Base, &(*Alloc)->Value,
4145                           LVal.Base.getDynamicAllocType());
4146   } else {
4147     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4148 
4149     if (!Frame) {
4150       if (const MaterializeTemporaryExpr *MTE =
4151               dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4152         assert(MTE->getStorageDuration() == SD_Static &&
4153                "should have a frame for a non-global materialized temporary");
4154 
4155         // C++20 [expr.const]p4: [DR2126]
4156         //   An object or reference is usable in constant expressions if it is
4157         //   - a temporary object of non-volatile const-qualified literal type
4158         //     whose lifetime is extended to that of a variable that is usable
4159         //     in constant expressions
4160         //
4161         // C++20 [expr.const]p5:
4162         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4163         //   - a non-volatile glvalue that refers to an object that is usable
4164         //     in constant expressions, or
4165         //   - a non-volatile glvalue of literal type that refers to a
4166         //     non-volatile object whose lifetime began within the evaluation
4167         //     of E;
4168         //
4169         // C++11 misses the 'began within the evaluation of e' check and
4170         // instead allows all temporaries, including things like:
4171         //   int &&r = 1;
4172         //   int x = ++r;
4173         //   constexpr int k = r;
4174         // Therefore we use the C++14-onwards rules in C++11 too.
4175         //
4176         // Note that temporaries whose lifetimes began while evaluating a
4177         // variable's constructor are not usable while evaluating the
4178         // corresponding destructor, not even if they're of const-qualified
4179         // types.
4180         if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4181             !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4182           if (!IsAccess)
4183             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4184           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4185           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4186           return CompleteObject();
4187         }
4188 
4189         BaseVal = MTE->getOrCreateValue(false);
4190         assert(BaseVal && "got reference to unevaluated temporary");
4191       } else {
4192         if (!IsAccess)
4193           return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4194         APValue Val;
4195         LVal.moveInto(Val);
4196         Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4197             << AK
4198             << Val.getAsString(Info.Ctx,
4199                                Info.Ctx.getLValueReferenceType(LValType));
4200         NoteLValueLocation(Info, LVal.Base);
4201         return CompleteObject();
4202       }
4203     } else {
4204       BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4205       assert(BaseVal && "missing value for temporary");
4206     }
4207   }
4208 
4209   // In C++14, we can't safely access any mutable state when we might be
4210   // evaluating after an unmodeled side effect. Parameters are modeled as state
4211   // in the caller, but aren't visible once the call returns, so they can be
4212   // modified in a speculatively-evaluated call.
4213   //
4214   // FIXME: Not all local state is mutable. Allow local constant subobjects
4215   // to be read here (but take care with 'mutable' fields).
4216   unsigned VisibleDepth = Depth;
4217   if (llvm::isa_and_nonnull<ParmVarDecl>(
4218           LVal.Base.dyn_cast<const ValueDecl *>()))
4219     ++VisibleDepth;
4220   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4221        Info.EvalStatus.HasSideEffects) ||
4222       (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4223     return CompleteObject();
4224 
4225   return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4226 }
4227 
4228 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4229 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4230 /// glvalue referred to by an entity of reference type.
4231 ///
4232 /// \param Info - Information about the ongoing evaluation.
4233 /// \param Conv - The expression for which we are performing the conversion.
4234 ///               Used for diagnostics.
4235 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4236 ///               case of a non-class type).
4237 /// \param LVal - The glvalue on which we are attempting to perform this action.
4238 /// \param RVal - The produced value will be placed here.
4239 /// \param WantObjectRepresentation - If true, we're looking for the object
4240 ///               representation rather than the value, and in particular,
4241 ///               there is no requirement that the result be fully initialized.
4242 static bool
4243 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
4244                                const LValue &LVal, APValue &RVal,
4245                                bool WantObjectRepresentation = false) {
4246   if (LVal.Designator.Invalid)
4247     return false;
4248 
4249   // Check for special cases where there is no existing APValue to look at.
4250   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4251 
4252   AccessKinds AK =
4253       WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4254 
4255   if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4256     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4257       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4258       // initializer until now for such expressions. Such an expression can't be
4259       // an ICE in C, so this only matters for fold.
4260       if (Type.isVolatileQualified()) {
4261         Info.FFDiag(Conv);
4262         return false;
4263       }
4264       APValue Lit;
4265       if (!Evaluate(Lit, Info, CLE->getInitializer()))
4266         return false;
4267       CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4268       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4269     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4270       // Special-case character extraction so we don't have to construct an
4271       // APValue for the whole string.
4272       assert(LVal.Designator.Entries.size() <= 1 &&
4273              "Can only read characters from string literals");
4274       if (LVal.Designator.Entries.empty()) {
4275         // Fail for now for LValue to RValue conversion of an array.
4276         // (This shouldn't show up in C/C++, but it could be triggered by a
4277         // weird EvaluateAsRValue call from a tool.)
4278         Info.FFDiag(Conv);
4279         return false;
4280       }
4281       if (LVal.Designator.isOnePastTheEnd()) {
4282         if (Info.getLangOpts().CPlusPlus11)
4283           Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4284         else
4285           Info.FFDiag(Conv);
4286         return false;
4287       }
4288       uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4289       RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4290       return true;
4291     }
4292   }
4293 
4294   CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4295   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4296 }
4297 
4298 /// Perform an assignment of Val to LVal. Takes ownership of Val.
4299 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4300                              QualType LValType, APValue &Val) {
4301   if (LVal.Designator.Invalid)
4302     return false;
4303 
4304   if (!Info.getLangOpts().CPlusPlus14) {
4305     Info.FFDiag(E);
4306     return false;
4307   }
4308 
4309   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4310   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4311 }
4312 
4313 namespace {
4314 struct CompoundAssignSubobjectHandler {
4315   EvalInfo &Info;
4316   const CompoundAssignOperator *E;
4317   QualType PromotedLHSType;
4318   BinaryOperatorKind Opcode;
4319   const APValue &RHS;
4320 
4321   static const AccessKinds AccessKind = AK_Assign;
4322 
4323   typedef bool result_type;
4324 
4325   bool checkConst(QualType QT) {
4326     // Assigning to a const object has undefined behavior.
4327     if (QT.isConstQualified()) {
4328       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4329       return false;
4330     }
4331     return true;
4332   }
4333 
4334   bool failed() { return false; }
4335   bool found(APValue &Subobj, QualType SubobjType) {
4336     switch (Subobj.getKind()) {
4337     case APValue::Int:
4338       return found(Subobj.getInt(), SubobjType);
4339     case APValue::Float:
4340       return found(Subobj.getFloat(), SubobjType);
4341     case APValue::ComplexInt:
4342     case APValue::ComplexFloat:
4343       // FIXME: Implement complex compound assignment.
4344       Info.FFDiag(E);
4345       return false;
4346     case APValue::LValue:
4347       return foundPointer(Subobj, SubobjType);
4348     case APValue::Vector:
4349       return foundVector(Subobj, SubobjType);
4350     default:
4351       // FIXME: can this happen?
4352       Info.FFDiag(E);
4353       return false;
4354     }
4355   }
4356 
4357   bool foundVector(APValue &Value, QualType SubobjType) {
4358     if (!checkConst(SubobjType))
4359       return false;
4360 
4361     if (!SubobjType->isVectorType()) {
4362       Info.FFDiag(E);
4363       return false;
4364     }
4365     return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4366   }
4367 
4368   bool found(APSInt &Value, QualType SubobjType) {
4369     if (!checkConst(SubobjType))
4370       return false;
4371 
4372     if (!SubobjType->isIntegerType()) {
4373       // We don't support compound assignment on integer-cast-to-pointer
4374       // values.
4375       Info.FFDiag(E);
4376       return false;
4377     }
4378 
4379     if (RHS.isInt()) {
4380       APSInt LHS =
4381           HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4382       if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4383         return false;
4384       Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4385       return true;
4386     } else if (RHS.isFloat()) {
4387       const FPOptions FPO = E->getFPFeaturesInEffect(
4388                                     Info.Ctx.getLangOpts());
4389       APFloat FValue(0.0);
4390       return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4391                                   PromotedLHSType, FValue) &&
4392              handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4393              HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4394                                   Value);
4395     }
4396 
4397     Info.FFDiag(E);
4398     return false;
4399   }
4400   bool found(APFloat &Value, QualType SubobjType) {
4401     return checkConst(SubobjType) &&
4402            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4403                                   Value) &&
4404            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4405            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4406   }
4407   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4408     if (!checkConst(SubobjType))
4409       return false;
4410 
4411     QualType PointeeType;
4412     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4413       PointeeType = PT->getPointeeType();
4414 
4415     if (PointeeType.isNull() || !RHS.isInt() ||
4416         (Opcode != BO_Add && Opcode != BO_Sub)) {
4417       Info.FFDiag(E);
4418       return false;
4419     }
4420 
4421     APSInt Offset = RHS.getInt();
4422     if (Opcode == BO_Sub)
4423       negateAsSigned(Offset);
4424 
4425     LValue LVal;
4426     LVal.setFrom(Info.Ctx, Subobj);
4427     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4428       return false;
4429     LVal.moveInto(Subobj);
4430     return true;
4431   }
4432 };
4433 } // end anonymous namespace
4434 
4435 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4436 
4437 /// Perform a compound assignment of LVal <op>= RVal.
4438 static bool handleCompoundAssignment(EvalInfo &Info,
4439                                      const CompoundAssignOperator *E,
4440                                      const LValue &LVal, QualType LValType,
4441                                      QualType PromotedLValType,
4442                                      BinaryOperatorKind Opcode,
4443                                      const APValue &RVal) {
4444   if (LVal.Designator.Invalid)
4445     return false;
4446 
4447   if (!Info.getLangOpts().CPlusPlus14) {
4448     Info.FFDiag(E);
4449     return false;
4450   }
4451 
4452   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4453   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4454                                              RVal };
4455   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4456 }
4457 
4458 namespace {
4459 struct IncDecSubobjectHandler {
4460   EvalInfo &Info;
4461   const UnaryOperator *E;
4462   AccessKinds AccessKind;
4463   APValue *Old;
4464 
4465   typedef bool result_type;
4466 
4467   bool checkConst(QualType QT) {
4468     // Assigning to a const object has undefined behavior.
4469     if (QT.isConstQualified()) {
4470       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4471       return false;
4472     }
4473     return true;
4474   }
4475 
4476   bool failed() { return false; }
4477   bool found(APValue &Subobj, QualType SubobjType) {
4478     // Stash the old value. Also clear Old, so we don't clobber it later
4479     // if we're post-incrementing a complex.
4480     if (Old) {
4481       *Old = Subobj;
4482       Old = nullptr;
4483     }
4484 
4485     switch (Subobj.getKind()) {
4486     case APValue::Int:
4487       return found(Subobj.getInt(), SubobjType);
4488     case APValue::Float:
4489       return found(Subobj.getFloat(), SubobjType);
4490     case APValue::ComplexInt:
4491       return found(Subobj.getComplexIntReal(),
4492                    SubobjType->castAs<ComplexType>()->getElementType()
4493                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4494     case APValue::ComplexFloat:
4495       return found(Subobj.getComplexFloatReal(),
4496                    SubobjType->castAs<ComplexType>()->getElementType()
4497                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4498     case APValue::LValue:
4499       return foundPointer(Subobj, SubobjType);
4500     default:
4501       // FIXME: can this happen?
4502       Info.FFDiag(E);
4503       return false;
4504     }
4505   }
4506   bool found(APSInt &Value, QualType SubobjType) {
4507     if (!checkConst(SubobjType))
4508       return false;
4509 
4510     if (!SubobjType->isIntegerType()) {
4511       // We don't support increment / decrement on integer-cast-to-pointer
4512       // values.
4513       Info.FFDiag(E);
4514       return false;
4515     }
4516 
4517     if (Old) *Old = APValue(Value);
4518 
4519     // bool arithmetic promotes to int, and the conversion back to bool
4520     // doesn't reduce mod 2^n, so special-case it.
4521     if (SubobjType->isBooleanType()) {
4522       if (AccessKind == AK_Increment)
4523         Value = 1;
4524       else
4525         Value = !Value;
4526       return true;
4527     }
4528 
4529     bool WasNegative = Value.isNegative();
4530     if (AccessKind == AK_Increment) {
4531       ++Value;
4532 
4533       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4534         APSInt ActualValue(Value, /*IsUnsigned*/true);
4535         return HandleOverflow(Info, E, ActualValue, SubobjType);
4536       }
4537     } else {
4538       --Value;
4539 
4540       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4541         unsigned BitWidth = Value.getBitWidth();
4542         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4543         ActualValue.setBit(BitWidth);
4544         return HandleOverflow(Info, E, ActualValue, SubobjType);
4545       }
4546     }
4547     return true;
4548   }
4549   bool found(APFloat &Value, QualType SubobjType) {
4550     if (!checkConst(SubobjType))
4551       return false;
4552 
4553     if (Old) *Old = APValue(Value);
4554 
4555     APFloat One(Value.getSemantics(), 1);
4556     if (AccessKind == AK_Increment)
4557       Value.add(One, APFloat::rmNearestTiesToEven);
4558     else
4559       Value.subtract(One, APFloat::rmNearestTiesToEven);
4560     return true;
4561   }
4562   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4563     if (!checkConst(SubobjType))
4564       return false;
4565 
4566     QualType PointeeType;
4567     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4568       PointeeType = PT->getPointeeType();
4569     else {
4570       Info.FFDiag(E);
4571       return false;
4572     }
4573 
4574     LValue LVal;
4575     LVal.setFrom(Info.Ctx, Subobj);
4576     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4577                                      AccessKind == AK_Increment ? 1 : -1))
4578       return false;
4579     LVal.moveInto(Subobj);
4580     return true;
4581   }
4582 };
4583 } // end anonymous namespace
4584 
4585 /// Perform an increment or decrement on LVal.
4586 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4587                          QualType LValType, bool IsIncrement, APValue *Old) {
4588   if (LVal.Designator.Invalid)
4589     return false;
4590 
4591   if (!Info.getLangOpts().CPlusPlus14) {
4592     Info.FFDiag(E);
4593     return false;
4594   }
4595 
4596   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4597   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4598   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4599   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4600 }
4601 
4602 /// Build an lvalue for the object argument of a member function call.
4603 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4604                                    LValue &This) {
4605   if (Object->getType()->isPointerType() && Object->isRValue())
4606     return EvaluatePointer(Object, This, Info);
4607 
4608   if (Object->isGLValue())
4609     return EvaluateLValue(Object, This, Info);
4610 
4611   if (Object->getType()->isLiteralType(Info.Ctx))
4612     return EvaluateTemporary(Object, This, Info);
4613 
4614   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4615   return false;
4616 }
4617 
4618 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
4619 /// lvalue referring to the result.
4620 ///
4621 /// \param Info - Information about the ongoing evaluation.
4622 /// \param LV - An lvalue referring to the base of the member pointer.
4623 /// \param RHS - The member pointer expression.
4624 /// \param IncludeMember - Specifies whether the member itself is included in
4625 ///        the resulting LValue subobject designator. This is not possible when
4626 ///        creating a bound member function.
4627 /// \return The field or method declaration to which the member pointer refers,
4628 ///         or 0 if evaluation fails.
4629 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4630                                                   QualType LVType,
4631                                                   LValue &LV,
4632                                                   const Expr *RHS,
4633                                                   bool IncludeMember = true) {
4634   MemberPtr MemPtr;
4635   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4636     return nullptr;
4637 
4638   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4639   // member value, the behavior is undefined.
4640   if (!MemPtr.getDecl()) {
4641     // FIXME: Specific diagnostic.
4642     Info.FFDiag(RHS);
4643     return nullptr;
4644   }
4645 
4646   if (MemPtr.isDerivedMember()) {
4647     // This is a member of some derived class. Truncate LV appropriately.
4648     // The end of the derived-to-base path for the base object must match the
4649     // derived-to-base path for the member pointer.
4650     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4651         LV.Designator.Entries.size()) {
4652       Info.FFDiag(RHS);
4653       return nullptr;
4654     }
4655     unsigned PathLengthToMember =
4656         LV.Designator.Entries.size() - MemPtr.Path.size();
4657     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4658       const CXXRecordDecl *LVDecl = getAsBaseClass(
4659           LV.Designator.Entries[PathLengthToMember + I]);
4660       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4661       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4662         Info.FFDiag(RHS);
4663         return nullptr;
4664       }
4665     }
4666 
4667     // Truncate the lvalue to the appropriate derived class.
4668     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4669                             PathLengthToMember))
4670       return nullptr;
4671   } else if (!MemPtr.Path.empty()) {
4672     // Extend the LValue path with the member pointer's path.
4673     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4674                                   MemPtr.Path.size() + IncludeMember);
4675 
4676     // Walk down to the appropriate base class.
4677     if (const PointerType *PT = LVType->getAs<PointerType>())
4678       LVType = PT->getPointeeType();
4679     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4680     assert(RD && "member pointer access on non-class-type expression");
4681     // The first class in the path is that of the lvalue.
4682     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4683       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4684       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4685         return nullptr;
4686       RD = Base;
4687     }
4688     // Finally cast to the class containing the member.
4689     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4690                                 MemPtr.getContainingRecord()))
4691       return nullptr;
4692   }
4693 
4694   // Add the member. Note that we cannot build bound member functions here.
4695   if (IncludeMember) {
4696     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4697       if (!HandleLValueMember(Info, RHS, LV, FD))
4698         return nullptr;
4699     } else if (const IndirectFieldDecl *IFD =
4700                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4701       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4702         return nullptr;
4703     } else {
4704       llvm_unreachable("can't construct reference to bound member function");
4705     }
4706   }
4707 
4708   return MemPtr.getDecl();
4709 }
4710 
4711 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4712                                                   const BinaryOperator *BO,
4713                                                   LValue &LV,
4714                                                   bool IncludeMember = true) {
4715   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4716 
4717   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4718     if (Info.noteFailure()) {
4719       MemberPtr MemPtr;
4720       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4721     }
4722     return nullptr;
4723   }
4724 
4725   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4726                                    BO->getRHS(), IncludeMember);
4727 }
4728 
4729 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4730 /// the provided lvalue, which currently refers to the base object.
4731 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4732                                     LValue &Result) {
4733   SubobjectDesignator &D = Result.Designator;
4734   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4735     return false;
4736 
4737   QualType TargetQT = E->getType();
4738   if (const PointerType *PT = TargetQT->getAs<PointerType>())
4739     TargetQT = PT->getPointeeType();
4740 
4741   // Check this cast lands within the final derived-to-base subobject path.
4742   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4743     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4744       << D.MostDerivedType << TargetQT;
4745     return false;
4746   }
4747 
4748   // Check the type of the final cast. We don't need to check the path,
4749   // since a cast can only be formed if the path is unique.
4750   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4751   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4752   const CXXRecordDecl *FinalType;
4753   if (NewEntriesSize == D.MostDerivedPathLength)
4754     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4755   else
4756     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4757   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4758     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4759       << D.MostDerivedType << TargetQT;
4760     return false;
4761   }
4762 
4763   // Truncate the lvalue to the appropriate derived class.
4764   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4765 }
4766 
4767 /// Get the value to use for a default-initialized object of type T.
4768 /// Return false if it encounters something invalid.
4769 static bool getDefaultInitValue(QualType T, APValue &Result) {
4770   bool Success = true;
4771   if (auto *RD = T->getAsCXXRecordDecl()) {
4772     if (RD->isInvalidDecl()) {
4773       Result = APValue();
4774       return false;
4775     }
4776     if (RD->isUnion()) {
4777       Result = APValue((const FieldDecl *)nullptr);
4778       return true;
4779     }
4780     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4781                      std::distance(RD->field_begin(), RD->field_end()));
4782 
4783     unsigned Index = 0;
4784     for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4785                                                   End = RD->bases_end();
4786          I != End; ++I, ++Index)
4787       Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index));
4788 
4789     for (const auto *I : RD->fields()) {
4790       if (I->isUnnamedBitfield())
4791         continue;
4792       Success &= getDefaultInitValue(I->getType(),
4793                                      Result.getStructField(I->getFieldIndex()));
4794     }
4795     return Success;
4796   }
4797 
4798   if (auto *AT =
4799           dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4800     Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4801     if (Result.hasArrayFiller())
4802       Success &=
4803           getDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
4804 
4805     return Success;
4806   }
4807 
4808   Result = APValue::IndeterminateValue();
4809   return true;
4810 }
4811 
4812 namespace {
4813 enum EvalStmtResult {
4814   /// Evaluation failed.
4815   ESR_Failed,
4816   /// Hit a 'return' statement.
4817   ESR_Returned,
4818   /// Evaluation succeeded.
4819   ESR_Succeeded,
4820   /// Hit a 'continue' statement.
4821   ESR_Continue,
4822   /// Hit a 'break' statement.
4823   ESR_Break,
4824   /// Still scanning for 'case' or 'default' statement.
4825   ESR_CaseNotFound
4826 };
4827 }
4828 
4829 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4830   // We don't need to evaluate the initializer for a static local.
4831   if (!VD->hasLocalStorage())
4832     return true;
4833 
4834   LValue Result;
4835   APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
4836                                                    ScopeKind::Block, Result);
4837 
4838   const Expr *InitE = VD->getInit();
4839   if (!InitE)
4840     return getDefaultInitValue(VD->getType(), Val);
4841 
4842   if (InitE->isValueDependent())
4843     return false;
4844 
4845   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4846     // Wipe out any partially-computed value, to allow tracking that this
4847     // evaluation failed.
4848     Val = APValue();
4849     return false;
4850   }
4851 
4852   return true;
4853 }
4854 
4855 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4856   bool OK = true;
4857 
4858   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4859     OK &= EvaluateVarDecl(Info, VD);
4860 
4861   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4862     for (auto *BD : DD->bindings())
4863       if (auto *VD = BD->getHoldingVar())
4864         OK &= EvaluateDecl(Info, VD);
4865 
4866   return OK;
4867 }
4868 
4869 
4870 /// Evaluate a condition (either a variable declaration or an expression).
4871 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4872                          const Expr *Cond, bool &Result) {
4873   FullExpressionRAII Scope(Info);
4874   if (CondDecl && !EvaluateDecl(Info, CondDecl))
4875     return false;
4876   if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4877     return false;
4878   return Scope.destroy();
4879 }
4880 
4881 namespace {
4882 /// A location where the result (returned value) of evaluating a
4883 /// statement should be stored.
4884 struct StmtResult {
4885   /// The APValue that should be filled in with the returned value.
4886   APValue &Value;
4887   /// The location containing the result, if any (used to support RVO).
4888   const LValue *Slot;
4889 };
4890 
4891 struct TempVersionRAII {
4892   CallStackFrame &Frame;
4893 
4894   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4895     Frame.pushTempVersion();
4896   }
4897 
4898   ~TempVersionRAII() {
4899     Frame.popTempVersion();
4900   }
4901 };
4902 
4903 }
4904 
4905 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4906                                    const Stmt *S,
4907                                    const SwitchCase *SC = nullptr);
4908 
4909 /// Evaluate the body of a loop, and translate the result as appropriate.
4910 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4911                                        const Stmt *Body,
4912                                        const SwitchCase *Case = nullptr) {
4913   BlockScopeRAII Scope(Info);
4914 
4915   EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4916   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4917     ESR = ESR_Failed;
4918 
4919   switch (ESR) {
4920   case ESR_Break:
4921     return ESR_Succeeded;
4922   case ESR_Succeeded:
4923   case ESR_Continue:
4924     return ESR_Continue;
4925   case ESR_Failed:
4926   case ESR_Returned:
4927   case ESR_CaseNotFound:
4928     return ESR;
4929   }
4930   llvm_unreachable("Invalid EvalStmtResult!");
4931 }
4932 
4933 /// Evaluate a switch statement.
4934 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4935                                      const SwitchStmt *SS) {
4936   BlockScopeRAII Scope(Info);
4937 
4938   // Evaluate the switch condition.
4939   APSInt Value;
4940   {
4941     if (const Stmt *Init = SS->getInit()) {
4942       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4943       if (ESR != ESR_Succeeded) {
4944         if (ESR != ESR_Failed && !Scope.destroy())
4945           ESR = ESR_Failed;
4946         return ESR;
4947       }
4948     }
4949 
4950     FullExpressionRAII CondScope(Info);
4951     if (SS->getConditionVariable() &&
4952         !EvaluateDecl(Info, SS->getConditionVariable()))
4953       return ESR_Failed;
4954     if (!EvaluateInteger(SS->getCond(), Value, Info))
4955       return ESR_Failed;
4956     if (!CondScope.destroy())
4957       return ESR_Failed;
4958   }
4959 
4960   // Find the switch case corresponding to the value of the condition.
4961   // FIXME: Cache this lookup.
4962   const SwitchCase *Found = nullptr;
4963   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4964        SC = SC->getNextSwitchCase()) {
4965     if (isa<DefaultStmt>(SC)) {
4966       Found = SC;
4967       continue;
4968     }
4969 
4970     const CaseStmt *CS = cast<CaseStmt>(SC);
4971     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4972     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4973                               : LHS;
4974     if (LHS <= Value && Value <= RHS) {
4975       Found = SC;
4976       break;
4977     }
4978   }
4979 
4980   if (!Found)
4981     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4982 
4983   // Search the switch body for the switch case and evaluate it from there.
4984   EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
4985   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4986     return ESR_Failed;
4987 
4988   switch (ESR) {
4989   case ESR_Break:
4990     return ESR_Succeeded;
4991   case ESR_Succeeded:
4992   case ESR_Continue:
4993   case ESR_Failed:
4994   case ESR_Returned:
4995     return ESR;
4996   case ESR_CaseNotFound:
4997     // This can only happen if the switch case is nested within a statement
4998     // expression. We have no intention of supporting that.
4999     Info.FFDiag(Found->getBeginLoc(),
5000                 diag::note_constexpr_stmt_expr_unsupported);
5001     return ESR_Failed;
5002   }
5003   llvm_unreachable("Invalid EvalStmtResult!");
5004 }
5005 
5006 // Evaluate a statement.
5007 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5008                                    const Stmt *S, const SwitchCase *Case) {
5009   if (!Info.nextStep(S))
5010     return ESR_Failed;
5011 
5012   // If we're hunting down a 'case' or 'default' label, recurse through
5013   // substatements until we hit the label.
5014   if (Case) {
5015     switch (S->getStmtClass()) {
5016     case Stmt::CompoundStmtClass:
5017       // FIXME: Precompute which substatement of a compound statement we
5018       // would jump to, and go straight there rather than performing a
5019       // linear scan each time.
5020     case Stmt::LabelStmtClass:
5021     case Stmt::AttributedStmtClass:
5022     case Stmt::DoStmtClass:
5023       break;
5024 
5025     case Stmt::CaseStmtClass:
5026     case Stmt::DefaultStmtClass:
5027       if (Case == S)
5028         Case = nullptr;
5029       break;
5030 
5031     case Stmt::IfStmtClass: {
5032       // FIXME: Precompute which side of an 'if' we would jump to, and go
5033       // straight there rather than scanning both sides.
5034       const IfStmt *IS = cast<IfStmt>(S);
5035 
5036       // Wrap the evaluation in a block scope, in case it's a DeclStmt
5037       // preceded by our switch label.
5038       BlockScopeRAII Scope(Info);
5039 
5040       // Step into the init statement in case it brings an (uninitialized)
5041       // variable into scope.
5042       if (const Stmt *Init = IS->getInit()) {
5043         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5044         if (ESR != ESR_CaseNotFound) {
5045           assert(ESR != ESR_Succeeded);
5046           return ESR;
5047         }
5048       }
5049 
5050       // Condition variable must be initialized if it exists.
5051       // FIXME: We can skip evaluating the body if there's a condition
5052       // variable, as there can't be any case labels within it.
5053       // (The same is true for 'for' statements.)
5054 
5055       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5056       if (ESR == ESR_Failed)
5057         return ESR;
5058       if (ESR != ESR_CaseNotFound)
5059         return Scope.destroy() ? ESR : ESR_Failed;
5060       if (!IS->getElse())
5061         return ESR_CaseNotFound;
5062 
5063       ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5064       if (ESR == ESR_Failed)
5065         return ESR;
5066       if (ESR != ESR_CaseNotFound)
5067         return Scope.destroy() ? ESR : ESR_Failed;
5068       return ESR_CaseNotFound;
5069     }
5070 
5071     case Stmt::WhileStmtClass: {
5072       EvalStmtResult ESR =
5073           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5074       if (ESR != ESR_Continue)
5075         return ESR;
5076       break;
5077     }
5078 
5079     case Stmt::ForStmtClass: {
5080       const ForStmt *FS = cast<ForStmt>(S);
5081       BlockScopeRAII Scope(Info);
5082 
5083       // Step into the init statement in case it brings an (uninitialized)
5084       // variable into scope.
5085       if (const Stmt *Init = FS->getInit()) {
5086         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5087         if (ESR != ESR_CaseNotFound) {
5088           assert(ESR != ESR_Succeeded);
5089           return ESR;
5090         }
5091       }
5092 
5093       EvalStmtResult ESR =
5094           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5095       if (ESR != ESR_Continue)
5096         return ESR;
5097       if (FS->getInc()) {
5098         FullExpressionRAII IncScope(Info);
5099         if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
5100           return ESR_Failed;
5101       }
5102       break;
5103     }
5104 
5105     case Stmt::DeclStmtClass: {
5106       // Start the lifetime of any uninitialized variables we encounter. They
5107       // might be used by the selected branch of the switch.
5108       const DeclStmt *DS = cast<DeclStmt>(S);
5109       for (const auto *D : DS->decls()) {
5110         if (const auto *VD = dyn_cast<VarDecl>(D)) {
5111           if (VD->hasLocalStorage() && !VD->getInit())
5112             if (!EvaluateVarDecl(Info, VD))
5113               return ESR_Failed;
5114           // FIXME: If the variable has initialization that can't be jumped
5115           // over, bail out of any immediately-surrounding compound-statement
5116           // too. There can't be any case labels here.
5117         }
5118       }
5119       return ESR_CaseNotFound;
5120     }
5121 
5122     default:
5123       return ESR_CaseNotFound;
5124     }
5125   }
5126 
5127   switch (S->getStmtClass()) {
5128   default:
5129     if (const Expr *E = dyn_cast<Expr>(S)) {
5130       // Don't bother evaluating beyond an expression-statement which couldn't
5131       // be evaluated.
5132       // FIXME: Do we need the FullExpressionRAII object here?
5133       // VisitExprWithCleanups should create one when necessary.
5134       FullExpressionRAII Scope(Info);
5135       if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5136         return ESR_Failed;
5137       return ESR_Succeeded;
5138     }
5139 
5140     Info.FFDiag(S->getBeginLoc());
5141     return ESR_Failed;
5142 
5143   case Stmt::NullStmtClass:
5144     return ESR_Succeeded;
5145 
5146   case Stmt::DeclStmtClass: {
5147     const DeclStmt *DS = cast<DeclStmt>(S);
5148     for (const auto *D : DS->decls()) {
5149       // Each declaration initialization is its own full-expression.
5150       FullExpressionRAII Scope(Info);
5151       if (!EvaluateDecl(Info, D) && !Info.noteFailure())
5152         return ESR_Failed;
5153       if (!Scope.destroy())
5154         return ESR_Failed;
5155     }
5156     return ESR_Succeeded;
5157   }
5158 
5159   case Stmt::ReturnStmtClass: {
5160     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5161     FullExpressionRAII Scope(Info);
5162     if (RetExpr &&
5163         !(Result.Slot
5164               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5165               : Evaluate(Result.Value, Info, RetExpr)))
5166       return ESR_Failed;
5167     return Scope.destroy() ? ESR_Returned : ESR_Failed;
5168   }
5169 
5170   case Stmt::CompoundStmtClass: {
5171     BlockScopeRAII Scope(Info);
5172 
5173     const CompoundStmt *CS = cast<CompoundStmt>(S);
5174     for (const auto *BI : CS->body()) {
5175       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5176       if (ESR == ESR_Succeeded)
5177         Case = nullptr;
5178       else if (ESR != ESR_CaseNotFound) {
5179         if (ESR != ESR_Failed && !Scope.destroy())
5180           return ESR_Failed;
5181         return ESR;
5182       }
5183     }
5184     if (Case)
5185       return ESR_CaseNotFound;
5186     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5187   }
5188 
5189   case Stmt::IfStmtClass: {
5190     const IfStmt *IS = cast<IfStmt>(S);
5191 
5192     // Evaluate the condition, as either a var decl or as an expression.
5193     BlockScopeRAII Scope(Info);
5194     if (const Stmt *Init = IS->getInit()) {
5195       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5196       if (ESR != ESR_Succeeded) {
5197         if (ESR != ESR_Failed && !Scope.destroy())
5198           return ESR_Failed;
5199         return ESR;
5200       }
5201     }
5202     bool Cond;
5203     if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
5204       return ESR_Failed;
5205 
5206     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5207       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5208       if (ESR != ESR_Succeeded) {
5209         if (ESR != ESR_Failed && !Scope.destroy())
5210           return ESR_Failed;
5211         return ESR;
5212       }
5213     }
5214     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5215   }
5216 
5217   case Stmt::WhileStmtClass: {
5218     const WhileStmt *WS = cast<WhileStmt>(S);
5219     while (true) {
5220       BlockScopeRAII Scope(Info);
5221       bool Continue;
5222       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5223                         Continue))
5224         return ESR_Failed;
5225       if (!Continue)
5226         break;
5227 
5228       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5229       if (ESR != ESR_Continue) {
5230         if (ESR != ESR_Failed && !Scope.destroy())
5231           return ESR_Failed;
5232         return ESR;
5233       }
5234       if (!Scope.destroy())
5235         return ESR_Failed;
5236     }
5237     return ESR_Succeeded;
5238   }
5239 
5240   case Stmt::DoStmtClass: {
5241     const DoStmt *DS = cast<DoStmt>(S);
5242     bool Continue;
5243     do {
5244       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5245       if (ESR != ESR_Continue)
5246         return ESR;
5247       Case = nullptr;
5248 
5249       FullExpressionRAII CondScope(Info);
5250       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5251           !CondScope.destroy())
5252         return ESR_Failed;
5253     } while (Continue);
5254     return ESR_Succeeded;
5255   }
5256 
5257   case Stmt::ForStmtClass: {
5258     const ForStmt *FS = cast<ForStmt>(S);
5259     BlockScopeRAII ForScope(Info);
5260     if (FS->getInit()) {
5261       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5262       if (ESR != ESR_Succeeded) {
5263         if (ESR != ESR_Failed && !ForScope.destroy())
5264           return ESR_Failed;
5265         return ESR;
5266       }
5267     }
5268     while (true) {
5269       BlockScopeRAII IterScope(Info);
5270       bool Continue = true;
5271       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5272                                          FS->getCond(), Continue))
5273         return ESR_Failed;
5274       if (!Continue)
5275         break;
5276 
5277       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5278       if (ESR != ESR_Continue) {
5279         if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5280           return ESR_Failed;
5281         return ESR;
5282       }
5283 
5284       if (FS->getInc()) {
5285         FullExpressionRAII IncScope(Info);
5286         if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
5287           return ESR_Failed;
5288       }
5289 
5290       if (!IterScope.destroy())
5291         return ESR_Failed;
5292     }
5293     return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5294   }
5295 
5296   case Stmt::CXXForRangeStmtClass: {
5297     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5298     BlockScopeRAII Scope(Info);
5299 
5300     // Evaluate the init-statement if present.
5301     if (FS->getInit()) {
5302       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5303       if (ESR != ESR_Succeeded) {
5304         if (ESR != ESR_Failed && !Scope.destroy())
5305           return ESR_Failed;
5306         return ESR;
5307       }
5308     }
5309 
5310     // Initialize the __range variable.
5311     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5312     if (ESR != ESR_Succeeded) {
5313       if (ESR != ESR_Failed && !Scope.destroy())
5314         return ESR_Failed;
5315       return ESR;
5316     }
5317 
5318     // Create the __begin and __end iterators.
5319     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5320     if (ESR != ESR_Succeeded) {
5321       if (ESR != ESR_Failed && !Scope.destroy())
5322         return ESR_Failed;
5323       return ESR;
5324     }
5325     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5326     if (ESR != ESR_Succeeded) {
5327       if (ESR != ESR_Failed && !Scope.destroy())
5328         return ESR_Failed;
5329       return ESR;
5330     }
5331 
5332     while (true) {
5333       // Condition: __begin != __end.
5334       {
5335         bool Continue = true;
5336         FullExpressionRAII CondExpr(Info);
5337         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5338           return ESR_Failed;
5339         if (!Continue)
5340           break;
5341       }
5342 
5343       // User's variable declaration, initialized by *__begin.
5344       BlockScopeRAII InnerScope(Info);
5345       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5346       if (ESR != ESR_Succeeded) {
5347         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5348           return ESR_Failed;
5349         return ESR;
5350       }
5351 
5352       // Loop body.
5353       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5354       if (ESR != ESR_Continue) {
5355         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5356           return ESR_Failed;
5357         return ESR;
5358       }
5359 
5360       // Increment: ++__begin
5361       if (!EvaluateIgnoredValue(Info, FS->getInc()))
5362         return ESR_Failed;
5363 
5364       if (!InnerScope.destroy())
5365         return ESR_Failed;
5366     }
5367 
5368     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5369   }
5370 
5371   case Stmt::SwitchStmtClass:
5372     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5373 
5374   case Stmt::ContinueStmtClass:
5375     return ESR_Continue;
5376 
5377   case Stmt::BreakStmtClass:
5378     return ESR_Break;
5379 
5380   case Stmt::LabelStmtClass:
5381     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5382 
5383   case Stmt::AttributedStmtClass:
5384     // As a general principle, C++11 attributes can be ignored without
5385     // any semantic impact.
5386     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
5387                         Case);
5388 
5389   case Stmt::CaseStmtClass:
5390   case Stmt::DefaultStmtClass:
5391     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5392   case Stmt::CXXTryStmtClass:
5393     // Evaluate try blocks by evaluating all sub statements.
5394     return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5395   }
5396 }
5397 
5398 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5399 /// default constructor. If so, we'll fold it whether or not it's marked as
5400 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
5401 /// so we need special handling.
5402 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5403                                            const CXXConstructorDecl *CD,
5404                                            bool IsValueInitialization) {
5405   if (!CD->isTrivial() || !CD->isDefaultConstructor())
5406     return false;
5407 
5408   // Value-initialization does not call a trivial default constructor, so such a
5409   // call is a core constant expression whether or not the constructor is
5410   // constexpr.
5411   if (!CD->isConstexpr() && !IsValueInitialization) {
5412     if (Info.getLangOpts().CPlusPlus11) {
5413       // FIXME: If DiagDecl is an implicitly-declared special member function,
5414       // we should be much more explicit about why it's not constexpr.
5415       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5416         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5417       Info.Note(CD->getLocation(), diag::note_declared_at);
5418     } else {
5419       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5420     }
5421   }
5422   return true;
5423 }
5424 
5425 /// CheckConstexprFunction - Check that a function can be called in a constant
5426 /// expression.
5427 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5428                                    const FunctionDecl *Declaration,
5429                                    const FunctionDecl *Definition,
5430                                    const Stmt *Body) {
5431   // Potential constant expressions can contain calls to declared, but not yet
5432   // defined, constexpr functions.
5433   if (Info.checkingPotentialConstantExpression() && !Definition &&
5434       Declaration->isConstexpr())
5435     return false;
5436 
5437   // Bail out if the function declaration itself is invalid.  We will
5438   // have produced a relevant diagnostic while parsing it, so just
5439   // note the problematic sub-expression.
5440   if (Declaration->isInvalidDecl()) {
5441     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5442     return false;
5443   }
5444 
5445   // DR1872: An instantiated virtual constexpr function can't be called in a
5446   // constant expression (prior to C++20). We can still constant-fold such a
5447   // call.
5448   if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5449       cast<CXXMethodDecl>(Declaration)->isVirtual())
5450     Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5451 
5452   if (Definition && Definition->isInvalidDecl()) {
5453     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5454     return false;
5455   }
5456 
5457   if (const auto *CtorDecl = dyn_cast_or_null<CXXConstructorDecl>(Definition)) {
5458     for (const auto *InitExpr : CtorDecl->inits()) {
5459       if (InitExpr->getInit() && InitExpr->getInit()->containsErrors())
5460         return false;
5461     }
5462   }
5463 
5464   // Can we evaluate this function call?
5465   if (Definition && Definition->isConstexpr() && Body)
5466     return true;
5467 
5468   if (Info.getLangOpts().CPlusPlus11) {
5469     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5470 
5471     // If this function is not constexpr because it is an inherited
5472     // non-constexpr constructor, diagnose that directly.
5473     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5474     if (CD && CD->isInheritingConstructor()) {
5475       auto *Inherited = CD->getInheritedConstructor().getConstructor();
5476       if (!Inherited->isConstexpr())
5477         DiagDecl = CD = Inherited;
5478     }
5479 
5480     // FIXME: If DiagDecl is an implicitly-declared special member function
5481     // or an inheriting constructor, we should be much more explicit about why
5482     // it's not constexpr.
5483     if (CD && CD->isInheritingConstructor())
5484       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5485         << CD->getInheritedConstructor().getConstructor()->getParent();
5486     else
5487       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5488         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5489     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5490   } else {
5491     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5492   }
5493   return false;
5494 }
5495 
5496 namespace {
5497 struct CheckDynamicTypeHandler {
5498   AccessKinds AccessKind;
5499   typedef bool result_type;
5500   bool failed() { return false; }
5501   bool found(APValue &Subobj, QualType SubobjType) { return true; }
5502   bool found(APSInt &Value, QualType SubobjType) { return true; }
5503   bool found(APFloat &Value, QualType SubobjType) { return true; }
5504 };
5505 } // end anonymous namespace
5506 
5507 /// Check that we can access the notional vptr of an object / determine its
5508 /// dynamic type.
5509 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5510                              AccessKinds AK, bool Polymorphic) {
5511   if (This.Designator.Invalid)
5512     return false;
5513 
5514   CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5515 
5516   if (!Obj)
5517     return false;
5518 
5519   if (!Obj.Value) {
5520     // The object is not usable in constant expressions, so we can't inspect
5521     // its value to see if it's in-lifetime or what the active union members
5522     // are. We can still check for a one-past-the-end lvalue.
5523     if (This.Designator.isOnePastTheEnd() ||
5524         This.Designator.isMostDerivedAnUnsizedArray()) {
5525       Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5526                          ? diag::note_constexpr_access_past_end
5527                          : diag::note_constexpr_access_unsized_array)
5528           << AK;
5529       return false;
5530     } else if (Polymorphic) {
5531       // Conservatively refuse to perform a polymorphic operation if we would
5532       // not be able to read a notional 'vptr' value.
5533       APValue Val;
5534       This.moveInto(Val);
5535       QualType StarThisType =
5536           Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5537       Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5538           << AK << Val.getAsString(Info.Ctx, StarThisType);
5539       return false;
5540     }
5541     return true;
5542   }
5543 
5544   CheckDynamicTypeHandler Handler{AK};
5545   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5546 }
5547 
5548 /// Check that the pointee of the 'this' pointer in a member function call is
5549 /// either within its lifetime or in its period of construction or destruction.
5550 static bool
5551 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5552                                      const LValue &This,
5553                                      const CXXMethodDecl *NamedMember) {
5554   return checkDynamicType(
5555       Info, E, This,
5556       isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5557 }
5558 
5559 struct DynamicType {
5560   /// The dynamic class type of the object.
5561   const CXXRecordDecl *Type;
5562   /// The corresponding path length in the lvalue.
5563   unsigned PathLength;
5564 };
5565 
5566 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5567                                              unsigned PathLength) {
5568   assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5569       Designator.Entries.size() && "invalid path length");
5570   return (PathLength == Designator.MostDerivedPathLength)
5571              ? Designator.MostDerivedType->getAsCXXRecordDecl()
5572              : getAsBaseClass(Designator.Entries[PathLength - 1]);
5573 }
5574 
5575 /// Determine the dynamic type of an object.
5576 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
5577                                                 LValue &This, AccessKinds AK) {
5578   // If we don't have an lvalue denoting an object of class type, there is no
5579   // meaningful dynamic type. (We consider objects of non-class type to have no
5580   // dynamic type.)
5581   if (!checkDynamicType(Info, E, This, AK, true))
5582     return None;
5583 
5584   // Refuse to compute a dynamic type in the presence of virtual bases. This
5585   // shouldn't happen other than in constant-folding situations, since literal
5586   // types can't have virtual bases.
5587   //
5588   // Note that consumers of DynamicType assume that the type has no virtual
5589   // bases, and will need modifications if this restriction is relaxed.
5590   const CXXRecordDecl *Class =
5591       This.Designator.MostDerivedType->getAsCXXRecordDecl();
5592   if (!Class || Class->getNumVBases()) {
5593     Info.FFDiag(E);
5594     return None;
5595   }
5596 
5597   // FIXME: For very deep class hierarchies, it might be beneficial to use a
5598   // binary search here instead. But the overwhelmingly common case is that
5599   // we're not in the middle of a constructor, so it probably doesn't matter
5600   // in practice.
5601   ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5602   for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5603        PathLength <= Path.size(); ++PathLength) {
5604     switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5605                                       Path.slice(0, PathLength))) {
5606     case ConstructionPhase::Bases:
5607     case ConstructionPhase::DestroyingBases:
5608       // We're constructing or destroying a base class. This is not the dynamic
5609       // type.
5610       break;
5611 
5612     case ConstructionPhase::None:
5613     case ConstructionPhase::AfterBases:
5614     case ConstructionPhase::AfterFields:
5615     case ConstructionPhase::Destroying:
5616       // We've finished constructing the base classes and not yet started
5617       // destroying them again, so this is the dynamic type.
5618       return DynamicType{getBaseClassType(This.Designator, PathLength),
5619                          PathLength};
5620     }
5621   }
5622 
5623   // CWG issue 1517: we're constructing a base class of the object described by
5624   // 'This', so that object has not yet begun its period of construction and
5625   // any polymorphic operation on it results in undefined behavior.
5626   Info.FFDiag(E);
5627   return None;
5628 }
5629 
5630 /// Perform virtual dispatch.
5631 static const CXXMethodDecl *HandleVirtualDispatch(
5632     EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5633     llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5634   Optional<DynamicType> DynType = ComputeDynamicType(
5635       Info, E, This,
5636       isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5637   if (!DynType)
5638     return nullptr;
5639 
5640   // Find the final overrider. It must be declared in one of the classes on the
5641   // path from the dynamic type to the static type.
5642   // FIXME: If we ever allow literal types to have virtual base classes, that
5643   // won't be true.
5644   const CXXMethodDecl *Callee = Found;
5645   unsigned PathLength = DynType->PathLength;
5646   for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5647     const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5648     const CXXMethodDecl *Overrider =
5649         Found->getCorrespondingMethodDeclaredInClass(Class, false);
5650     if (Overrider) {
5651       Callee = Overrider;
5652       break;
5653     }
5654   }
5655 
5656   // C++2a [class.abstract]p6:
5657   //   the effect of making a virtual call to a pure virtual function [...] is
5658   //   undefined
5659   if (Callee->isPure()) {
5660     Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5661     Info.Note(Callee->getLocation(), diag::note_declared_at);
5662     return nullptr;
5663   }
5664 
5665   // If necessary, walk the rest of the path to determine the sequence of
5666   // covariant adjustment steps to apply.
5667   if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5668                                        Found->getReturnType())) {
5669     CovariantAdjustmentPath.push_back(Callee->getReturnType());
5670     for (unsigned CovariantPathLength = PathLength + 1;
5671          CovariantPathLength != This.Designator.Entries.size();
5672          ++CovariantPathLength) {
5673       const CXXRecordDecl *NextClass =
5674           getBaseClassType(This.Designator, CovariantPathLength);
5675       const CXXMethodDecl *Next =
5676           Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5677       if (Next && !Info.Ctx.hasSameUnqualifiedType(
5678                       Next->getReturnType(), CovariantAdjustmentPath.back()))
5679         CovariantAdjustmentPath.push_back(Next->getReturnType());
5680     }
5681     if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5682                                          CovariantAdjustmentPath.back()))
5683       CovariantAdjustmentPath.push_back(Found->getReturnType());
5684   }
5685 
5686   // Perform 'this' adjustment.
5687   if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5688     return nullptr;
5689 
5690   return Callee;
5691 }
5692 
5693 /// Perform the adjustment from a value returned by a virtual function to
5694 /// a value of the statically expected type, which may be a pointer or
5695 /// reference to a base class of the returned type.
5696 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5697                                             APValue &Result,
5698                                             ArrayRef<QualType> Path) {
5699   assert(Result.isLValue() &&
5700          "unexpected kind of APValue for covariant return");
5701   if (Result.isNullPointer())
5702     return true;
5703 
5704   LValue LVal;
5705   LVal.setFrom(Info.Ctx, Result);
5706 
5707   const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5708   for (unsigned I = 1; I != Path.size(); ++I) {
5709     const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5710     assert(OldClass && NewClass && "unexpected kind of covariant return");
5711     if (OldClass != NewClass &&
5712         !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5713       return false;
5714     OldClass = NewClass;
5715   }
5716 
5717   LVal.moveInto(Result);
5718   return true;
5719 }
5720 
5721 /// Determine whether \p Base, which is known to be a direct base class of
5722 /// \p Derived, is a public base class.
5723 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5724                               const CXXRecordDecl *Base) {
5725   for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5726     auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5727     if (BaseClass && declaresSameEntity(BaseClass, Base))
5728       return BaseSpec.getAccessSpecifier() == AS_public;
5729   }
5730   llvm_unreachable("Base is not a direct base of Derived");
5731 }
5732 
5733 /// Apply the given dynamic cast operation on the provided lvalue.
5734 ///
5735 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
5736 /// to find a suitable target subobject.
5737 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5738                               LValue &Ptr) {
5739   // We can't do anything with a non-symbolic pointer value.
5740   SubobjectDesignator &D = Ptr.Designator;
5741   if (D.Invalid)
5742     return false;
5743 
5744   // C++ [expr.dynamic.cast]p6:
5745   //   If v is a null pointer value, the result is a null pointer value.
5746   if (Ptr.isNullPointer() && !E->isGLValue())
5747     return true;
5748 
5749   // For all the other cases, we need the pointer to point to an object within
5750   // its lifetime / period of construction / destruction, and we need to know
5751   // its dynamic type.
5752   Optional<DynamicType> DynType =
5753       ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5754   if (!DynType)
5755     return false;
5756 
5757   // C++ [expr.dynamic.cast]p7:
5758   //   If T is "pointer to cv void", then the result is a pointer to the most
5759   //   derived object
5760   if (E->getType()->isVoidPointerType())
5761     return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5762 
5763   const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5764   assert(C && "dynamic_cast target is not void pointer nor class");
5765   CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5766 
5767   auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5768     // C++ [expr.dynamic.cast]p9:
5769     if (!E->isGLValue()) {
5770       //   The value of a failed cast to pointer type is the null pointer value
5771       //   of the required result type.
5772       Ptr.setNull(Info.Ctx, E->getType());
5773       return true;
5774     }
5775 
5776     //   A failed cast to reference type throws [...] std::bad_cast.
5777     unsigned DiagKind;
5778     if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5779                    DynType->Type->isDerivedFrom(C)))
5780       DiagKind = 0;
5781     else if (!Paths || Paths->begin() == Paths->end())
5782       DiagKind = 1;
5783     else if (Paths->isAmbiguous(CQT))
5784       DiagKind = 2;
5785     else {
5786       assert(Paths->front().Access != AS_public && "why did the cast fail?");
5787       DiagKind = 3;
5788     }
5789     Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5790         << DiagKind << Ptr.Designator.getType(Info.Ctx)
5791         << Info.Ctx.getRecordType(DynType->Type)
5792         << E->getType().getUnqualifiedType();
5793     return false;
5794   };
5795 
5796   // Runtime check, phase 1:
5797   //   Walk from the base subobject towards the derived object looking for the
5798   //   target type.
5799   for (int PathLength = Ptr.Designator.Entries.size();
5800        PathLength >= (int)DynType->PathLength; --PathLength) {
5801     const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5802     if (declaresSameEntity(Class, C))
5803       return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5804     // We can only walk across public inheritance edges.
5805     if (PathLength > (int)DynType->PathLength &&
5806         !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5807                            Class))
5808       return RuntimeCheckFailed(nullptr);
5809   }
5810 
5811   // Runtime check, phase 2:
5812   //   Search the dynamic type for an unambiguous public base of type C.
5813   CXXBasePaths Paths(/*FindAmbiguities=*/true,
5814                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
5815   if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5816       Paths.front().Access == AS_public) {
5817     // Downcast to the dynamic type...
5818     if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5819       return false;
5820     // ... then upcast to the chosen base class subobject.
5821     for (CXXBasePathElement &Elem : Paths.front())
5822       if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5823         return false;
5824     return true;
5825   }
5826 
5827   // Otherwise, the runtime check fails.
5828   return RuntimeCheckFailed(&Paths);
5829 }
5830 
5831 namespace {
5832 struct StartLifetimeOfUnionMemberHandler {
5833   EvalInfo &Info;
5834   const Expr *LHSExpr;
5835   const FieldDecl *Field;
5836   bool DuringInit;
5837   bool Failed = false;
5838   static const AccessKinds AccessKind = AK_Assign;
5839 
5840   typedef bool result_type;
5841   bool failed() { return Failed; }
5842   bool found(APValue &Subobj, QualType SubobjType) {
5843     // We are supposed to perform no initialization but begin the lifetime of
5844     // the object. We interpret that as meaning to do what default
5845     // initialization of the object would do if all constructors involved were
5846     // trivial:
5847     //  * All base, non-variant member, and array element subobjects' lifetimes
5848     //    begin
5849     //  * No variant members' lifetimes begin
5850     //  * All scalar subobjects whose lifetimes begin have indeterminate values
5851     assert(SubobjType->isUnionType());
5852     if (declaresSameEntity(Subobj.getUnionField(), Field)) {
5853       // This union member is already active. If it's also in-lifetime, there's
5854       // nothing to do.
5855       if (Subobj.getUnionValue().hasValue())
5856         return true;
5857     } else if (DuringInit) {
5858       // We're currently in the process of initializing a different union
5859       // member.  If we carried on, that initialization would attempt to
5860       // store to an inactive union member, resulting in undefined behavior.
5861       Info.FFDiag(LHSExpr,
5862                   diag::note_constexpr_union_member_change_during_init);
5863       return false;
5864     }
5865     APValue Result;
5866     Failed = !getDefaultInitValue(Field->getType(), Result);
5867     Subobj.setUnion(Field, Result);
5868     return true;
5869   }
5870   bool found(APSInt &Value, QualType SubobjType) {
5871     llvm_unreachable("wrong value kind for union object");
5872   }
5873   bool found(APFloat &Value, QualType SubobjType) {
5874     llvm_unreachable("wrong value kind for union object");
5875   }
5876 };
5877 } // end anonymous namespace
5878 
5879 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5880 
5881 /// Handle a builtin simple-assignment or a call to a trivial assignment
5882 /// operator whose left-hand side might involve a union member access. If it
5883 /// does, implicitly start the lifetime of any accessed union elements per
5884 /// C++20 [class.union]5.
5885 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5886                                           const LValue &LHS) {
5887   if (LHS.InvalidBase || LHS.Designator.Invalid)
5888     return false;
5889 
5890   llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5891   // C++ [class.union]p5:
5892   //   define the set S(E) of subexpressions of E as follows:
5893   unsigned PathLength = LHS.Designator.Entries.size();
5894   for (const Expr *E = LHSExpr; E != nullptr;) {
5895     //   -- If E is of the form A.B, S(E) contains the elements of S(A)...
5896     if (auto *ME = dyn_cast<MemberExpr>(E)) {
5897       auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5898       // Note that we can't implicitly start the lifetime of a reference,
5899       // so we don't need to proceed any further if we reach one.
5900       if (!FD || FD->getType()->isReferenceType())
5901         break;
5902 
5903       //    ... and also contains A.B if B names a union member ...
5904       if (FD->getParent()->isUnion()) {
5905         //    ... of a non-class, non-array type, or of a class type with a
5906         //    trivial default constructor that is not deleted, or an array of
5907         //    such types.
5908         auto *RD =
5909             FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5910         if (!RD || RD->hasTrivialDefaultConstructor())
5911           UnionPathLengths.push_back({PathLength - 1, FD});
5912       }
5913 
5914       E = ME->getBase();
5915       --PathLength;
5916       assert(declaresSameEntity(FD,
5917                                 LHS.Designator.Entries[PathLength]
5918                                     .getAsBaseOrMember().getPointer()));
5919 
5920       //   -- If E is of the form A[B] and is interpreted as a built-in array
5921       //      subscripting operator, S(E) is [S(the array operand, if any)].
5922     } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5923       // Step over an ArrayToPointerDecay implicit cast.
5924       auto *Base = ASE->getBase()->IgnoreImplicit();
5925       if (!Base->getType()->isArrayType())
5926         break;
5927 
5928       E = Base;
5929       --PathLength;
5930 
5931     } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5932       // Step over a derived-to-base conversion.
5933       E = ICE->getSubExpr();
5934       if (ICE->getCastKind() == CK_NoOp)
5935         continue;
5936       if (ICE->getCastKind() != CK_DerivedToBase &&
5937           ICE->getCastKind() != CK_UncheckedDerivedToBase)
5938         break;
5939       // Walk path backwards as we walk up from the base to the derived class.
5940       for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
5941         --PathLength;
5942         (void)Elt;
5943         assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
5944                                   LHS.Designator.Entries[PathLength]
5945                                       .getAsBaseOrMember().getPointer()));
5946       }
5947 
5948     //   -- Otherwise, S(E) is empty.
5949     } else {
5950       break;
5951     }
5952   }
5953 
5954   // Common case: no unions' lifetimes are started.
5955   if (UnionPathLengths.empty())
5956     return true;
5957 
5958   //   if modification of X [would access an inactive union member], an object
5959   //   of the type of X is implicitly created
5960   CompleteObject Obj =
5961       findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
5962   if (!Obj)
5963     return false;
5964   for (std::pair<unsigned, const FieldDecl *> LengthAndField :
5965            llvm::reverse(UnionPathLengths)) {
5966     // Form a designator for the union object.
5967     SubobjectDesignator D = LHS.Designator;
5968     D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
5969 
5970     bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
5971                       ConstructionPhase::AfterBases;
5972     StartLifetimeOfUnionMemberHandler StartLifetime{
5973         Info, LHSExpr, LengthAndField.second, DuringInit};
5974     if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
5975       return false;
5976   }
5977 
5978   return true;
5979 }
5980 
5981 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
5982                             CallRef Call, EvalInfo &Info,
5983                             bool NonNull = false) {
5984   LValue LV;
5985   // Create the parameter slot and register its destruction. For a vararg
5986   // argument, create a temporary.
5987   // FIXME: For calling conventions that destroy parameters in the callee,
5988   // should we consider performing destruction when the function returns
5989   // instead?
5990   APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
5991                    : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
5992                                                        ScopeKind::Call, LV);
5993   if (!EvaluateInPlace(V, Info, LV, Arg))
5994     return false;
5995 
5996   // Passing a null pointer to an __attribute__((nonnull)) parameter results in
5997   // undefined behavior, so is non-constant.
5998   if (NonNull && V.isLValue() && V.isNullPointer()) {
5999     Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6000     return false;
6001   }
6002 
6003   return true;
6004 }
6005 
6006 /// Evaluate the arguments to a function call.
6007 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6008                          EvalInfo &Info, const FunctionDecl *Callee,
6009                          bool RightToLeft = false) {
6010   bool Success = true;
6011   llvm::SmallBitVector ForbiddenNullArgs;
6012   if (Callee->hasAttr<NonNullAttr>()) {
6013     ForbiddenNullArgs.resize(Args.size());
6014     for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6015       if (!Attr->args_size()) {
6016         ForbiddenNullArgs.set();
6017         break;
6018       } else
6019         for (auto Idx : Attr->args()) {
6020           unsigned ASTIdx = Idx.getASTIndex();
6021           if (ASTIdx >= Args.size())
6022             continue;
6023           ForbiddenNullArgs[ASTIdx] = 1;
6024         }
6025     }
6026   }
6027   for (unsigned I = 0; I < Args.size(); I++) {
6028     unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6029     const ParmVarDecl *PVD =
6030         Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6031     bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6032     if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) {
6033       // If we're checking for a potential constant expression, evaluate all
6034       // initializers even if some of them fail.
6035       if (!Info.noteFailure())
6036         return false;
6037       Success = false;
6038     }
6039   }
6040   return Success;
6041 }
6042 
6043 /// Perform a trivial copy from Param, which is the parameter of a copy or move
6044 /// constructor or assignment operator.
6045 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6046                               const Expr *E, APValue &Result,
6047                               bool CopyObjectRepresentation) {
6048   // Find the reference argument.
6049   CallStackFrame *Frame = Info.CurrentCall;
6050   APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6051   if (!RefValue) {
6052     Info.FFDiag(E);
6053     return false;
6054   }
6055 
6056   // Copy out the contents of the RHS object.
6057   LValue RefLValue;
6058   RefLValue.setFrom(Info.Ctx, *RefValue);
6059   return handleLValueToRValueConversion(
6060       Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6061       CopyObjectRepresentation);
6062 }
6063 
6064 /// Evaluate a function call.
6065 static bool HandleFunctionCall(SourceLocation CallLoc,
6066                                const FunctionDecl *Callee, const LValue *This,
6067                                ArrayRef<const Expr *> Args, CallRef Call,
6068                                const Stmt *Body, EvalInfo &Info,
6069                                APValue &Result, const LValue *ResultSlot) {
6070   if (!Info.CheckCallLimit(CallLoc))
6071     return false;
6072 
6073   CallStackFrame Frame(Info, CallLoc, Callee, This, Call);
6074 
6075   // For a trivial copy or move assignment, perform an APValue copy. This is
6076   // essential for unions, where the operations performed by the assignment
6077   // operator cannot be represented as statements.
6078   //
6079   // Skip this for non-union classes with no fields; in that case, the defaulted
6080   // copy/move does not actually read the object.
6081   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6082   if (MD && MD->isDefaulted() &&
6083       (MD->getParent()->isUnion() ||
6084        (MD->isTrivial() &&
6085         isReadByLvalueToRvalueConversion(MD->getParent())))) {
6086     assert(This &&
6087            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
6088     APValue RHSValue;
6089     if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6090                            MD->getParent()->isUnion()))
6091       return false;
6092     if (Info.getLangOpts().CPlusPlus20 && MD->isTrivial() &&
6093         !HandleUnionActiveMemberChange(Info, Args[0], *This))
6094       return false;
6095     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
6096                           RHSValue))
6097       return false;
6098     This->moveInto(Result);
6099     return true;
6100   } else if (MD && isLambdaCallOperator(MD)) {
6101     // We're in a lambda; determine the lambda capture field maps unless we're
6102     // just constexpr checking a lambda's call operator. constexpr checking is
6103     // done before the captures have been added to the closure object (unless
6104     // we're inferring constexpr-ness), so we don't have access to them in this
6105     // case. But since we don't need the captures to constexpr check, we can
6106     // just ignore them.
6107     if (!Info.checkingPotentialConstantExpression())
6108       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6109                                         Frame.LambdaThisCaptureField);
6110   }
6111 
6112   StmtResult Ret = {Result, ResultSlot};
6113   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6114   if (ESR == ESR_Succeeded) {
6115     if (Callee->getReturnType()->isVoidType())
6116       return true;
6117     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6118   }
6119   return ESR == ESR_Returned;
6120 }
6121 
6122 /// Evaluate a constructor call.
6123 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6124                                   CallRef Call,
6125                                   const CXXConstructorDecl *Definition,
6126                                   EvalInfo &Info, APValue &Result) {
6127   SourceLocation CallLoc = E->getExprLoc();
6128   if (!Info.CheckCallLimit(CallLoc))
6129     return false;
6130 
6131   const CXXRecordDecl *RD = Definition->getParent();
6132   if (RD->getNumVBases()) {
6133     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6134     return false;
6135   }
6136 
6137   EvalInfo::EvaluatingConstructorRAII EvalObj(
6138       Info,
6139       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6140       RD->getNumBases());
6141   CallStackFrame Frame(Info, CallLoc, Definition, &This, Call);
6142 
6143   // FIXME: Creating an APValue just to hold a nonexistent return value is
6144   // wasteful.
6145   APValue RetVal;
6146   StmtResult Ret = {RetVal, nullptr};
6147 
6148   // If it's a delegating constructor, delegate.
6149   if (Definition->isDelegatingConstructor()) {
6150     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
6151     {
6152       FullExpressionRAII InitScope(Info);
6153       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6154           !InitScope.destroy())
6155         return false;
6156     }
6157     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6158   }
6159 
6160   // For a trivial copy or move constructor, perform an APValue copy. This is
6161   // essential for unions (or classes with anonymous union members), where the
6162   // operations performed by the constructor cannot be represented by
6163   // ctor-initializers.
6164   //
6165   // Skip this for empty non-union classes; we should not perform an
6166   // lvalue-to-rvalue conversion on them because their copy constructor does not
6167   // actually read them.
6168   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6169       (Definition->getParent()->isUnion() ||
6170        (Definition->isTrivial() &&
6171         isReadByLvalueToRvalueConversion(Definition->getParent())))) {
6172     return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6173                              Definition->getParent()->isUnion());
6174   }
6175 
6176   // Reserve space for the struct members.
6177   if (!Result.hasValue()) {
6178     if (!RD->isUnion())
6179       Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6180                        std::distance(RD->field_begin(), RD->field_end()));
6181     else
6182       // A union starts with no active member.
6183       Result = APValue((const FieldDecl*)nullptr);
6184   }
6185 
6186   if (RD->isInvalidDecl()) return false;
6187   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6188 
6189   // A scope for temporaries lifetime-extended by reference members.
6190   BlockScopeRAII LifetimeExtendedScope(Info);
6191 
6192   bool Success = true;
6193   unsigned BasesSeen = 0;
6194 #ifndef NDEBUG
6195   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
6196 #endif
6197   CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
6198   auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6199     // We might be initializing the same field again if this is an indirect
6200     // field initialization.
6201     if (FieldIt == RD->field_end() ||
6202         FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6203       assert(Indirect && "fields out of order?");
6204       return;
6205     }
6206 
6207     // Default-initialize any fields with no explicit initializer.
6208     for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6209       assert(FieldIt != RD->field_end() && "missing field?");
6210       if (!FieldIt->isUnnamedBitfield())
6211         Success &= getDefaultInitValue(
6212             FieldIt->getType(),
6213             Result.getStructField(FieldIt->getFieldIndex()));
6214     }
6215     ++FieldIt;
6216   };
6217   for (const auto *I : Definition->inits()) {
6218     LValue Subobject = This;
6219     LValue SubobjectParent = This;
6220     APValue *Value = &Result;
6221 
6222     // Determine the subobject to initialize.
6223     FieldDecl *FD = nullptr;
6224     if (I->isBaseInitializer()) {
6225       QualType BaseType(I->getBaseClass(), 0);
6226 #ifndef NDEBUG
6227       // Non-virtual base classes are initialized in the order in the class
6228       // definition. We have already checked for virtual base classes.
6229       assert(!BaseIt->isVirtual() && "virtual base for literal type");
6230       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
6231              "base class initializers not in expected order");
6232       ++BaseIt;
6233 #endif
6234       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6235                                   BaseType->getAsCXXRecordDecl(), &Layout))
6236         return false;
6237       Value = &Result.getStructBase(BasesSeen++);
6238     } else if ((FD = I->getMember())) {
6239       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6240         return false;
6241       if (RD->isUnion()) {
6242         Result = APValue(FD);
6243         Value = &Result.getUnionValue();
6244       } else {
6245         SkipToField(FD, false);
6246         Value = &Result.getStructField(FD->getFieldIndex());
6247       }
6248     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6249       // Walk the indirect field decl's chain to find the object to initialize,
6250       // and make sure we've initialized every step along it.
6251       auto IndirectFieldChain = IFD->chain();
6252       for (auto *C : IndirectFieldChain) {
6253         FD = cast<FieldDecl>(C);
6254         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6255         // Switch the union field if it differs. This happens if we had
6256         // preceding zero-initialization, and we're now initializing a union
6257         // subobject other than the first.
6258         // FIXME: In this case, the values of the other subobjects are
6259         // specified, since zero-initialization sets all padding bits to zero.
6260         if (!Value->hasValue() ||
6261             (Value->isUnion() && Value->getUnionField() != FD)) {
6262           if (CD->isUnion())
6263             *Value = APValue(FD);
6264           else
6265             // FIXME: This immediately starts the lifetime of all members of
6266             // an anonymous struct. It would be preferable to strictly start
6267             // member lifetime in initialization order.
6268             Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
6269         }
6270         // Store Subobject as its parent before updating it for the last element
6271         // in the chain.
6272         if (C == IndirectFieldChain.back())
6273           SubobjectParent = Subobject;
6274         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6275           return false;
6276         if (CD->isUnion())
6277           Value = &Value->getUnionValue();
6278         else {
6279           if (C == IndirectFieldChain.front() && !RD->isUnion())
6280             SkipToField(FD, true);
6281           Value = &Value->getStructField(FD->getFieldIndex());
6282         }
6283       }
6284     } else {
6285       llvm_unreachable("unknown base initializer kind");
6286     }
6287 
6288     // Need to override This for implicit field initializers as in this case
6289     // This refers to innermost anonymous struct/union containing initializer,
6290     // not to currently constructed class.
6291     const Expr *Init = I->getInit();
6292     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6293                                   isa<CXXDefaultInitExpr>(Init));
6294     FullExpressionRAII InitScope(Info);
6295     if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6296         (FD && FD->isBitField() &&
6297          !truncateBitfieldValue(Info, Init, *Value, FD))) {
6298       // If we're checking for a potential constant expression, evaluate all
6299       // initializers even if some of them fail.
6300       if (!Info.noteFailure())
6301         return false;
6302       Success = false;
6303     }
6304 
6305     // This is the point at which the dynamic type of the object becomes this
6306     // class type.
6307     if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6308       EvalObj.finishedConstructingBases();
6309   }
6310 
6311   // Default-initialize any remaining fields.
6312   if (!RD->isUnion()) {
6313     for (; FieldIt != RD->field_end(); ++FieldIt) {
6314       if (!FieldIt->isUnnamedBitfield())
6315         Success &= getDefaultInitValue(
6316             FieldIt->getType(),
6317             Result.getStructField(FieldIt->getFieldIndex()));
6318     }
6319   }
6320 
6321   EvalObj.finishedConstructingFields();
6322 
6323   return Success &&
6324          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6325          LifetimeExtendedScope.destroy();
6326 }
6327 
6328 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6329                                   ArrayRef<const Expr*> Args,
6330                                   const CXXConstructorDecl *Definition,
6331                                   EvalInfo &Info, APValue &Result) {
6332   CallScopeRAII CallScope(Info);
6333   CallRef Call = Info.CurrentCall->createCall(Definition);
6334   if (!EvaluateArgs(Args, Call, Info, Definition))
6335     return false;
6336 
6337   return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6338          CallScope.destroy();
6339 }
6340 
6341 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
6342                                   const LValue &This, APValue &Value,
6343                                   QualType T) {
6344   // Objects can only be destroyed while they're within their lifetimes.
6345   // FIXME: We have no representation for whether an object of type nullptr_t
6346   // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6347   // as indeterminate instead?
6348   if (Value.isAbsent() && !T->isNullPtrType()) {
6349     APValue Printable;
6350     This.moveInto(Printable);
6351     Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
6352       << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6353     return false;
6354   }
6355 
6356   // Invent an expression for location purposes.
6357   // FIXME: We shouldn't need to do this.
6358   OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue);
6359 
6360   // For arrays, destroy elements right-to-left.
6361   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6362     uint64_t Size = CAT->getSize().getZExtValue();
6363     QualType ElemT = CAT->getElementType();
6364 
6365     LValue ElemLV = This;
6366     ElemLV.addArray(Info, &LocE, CAT);
6367     if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6368       return false;
6369 
6370     // Ensure that we have actual array elements available to destroy; the
6371     // destructors might mutate the value, so we can't run them on the array
6372     // filler.
6373     if (Size && Size > Value.getArrayInitializedElts())
6374       expandArray(Value, Value.getArraySize() - 1);
6375 
6376     for (; Size != 0; --Size) {
6377       APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6378       if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6379           !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
6380         return false;
6381     }
6382 
6383     // End the lifetime of this array now.
6384     Value = APValue();
6385     return true;
6386   }
6387 
6388   const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6389   if (!RD) {
6390     if (T.isDestructedType()) {
6391       Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
6392       return false;
6393     }
6394 
6395     Value = APValue();
6396     return true;
6397   }
6398 
6399   if (RD->getNumVBases()) {
6400     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6401     return false;
6402   }
6403 
6404   const CXXDestructorDecl *DD = RD->getDestructor();
6405   if (!DD && !RD->hasTrivialDestructor()) {
6406     Info.FFDiag(CallLoc);
6407     return false;
6408   }
6409 
6410   if (!DD || DD->isTrivial() ||
6411       (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6412     // A trivial destructor just ends the lifetime of the object. Check for
6413     // this case before checking for a body, because we might not bother
6414     // building a body for a trivial destructor. Note that it doesn't matter
6415     // whether the destructor is constexpr in this case; all trivial
6416     // destructors are constexpr.
6417     //
6418     // If an anonymous union would be destroyed, some enclosing destructor must
6419     // have been explicitly defined, and the anonymous union destruction should
6420     // have no effect.
6421     Value = APValue();
6422     return true;
6423   }
6424 
6425   if (!Info.CheckCallLimit(CallLoc))
6426     return false;
6427 
6428   const FunctionDecl *Definition = nullptr;
6429   const Stmt *Body = DD->getBody(Definition);
6430 
6431   if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
6432     return false;
6433 
6434   CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef());
6435 
6436   // We're now in the period of destruction of this object.
6437   unsigned BasesLeft = RD->getNumBases();
6438   EvalInfo::EvaluatingDestructorRAII EvalObj(
6439       Info,
6440       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6441   if (!EvalObj.DidInsert) {
6442     // C++2a [class.dtor]p19:
6443     //   the behavior is undefined if the destructor is invoked for an object
6444     //   whose lifetime has ended
6445     // (Note that formally the lifetime ends when the period of destruction
6446     // begins, even though certain uses of the object remain valid until the
6447     // period of destruction ends.)
6448     Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
6449     return false;
6450   }
6451 
6452   // FIXME: Creating an APValue just to hold a nonexistent return value is
6453   // wasteful.
6454   APValue RetVal;
6455   StmtResult Ret = {RetVal, nullptr};
6456   if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6457     return false;
6458 
6459   // A union destructor does not implicitly destroy its members.
6460   if (RD->isUnion())
6461     return true;
6462 
6463   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6464 
6465   // We don't have a good way to iterate fields in reverse, so collect all the
6466   // fields first and then walk them backwards.
6467   SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
6468   for (const FieldDecl *FD : llvm::reverse(Fields)) {
6469     if (FD->isUnnamedBitfield())
6470       continue;
6471 
6472     LValue Subobject = This;
6473     if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6474       return false;
6475 
6476     APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6477     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6478                                FD->getType()))
6479       return false;
6480   }
6481 
6482   if (BasesLeft != 0)
6483     EvalObj.startedDestroyingBases();
6484 
6485   // Destroy base classes in reverse order.
6486   for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6487     --BasesLeft;
6488 
6489     QualType BaseType = Base.getType();
6490     LValue Subobject = This;
6491     if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
6492                                 BaseType->getAsCXXRecordDecl(), &Layout))
6493       return false;
6494 
6495     APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
6496     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6497                                BaseType))
6498       return false;
6499   }
6500   assert(BasesLeft == 0 && "NumBases was wrong?");
6501 
6502   // The period of destruction ends now. The object is gone.
6503   Value = APValue();
6504   return true;
6505 }
6506 
6507 namespace {
6508 struct DestroyObjectHandler {
6509   EvalInfo &Info;
6510   const Expr *E;
6511   const LValue &This;
6512   const AccessKinds AccessKind;
6513 
6514   typedef bool result_type;
6515   bool failed() { return false; }
6516   bool found(APValue &Subobj, QualType SubobjType) {
6517     return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
6518                                  SubobjType);
6519   }
6520   bool found(APSInt &Value, QualType SubobjType) {
6521     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6522     return false;
6523   }
6524   bool found(APFloat &Value, QualType SubobjType) {
6525     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6526     return false;
6527   }
6528 };
6529 }
6530 
6531 /// Perform a destructor or pseudo-destructor call on the given object, which
6532 /// might in general not be a complete object.
6533 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6534                               const LValue &This, QualType ThisType) {
6535   CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6536   DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6537   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6538 }
6539 
6540 /// Destroy and end the lifetime of the given complete object.
6541 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6542                               APValue::LValueBase LVBase, APValue &Value,
6543                               QualType T) {
6544   // If we've had an unmodeled side-effect, we can't rely on mutable state
6545   // (such as the object we're about to destroy) being correct.
6546   if (Info.EvalStatus.HasSideEffects)
6547     return false;
6548 
6549   LValue LV;
6550   LV.set({LVBase});
6551   return HandleDestructionImpl(Info, Loc, LV, Value, T);
6552 }
6553 
6554 /// Perform a call to 'perator new' or to `__builtin_operator_new'.
6555 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6556                                   LValue &Result) {
6557   if (Info.checkingPotentialConstantExpression() ||
6558       Info.SpeculativeEvaluationDepth)
6559     return false;
6560 
6561   // This is permitted only within a call to std::allocator<T>::allocate.
6562   auto Caller = Info.getStdAllocatorCaller("allocate");
6563   if (!Caller) {
6564     Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
6565                                      ? diag::note_constexpr_new_untyped
6566                                      : diag::note_constexpr_new);
6567     return false;
6568   }
6569 
6570   QualType ElemType = Caller.ElemType;
6571   if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6572     Info.FFDiag(E->getExprLoc(),
6573                 diag::note_constexpr_new_not_complete_object_type)
6574         << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6575     return false;
6576   }
6577 
6578   APSInt ByteSize;
6579   if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6580     return false;
6581   bool IsNothrow = false;
6582   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6583     EvaluateIgnoredValue(Info, E->getArg(I));
6584     IsNothrow |= E->getType()->isNothrowT();
6585   }
6586 
6587   CharUnits ElemSize;
6588   if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6589     return false;
6590   APInt Size, Remainder;
6591   APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6592   APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6593   if (Remainder != 0) {
6594     // This likely indicates a bug in the implementation of 'std::allocator'.
6595     Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6596         << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6597     return false;
6598   }
6599 
6600   if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
6601     if (IsNothrow) {
6602       Result.setNull(Info.Ctx, E->getType());
6603       return true;
6604     }
6605 
6606     Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
6607     return false;
6608   }
6609 
6610   QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
6611                                                      ArrayType::Normal, 0);
6612   APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6613   *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6614   Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6615   return true;
6616 }
6617 
6618 static bool hasVirtualDestructor(QualType T) {
6619   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6620     if (CXXDestructorDecl *DD = RD->getDestructor())
6621       return DD->isVirtual();
6622   return false;
6623 }
6624 
6625 static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6626   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6627     if (CXXDestructorDecl *DD = RD->getDestructor())
6628       return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6629   return nullptr;
6630 }
6631 
6632 /// Check that the given object is a suitable pointer to a heap allocation that
6633 /// still exists and is of the right kind for the purpose of a deletion.
6634 ///
6635 /// On success, returns the heap allocation to deallocate. On failure, produces
6636 /// a diagnostic and returns None.
6637 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6638                                             const LValue &Pointer,
6639                                             DynAlloc::Kind DeallocKind) {
6640   auto PointerAsString = [&] {
6641     return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6642   };
6643 
6644   DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6645   if (!DA) {
6646     Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6647         << PointerAsString();
6648     if (Pointer.Base)
6649       NoteLValueLocation(Info, Pointer.Base);
6650     return None;
6651   }
6652 
6653   Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6654   if (!Alloc) {
6655     Info.FFDiag(E, diag::note_constexpr_double_delete);
6656     return None;
6657   }
6658 
6659   QualType AllocType = Pointer.Base.getDynamicAllocType();
6660   if (DeallocKind != (*Alloc)->getKind()) {
6661     Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6662         << DeallocKind << (*Alloc)->getKind() << AllocType;
6663     NoteLValueLocation(Info, Pointer.Base);
6664     return None;
6665   }
6666 
6667   bool Subobject = false;
6668   if (DeallocKind == DynAlloc::New) {
6669     Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6670                 Pointer.Designator.isOnePastTheEnd();
6671   } else {
6672     Subobject = Pointer.Designator.Entries.size() != 1 ||
6673                 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6674   }
6675   if (Subobject) {
6676     Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6677         << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6678     return None;
6679   }
6680 
6681   return Alloc;
6682 }
6683 
6684 // Perform a call to 'operator delete' or '__builtin_operator_delete'.
6685 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6686   if (Info.checkingPotentialConstantExpression() ||
6687       Info.SpeculativeEvaluationDepth)
6688     return false;
6689 
6690   // This is permitted only within a call to std::allocator<T>::deallocate.
6691   if (!Info.getStdAllocatorCaller("deallocate")) {
6692     Info.FFDiag(E->getExprLoc());
6693     return true;
6694   }
6695 
6696   LValue Pointer;
6697   if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6698     return false;
6699   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6700     EvaluateIgnoredValue(Info, E->getArg(I));
6701 
6702   if (Pointer.Designator.Invalid)
6703     return false;
6704 
6705   // Deleting a null pointer has no effect.
6706   if (Pointer.isNullPointer())
6707     return true;
6708 
6709   if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6710     return false;
6711 
6712   Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6713   return true;
6714 }
6715 
6716 //===----------------------------------------------------------------------===//
6717 // Generic Evaluation
6718 //===----------------------------------------------------------------------===//
6719 namespace {
6720 
6721 class BitCastBuffer {
6722   // FIXME: We're going to need bit-level granularity when we support
6723   // bit-fields.
6724   // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6725   // we don't support a host or target where that is the case. Still, we should
6726   // use a more generic type in case we ever do.
6727   SmallVector<Optional<unsigned char>, 32> Bytes;
6728 
6729   static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6730                 "Need at least 8 bit unsigned char");
6731 
6732   bool TargetIsLittleEndian;
6733 
6734 public:
6735   BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6736       : Bytes(Width.getQuantity()),
6737         TargetIsLittleEndian(TargetIsLittleEndian) {}
6738 
6739   LLVM_NODISCARD
6740   bool readObject(CharUnits Offset, CharUnits Width,
6741                   SmallVectorImpl<unsigned char> &Output) const {
6742     for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6743       // If a byte of an integer is uninitialized, then the whole integer is
6744       // uninitalized.
6745       if (!Bytes[I.getQuantity()])
6746         return false;
6747       Output.push_back(*Bytes[I.getQuantity()]);
6748     }
6749     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6750       std::reverse(Output.begin(), Output.end());
6751     return true;
6752   }
6753 
6754   void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6755     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6756       std::reverse(Input.begin(), Input.end());
6757 
6758     size_t Index = 0;
6759     for (unsigned char Byte : Input) {
6760       assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
6761       Bytes[Offset.getQuantity() + Index] = Byte;
6762       ++Index;
6763     }
6764   }
6765 
6766   size_t size() { return Bytes.size(); }
6767 };
6768 
6769 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6770 /// target would represent the value at runtime.
6771 class APValueToBufferConverter {
6772   EvalInfo &Info;
6773   BitCastBuffer Buffer;
6774   const CastExpr *BCE;
6775 
6776   APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6777                            const CastExpr *BCE)
6778       : Info(Info),
6779         Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6780         BCE(BCE) {}
6781 
6782   bool visit(const APValue &Val, QualType Ty) {
6783     return visit(Val, Ty, CharUnits::fromQuantity(0));
6784   }
6785 
6786   // Write out Val with type Ty into Buffer starting at Offset.
6787   bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6788     assert((size_t)Offset.getQuantity() <= Buffer.size());
6789 
6790     // As a special case, nullptr_t has an indeterminate value.
6791     if (Ty->isNullPtrType())
6792       return true;
6793 
6794     // Dig through Src to find the byte at SrcOffset.
6795     switch (Val.getKind()) {
6796     case APValue::Indeterminate:
6797     case APValue::None:
6798       return true;
6799 
6800     case APValue::Int:
6801       return visitInt(Val.getInt(), Ty, Offset);
6802     case APValue::Float:
6803       return visitFloat(Val.getFloat(), Ty, Offset);
6804     case APValue::Array:
6805       return visitArray(Val, Ty, Offset);
6806     case APValue::Struct:
6807       return visitRecord(Val, Ty, Offset);
6808 
6809     case APValue::ComplexInt:
6810     case APValue::ComplexFloat:
6811     case APValue::Vector:
6812     case APValue::FixedPoint:
6813       // FIXME: We should support these.
6814 
6815     case APValue::Union:
6816     case APValue::MemberPointer:
6817     case APValue::AddrLabelDiff: {
6818       Info.FFDiag(BCE->getBeginLoc(),
6819                   diag::note_constexpr_bit_cast_unsupported_type)
6820           << Ty;
6821       return false;
6822     }
6823 
6824     case APValue::LValue:
6825       llvm_unreachable("LValue subobject in bit_cast?");
6826     }
6827     llvm_unreachable("Unhandled APValue::ValueKind");
6828   }
6829 
6830   bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
6831     const RecordDecl *RD = Ty->getAsRecordDecl();
6832     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6833 
6834     // Visit the base classes.
6835     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6836       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6837         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6838         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6839 
6840         if (!visitRecord(Val.getStructBase(I), BS.getType(),
6841                          Layout.getBaseClassOffset(BaseDecl) + Offset))
6842           return false;
6843       }
6844     }
6845 
6846     // Visit the fields.
6847     unsigned FieldIdx = 0;
6848     for (FieldDecl *FD : RD->fields()) {
6849       if (FD->isBitField()) {
6850         Info.FFDiag(BCE->getBeginLoc(),
6851                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6852         return false;
6853       }
6854 
6855       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6856 
6857       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
6858              "only bit-fields can have sub-char alignment");
6859       CharUnits FieldOffset =
6860           Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
6861       QualType FieldTy = FD->getType();
6862       if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
6863         return false;
6864       ++FieldIdx;
6865     }
6866 
6867     return true;
6868   }
6869 
6870   bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
6871     const auto *CAT =
6872         dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
6873     if (!CAT)
6874       return false;
6875 
6876     CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
6877     unsigned NumInitializedElts = Val.getArrayInitializedElts();
6878     unsigned ArraySize = Val.getArraySize();
6879     // First, initialize the initialized elements.
6880     for (unsigned I = 0; I != NumInitializedElts; ++I) {
6881       const APValue &SubObj = Val.getArrayInitializedElt(I);
6882       if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
6883         return false;
6884     }
6885 
6886     // Next, initialize the rest of the array using the filler.
6887     if (Val.hasArrayFiller()) {
6888       const APValue &Filler = Val.getArrayFiller();
6889       for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
6890         if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
6891           return false;
6892       }
6893     }
6894 
6895     return true;
6896   }
6897 
6898   bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
6899     APSInt AdjustedVal = Val;
6900     unsigned Width = AdjustedVal.getBitWidth();
6901     if (Ty->isBooleanType()) {
6902       Width = Info.Ctx.getTypeSize(Ty);
6903       AdjustedVal = AdjustedVal.extend(Width);
6904     }
6905 
6906     SmallVector<unsigned char, 8> Bytes(Width / 8);
6907     llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
6908     Buffer.writeObject(Offset, Bytes);
6909     return true;
6910   }
6911 
6912   bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
6913     APSInt AsInt(Val.bitcastToAPInt());
6914     return visitInt(AsInt, Ty, Offset);
6915   }
6916 
6917 public:
6918   static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
6919                                          const CastExpr *BCE) {
6920     CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
6921     APValueToBufferConverter Converter(Info, DstSize, BCE);
6922     if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
6923       return None;
6924     return Converter.Buffer;
6925   }
6926 };
6927 
6928 /// Write an BitCastBuffer into an APValue.
6929 class BufferToAPValueConverter {
6930   EvalInfo &Info;
6931   const BitCastBuffer &Buffer;
6932   const CastExpr *BCE;
6933 
6934   BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
6935                            const CastExpr *BCE)
6936       : Info(Info), Buffer(Buffer), BCE(BCE) {}
6937 
6938   // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
6939   // with an invalid type, so anything left is a deficiency on our part (FIXME).
6940   // Ideally this will be unreachable.
6941   llvm::NoneType unsupportedType(QualType Ty) {
6942     Info.FFDiag(BCE->getBeginLoc(),
6943                 diag::note_constexpr_bit_cast_unsupported_type)
6944         << Ty;
6945     return None;
6946   }
6947 
6948   llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) {
6949     Info.FFDiag(BCE->getBeginLoc(),
6950                 diag::note_constexpr_bit_cast_unrepresentable_value)
6951         << Ty << Val.toString(/*Radix=*/10);
6952     return None;
6953   }
6954 
6955   Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
6956                           const EnumType *EnumSugar = nullptr) {
6957     if (T->isNullPtrType()) {
6958       uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
6959       return APValue((Expr *)nullptr,
6960                      /*Offset=*/CharUnits::fromQuantity(NullValue),
6961                      APValue::NoLValuePath{}, /*IsNullPtr=*/true);
6962     }
6963 
6964     CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
6965 
6966     // Work around floating point types that contain unused padding bytes. This
6967     // is really just `long double` on x86, which is the only fundamental type
6968     // with padding bytes.
6969     if (T->isRealFloatingType()) {
6970       const llvm::fltSemantics &Semantics =
6971           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
6972       unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
6973       assert(NumBits % 8 == 0);
6974       CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
6975       if (NumBytes != SizeOf)
6976         SizeOf = NumBytes;
6977     }
6978 
6979     SmallVector<uint8_t, 8> Bytes;
6980     if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
6981       // If this is std::byte or unsigned char, then its okay to store an
6982       // indeterminate value.
6983       bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
6984       bool IsUChar =
6985           !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
6986                          T->isSpecificBuiltinType(BuiltinType::Char_U));
6987       if (!IsStdByte && !IsUChar) {
6988         QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
6989         Info.FFDiag(BCE->getExprLoc(),
6990                     diag::note_constexpr_bit_cast_indet_dest)
6991             << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
6992         return None;
6993       }
6994 
6995       return APValue::IndeterminateValue();
6996     }
6997 
6998     APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
6999     llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
7000 
7001     if (T->isIntegralOrEnumerationType()) {
7002       Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7003 
7004       unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
7005       if (IntWidth != Val.getBitWidth()) {
7006         APSInt Truncated = Val.trunc(IntWidth);
7007         if (Truncated.extend(Val.getBitWidth()) != Val)
7008           return unrepresentableValue(QualType(T, 0), Val);
7009         Val = Truncated;
7010       }
7011 
7012       return APValue(Val);
7013     }
7014 
7015     if (T->isRealFloatingType()) {
7016       const llvm::fltSemantics &Semantics =
7017           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7018       return APValue(APFloat(Semantics, Val));
7019     }
7020 
7021     return unsupportedType(QualType(T, 0));
7022   }
7023 
7024   Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7025     const RecordDecl *RD = RTy->getAsRecordDecl();
7026     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7027 
7028     unsigned NumBases = 0;
7029     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7030       NumBases = CXXRD->getNumBases();
7031 
7032     APValue ResultVal(APValue::UninitStruct(), NumBases,
7033                       std::distance(RD->field_begin(), RD->field_end()));
7034 
7035     // Visit the base classes.
7036     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7037       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7038         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7039         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7040         if (BaseDecl->isEmpty() ||
7041             Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
7042           continue;
7043 
7044         Optional<APValue> SubObj = visitType(
7045             BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7046         if (!SubObj)
7047           return None;
7048         ResultVal.getStructBase(I) = *SubObj;
7049       }
7050     }
7051 
7052     // Visit the fields.
7053     unsigned FieldIdx = 0;
7054     for (FieldDecl *FD : RD->fields()) {
7055       // FIXME: We don't currently support bit-fields. A lot of the logic for
7056       // this is in CodeGen, so we need to factor it around.
7057       if (FD->isBitField()) {
7058         Info.FFDiag(BCE->getBeginLoc(),
7059                     diag::note_constexpr_bit_cast_unsupported_bitfield);
7060         return None;
7061       }
7062 
7063       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7064       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
7065 
7066       CharUnits FieldOffset =
7067           CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7068           Offset;
7069       QualType FieldTy = FD->getType();
7070       Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7071       if (!SubObj)
7072         return None;
7073       ResultVal.getStructField(FieldIdx) = *SubObj;
7074       ++FieldIdx;
7075     }
7076 
7077     return ResultVal;
7078   }
7079 
7080   Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7081     QualType RepresentationType = Ty->getDecl()->getIntegerType();
7082     assert(!RepresentationType.isNull() &&
7083            "enum forward decl should be caught by Sema");
7084     const auto *AsBuiltin =
7085         RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7086     // Recurse into the underlying type. Treat std::byte transparently as
7087     // unsigned char.
7088     return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7089   }
7090 
7091   Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7092     size_t Size = Ty->getSize().getLimitedValue();
7093     CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7094 
7095     APValue ArrayValue(APValue::UninitArray(), Size, Size);
7096     for (size_t I = 0; I != Size; ++I) {
7097       Optional<APValue> ElementValue =
7098           visitType(Ty->getElementType(), Offset + I * ElementWidth);
7099       if (!ElementValue)
7100         return None;
7101       ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7102     }
7103 
7104     return ArrayValue;
7105   }
7106 
7107   Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7108     return unsupportedType(QualType(Ty, 0));
7109   }
7110 
7111   Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7112     QualType Can = Ty.getCanonicalType();
7113 
7114     switch (Can->getTypeClass()) {
7115 #define TYPE(Class, Base)                                                      \
7116   case Type::Class:                                                            \
7117     return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7118 #define ABSTRACT_TYPE(Class, Base)
7119 #define NON_CANONICAL_TYPE(Class, Base)                                        \
7120   case Type::Class:                                                            \
7121     llvm_unreachable("non-canonical type should be impossible!");
7122 #define DEPENDENT_TYPE(Class, Base)                                            \
7123   case Type::Class:                                                            \
7124     llvm_unreachable(                                                          \
7125         "dependent types aren't supported in the constant evaluator!");
7126 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)                            \
7127   case Type::Class:                                                            \
7128     llvm_unreachable("either dependent or not canonical!");
7129 #include "clang/AST/TypeNodes.inc"
7130     }
7131     llvm_unreachable("Unhandled Type::TypeClass");
7132   }
7133 
7134 public:
7135   // Pull out a full value of type DstType.
7136   static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7137                                    const CastExpr *BCE) {
7138     BufferToAPValueConverter Converter(Info, Buffer, BCE);
7139     return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7140   }
7141 };
7142 
7143 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7144                                                  QualType Ty, EvalInfo *Info,
7145                                                  const ASTContext &Ctx,
7146                                                  bool CheckingDest) {
7147   Ty = Ty.getCanonicalType();
7148 
7149   auto diag = [&](int Reason) {
7150     if (Info)
7151       Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7152           << CheckingDest << (Reason == 4) << Reason;
7153     return false;
7154   };
7155   auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7156     if (Info)
7157       Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7158           << NoteTy << Construct << Ty;
7159     return false;
7160   };
7161 
7162   if (Ty->isUnionType())
7163     return diag(0);
7164   if (Ty->isPointerType())
7165     return diag(1);
7166   if (Ty->isMemberPointerType())
7167     return diag(2);
7168   if (Ty.isVolatileQualified())
7169     return diag(3);
7170 
7171   if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7172     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7173       for (CXXBaseSpecifier &BS : CXXRD->bases())
7174         if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7175                                                   CheckingDest))
7176           return note(1, BS.getType(), BS.getBeginLoc());
7177     }
7178     for (FieldDecl *FD : Record->fields()) {
7179       if (FD->getType()->isReferenceType())
7180         return diag(4);
7181       if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7182                                                 CheckingDest))
7183         return note(0, FD->getType(), FD->getBeginLoc());
7184     }
7185   }
7186 
7187   if (Ty->isArrayType() &&
7188       !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7189                                             Info, Ctx, CheckingDest))
7190     return false;
7191 
7192   return true;
7193 }
7194 
7195 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
7196                                              const ASTContext &Ctx,
7197                                              const CastExpr *BCE) {
7198   bool DestOK = checkBitCastConstexprEligibilityType(
7199       BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
7200   bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
7201                                 BCE->getBeginLoc(),
7202                                 BCE->getSubExpr()->getType(), Info, Ctx, false);
7203   return SourceOK;
7204 }
7205 
7206 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7207                                         APValue &SourceValue,
7208                                         const CastExpr *BCE) {
7209   assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7210          "no host or target supports non 8-bit chars");
7211   assert(SourceValue.isLValue() &&
7212          "LValueToRValueBitcast requires an lvalue operand!");
7213 
7214   if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
7215     return false;
7216 
7217   LValue SourceLValue;
7218   APValue SourceRValue;
7219   SourceLValue.setFrom(Info.Ctx, SourceValue);
7220   if (!handleLValueToRValueConversion(
7221           Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
7222           SourceRValue, /*WantObjectRepresentation=*/true))
7223     return false;
7224 
7225   // Read out SourceValue into a char buffer.
7226   Optional<BitCastBuffer> Buffer =
7227       APValueToBufferConverter::convert(Info, SourceRValue, BCE);
7228   if (!Buffer)
7229     return false;
7230 
7231   // Write out the buffer into a new APValue.
7232   Optional<APValue> MaybeDestValue =
7233       BufferToAPValueConverter::convert(Info, *Buffer, BCE);
7234   if (!MaybeDestValue)
7235     return false;
7236 
7237   DestValue = std::move(*MaybeDestValue);
7238   return true;
7239 }
7240 
7241 template <class Derived>
7242 class ExprEvaluatorBase
7243   : public ConstStmtVisitor<Derived, bool> {
7244 private:
7245   Derived &getDerived() { return static_cast<Derived&>(*this); }
7246   bool DerivedSuccess(const APValue &V, const Expr *E) {
7247     return getDerived().Success(V, E);
7248   }
7249   bool DerivedZeroInitialization(const Expr *E) {
7250     return getDerived().ZeroInitialization(E);
7251   }
7252 
7253   // Check whether a conditional operator with a non-constant condition is a
7254   // potential constant expression. If neither arm is a potential constant
7255   // expression, then the conditional operator is not either.
7256   template<typename ConditionalOperator>
7257   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7258     assert(Info.checkingPotentialConstantExpression());
7259 
7260     // Speculatively evaluate both arms.
7261     SmallVector<PartialDiagnosticAt, 8> Diag;
7262     {
7263       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7264       StmtVisitorTy::Visit(E->getFalseExpr());
7265       if (Diag.empty())
7266         return;
7267     }
7268 
7269     {
7270       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7271       Diag.clear();
7272       StmtVisitorTy::Visit(E->getTrueExpr());
7273       if (Diag.empty())
7274         return;
7275     }
7276 
7277     Error(E, diag::note_constexpr_conditional_never_const);
7278   }
7279 
7280 
7281   template<typename ConditionalOperator>
7282   bool HandleConditionalOperator(const ConditionalOperator *E) {
7283     bool BoolResult;
7284     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7285       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7286         CheckPotentialConstantConditional(E);
7287         return false;
7288       }
7289       if (Info.noteFailure()) {
7290         StmtVisitorTy::Visit(E->getTrueExpr());
7291         StmtVisitorTy::Visit(E->getFalseExpr());
7292       }
7293       return false;
7294     }
7295 
7296     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
7297     return StmtVisitorTy::Visit(EvalExpr);
7298   }
7299 
7300 protected:
7301   EvalInfo &Info;
7302   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
7303   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
7304 
7305   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7306     return Info.CCEDiag(E, D);
7307   }
7308 
7309   bool ZeroInitialization(const Expr *E) { return Error(E); }
7310 
7311 public:
7312   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
7313 
7314   EvalInfo &getEvalInfo() { return Info; }
7315 
7316   /// Report an evaluation error. This should only be called when an error is
7317   /// first discovered. When propagating an error, just return false.
7318   bool Error(const Expr *E, diag::kind D) {
7319     Info.FFDiag(E, D);
7320     return false;
7321   }
7322   bool Error(const Expr *E) {
7323     return Error(E, diag::note_invalid_subexpr_in_const_expr);
7324   }
7325 
7326   bool VisitStmt(const Stmt *) {
7327     llvm_unreachable("Expression evaluator should not be called on stmts");
7328   }
7329   bool VisitExpr(const Expr *E) {
7330     return Error(E);
7331   }
7332 
7333   bool VisitConstantExpr(const ConstantExpr *E) {
7334     if (E->hasAPValueResult())
7335       return DerivedSuccess(E->getAPValueResult(), E);
7336 
7337     return StmtVisitorTy::Visit(E->getSubExpr());
7338   }
7339 
7340   bool VisitParenExpr(const ParenExpr *E)
7341     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7342   bool VisitUnaryExtension(const UnaryOperator *E)
7343     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7344   bool VisitUnaryPlus(const UnaryOperator *E)
7345     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7346   bool VisitChooseExpr(const ChooseExpr *E)
7347     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
7348   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
7349     { return StmtVisitorTy::Visit(E->getResultExpr()); }
7350   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
7351     { return StmtVisitorTy::Visit(E->getReplacement()); }
7352   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7353     TempVersionRAII RAII(*Info.CurrentCall);
7354     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7355     return StmtVisitorTy::Visit(E->getExpr());
7356   }
7357   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7358     TempVersionRAII RAII(*Info.CurrentCall);
7359     // The initializer may not have been parsed yet, or might be erroneous.
7360     if (!E->getExpr())
7361       return Error(E);
7362     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7363     return StmtVisitorTy::Visit(E->getExpr());
7364   }
7365 
7366   bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7367     FullExpressionRAII Scope(Info);
7368     return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
7369   }
7370 
7371   // Temporaries are registered when created, so we don't care about
7372   // CXXBindTemporaryExpr.
7373   bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7374     return StmtVisitorTy::Visit(E->getSubExpr());
7375   }
7376 
7377   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7378     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7379     return static_cast<Derived*>(this)->VisitCastExpr(E);
7380   }
7381   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7382     if (!Info.Ctx.getLangOpts().CPlusPlus20)
7383       CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
7384     return static_cast<Derived*>(this)->VisitCastExpr(E);
7385   }
7386   bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7387     return static_cast<Derived*>(this)->VisitCastExpr(E);
7388   }
7389 
7390   bool VisitBinaryOperator(const BinaryOperator *E) {
7391     switch (E->getOpcode()) {
7392     default:
7393       return Error(E);
7394 
7395     case BO_Comma:
7396       VisitIgnoredValue(E->getLHS());
7397       return StmtVisitorTy::Visit(E->getRHS());
7398 
7399     case BO_PtrMemD:
7400     case BO_PtrMemI: {
7401       LValue Obj;
7402       if (!HandleMemberPointerAccess(Info, E, Obj))
7403         return false;
7404       APValue Result;
7405       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7406         return false;
7407       return DerivedSuccess(Result, E);
7408     }
7409     }
7410   }
7411 
7412   bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
7413     return StmtVisitorTy::Visit(E->getSemanticForm());
7414   }
7415 
7416   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7417     // Evaluate and cache the common expression. We treat it as a temporary,
7418     // even though it's not quite the same thing.
7419     LValue CommonLV;
7420     if (!Evaluate(Info.CurrentCall->createTemporary(
7421                       E->getOpaqueValue(),
7422                       getStorageType(Info.Ctx, E->getOpaqueValue()),
7423                       ScopeKind::FullExpression, CommonLV),
7424                   Info, E->getCommon()))
7425       return false;
7426 
7427     return HandleConditionalOperator(E);
7428   }
7429 
7430   bool VisitConditionalOperator(const ConditionalOperator *E) {
7431     bool IsBcpCall = false;
7432     // If the condition (ignoring parens) is a __builtin_constant_p call,
7433     // the result is a constant expression if it can be folded without
7434     // side-effects. This is an important GNU extension. See GCC PR38377
7435     // for discussion.
7436     if (const CallExpr *CallCE =
7437           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7438       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7439         IsBcpCall = true;
7440 
7441     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7442     // constant expression; we can't check whether it's potentially foldable.
7443     // FIXME: We should instead treat __builtin_constant_p as non-constant if
7444     // it would return 'false' in this mode.
7445     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
7446       return false;
7447 
7448     FoldConstant Fold(Info, IsBcpCall);
7449     if (!HandleConditionalOperator(E)) {
7450       Fold.keepDiagnostics();
7451       return false;
7452     }
7453 
7454     return true;
7455   }
7456 
7457   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7458     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
7459       return DerivedSuccess(*Value, E);
7460 
7461     const Expr *Source = E->getSourceExpr();
7462     if (!Source)
7463       return Error(E);
7464     if (Source == E) { // sanity checking.
7465       assert(0 && "OpaqueValueExpr recursively refers to itself");
7466       return Error(E);
7467     }
7468     return StmtVisitorTy::Visit(Source);
7469   }
7470 
7471   bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7472     for (const Expr *SemE : E->semantics()) {
7473       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7474         // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7475         // result expression: there could be two different LValues that would
7476         // refer to the same object in that case, and we can't model that.
7477         if (SemE == E->getResultExpr())
7478           return Error(E);
7479 
7480         // Unique OVEs get evaluated if and when we encounter them when
7481         // emitting the rest of the semantic form, rather than eagerly.
7482         if (OVE->isUnique())
7483           continue;
7484 
7485         LValue LV;
7486         if (!Evaluate(Info.CurrentCall->createTemporary(
7487                           OVE, getStorageType(Info.Ctx, OVE),
7488                           ScopeKind::FullExpression, LV),
7489                       Info, OVE->getSourceExpr()))
7490           return false;
7491       } else if (SemE == E->getResultExpr()) {
7492         if (!StmtVisitorTy::Visit(SemE))
7493           return false;
7494       } else {
7495         if (!EvaluateIgnoredValue(Info, SemE))
7496           return false;
7497       }
7498     }
7499     return true;
7500   }
7501 
7502   bool VisitCallExpr(const CallExpr *E) {
7503     APValue Result;
7504     if (!handleCallExpr(E, Result, nullptr))
7505       return false;
7506     return DerivedSuccess(Result, E);
7507   }
7508 
7509   bool handleCallExpr(const CallExpr *E, APValue &Result,
7510                      const LValue *ResultSlot) {
7511     CallScopeRAII CallScope(Info);
7512 
7513     const Expr *Callee = E->getCallee()->IgnoreParens();
7514     QualType CalleeType = Callee->getType();
7515 
7516     const FunctionDecl *FD = nullptr;
7517     LValue *This = nullptr, ThisVal;
7518     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
7519     bool HasQualifier = false;
7520 
7521     CallRef Call;
7522 
7523     // Extract function decl and 'this' pointer from the callee.
7524     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7525       const CXXMethodDecl *Member = nullptr;
7526       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7527         // Explicit bound member calls, such as x.f() or p->g();
7528         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7529           return false;
7530         Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7531         if (!Member)
7532           return Error(Callee);
7533         This = &ThisVal;
7534         HasQualifier = ME->hasQualifier();
7535       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
7536         // Indirect bound member calls ('.*' or '->*').
7537         const ValueDecl *D =
7538             HandleMemberPointerAccess(Info, BE, ThisVal, false);
7539         if (!D)
7540           return false;
7541         Member = dyn_cast<CXXMethodDecl>(D);
7542         if (!Member)
7543           return Error(Callee);
7544         This = &ThisVal;
7545       } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7546         if (!Info.getLangOpts().CPlusPlus20)
7547           Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7548         return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7549                HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7550       } else
7551         return Error(Callee);
7552       FD = Member;
7553     } else if (CalleeType->isFunctionPointerType()) {
7554       LValue CalleeLV;
7555       if (!EvaluatePointer(Callee, CalleeLV, Info))
7556         return false;
7557 
7558       if (!CalleeLV.getLValueOffset().isZero())
7559         return Error(Callee);
7560       FD = dyn_cast_or_null<FunctionDecl>(
7561           CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
7562       if (!FD)
7563         return Error(Callee);
7564       // Don't call function pointers which have been cast to some other type.
7565       // Per DR (no number yet), the caller and callee can differ in noexcept.
7566       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7567         CalleeType->getPointeeType(), FD->getType())) {
7568         return Error(E);
7569       }
7570 
7571       // For an (overloaded) assignment expression, evaluate the RHS before the
7572       // LHS.
7573       auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
7574       if (OCE && OCE->isAssignmentOp()) {
7575         assert(Args.size() == 2 && "wrong number of arguments in assignment");
7576         Call = Info.CurrentCall->createCall(FD);
7577         if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call,
7578                           Info, FD, /*RightToLeft=*/true))
7579           return false;
7580       }
7581 
7582       // Overloaded operator calls to member functions are represented as normal
7583       // calls with '*this' as the first argument.
7584       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7585       if (MD && !MD->isStatic()) {
7586         // FIXME: When selecting an implicit conversion for an overloaded
7587         // operator delete, we sometimes try to evaluate calls to conversion
7588         // operators without a 'this' parameter!
7589         if (Args.empty())
7590           return Error(E);
7591 
7592         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7593           return false;
7594         This = &ThisVal;
7595         Args = Args.slice(1);
7596       } else if (MD && MD->isLambdaStaticInvoker()) {
7597         // Map the static invoker for the lambda back to the call operator.
7598         // Conveniently, we don't have to slice out the 'this' argument (as is
7599         // being done for the non-static case), since a static member function
7600         // doesn't have an implicit argument passed in.
7601         const CXXRecordDecl *ClosureClass = MD->getParent();
7602         assert(
7603             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7604             "Number of captures must be zero for conversion to function-ptr");
7605 
7606         const CXXMethodDecl *LambdaCallOp =
7607             ClosureClass->getLambdaCallOperator();
7608 
7609         // Set 'FD', the function that will be called below, to the call
7610         // operator.  If the closure object represents a generic lambda, find
7611         // the corresponding specialization of the call operator.
7612 
7613         if (ClosureClass->isGenericLambda()) {
7614           assert(MD->isFunctionTemplateSpecialization() &&
7615                  "A generic lambda's static-invoker function must be a "
7616                  "template specialization");
7617           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7618           FunctionTemplateDecl *CallOpTemplate =
7619               LambdaCallOp->getDescribedFunctionTemplate();
7620           void *InsertPos = nullptr;
7621           FunctionDecl *CorrespondingCallOpSpecialization =
7622               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7623           assert(CorrespondingCallOpSpecialization &&
7624                  "We must always have a function call operator specialization "
7625                  "that corresponds to our static invoker specialization");
7626           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7627         } else
7628           FD = LambdaCallOp;
7629       } else if (FD->isReplaceableGlobalAllocationFunction()) {
7630         if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7631             FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7632           LValue Ptr;
7633           if (!HandleOperatorNewCall(Info, E, Ptr))
7634             return false;
7635           Ptr.moveInto(Result);
7636           return CallScope.destroy();
7637         } else {
7638           return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
7639         }
7640       }
7641     } else
7642       return Error(E);
7643 
7644     // Evaluate the arguments now if we've not already done so.
7645     if (!Call) {
7646       Call = Info.CurrentCall->createCall(FD);
7647       if (!EvaluateArgs(Args, Call, Info, FD))
7648         return false;
7649     }
7650 
7651     SmallVector<QualType, 4> CovariantAdjustmentPath;
7652     if (This) {
7653       auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7654       if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
7655         // Perform virtual dispatch, if necessary.
7656         FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
7657                                    CovariantAdjustmentPath);
7658         if (!FD)
7659           return false;
7660       } else {
7661         // Check that the 'this' pointer points to an object of the right type.
7662         // FIXME: If this is an assignment operator call, we may need to change
7663         // the active union member before we check this.
7664         if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
7665           return false;
7666       }
7667     }
7668 
7669     // Destructor calls are different enough that they have their own codepath.
7670     if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
7671       assert(This && "no 'this' pointer for destructor call");
7672       return HandleDestruction(Info, E, *This,
7673                                Info.Ctx.getRecordType(DD->getParent())) &&
7674              CallScope.destroy();
7675     }
7676 
7677     const FunctionDecl *Definition = nullptr;
7678     Stmt *Body = FD->getBody(Definition);
7679 
7680     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
7681         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call,
7682                             Body, Info, Result, ResultSlot))
7683       return false;
7684 
7685     if (!CovariantAdjustmentPath.empty() &&
7686         !HandleCovariantReturnAdjustment(Info, E, Result,
7687                                          CovariantAdjustmentPath))
7688       return false;
7689 
7690     return CallScope.destroy();
7691   }
7692 
7693   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7694     return StmtVisitorTy::Visit(E->getInitializer());
7695   }
7696   bool VisitInitListExpr(const InitListExpr *E) {
7697     if (E->getNumInits() == 0)
7698       return DerivedZeroInitialization(E);
7699     if (E->getNumInits() == 1)
7700       return StmtVisitorTy::Visit(E->getInit(0));
7701     return Error(E);
7702   }
7703   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
7704     return DerivedZeroInitialization(E);
7705   }
7706   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
7707     return DerivedZeroInitialization(E);
7708   }
7709   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
7710     return DerivedZeroInitialization(E);
7711   }
7712 
7713   /// A member expression where the object is a prvalue is itself a prvalue.
7714   bool VisitMemberExpr(const MemberExpr *E) {
7715     assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
7716            "missing temporary materialization conversion");
7717     assert(!E->isArrow() && "missing call to bound member function?");
7718 
7719     APValue Val;
7720     if (!Evaluate(Val, Info, E->getBase()))
7721       return false;
7722 
7723     QualType BaseTy = E->getBase()->getType();
7724 
7725     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
7726     if (!FD) return Error(E);
7727     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
7728     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7729            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7730 
7731     // Note: there is no lvalue base here. But this case should only ever
7732     // happen in C or in C++98, where we cannot be evaluating a constexpr
7733     // constructor, which is the only case the base matters.
7734     CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
7735     SubobjectDesignator Designator(BaseTy);
7736     Designator.addDeclUnchecked(FD);
7737 
7738     APValue Result;
7739     return extractSubobject(Info, E, Obj, Designator, Result) &&
7740            DerivedSuccess(Result, E);
7741   }
7742 
7743   bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
7744     APValue Val;
7745     if (!Evaluate(Val, Info, E->getBase()))
7746       return false;
7747 
7748     if (Val.isVector()) {
7749       SmallVector<uint32_t, 4> Indices;
7750       E->getEncodedElementAccess(Indices);
7751       if (Indices.size() == 1) {
7752         // Return scalar.
7753         return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
7754       } else {
7755         // Construct new APValue vector.
7756         SmallVector<APValue, 4> Elts;
7757         for (unsigned I = 0; I < Indices.size(); ++I) {
7758           Elts.push_back(Val.getVectorElt(Indices[I]));
7759         }
7760         APValue VecResult(Elts.data(), Indices.size());
7761         return DerivedSuccess(VecResult, E);
7762       }
7763     }
7764 
7765     return false;
7766   }
7767 
7768   bool VisitCastExpr(const CastExpr *E) {
7769     switch (E->getCastKind()) {
7770     default:
7771       break;
7772 
7773     case CK_AtomicToNonAtomic: {
7774       APValue AtomicVal;
7775       // This does not need to be done in place even for class/array types:
7776       // atomic-to-non-atomic conversion implies copying the object
7777       // representation.
7778       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
7779         return false;
7780       return DerivedSuccess(AtomicVal, E);
7781     }
7782 
7783     case CK_NoOp:
7784     case CK_UserDefinedConversion:
7785       return StmtVisitorTy::Visit(E->getSubExpr());
7786 
7787     case CK_LValueToRValue: {
7788       LValue LVal;
7789       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
7790         return false;
7791       APValue RVal;
7792       // Note, we use the subexpression's type in order to retain cv-qualifiers.
7793       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7794                                           LVal, RVal))
7795         return false;
7796       return DerivedSuccess(RVal, E);
7797     }
7798     case CK_LValueToRValueBitCast: {
7799       APValue DestValue, SourceValue;
7800       if (!Evaluate(SourceValue, Info, E->getSubExpr()))
7801         return false;
7802       if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
7803         return false;
7804       return DerivedSuccess(DestValue, E);
7805     }
7806 
7807     case CK_AddressSpaceConversion: {
7808       APValue Value;
7809       if (!Evaluate(Value, Info, E->getSubExpr()))
7810         return false;
7811       return DerivedSuccess(Value, E);
7812     }
7813     }
7814 
7815     return Error(E);
7816   }
7817 
7818   bool VisitUnaryPostInc(const UnaryOperator *UO) {
7819     return VisitUnaryPostIncDec(UO);
7820   }
7821   bool VisitUnaryPostDec(const UnaryOperator *UO) {
7822     return VisitUnaryPostIncDec(UO);
7823   }
7824   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
7825     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7826       return Error(UO);
7827 
7828     LValue LVal;
7829     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
7830       return false;
7831     APValue RVal;
7832     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
7833                       UO->isIncrementOp(), &RVal))
7834       return false;
7835     return DerivedSuccess(RVal, UO);
7836   }
7837 
7838   bool VisitStmtExpr(const StmtExpr *E) {
7839     // We will have checked the full-expressions inside the statement expression
7840     // when they were completed, and don't need to check them again now.
7841     if (Info.checkingForUndefinedBehavior())
7842       return Error(E);
7843 
7844     const CompoundStmt *CS = E->getSubStmt();
7845     if (CS->body_empty())
7846       return true;
7847 
7848     BlockScopeRAII Scope(Info);
7849     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
7850                                            BE = CS->body_end();
7851          /**/; ++BI) {
7852       if (BI + 1 == BE) {
7853         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
7854         if (!FinalExpr) {
7855           Info.FFDiag((*BI)->getBeginLoc(),
7856                       diag::note_constexpr_stmt_expr_unsupported);
7857           return false;
7858         }
7859         return this->Visit(FinalExpr) && Scope.destroy();
7860       }
7861 
7862       APValue ReturnValue;
7863       StmtResult Result = { ReturnValue, nullptr };
7864       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
7865       if (ESR != ESR_Succeeded) {
7866         // FIXME: If the statement-expression terminated due to 'return',
7867         // 'break', or 'continue', it would be nice to propagate that to
7868         // the outer statement evaluation rather than bailing out.
7869         if (ESR != ESR_Failed)
7870           Info.FFDiag((*BI)->getBeginLoc(),
7871                       diag::note_constexpr_stmt_expr_unsupported);
7872         return false;
7873       }
7874     }
7875 
7876     llvm_unreachable("Return from function from the loop above.");
7877   }
7878 
7879   /// Visit a value which is evaluated, but whose value is ignored.
7880   void VisitIgnoredValue(const Expr *E) {
7881     EvaluateIgnoredValue(Info, E);
7882   }
7883 
7884   /// Potentially visit a MemberExpr's base expression.
7885   void VisitIgnoredBaseExpression(const Expr *E) {
7886     // While MSVC doesn't evaluate the base expression, it does diagnose the
7887     // presence of side-effecting behavior.
7888     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
7889       return;
7890     VisitIgnoredValue(E);
7891   }
7892 };
7893 
7894 } // namespace
7895 
7896 //===----------------------------------------------------------------------===//
7897 // Common base class for lvalue and temporary evaluation.
7898 //===----------------------------------------------------------------------===//
7899 namespace {
7900 template<class Derived>
7901 class LValueExprEvaluatorBase
7902   : public ExprEvaluatorBase<Derived> {
7903 protected:
7904   LValue &Result;
7905   bool InvalidBaseOK;
7906   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
7907   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
7908 
7909   bool Success(APValue::LValueBase B) {
7910     Result.set(B);
7911     return true;
7912   }
7913 
7914   bool evaluatePointer(const Expr *E, LValue &Result) {
7915     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
7916   }
7917 
7918 public:
7919   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
7920       : ExprEvaluatorBaseTy(Info), Result(Result),
7921         InvalidBaseOK(InvalidBaseOK) {}
7922 
7923   bool Success(const APValue &V, const Expr *E) {
7924     Result.setFrom(this->Info.Ctx, V);
7925     return true;
7926   }
7927 
7928   bool VisitMemberExpr(const MemberExpr *E) {
7929     // Handle non-static data members.
7930     QualType BaseTy;
7931     bool EvalOK;
7932     if (E->isArrow()) {
7933       EvalOK = evaluatePointer(E->getBase(), Result);
7934       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
7935     } else if (E->getBase()->isRValue()) {
7936       assert(E->getBase()->getType()->isRecordType());
7937       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
7938       BaseTy = E->getBase()->getType();
7939     } else {
7940       EvalOK = this->Visit(E->getBase());
7941       BaseTy = E->getBase()->getType();
7942     }
7943     if (!EvalOK) {
7944       if (!InvalidBaseOK)
7945         return false;
7946       Result.setInvalid(E);
7947       return true;
7948     }
7949 
7950     const ValueDecl *MD = E->getMemberDecl();
7951     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
7952       assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7953              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7954       (void)BaseTy;
7955       if (!HandleLValueMember(this->Info, E, Result, FD))
7956         return false;
7957     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
7958       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
7959         return false;
7960     } else
7961       return this->Error(E);
7962 
7963     if (MD->getType()->isReferenceType()) {
7964       APValue RefValue;
7965       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
7966                                           RefValue))
7967         return false;
7968       return Success(RefValue, E);
7969     }
7970     return true;
7971   }
7972 
7973   bool VisitBinaryOperator(const BinaryOperator *E) {
7974     switch (E->getOpcode()) {
7975     default:
7976       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7977 
7978     case BO_PtrMemD:
7979     case BO_PtrMemI:
7980       return HandleMemberPointerAccess(this->Info, E, Result);
7981     }
7982   }
7983 
7984   bool VisitCastExpr(const CastExpr *E) {
7985     switch (E->getCastKind()) {
7986     default:
7987       return ExprEvaluatorBaseTy::VisitCastExpr(E);
7988 
7989     case CK_DerivedToBase:
7990     case CK_UncheckedDerivedToBase:
7991       if (!this->Visit(E->getSubExpr()))
7992         return false;
7993 
7994       // Now figure out the necessary offset to add to the base LV to get from
7995       // the derived class to the base class.
7996       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
7997                                   Result);
7998     }
7999   }
8000 };
8001 }
8002 
8003 //===----------------------------------------------------------------------===//
8004 // LValue Evaluation
8005 //
8006 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8007 // function designators (in C), decl references to void objects (in C), and
8008 // temporaries (if building with -Wno-address-of-temporary).
8009 //
8010 // LValue evaluation produces values comprising a base expression of one of the
8011 // following types:
8012 // - Declarations
8013 //  * VarDecl
8014 //  * FunctionDecl
8015 // - Literals
8016 //  * CompoundLiteralExpr in C (and in global scope in C++)
8017 //  * StringLiteral
8018 //  * PredefinedExpr
8019 //  * ObjCStringLiteralExpr
8020 //  * ObjCEncodeExpr
8021 //  * AddrLabelExpr
8022 //  * BlockExpr
8023 //  * CallExpr for a MakeStringConstant builtin
8024 // - typeid(T) expressions, as TypeInfoLValues
8025 // - Locals and temporaries
8026 //  * MaterializeTemporaryExpr
8027 //  * Any Expr, with a CallIndex indicating the function in which the temporary
8028 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
8029 //    from the AST (FIXME).
8030 //  * A MaterializeTemporaryExpr that has static storage duration, with no
8031 //    CallIndex, for a lifetime-extended temporary.
8032 //  * The ConstantExpr that is currently being evaluated during evaluation of an
8033 //    immediate invocation.
8034 // plus an offset in bytes.
8035 //===----------------------------------------------------------------------===//
8036 namespace {
8037 class LValueExprEvaluator
8038   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8039 public:
8040   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8041     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8042 
8043   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8044   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8045 
8046   bool VisitDeclRefExpr(const DeclRefExpr *E);
8047   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8048   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8049   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8050   bool VisitMemberExpr(const MemberExpr *E);
8051   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
8052   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8053   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8054   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8055   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8056   bool VisitUnaryDeref(const UnaryOperator *E);
8057   bool VisitUnaryReal(const UnaryOperator *E);
8058   bool VisitUnaryImag(const UnaryOperator *E);
8059   bool VisitUnaryPreInc(const UnaryOperator *UO) {
8060     return VisitUnaryPreIncDec(UO);
8061   }
8062   bool VisitUnaryPreDec(const UnaryOperator *UO) {
8063     return VisitUnaryPreIncDec(UO);
8064   }
8065   bool VisitBinAssign(const BinaryOperator *BO);
8066   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8067 
8068   bool VisitCastExpr(const CastExpr *E) {
8069     switch (E->getCastKind()) {
8070     default:
8071       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8072 
8073     case CK_LValueBitCast:
8074       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8075       if (!Visit(E->getSubExpr()))
8076         return false;
8077       Result.Designator.setInvalid();
8078       return true;
8079 
8080     case CK_BaseToDerived:
8081       if (!Visit(E->getSubExpr()))
8082         return false;
8083       return HandleBaseToDerivedCast(Info, E, Result);
8084 
8085     case CK_Dynamic:
8086       if (!Visit(E->getSubExpr()))
8087         return false;
8088       return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8089     }
8090   }
8091 };
8092 } // end anonymous namespace
8093 
8094 /// Evaluate an expression as an lvalue. This can be legitimately called on
8095 /// expressions which are not glvalues, in three cases:
8096 ///  * function designators in C, and
8097 ///  * "extern void" objects
8098 ///  * @selector() expressions in Objective-C
8099 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
8100                            bool InvalidBaseOK) {
8101   assert(E->isGLValue() || E->getType()->isFunctionType() ||
8102          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
8103   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8104 }
8105 
8106 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
8107   const NamedDecl *D = E->getDecl();
8108   if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl>(D))
8109     return Success(cast<ValueDecl>(D));
8110   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
8111     return VisitVarDecl(E, VD);
8112   if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
8113     return Visit(BD->getBinding());
8114   return Error(E);
8115 }
8116 
8117 
8118 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
8119 
8120   // If we are within a lambda's call operator, check whether the 'VD' referred
8121   // to within 'E' actually represents a lambda-capture that maps to a
8122   // data-member/field within the closure object, and if so, evaluate to the
8123   // field or what the field refers to.
8124   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
8125       isa<DeclRefExpr>(E) &&
8126       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
8127     // We don't always have a complete capture-map when checking or inferring if
8128     // the function call operator meets the requirements of a constexpr function
8129     // - but we don't need to evaluate the captures to determine constexprness
8130     // (dcl.constexpr C++17).
8131     if (Info.checkingPotentialConstantExpression())
8132       return false;
8133 
8134     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
8135       // Start with 'Result' referring to the complete closure object...
8136       Result = *Info.CurrentCall->This;
8137       // ... then update it to refer to the field of the closure object
8138       // that represents the capture.
8139       if (!HandleLValueMember(Info, E, Result, FD))
8140         return false;
8141       // And if the field is of reference type, update 'Result' to refer to what
8142       // the field refers to.
8143       if (FD->getType()->isReferenceType()) {
8144         APValue RVal;
8145         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
8146                                             RVal))
8147           return false;
8148         Result.setFrom(Info.Ctx, RVal);
8149       }
8150       return true;
8151     }
8152   }
8153 
8154   CallStackFrame *Frame = nullptr;
8155   unsigned Version = 0;
8156   if (VD->hasLocalStorage()) {
8157     // Only if a local variable was declared in the function currently being
8158     // evaluated, do we expect to be able to find its value in the current
8159     // frame. (Otherwise it was likely declared in an enclosing context and
8160     // could either have a valid evaluatable value (for e.g. a constexpr
8161     // variable) or be ill-formed (and trigger an appropriate evaluation
8162     // diagnostic)).
8163     CallStackFrame *CurrFrame = Info.CurrentCall;
8164     if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
8165       // Function parameters are stored in some caller's frame. (Usually the
8166       // immediate caller, but for an inherited constructor they may be more
8167       // distant.)
8168       if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
8169         if (CurrFrame->Arguments) {
8170           VD = CurrFrame->Arguments.getOrigParam(PVD);
8171           Frame =
8172               Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
8173           Version = CurrFrame->Arguments.Version;
8174         }
8175       } else {
8176         Frame = CurrFrame;
8177         Version = CurrFrame->getCurrentTemporaryVersion(VD);
8178       }
8179     }
8180   }
8181 
8182   if (!VD->getType()->isReferenceType()) {
8183     if (Frame) {
8184       Result.set({VD, Frame->Index, Version});
8185       return true;
8186     }
8187     return Success(VD);
8188   }
8189 
8190   if (!Info.getLangOpts().CPlusPlus11) {
8191     Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
8192         << VD << VD->getType();
8193     Info.Note(VD->getLocation(), diag::note_declared_at);
8194   }
8195 
8196   APValue *V;
8197   if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
8198     return false;
8199   if (!V->hasValue()) {
8200     // FIXME: Is it possible for V to be indeterminate here? If so, we should
8201     // adjust the diagnostic to say that.
8202     if (!Info.checkingPotentialConstantExpression())
8203       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
8204     return false;
8205   }
8206   return Success(*V, E);
8207 }
8208 
8209 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
8210     const MaterializeTemporaryExpr *E) {
8211   // Walk through the expression to find the materialized temporary itself.
8212   SmallVector<const Expr *, 2> CommaLHSs;
8213   SmallVector<SubobjectAdjustment, 2> Adjustments;
8214   const Expr *Inner =
8215       E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
8216 
8217   // If we passed any comma operators, evaluate their LHSs.
8218   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
8219     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
8220       return false;
8221 
8222   // A materialized temporary with static storage duration can appear within the
8223   // result of a constant expression evaluation, so we need to preserve its
8224   // value for use outside this evaluation.
8225   APValue *Value;
8226   if (E->getStorageDuration() == SD_Static) {
8227     // FIXME: What about SD_Thread?
8228     Value = E->getOrCreateValue(true);
8229     *Value = APValue();
8230     Result.set(E);
8231   } else {
8232     Value = &Info.CurrentCall->createTemporary(
8233         E, E->getType(),
8234         E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
8235                                                      : ScopeKind::Block,
8236         Result);
8237   }
8238 
8239   QualType Type = Inner->getType();
8240 
8241   // Materialize the temporary itself.
8242   if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
8243     *Value = APValue();
8244     return false;
8245   }
8246 
8247   // Adjust our lvalue to refer to the desired subobject.
8248   for (unsigned I = Adjustments.size(); I != 0; /**/) {
8249     --I;
8250     switch (Adjustments[I].Kind) {
8251     case SubobjectAdjustment::DerivedToBaseAdjustment:
8252       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
8253                                 Type, Result))
8254         return false;
8255       Type = Adjustments[I].DerivedToBase.BasePath->getType();
8256       break;
8257 
8258     case SubobjectAdjustment::FieldAdjustment:
8259       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
8260         return false;
8261       Type = Adjustments[I].Field->getType();
8262       break;
8263 
8264     case SubobjectAdjustment::MemberPointerAdjustment:
8265       if (!HandleMemberPointerAccess(this->Info, Type, Result,
8266                                      Adjustments[I].Ptr.RHS))
8267         return false;
8268       Type = Adjustments[I].Ptr.MPT->getPointeeType();
8269       break;
8270     }
8271   }
8272 
8273   return true;
8274 }
8275 
8276 bool
8277 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8278   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
8279          "lvalue compound literal in c++?");
8280   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
8281   // only see this when folding in C, so there's no standard to follow here.
8282   return Success(E);
8283 }
8284 
8285 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
8286   TypeInfoLValue TypeInfo;
8287 
8288   if (!E->isPotentiallyEvaluated()) {
8289     if (E->isTypeOperand())
8290       TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
8291     else
8292       TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
8293   } else {
8294     if (!Info.Ctx.getLangOpts().CPlusPlus20) {
8295       Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
8296         << E->getExprOperand()->getType()
8297         << E->getExprOperand()->getSourceRange();
8298     }
8299 
8300     if (!Visit(E->getExprOperand()))
8301       return false;
8302 
8303     Optional<DynamicType> DynType =
8304         ComputeDynamicType(Info, E, Result, AK_TypeId);
8305     if (!DynType)
8306       return false;
8307 
8308     TypeInfo =
8309         TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
8310   }
8311 
8312   return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
8313 }
8314 
8315 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
8316   return Success(E->getGuidDecl());
8317 }
8318 
8319 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
8320   // Handle static data members.
8321   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
8322     VisitIgnoredBaseExpression(E->getBase());
8323     return VisitVarDecl(E, VD);
8324   }
8325 
8326   // Handle static member functions.
8327   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
8328     if (MD->isStatic()) {
8329       VisitIgnoredBaseExpression(E->getBase());
8330       return Success(MD);
8331     }
8332   }
8333 
8334   // Handle non-static data members.
8335   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
8336 }
8337 
8338 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
8339   // FIXME: Deal with vectors as array subscript bases.
8340   if (E->getBase()->getType()->isVectorType())
8341     return Error(E);
8342 
8343   APSInt Index;
8344   bool Success = true;
8345 
8346   // C++17's rules require us to evaluate the LHS first, regardless of which
8347   // side is the base.
8348   for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
8349     if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
8350                                 : !EvaluateInteger(SubExpr, Index, Info)) {
8351       if (!Info.noteFailure())
8352         return false;
8353       Success = false;
8354     }
8355   }
8356 
8357   return Success &&
8358          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
8359 }
8360 
8361 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
8362   return evaluatePointer(E->getSubExpr(), Result);
8363 }
8364 
8365 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8366   if (!Visit(E->getSubExpr()))
8367     return false;
8368   // __real is a no-op on scalar lvalues.
8369   if (E->getSubExpr()->getType()->isAnyComplexType())
8370     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
8371   return true;
8372 }
8373 
8374 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8375   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
8376          "lvalue __imag__ on scalar?");
8377   if (!Visit(E->getSubExpr()))
8378     return false;
8379   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
8380   return true;
8381 }
8382 
8383 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
8384   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8385     return Error(UO);
8386 
8387   if (!this->Visit(UO->getSubExpr()))
8388     return false;
8389 
8390   return handleIncDec(
8391       this->Info, UO, Result, UO->getSubExpr()->getType(),
8392       UO->isIncrementOp(), nullptr);
8393 }
8394 
8395 bool LValueExprEvaluator::VisitCompoundAssignOperator(
8396     const CompoundAssignOperator *CAO) {
8397   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8398     return Error(CAO);
8399 
8400   bool Success = true;
8401 
8402   // C++17 onwards require that we evaluate the RHS first.
8403   APValue RHS;
8404   if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
8405     if (!Info.noteFailure())
8406       return false;
8407     Success = false;
8408   }
8409 
8410   // The overall lvalue result is the result of evaluating the LHS.
8411   if (!this->Visit(CAO->getLHS()) || !Success)
8412     return false;
8413 
8414   return handleCompoundAssignment(
8415       this->Info, CAO,
8416       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
8417       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
8418 }
8419 
8420 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
8421   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8422     return Error(E);
8423 
8424   bool Success = true;
8425 
8426   // C++17 onwards require that we evaluate the RHS first.
8427   APValue NewVal;
8428   if (!Evaluate(NewVal, this->Info, E->getRHS())) {
8429     if (!Info.noteFailure())
8430       return false;
8431     Success = false;
8432   }
8433 
8434   if (!this->Visit(E->getLHS()) || !Success)
8435     return false;
8436 
8437   if (Info.getLangOpts().CPlusPlus20 &&
8438       !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
8439     return false;
8440 
8441   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
8442                           NewVal);
8443 }
8444 
8445 //===----------------------------------------------------------------------===//
8446 // Pointer Evaluation
8447 //===----------------------------------------------------------------------===//
8448 
8449 /// Attempts to compute the number of bytes available at the pointer
8450 /// returned by a function with the alloc_size attribute. Returns true if we
8451 /// were successful. Places an unsigned number into `Result`.
8452 ///
8453 /// This expects the given CallExpr to be a call to a function with an
8454 /// alloc_size attribute.
8455 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8456                                             const CallExpr *Call,
8457                                             llvm::APInt &Result) {
8458   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
8459 
8460   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
8461   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
8462   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
8463   if (Call->getNumArgs() <= SizeArgNo)
8464     return false;
8465 
8466   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
8467     Expr::EvalResult ExprResult;
8468     if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
8469       return false;
8470     Into = ExprResult.Val.getInt();
8471     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
8472       return false;
8473     Into = Into.zextOrSelf(BitsInSizeT);
8474     return true;
8475   };
8476 
8477   APSInt SizeOfElem;
8478   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
8479     return false;
8480 
8481   if (!AllocSize->getNumElemsParam().isValid()) {
8482     Result = std::move(SizeOfElem);
8483     return true;
8484   }
8485 
8486   APSInt NumberOfElems;
8487   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
8488   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
8489     return false;
8490 
8491   bool Overflow;
8492   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
8493   if (Overflow)
8494     return false;
8495 
8496   Result = std::move(BytesAvailable);
8497   return true;
8498 }
8499 
8500 /// Convenience function. LVal's base must be a call to an alloc_size
8501 /// function.
8502 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8503                                             const LValue &LVal,
8504                                             llvm::APInt &Result) {
8505   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8506          "Can't get the size of a non alloc_size function");
8507   const auto *Base = LVal.getLValueBase().get<const Expr *>();
8508   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
8509   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
8510 }
8511 
8512 /// Attempts to evaluate the given LValueBase as the result of a call to
8513 /// a function with the alloc_size attribute. If it was possible to do so, this
8514 /// function will return true, make Result's Base point to said function call,
8515 /// and mark Result's Base as invalid.
8516 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
8517                                       LValue &Result) {
8518   if (Base.isNull())
8519     return false;
8520 
8521   // Because we do no form of static analysis, we only support const variables.
8522   //
8523   // Additionally, we can't support parameters, nor can we support static
8524   // variables (in the latter case, use-before-assign isn't UB; in the former,
8525   // we have no clue what they'll be assigned to).
8526   const auto *VD =
8527       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
8528   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
8529     return false;
8530 
8531   const Expr *Init = VD->getAnyInitializer();
8532   if (!Init)
8533     return false;
8534 
8535   const Expr *E = Init->IgnoreParens();
8536   if (!tryUnwrapAllocSizeCall(E))
8537     return false;
8538 
8539   // Store E instead of E unwrapped so that the type of the LValue's base is
8540   // what the user wanted.
8541   Result.setInvalid(E);
8542 
8543   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
8544   Result.addUnsizedArray(Info, E, Pointee);
8545   return true;
8546 }
8547 
8548 namespace {
8549 class PointerExprEvaluator
8550   : public ExprEvaluatorBase<PointerExprEvaluator> {
8551   LValue &Result;
8552   bool InvalidBaseOK;
8553 
8554   bool Success(const Expr *E) {
8555     Result.set(E);
8556     return true;
8557   }
8558 
8559   bool evaluateLValue(const Expr *E, LValue &Result) {
8560     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
8561   }
8562 
8563   bool evaluatePointer(const Expr *E, LValue &Result) {
8564     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
8565   }
8566 
8567   bool visitNonBuiltinCallExpr(const CallExpr *E);
8568 public:
8569 
8570   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
8571       : ExprEvaluatorBaseTy(info), Result(Result),
8572         InvalidBaseOK(InvalidBaseOK) {}
8573 
8574   bool Success(const APValue &V, const Expr *E) {
8575     Result.setFrom(Info.Ctx, V);
8576     return true;
8577   }
8578   bool ZeroInitialization(const Expr *E) {
8579     Result.setNull(Info.Ctx, E->getType());
8580     return true;
8581   }
8582 
8583   bool VisitBinaryOperator(const BinaryOperator *E);
8584   bool VisitCastExpr(const CastExpr* E);
8585   bool VisitUnaryAddrOf(const UnaryOperator *E);
8586   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
8587       { return Success(E); }
8588   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
8589     if (E->isExpressibleAsConstantInitializer())
8590       return Success(E);
8591     if (Info.noteFailure())
8592       EvaluateIgnoredValue(Info, E->getSubExpr());
8593     return Error(E);
8594   }
8595   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
8596       { return Success(E); }
8597   bool VisitCallExpr(const CallExpr *E);
8598   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
8599   bool VisitBlockExpr(const BlockExpr *E) {
8600     if (!E->getBlockDecl()->hasCaptures())
8601       return Success(E);
8602     return Error(E);
8603   }
8604   bool VisitCXXThisExpr(const CXXThisExpr *E) {
8605     // Can't look at 'this' when checking a potential constant expression.
8606     if (Info.checkingPotentialConstantExpression())
8607       return false;
8608     if (!Info.CurrentCall->This) {
8609       if (Info.getLangOpts().CPlusPlus11)
8610         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
8611       else
8612         Info.FFDiag(E);
8613       return false;
8614     }
8615     Result = *Info.CurrentCall->This;
8616     // If we are inside a lambda's call operator, the 'this' expression refers
8617     // to the enclosing '*this' object (either by value or reference) which is
8618     // either copied into the closure object's field that represents the '*this'
8619     // or refers to '*this'.
8620     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
8621       // Ensure we actually have captured 'this'. (an error will have
8622       // been previously reported if not).
8623       if (!Info.CurrentCall->LambdaThisCaptureField)
8624         return false;
8625 
8626       // Update 'Result' to refer to the data member/field of the closure object
8627       // that represents the '*this' capture.
8628       if (!HandleLValueMember(Info, E, Result,
8629                              Info.CurrentCall->LambdaThisCaptureField))
8630         return false;
8631       // If we captured '*this' by reference, replace the field with its referent.
8632       if (Info.CurrentCall->LambdaThisCaptureField->getType()
8633               ->isPointerType()) {
8634         APValue RVal;
8635         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
8636                                             RVal))
8637           return false;
8638 
8639         Result.setFrom(Info.Ctx, RVal);
8640       }
8641     }
8642     return true;
8643   }
8644 
8645   bool VisitCXXNewExpr(const CXXNewExpr *E);
8646 
8647   bool VisitSourceLocExpr(const SourceLocExpr *E) {
8648     assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
8649     APValue LValResult = E->EvaluateInContext(
8650         Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8651     Result.setFrom(Info.Ctx, LValResult);
8652     return true;
8653   }
8654 
8655   // FIXME: Missing: @protocol, @selector
8656 };
8657 } // end anonymous namespace
8658 
8659 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
8660                             bool InvalidBaseOK) {
8661   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
8662   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8663 }
8664 
8665 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8666   if (E->getOpcode() != BO_Add &&
8667       E->getOpcode() != BO_Sub)
8668     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8669 
8670   const Expr *PExp = E->getLHS();
8671   const Expr *IExp = E->getRHS();
8672   if (IExp->getType()->isPointerType())
8673     std::swap(PExp, IExp);
8674 
8675   bool EvalPtrOK = evaluatePointer(PExp, Result);
8676   if (!EvalPtrOK && !Info.noteFailure())
8677     return false;
8678 
8679   llvm::APSInt Offset;
8680   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
8681     return false;
8682 
8683   if (E->getOpcode() == BO_Sub)
8684     negateAsSigned(Offset);
8685 
8686   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
8687   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
8688 }
8689 
8690 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8691   return evaluateLValue(E->getSubExpr(), Result);
8692 }
8693 
8694 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8695   const Expr *SubExpr = E->getSubExpr();
8696 
8697   switch (E->getCastKind()) {
8698   default:
8699     break;
8700   case CK_BitCast:
8701   case CK_CPointerToObjCPointerCast:
8702   case CK_BlockPointerToObjCPointerCast:
8703   case CK_AnyPointerToBlockPointerCast:
8704   case CK_AddressSpaceConversion:
8705     if (!Visit(SubExpr))
8706       return false;
8707     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
8708     // permitted in constant expressions in C++11. Bitcasts from cv void* are
8709     // also static_casts, but we disallow them as a resolution to DR1312.
8710     if (!E->getType()->isVoidPointerType()) {
8711       if (!Result.InvalidBase && !Result.Designator.Invalid &&
8712           !Result.IsNullPtr &&
8713           Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
8714                                           E->getType()->getPointeeType()) &&
8715           Info.getStdAllocatorCaller("allocate")) {
8716         // Inside a call to std::allocator::allocate and friends, we permit
8717         // casting from void* back to cv1 T* for a pointer that points to a
8718         // cv2 T.
8719       } else {
8720         Result.Designator.setInvalid();
8721         if (SubExpr->getType()->isVoidPointerType())
8722           CCEDiag(E, diag::note_constexpr_invalid_cast)
8723             << 3 << SubExpr->getType();
8724         else
8725           CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8726       }
8727     }
8728     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
8729       ZeroInitialization(E);
8730     return true;
8731 
8732   case CK_DerivedToBase:
8733   case CK_UncheckedDerivedToBase:
8734     if (!evaluatePointer(E->getSubExpr(), Result))
8735       return false;
8736     if (!Result.Base && Result.Offset.isZero())
8737       return true;
8738 
8739     // Now figure out the necessary offset to add to the base LV to get from
8740     // the derived class to the base class.
8741     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
8742                                   castAs<PointerType>()->getPointeeType(),
8743                                 Result);
8744 
8745   case CK_BaseToDerived:
8746     if (!Visit(E->getSubExpr()))
8747       return false;
8748     if (!Result.Base && Result.Offset.isZero())
8749       return true;
8750     return HandleBaseToDerivedCast(Info, E, Result);
8751 
8752   case CK_Dynamic:
8753     if (!Visit(E->getSubExpr()))
8754       return false;
8755     return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8756 
8757   case CK_NullToPointer:
8758     VisitIgnoredValue(E->getSubExpr());
8759     return ZeroInitialization(E);
8760 
8761   case CK_IntegralToPointer: {
8762     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8763 
8764     APValue Value;
8765     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
8766       break;
8767 
8768     if (Value.isInt()) {
8769       unsigned Size = Info.Ctx.getTypeSize(E->getType());
8770       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
8771       Result.Base = (Expr*)nullptr;
8772       Result.InvalidBase = false;
8773       Result.Offset = CharUnits::fromQuantity(N);
8774       Result.Designator.setInvalid();
8775       Result.IsNullPtr = false;
8776       return true;
8777     } else {
8778       // Cast is of an lvalue, no need to change value.
8779       Result.setFrom(Info.Ctx, Value);
8780       return true;
8781     }
8782   }
8783 
8784   case CK_ArrayToPointerDecay: {
8785     if (SubExpr->isGLValue()) {
8786       if (!evaluateLValue(SubExpr, Result))
8787         return false;
8788     } else {
8789       APValue &Value = Info.CurrentCall->createTemporary(
8790           SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
8791       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
8792         return false;
8793     }
8794     // The result is a pointer to the first element of the array.
8795     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
8796     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
8797       Result.addArray(Info, E, CAT);
8798     else
8799       Result.addUnsizedArray(Info, E, AT->getElementType());
8800     return true;
8801   }
8802 
8803   case CK_FunctionToPointerDecay:
8804     return evaluateLValue(SubExpr, Result);
8805 
8806   case CK_LValueToRValue: {
8807     LValue LVal;
8808     if (!evaluateLValue(E->getSubExpr(), LVal))
8809       return false;
8810 
8811     APValue RVal;
8812     // Note, we use the subexpression's type in order to retain cv-qualifiers.
8813     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8814                                         LVal, RVal))
8815       return InvalidBaseOK &&
8816              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
8817     return Success(RVal, E);
8818   }
8819   }
8820 
8821   return ExprEvaluatorBaseTy::VisitCastExpr(E);
8822 }
8823 
8824 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
8825                                 UnaryExprOrTypeTrait ExprKind) {
8826   // C++ [expr.alignof]p3:
8827   //     When alignof is applied to a reference type, the result is the
8828   //     alignment of the referenced type.
8829   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
8830     T = Ref->getPointeeType();
8831 
8832   if (T.getQualifiers().hasUnaligned())
8833     return CharUnits::One();
8834 
8835   const bool AlignOfReturnsPreferred =
8836       Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
8837 
8838   // __alignof is defined to return the preferred alignment.
8839   // Before 8, clang returned the preferred alignment for alignof and _Alignof
8840   // as well.
8841   if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
8842     return Info.Ctx.toCharUnitsFromBits(
8843       Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
8844   // alignof and _Alignof are defined to return the ABI alignment.
8845   else if (ExprKind == UETT_AlignOf)
8846     return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
8847   else
8848     llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
8849 }
8850 
8851 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
8852                                 UnaryExprOrTypeTrait ExprKind) {
8853   E = E->IgnoreParens();
8854 
8855   // The kinds of expressions that we have special-case logic here for
8856   // should be kept up to date with the special checks for those
8857   // expressions in Sema.
8858 
8859   // alignof decl is always accepted, even if it doesn't make sense: we default
8860   // to 1 in those cases.
8861   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8862     return Info.Ctx.getDeclAlign(DRE->getDecl(),
8863                                  /*RefAsPointee*/true);
8864 
8865   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
8866     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
8867                                  /*RefAsPointee*/true);
8868 
8869   return GetAlignOfType(Info, E->getType(), ExprKind);
8870 }
8871 
8872 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
8873   if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
8874     return Info.Ctx.getDeclAlign(VD);
8875   if (const auto *E = Value.Base.dyn_cast<const Expr *>())
8876     return GetAlignOfExpr(Info, E, UETT_AlignOf);
8877   return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
8878 }
8879 
8880 /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
8881 /// __builtin_is_aligned and __builtin_assume_aligned.
8882 static bool getAlignmentArgument(const Expr *E, QualType ForType,
8883                                  EvalInfo &Info, APSInt &Alignment) {
8884   if (!EvaluateInteger(E, Alignment, Info))
8885     return false;
8886   if (Alignment < 0 || !Alignment.isPowerOf2()) {
8887     Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
8888     return false;
8889   }
8890   unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
8891   APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
8892   if (APSInt::compareValues(Alignment, MaxValue) > 0) {
8893     Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
8894         << MaxValue << ForType << Alignment;
8895     return false;
8896   }
8897   // Ensure both alignment and source value have the same bit width so that we
8898   // don't assert when computing the resulting value.
8899   APSInt ExtAlignment =
8900       APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
8901   assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
8902          "Alignment should not be changed by ext/trunc");
8903   Alignment = ExtAlignment;
8904   assert(Alignment.getBitWidth() == SrcWidth);
8905   return true;
8906 }
8907 
8908 // To be clear: this happily visits unsupported builtins. Better name welcomed.
8909 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
8910   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
8911     return true;
8912 
8913   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
8914     return false;
8915 
8916   Result.setInvalid(E);
8917   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
8918   Result.addUnsizedArray(Info, E, PointeeTy);
8919   return true;
8920 }
8921 
8922 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
8923   if (IsStringLiteralCall(E))
8924     return Success(E);
8925 
8926   if (unsigned BuiltinOp = E->getBuiltinCallee())
8927     return VisitBuiltinCallExpr(E, BuiltinOp);
8928 
8929   return visitNonBuiltinCallExpr(E);
8930 }
8931 
8932 // Determine if T is a character type for which we guarantee that
8933 // sizeof(T) == 1.
8934 static bool isOneByteCharacterType(QualType T) {
8935   return T->isCharType() || T->isChar8Type();
8936 }
8937 
8938 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8939                                                 unsigned BuiltinOp) {
8940   switch (BuiltinOp) {
8941   case Builtin::BI__builtin_addressof:
8942     return evaluateLValue(E->getArg(0), Result);
8943   case Builtin::BI__builtin_assume_aligned: {
8944     // We need to be very careful here because: if the pointer does not have the
8945     // asserted alignment, then the behavior is undefined, and undefined
8946     // behavior is non-constant.
8947     if (!evaluatePointer(E->getArg(0), Result))
8948       return false;
8949 
8950     LValue OffsetResult(Result);
8951     APSInt Alignment;
8952     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
8953                               Alignment))
8954       return false;
8955     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
8956 
8957     if (E->getNumArgs() > 2) {
8958       APSInt Offset;
8959       if (!EvaluateInteger(E->getArg(2), Offset, Info))
8960         return false;
8961 
8962       int64_t AdditionalOffset = -Offset.getZExtValue();
8963       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
8964     }
8965 
8966     // If there is a base object, then it must have the correct alignment.
8967     if (OffsetResult.Base) {
8968       CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
8969 
8970       if (BaseAlignment < Align) {
8971         Result.Designator.setInvalid();
8972         // FIXME: Add support to Diagnostic for long / long long.
8973         CCEDiag(E->getArg(0),
8974                 diag::note_constexpr_baa_insufficient_alignment) << 0
8975           << (unsigned)BaseAlignment.getQuantity()
8976           << (unsigned)Align.getQuantity();
8977         return false;
8978       }
8979     }
8980 
8981     // The offset must also have the correct alignment.
8982     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
8983       Result.Designator.setInvalid();
8984 
8985       (OffsetResult.Base
8986            ? CCEDiag(E->getArg(0),
8987                      diag::note_constexpr_baa_insufficient_alignment) << 1
8988            : CCEDiag(E->getArg(0),
8989                      diag::note_constexpr_baa_value_insufficient_alignment))
8990         << (int)OffsetResult.Offset.getQuantity()
8991         << (unsigned)Align.getQuantity();
8992       return false;
8993     }
8994 
8995     return true;
8996   }
8997   case Builtin::BI__builtin_align_up:
8998   case Builtin::BI__builtin_align_down: {
8999     if (!evaluatePointer(E->getArg(0), Result))
9000       return false;
9001     APSInt Alignment;
9002     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9003                               Alignment))
9004       return false;
9005     CharUnits BaseAlignment = getBaseAlignment(Info, Result);
9006     CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
9007     // For align_up/align_down, we can return the same value if the alignment
9008     // is known to be greater or equal to the requested value.
9009     if (PtrAlign.getQuantity() >= Alignment)
9010       return true;
9011 
9012     // The alignment could be greater than the minimum at run-time, so we cannot
9013     // infer much about the resulting pointer value. One case is possible:
9014     // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
9015     // can infer the correct index if the requested alignment is smaller than
9016     // the base alignment so we can perform the computation on the offset.
9017     if (BaseAlignment.getQuantity() >= Alignment) {
9018       assert(Alignment.getBitWidth() <= 64 &&
9019              "Cannot handle > 64-bit address-space");
9020       uint64_t Alignment64 = Alignment.getZExtValue();
9021       CharUnits NewOffset = CharUnits::fromQuantity(
9022           BuiltinOp == Builtin::BI__builtin_align_down
9023               ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
9024               : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
9025       Result.adjustOffset(NewOffset - Result.Offset);
9026       // TODO: diagnose out-of-bounds values/only allow for arrays?
9027       return true;
9028     }
9029     // Otherwise, we cannot constant-evaluate the result.
9030     Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
9031         << Alignment;
9032     return false;
9033   }
9034   case Builtin::BI__builtin_operator_new:
9035     return HandleOperatorNewCall(Info, E, Result);
9036   case Builtin::BI__builtin_launder:
9037     return evaluatePointer(E->getArg(0), Result);
9038   case Builtin::BIstrchr:
9039   case Builtin::BIwcschr:
9040   case Builtin::BImemchr:
9041   case Builtin::BIwmemchr:
9042     if (Info.getLangOpts().CPlusPlus11)
9043       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9044         << /*isConstexpr*/0 << /*isConstructor*/0
9045         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9046     else
9047       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9048     LLVM_FALLTHROUGH;
9049   case Builtin::BI__builtin_strchr:
9050   case Builtin::BI__builtin_wcschr:
9051   case Builtin::BI__builtin_memchr:
9052   case Builtin::BI__builtin_char_memchr:
9053   case Builtin::BI__builtin_wmemchr: {
9054     if (!Visit(E->getArg(0)))
9055       return false;
9056     APSInt Desired;
9057     if (!EvaluateInteger(E->getArg(1), Desired, Info))
9058       return false;
9059     uint64_t MaxLength = uint64_t(-1);
9060     if (BuiltinOp != Builtin::BIstrchr &&
9061         BuiltinOp != Builtin::BIwcschr &&
9062         BuiltinOp != Builtin::BI__builtin_strchr &&
9063         BuiltinOp != Builtin::BI__builtin_wcschr) {
9064       APSInt N;
9065       if (!EvaluateInteger(E->getArg(2), N, Info))
9066         return false;
9067       MaxLength = N.getExtValue();
9068     }
9069     // We cannot find the value if there are no candidates to match against.
9070     if (MaxLength == 0u)
9071       return ZeroInitialization(E);
9072     if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9073         Result.Designator.Invalid)
9074       return false;
9075     QualType CharTy = Result.Designator.getType(Info.Ctx);
9076     bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
9077                      BuiltinOp == Builtin::BI__builtin_memchr;
9078     assert(IsRawByte ||
9079            Info.Ctx.hasSameUnqualifiedType(
9080                CharTy, E->getArg(0)->getType()->getPointeeType()));
9081     // Pointers to const void may point to objects of incomplete type.
9082     if (IsRawByte && CharTy->isIncompleteType()) {
9083       Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
9084       return false;
9085     }
9086     // Give up on byte-oriented matching against multibyte elements.
9087     // FIXME: We can compare the bytes in the correct order.
9088     if (IsRawByte && !isOneByteCharacterType(CharTy)) {
9089       Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
9090           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
9091           << CharTy;
9092       return false;
9093     }
9094     // Figure out what value we're actually looking for (after converting to
9095     // the corresponding unsigned type if necessary).
9096     uint64_t DesiredVal;
9097     bool StopAtNull = false;
9098     switch (BuiltinOp) {
9099     case Builtin::BIstrchr:
9100     case Builtin::BI__builtin_strchr:
9101       // strchr compares directly to the passed integer, and therefore
9102       // always fails if given an int that is not a char.
9103       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
9104                                                   E->getArg(1)->getType(),
9105                                                   Desired),
9106                                Desired))
9107         return ZeroInitialization(E);
9108       StopAtNull = true;
9109       LLVM_FALLTHROUGH;
9110     case Builtin::BImemchr:
9111     case Builtin::BI__builtin_memchr:
9112     case Builtin::BI__builtin_char_memchr:
9113       // memchr compares by converting both sides to unsigned char. That's also
9114       // correct for strchr if we get this far (to cope with plain char being
9115       // unsigned in the strchr case).
9116       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
9117       break;
9118 
9119     case Builtin::BIwcschr:
9120     case Builtin::BI__builtin_wcschr:
9121       StopAtNull = true;
9122       LLVM_FALLTHROUGH;
9123     case Builtin::BIwmemchr:
9124     case Builtin::BI__builtin_wmemchr:
9125       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
9126       DesiredVal = Desired.getZExtValue();
9127       break;
9128     }
9129 
9130     for (; MaxLength; --MaxLength) {
9131       APValue Char;
9132       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
9133           !Char.isInt())
9134         return false;
9135       if (Char.getInt().getZExtValue() == DesiredVal)
9136         return true;
9137       if (StopAtNull && !Char.getInt())
9138         break;
9139       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
9140         return false;
9141     }
9142     // Not found: return nullptr.
9143     return ZeroInitialization(E);
9144   }
9145 
9146   case Builtin::BImemcpy:
9147   case Builtin::BImemmove:
9148   case Builtin::BIwmemcpy:
9149   case Builtin::BIwmemmove:
9150     if (Info.getLangOpts().CPlusPlus11)
9151       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9152         << /*isConstexpr*/0 << /*isConstructor*/0
9153         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9154     else
9155       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9156     LLVM_FALLTHROUGH;
9157   case Builtin::BI__builtin_memcpy:
9158   case Builtin::BI__builtin_memmove:
9159   case Builtin::BI__builtin_wmemcpy:
9160   case Builtin::BI__builtin_wmemmove: {
9161     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
9162                  BuiltinOp == Builtin::BIwmemmove ||
9163                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
9164                  BuiltinOp == Builtin::BI__builtin_wmemmove;
9165     bool Move = BuiltinOp == Builtin::BImemmove ||
9166                 BuiltinOp == Builtin::BIwmemmove ||
9167                 BuiltinOp == Builtin::BI__builtin_memmove ||
9168                 BuiltinOp == Builtin::BI__builtin_wmemmove;
9169 
9170     // The result of mem* is the first argument.
9171     if (!Visit(E->getArg(0)))
9172       return false;
9173     LValue Dest = Result;
9174 
9175     LValue Src;
9176     if (!EvaluatePointer(E->getArg(1), Src, Info))
9177       return false;
9178 
9179     APSInt N;
9180     if (!EvaluateInteger(E->getArg(2), N, Info))
9181       return false;
9182     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
9183 
9184     // If the size is zero, we treat this as always being a valid no-op.
9185     // (Even if one of the src and dest pointers is null.)
9186     if (!N)
9187       return true;
9188 
9189     // Otherwise, if either of the operands is null, we can't proceed. Don't
9190     // try to determine the type of the copied objects, because there aren't
9191     // any.
9192     if (!Src.Base || !Dest.Base) {
9193       APValue Val;
9194       (!Src.Base ? Src : Dest).moveInto(Val);
9195       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
9196           << Move << WChar << !!Src.Base
9197           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
9198       return false;
9199     }
9200     if (Src.Designator.Invalid || Dest.Designator.Invalid)
9201       return false;
9202 
9203     // We require that Src and Dest are both pointers to arrays of
9204     // trivially-copyable type. (For the wide version, the designator will be
9205     // invalid if the designated object is not a wchar_t.)
9206     QualType T = Dest.Designator.getType(Info.Ctx);
9207     QualType SrcT = Src.Designator.getType(Info.Ctx);
9208     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
9209       // FIXME: Consider using our bit_cast implementation to support this.
9210       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
9211       return false;
9212     }
9213     if (T->isIncompleteType()) {
9214       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
9215       return false;
9216     }
9217     if (!T.isTriviallyCopyableType(Info.Ctx)) {
9218       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
9219       return false;
9220     }
9221 
9222     // Figure out how many T's we're copying.
9223     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
9224     if (!WChar) {
9225       uint64_t Remainder;
9226       llvm::APInt OrigN = N;
9227       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
9228       if (Remainder) {
9229         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9230             << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
9231             << (unsigned)TSize;
9232         return false;
9233       }
9234     }
9235 
9236     // Check that the copying will remain within the arrays, just so that we
9237     // can give a more meaningful diagnostic. This implicitly also checks that
9238     // N fits into 64 bits.
9239     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
9240     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
9241     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
9242       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9243           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
9244           << N.toString(10, /*Signed*/false);
9245       return false;
9246     }
9247     uint64_t NElems = N.getZExtValue();
9248     uint64_t NBytes = NElems * TSize;
9249 
9250     // Check for overlap.
9251     int Direction = 1;
9252     if (HasSameBase(Src, Dest)) {
9253       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
9254       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
9255       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
9256         // Dest is inside the source region.
9257         if (!Move) {
9258           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9259           return false;
9260         }
9261         // For memmove and friends, copy backwards.
9262         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
9263             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
9264           return false;
9265         Direction = -1;
9266       } else if (!Move && SrcOffset >= DestOffset &&
9267                  SrcOffset - DestOffset < NBytes) {
9268         // Src is inside the destination region for memcpy: invalid.
9269         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9270         return false;
9271       }
9272     }
9273 
9274     while (true) {
9275       APValue Val;
9276       // FIXME: Set WantObjectRepresentation to true if we're copying a
9277       // char-like type?
9278       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
9279           !handleAssignment(Info, E, Dest, T, Val))
9280         return false;
9281       // Do not iterate past the last element; if we're copying backwards, that
9282       // might take us off the start of the array.
9283       if (--NElems == 0)
9284         return true;
9285       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
9286           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
9287         return false;
9288     }
9289   }
9290 
9291   default:
9292     break;
9293   }
9294 
9295   return visitNonBuiltinCallExpr(E);
9296 }
9297 
9298 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9299                                      APValue &Result, const InitListExpr *ILE,
9300                                      QualType AllocType);
9301 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
9302                                           APValue &Result,
9303                                           const CXXConstructExpr *CCE,
9304                                           QualType AllocType);
9305 
9306 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
9307   if (!Info.getLangOpts().CPlusPlus20)
9308     Info.CCEDiag(E, diag::note_constexpr_new);
9309 
9310   // We cannot speculatively evaluate a delete expression.
9311   if (Info.SpeculativeEvaluationDepth)
9312     return false;
9313 
9314   FunctionDecl *OperatorNew = E->getOperatorNew();
9315 
9316   bool IsNothrow = false;
9317   bool IsPlacement = false;
9318   if (OperatorNew->isReservedGlobalPlacementOperator() &&
9319       Info.CurrentCall->isStdFunction() && !E->isArray()) {
9320     // FIXME Support array placement new.
9321     assert(E->getNumPlacementArgs() == 1);
9322     if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
9323       return false;
9324     if (Result.Designator.Invalid)
9325       return false;
9326     IsPlacement = true;
9327   } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
9328     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
9329         << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
9330     return false;
9331   } else if (E->getNumPlacementArgs()) {
9332     // The only new-placement list we support is of the form (std::nothrow).
9333     //
9334     // FIXME: There is no restriction on this, but it's not clear that any
9335     // other form makes any sense. We get here for cases such as:
9336     //
9337     //   new (std::align_val_t{N}) X(int)
9338     //
9339     // (which should presumably be valid only if N is a multiple of
9340     // alignof(int), and in any case can't be deallocated unless N is
9341     // alignof(X) and X has new-extended alignment).
9342     if (E->getNumPlacementArgs() != 1 ||
9343         !E->getPlacementArg(0)->getType()->isNothrowT())
9344       return Error(E, diag::note_constexpr_new_placement);
9345 
9346     LValue Nothrow;
9347     if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
9348       return false;
9349     IsNothrow = true;
9350   }
9351 
9352   const Expr *Init = E->getInitializer();
9353   const InitListExpr *ResizedArrayILE = nullptr;
9354   const CXXConstructExpr *ResizedArrayCCE = nullptr;
9355   bool ValueInit = false;
9356 
9357   QualType AllocType = E->getAllocatedType();
9358   if (Optional<const Expr*> ArraySize = E->getArraySize()) {
9359     const Expr *Stripped = *ArraySize;
9360     for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
9361          Stripped = ICE->getSubExpr())
9362       if (ICE->getCastKind() != CK_NoOp &&
9363           ICE->getCastKind() != CK_IntegralCast)
9364         break;
9365 
9366     llvm::APSInt ArrayBound;
9367     if (!EvaluateInteger(Stripped, ArrayBound, Info))
9368       return false;
9369 
9370     // C++ [expr.new]p9:
9371     //   The expression is erroneous if:
9372     //   -- [...] its value before converting to size_t [or] applying the
9373     //      second standard conversion sequence is less than zero
9374     if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
9375       if (IsNothrow)
9376         return ZeroInitialization(E);
9377 
9378       Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
9379           << ArrayBound << (*ArraySize)->getSourceRange();
9380       return false;
9381     }
9382 
9383     //   -- its value is such that the size of the allocated object would
9384     //      exceed the implementation-defined limit
9385     if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
9386                                                 ArrayBound) >
9387         ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
9388       if (IsNothrow)
9389         return ZeroInitialization(E);
9390 
9391       Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
9392         << ArrayBound << (*ArraySize)->getSourceRange();
9393       return false;
9394     }
9395 
9396     //   -- the new-initializer is a braced-init-list and the number of
9397     //      array elements for which initializers are provided [...]
9398     //      exceeds the number of elements to initialize
9399     if (!Init) {
9400       // No initialization is performed.
9401     } else if (isa<CXXScalarValueInitExpr>(Init) ||
9402                isa<ImplicitValueInitExpr>(Init)) {
9403       ValueInit = true;
9404     } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
9405       ResizedArrayCCE = CCE;
9406     } else {
9407       auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
9408       assert(CAT && "unexpected type for array initializer");
9409 
9410       unsigned Bits =
9411           std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
9412       llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits);
9413       llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits);
9414       if (InitBound.ugt(AllocBound)) {
9415         if (IsNothrow)
9416           return ZeroInitialization(E);
9417 
9418         Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
9419             << AllocBound.toString(10, /*Signed=*/false)
9420             << InitBound.toString(10, /*Signed=*/false)
9421             << (*ArraySize)->getSourceRange();
9422         return false;
9423       }
9424 
9425       // If the sizes differ, we must have an initializer list, and we need
9426       // special handling for this case when we initialize.
9427       if (InitBound != AllocBound)
9428         ResizedArrayILE = cast<InitListExpr>(Init);
9429     }
9430 
9431     AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
9432                                               ArrayType::Normal, 0);
9433   } else {
9434     assert(!AllocType->isArrayType() &&
9435            "array allocation with non-array new");
9436   }
9437 
9438   APValue *Val;
9439   if (IsPlacement) {
9440     AccessKinds AK = AK_Construct;
9441     struct FindObjectHandler {
9442       EvalInfo &Info;
9443       const Expr *E;
9444       QualType AllocType;
9445       const AccessKinds AccessKind;
9446       APValue *Value;
9447 
9448       typedef bool result_type;
9449       bool failed() { return false; }
9450       bool found(APValue &Subobj, QualType SubobjType) {
9451         // FIXME: Reject the cases where [basic.life]p8 would not permit the
9452         // old name of the object to be used to name the new object.
9453         if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
9454           Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
9455             SubobjType << AllocType;
9456           return false;
9457         }
9458         Value = &Subobj;
9459         return true;
9460       }
9461       bool found(APSInt &Value, QualType SubobjType) {
9462         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9463         return false;
9464       }
9465       bool found(APFloat &Value, QualType SubobjType) {
9466         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9467         return false;
9468       }
9469     } Handler = {Info, E, AllocType, AK, nullptr};
9470 
9471     CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
9472     if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
9473       return false;
9474 
9475     Val = Handler.Value;
9476 
9477     // [basic.life]p1:
9478     //   The lifetime of an object o of type T ends when [...] the storage
9479     //   which the object occupies is [...] reused by an object that is not
9480     //   nested within o (6.6.2).
9481     *Val = APValue();
9482   } else {
9483     // Perform the allocation and obtain a pointer to the resulting object.
9484     Val = Info.createHeapAlloc(E, AllocType, Result);
9485     if (!Val)
9486       return false;
9487   }
9488 
9489   if (ValueInit) {
9490     ImplicitValueInitExpr VIE(AllocType);
9491     if (!EvaluateInPlace(*Val, Info, Result, &VIE))
9492       return false;
9493   } else if (ResizedArrayILE) {
9494     if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
9495                                   AllocType))
9496       return false;
9497   } else if (ResizedArrayCCE) {
9498     if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
9499                                        AllocType))
9500       return false;
9501   } else if (Init) {
9502     if (!EvaluateInPlace(*Val, Info, Result, Init))
9503       return false;
9504   } else if (!getDefaultInitValue(AllocType, *Val)) {
9505     return false;
9506   }
9507 
9508   // Array new returns a pointer to the first element, not a pointer to the
9509   // array.
9510   if (auto *AT = AllocType->getAsArrayTypeUnsafe())
9511     Result.addArray(Info, E, cast<ConstantArrayType>(AT));
9512 
9513   return true;
9514 }
9515 //===----------------------------------------------------------------------===//
9516 // Member Pointer Evaluation
9517 //===----------------------------------------------------------------------===//
9518 
9519 namespace {
9520 class MemberPointerExprEvaluator
9521   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
9522   MemberPtr &Result;
9523 
9524   bool Success(const ValueDecl *D) {
9525     Result = MemberPtr(D);
9526     return true;
9527   }
9528 public:
9529 
9530   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
9531     : ExprEvaluatorBaseTy(Info), Result(Result) {}
9532 
9533   bool Success(const APValue &V, const Expr *E) {
9534     Result.setFrom(V);
9535     return true;
9536   }
9537   bool ZeroInitialization(const Expr *E) {
9538     return Success((const ValueDecl*)nullptr);
9539   }
9540 
9541   bool VisitCastExpr(const CastExpr *E);
9542   bool VisitUnaryAddrOf(const UnaryOperator *E);
9543 };
9544 } // end anonymous namespace
9545 
9546 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
9547                                   EvalInfo &Info) {
9548   assert(E->isRValue() && E->getType()->isMemberPointerType());
9549   return MemberPointerExprEvaluator(Info, Result).Visit(E);
9550 }
9551 
9552 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9553   switch (E->getCastKind()) {
9554   default:
9555     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9556 
9557   case CK_NullToMemberPointer:
9558     VisitIgnoredValue(E->getSubExpr());
9559     return ZeroInitialization(E);
9560 
9561   case CK_BaseToDerivedMemberPointer: {
9562     if (!Visit(E->getSubExpr()))
9563       return false;
9564     if (E->path_empty())
9565       return true;
9566     // Base-to-derived member pointer casts store the path in derived-to-base
9567     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
9568     // the wrong end of the derived->base arc, so stagger the path by one class.
9569     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
9570     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
9571          PathI != PathE; ++PathI) {
9572       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9573       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
9574       if (!Result.castToDerived(Derived))
9575         return Error(E);
9576     }
9577     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
9578     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
9579       return Error(E);
9580     return true;
9581   }
9582 
9583   case CK_DerivedToBaseMemberPointer:
9584     if (!Visit(E->getSubExpr()))
9585       return false;
9586     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9587          PathE = E->path_end(); PathI != PathE; ++PathI) {
9588       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9589       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9590       if (!Result.castToBase(Base))
9591         return Error(E);
9592     }
9593     return true;
9594   }
9595 }
9596 
9597 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9598   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
9599   // member can be formed.
9600   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
9601 }
9602 
9603 //===----------------------------------------------------------------------===//
9604 // Record Evaluation
9605 //===----------------------------------------------------------------------===//
9606 
9607 namespace {
9608   class RecordExprEvaluator
9609   : public ExprEvaluatorBase<RecordExprEvaluator> {
9610     const LValue &This;
9611     APValue &Result;
9612   public:
9613 
9614     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
9615       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
9616 
9617     bool Success(const APValue &V, const Expr *E) {
9618       Result = V;
9619       return true;
9620     }
9621     bool ZeroInitialization(const Expr *E) {
9622       return ZeroInitialization(E, E->getType());
9623     }
9624     bool ZeroInitialization(const Expr *E, QualType T);
9625 
9626     bool VisitCallExpr(const CallExpr *E) {
9627       return handleCallExpr(E, Result, &This);
9628     }
9629     bool VisitCastExpr(const CastExpr *E);
9630     bool VisitInitListExpr(const InitListExpr *E);
9631     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9632       return VisitCXXConstructExpr(E, E->getType());
9633     }
9634     bool VisitLambdaExpr(const LambdaExpr *E);
9635     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
9636     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
9637     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
9638     bool VisitBinCmp(const BinaryOperator *E);
9639   };
9640 }
9641 
9642 /// Perform zero-initialization on an object of non-union class type.
9643 /// C++11 [dcl.init]p5:
9644 ///  To zero-initialize an object or reference of type T means:
9645 ///    [...]
9646 ///    -- if T is a (possibly cv-qualified) non-union class type,
9647 ///       each non-static data member and each base-class subobject is
9648 ///       zero-initialized
9649 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
9650                                           const RecordDecl *RD,
9651                                           const LValue &This, APValue &Result) {
9652   assert(!RD->isUnion() && "Expected non-union class type");
9653   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
9654   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
9655                    std::distance(RD->field_begin(), RD->field_end()));
9656 
9657   if (RD->isInvalidDecl()) return false;
9658   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9659 
9660   if (CD) {
9661     unsigned Index = 0;
9662     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
9663            End = CD->bases_end(); I != End; ++I, ++Index) {
9664       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
9665       LValue Subobject = This;
9666       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
9667         return false;
9668       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
9669                                          Result.getStructBase(Index)))
9670         return false;
9671     }
9672   }
9673 
9674   for (const auto *I : RD->fields()) {
9675     // -- if T is a reference type, no initialization is performed.
9676     if (I->isUnnamedBitfield() || I->getType()->isReferenceType())
9677       continue;
9678 
9679     LValue Subobject = This;
9680     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
9681       return false;
9682 
9683     ImplicitValueInitExpr VIE(I->getType());
9684     if (!EvaluateInPlace(
9685           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
9686       return false;
9687   }
9688 
9689   return true;
9690 }
9691 
9692 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
9693   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
9694   if (RD->isInvalidDecl()) return false;
9695   if (RD->isUnion()) {
9696     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
9697     // object's first non-static named data member is zero-initialized
9698     RecordDecl::field_iterator I = RD->field_begin();
9699     while (I != RD->field_end() && (*I)->isUnnamedBitfield())
9700       ++I;
9701     if (I == RD->field_end()) {
9702       Result = APValue((const FieldDecl*)nullptr);
9703       return true;
9704     }
9705 
9706     LValue Subobject = This;
9707     if (!HandleLValueMember(Info, E, Subobject, *I))
9708       return false;
9709     Result = APValue(*I);
9710     ImplicitValueInitExpr VIE(I->getType());
9711     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
9712   }
9713 
9714   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
9715     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
9716     return false;
9717   }
9718 
9719   return HandleClassZeroInitialization(Info, E, RD, This, Result);
9720 }
9721 
9722 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
9723   switch (E->getCastKind()) {
9724   default:
9725     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9726 
9727   case CK_ConstructorConversion:
9728     return Visit(E->getSubExpr());
9729 
9730   case CK_DerivedToBase:
9731   case CK_UncheckedDerivedToBase: {
9732     APValue DerivedObject;
9733     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
9734       return false;
9735     if (!DerivedObject.isStruct())
9736       return Error(E->getSubExpr());
9737 
9738     // Derived-to-base rvalue conversion: just slice off the derived part.
9739     APValue *Value = &DerivedObject;
9740     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
9741     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9742          PathE = E->path_end(); PathI != PathE; ++PathI) {
9743       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
9744       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9745       Value = &Value->getStructBase(getBaseIndex(RD, Base));
9746       RD = Base;
9747     }
9748     Result = *Value;
9749     return true;
9750   }
9751   }
9752 }
9753 
9754 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9755   if (E->isTransparent())
9756     return Visit(E->getInit(0));
9757 
9758   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
9759   if (RD->isInvalidDecl()) return false;
9760   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9761   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
9762 
9763   EvalInfo::EvaluatingConstructorRAII EvalObj(
9764       Info,
9765       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
9766       CXXRD && CXXRD->getNumBases());
9767 
9768   if (RD->isUnion()) {
9769     const FieldDecl *Field = E->getInitializedFieldInUnion();
9770     Result = APValue(Field);
9771     if (!Field)
9772       return true;
9773 
9774     // If the initializer list for a union does not contain any elements, the
9775     // first element of the union is value-initialized.
9776     // FIXME: The element should be initialized from an initializer list.
9777     //        Is this difference ever observable for initializer lists which
9778     //        we don't build?
9779     ImplicitValueInitExpr VIE(Field->getType());
9780     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
9781 
9782     LValue Subobject = This;
9783     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
9784       return false;
9785 
9786     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9787     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9788                                   isa<CXXDefaultInitExpr>(InitExpr));
9789 
9790     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
9791   }
9792 
9793   if (!Result.hasValue())
9794     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
9795                      std::distance(RD->field_begin(), RD->field_end()));
9796   unsigned ElementNo = 0;
9797   bool Success = true;
9798 
9799   // Initialize base classes.
9800   if (CXXRD && CXXRD->getNumBases()) {
9801     for (const auto &Base : CXXRD->bases()) {
9802       assert(ElementNo < E->getNumInits() && "missing init for base class");
9803       const Expr *Init = E->getInit(ElementNo);
9804 
9805       LValue Subobject = This;
9806       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
9807         return false;
9808 
9809       APValue &FieldVal = Result.getStructBase(ElementNo);
9810       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
9811         if (!Info.noteFailure())
9812           return false;
9813         Success = false;
9814       }
9815       ++ElementNo;
9816     }
9817 
9818     EvalObj.finishedConstructingBases();
9819   }
9820 
9821   // Initialize members.
9822   for (const auto *Field : RD->fields()) {
9823     // Anonymous bit-fields are not considered members of the class for
9824     // purposes of aggregate initialization.
9825     if (Field->isUnnamedBitfield())
9826       continue;
9827 
9828     LValue Subobject = This;
9829 
9830     bool HaveInit = ElementNo < E->getNumInits();
9831 
9832     // FIXME: Diagnostics here should point to the end of the initializer
9833     // list, not the start.
9834     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
9835                             Subobject, Field, &Layout))
9836       return false;
9837 
9838     // Perform an implicit value-initialization for members beyond the end of
9839     // the initializer list.
9840     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
9841     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
9842 
9843     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9844     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9845                                   isa<CXXDefaultInitExpr>(Init));
9846 
9847     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9848     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
9849         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
9850                                                        FieldVal, Field))) {
9851       if (!Info.noteFailure())
9852         return false;
9853       Success = false;
9854     }
9855   }
9856 
9857   EvalObj.finishedConstructingFields();
9858 
9859   return Success;
9860 }
9861 
9862 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
9863                                                 QualType T) {
9864   // Note that E's type is not necessarily the type of our class here; we might
9865   // be initializing an array element instead.
9866   const CXXConstructorDecl *FD = E->getConstructor();
9867   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
9868 
9869   bool ZeroInit = E->requiresZeroInitialization();
9870   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
9871     // If we've already performed zero-initialization, we're already done.
9872     if (Result.hasValue())
9873       return true;
9874 
9875     if (ZeroInit)
9876       return ZeroInitialization(E, T);
9877 
9878     return getDefaultInitValue(T, Result);
9879   }
9880 
9881   const FunctionDecl *Definition = nullptr;
9882   auto Body = FD->getBody(Definition);
9883 
9884   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9885     return false;
9886 
9887   // Avoid materializing a temporary for an elidable copy/move constructor.
9888   if (E->isElidable() && !ZeroInit)
9889     if (const MaterializeTemporaryExpr *ME
9890           = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
9891       return Visit(ME->getSubExpr());
9892 
9893   if (ZeroInit && !ZeroInitialization(E, T))
9894     return false;
9895 
9896   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
9897   return HandleConstructorCall(E, This, Args,
9898                                cast<CXXConstructorDecl>(Definition), Info,
9899                                Result);
9900 }
9901 
9902 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
9903     const CXXInheritedCtorInitExpr *E) {
9904   if (!Info.CurrentCall) {
9905     assert(Info.checkingPotentialConstantExpression());
9906     return false;
9907   }
9908 
9909   const CXXConstructorDecl *FD = E->getConstructor();
9910   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
9911     return false;
9912 
9913   const FunctionDecl *Definition = nullptr;
9914   auto Body = FD->getBody(Definition);
9915 
9916   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9917     return false;
9918 
9919   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
9920                                cast<CXXConstructorDecl>(Definition), Info,
9921                                Result);
9922 }
9923 
9924 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
9925     const CXXStdInitializerListExpr *E) {
9926   const ConstantArrayType *ArrayType =
9927       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
9928 
9929   LValue Array;
9930   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
9931     return false;
9932 
9933   // Get a pointer to the first element of the array.
9934   Array.addArray(Info, E, ArrayType);
9935 
9936   auto InvalidType = [&] {
9937     Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
9938       << E->getType();
9939     return false;
9940   };
9941 
9942   // FIXME: Perform the checks on the field types in SemaInit.
9943   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
9944   RecordDecl::field_iterator Field = Record->field_begin();
9945   if (Field == Record->field_end())
9946     return InvalidType();
9947 
9948   // Start pointer.
9949   if (!Field->getType()->isPointerType() ||
9950       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
9951                             ArrayType->getElementType()))
9952     return InvalidType();
9953 
9954   // FIXME: What if the initializer_list type has base classes, etc?
9955   Result = APValue(APValue::UninitStruct(), 0, 2);
9956   Array.moveInto(Result.getStructField(0));
9957 
9958   if (++Field == Record->field_end())
9959     return InvalidType();
9960 
9961   if (Field->getType()->isPointerType() &&
9962       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
9963                            ArrayType->getElementType())) {
9964     // End pointer.
9965     if (!HandleLValueArrayAdjustment(Info, E, Array,
9966                                      ArrayType->getElementType(),
9967                                      ArrayType->getSize().getZExtValue()))
9968       return false;
9969     Array.moveInto(Result.getStructField(1));
9970   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
9971     // Length.
9972     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
9973   else
9974     return InvalidType();
9975 
9976   if (++Field != Record->field_end())
9977     return InvalidType();
9978 
9979   return true;
9980 }
9981 
9982 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
9983   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
9984   if (ClosureClass->isInvalidDecl())
9985     return false;
9986 
9987   const size_t NumFields =
9988       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
9989 
9990   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
9991                                             E->capture_init_end()) &&
9992          "The number of lambda capture initializers should equal the number of "
9993          "fields within the closure type");
9994 
9995   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
9996   // Iterate through all the lambda's closure object's fields and initialize
9997   // them.
9998   auto *CaptureInitIt = E->capture_init_begin();
9999   const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
10000   bool Success = true;
10001   for (const auto *Field : ClosureClass->fields()) {
10002     assert(CaptureInitIt != E->capture_init_end());
10003     // Get the initializer for this field
10004     Expr *const CurFieldInit = *CaptureInitIt++;
10005 
10006     // If there is no initializer, either this is a VLA or an error has
10007     // occurred.
10008     if (!CurFieldInit)
10009       return Error(E);
10010 
10011     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10012     if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
10013       if (!Info.keepEvaluatingAfterFailure())
10014         return false;
10015       Success = false;
10016     }
10017     ++CaptureIt;
10018   }
10019   return Success;
10020 }
10021 
10022 static bool EvaluateRecord(const Expr *E, const LValue &This,
10023                            APValue &Result, EvalInfo &Info) {
10024   assert(E->isRValue() && E->getType()->isRecordType() &&
10025          "can't evaluate expression as a record rvalue");
10026   return RecordExprEvaluator(Info, This, Result).Visit(E);
10027 }
10028 
10029 //===----------------------------------------------------------------------===//
10030 // Temporary Evaluation
10031 //
10032 // Temporaries are represented in the AST as rvalues, but generally behave like
10033 // lvalues. The full-object of which the temporary is a subobject is implicitly
10034 // materialized so that a reference can bind to it.
10035 //===----------------------------------------------------------------------===//
10036 namespace {
10037 class TemporaryExprEvaluator
10038   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
10039 public:
10040   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
10041     LValueExprEvaluatorBaseTy(Info, Result, false) {}
10042 
10043   /// Visit an expression which constructs the value of this temporary.
10044   bool VisitConstructExpr(const Expr *E) {
10045     APValue &Value = Info.CurrentCall->createTemporary(
10046         E, E->getType(), ScopeKind::FullExpression, Result);
10047     return EvaluateInPlace(Value, Info, Result, E);
10048   }
10049 
10050   bool VisitCastExpr(const CastExpr *E) {
10051     switch (E->getCastKind()) {
10052     default:
10053       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
10054 
10055     case CK_ConstructorConversion:
10056       return VisitConstructExpr(E->getSubExpr());
10057     }
10058   }
10059   bool VisitInitListExpr(const InitListExpr *E) {
10060     return VisitConstructExpr(E);
10061   }
10062   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10063     return VisitConstructExpr(E);
10064   }
10065   bool VisitCallExpr(const CallExpr *E) {
10066     return VisitConstructExpr(E);
10067   }
10068   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
10069     return VisitConstructExpr(E);
10070   }
10071   bool VisitLambdaExpr(const LambdaExpr *E) {
10072     return VisitConstructExpr(E);
10073   }
10074 };
10075 } // end anonymous namespace
10076 
10077 /// Evaluate an expression of record type as a temporary.
10078 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
10079   assert(E->isRValue() && E->getType()->isRecordType());
10080   return TemporaryExprEvaluator(Info, Result).Visit(E);
10081 }
10082 
10083 //===----------------------------------------------------------------------===//
10084 // Vector Evaluation
10085 //===----------------------------------------------------------------------===//
10086 
10087 namespace {
10088   class VectorExprEvaluator
10089   : public ExprEvaluatorBase<VectorExprEvaluator> {
10090     APValue &Result;
10091   public:
10092 
10093     VectorExprEvaluator(EvalInfo &info, APValue &Result)
10094       : ExprEvaluatorBaseTy(info), Result(Result) {}
10095 
10096     bool Success(ArrayRef<APValue> V, const Expr *E) {
10097       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
10098       // FIXME: remove this APValue copy.
10099       Result = APValue(V.data(), V.size());
10100       return true;
10101     }
10102     bool Success(const APValue &V, const Expr *E) {
10103       assert(V.isVector());
10104       Result = V;
10105       return true;
10106     }
10107     bool ZeroInitialization(const Expr *E);
10108 
10109     bool VisitUnaryReal(const UnaryOperator *E)
10110       { return Visit(E->getSubExpr()); }
10111     bool VisitCastExpr(const CastExpr* E);
10112     bool VisitInitListExpr(const InitListExpr *E);
10113     bool VisitUnaryImag(const UnaryOperator *E);
10114     bool VisitBinaryOperator(const BinaryOperator *E);
10115     // FIXME: Missing: unary -, unary ~, conditional operator (for GNU
10116     //                 conditional select), shufflevector, ExtVectorElementExpr
10117   };
10118 } // end anonymous namespace
10119 
10120 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
10121   assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
10122   return VectorExprEvaluator(Info, Result).Visit(E);
10123 }
10124 
10125 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
10126   const VectorType *VTy = E->getType()->castAs<VectorType>();
10127   unsigned NElts = VTy->getNumElements();
10128 
10129   const Expr *SE = E->getSubExpr();
10130   QualType SETy = SE->getType();
10131 
10132   switch (E->getCastKind()) {
10133   case CK_VectorSplat: {
10134     APValue Val = APValue();
10135     if (SETy->isIntegerType()) {
10136       APSInt IntResult;
10137       if (!EvaluateInteger(SE, IntResult, Info))
10138         return false;
10139       Val = APValue(std::move(IntResult));
10140     } else if (SETy->isRealFloatingType()) {
10141       APFloat FloatResult(0.0);
10142       if (!EvaluateFloat(SE, FloatResult, Info))
10143         return false;
10144       Val = APValue(std::move(FloatResult));
10145     } else {
10146       return Error(E);
10147     }
10148 
10149     // Splat and create vector APValue.
10150     SmallVector<APValue, 4> Elts(NElts, Val);
10151     return Success(Elts, E);
10152   }
10153   case CK_BitCast: {
10154     // Evaluate the operand into an APInt we can extract from.
10155     llvm::APInt SValInt;
10156     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
10157       return false;
10158     // Extract the elements
10159     QualType EltTy = VTy->getElementType();
10160     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
10161     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
10162     SmallVector<APValue, 4> Elts;
10163     if (EltTy->isRealFloatingType()) {
10164       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
10165       unsigned FloatEltSize = EltSize;
10166       if (&Sem == &APFloat::x87DoubleExtended())
10167         FloatEltSize = 80;
10168       for (unsigned i = 0; i < NElts; i++) {
10169         llvm::APInt Elt;
10170         if (BigEndian)
10171           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
10172         else
10173           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
10174         Elts.push_back(APValue(APFloat(Sem, Elt)));
10175       }
10176     } else if (EltTy->isIntegerType()) {
10177       for (unsigned i = 0; i < NElts; i++) {
10178         llvm::APInt Elt;
10179         if (BigEndian)
10180           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
10181         else
10182           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
10183         Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
10184       }
10185     } else {
10186       return Error(E);
10187     }
10188     return Success(Elts, E);
10189   }
10190   default:
10191     return ExprEvaluatorBaseTy::VisitCastExpr(E);
10192   }
10193 }
10194 
10195 bool
10196 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10197   const VectorType *VT = E->getType()->castAs<VectorType>();
10198   unsigned NumInits = E->getNumInits();
10199   unsigned NumElements = VT->getNumElements();
10200 
10201   QualType EltTy = VT->getElementType();
10202   SmallVector<APValue, 4> Elements;
10203 
10204   // The number of initializers can be less than the number of
10205   // vector elements. For OpenCL, this can be due to nested vector
10206   // initialization. For GCC compatibility, missing trailing elements
10207   // should be initialized with zeroes.
10208   unsigned CountInits = 0, CountElts = 0;
10209   while (CountElts < NumElements) {
10210     // Handle nested vector initialization.
10211     if (CountInits < NumInits
10212         && E->getInit(CountInits)->getType()->isVectorType()) {
10213       APValue v;
10214       if (!EvaluateVector(E->getInit(CountInits), v, Info))
10215         return Error(E);
10216       unsigned vlen = v.getVectorLength();
10217       for (unsigned j = 0; j < vlen; j++)
10218         Elements.push_back(v.getVectorElt(j));
10219       CountElts += vlen;
10220     } else if (EltTy->isIntegerType()) {
10221       llvm::APSInt sInt(32);
10222       if (CountInits < NumInits) {
10223         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
10224           return false;
10225       } else // trailing integer zero.
10226         sInt = Info.Ctx.MakeIntValue(0, EltTy);
10227       Elements.push_back(APValue(sInt));
10228       CountElts++;
10229     } else {
10230       llvm::APFloat f(0.0);
10231       if (CountInits < NumInits) {
10232         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
10233           return false;
10234       } else // trailing float zero.
10235         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
10236       Elements.push_back(APValue(f));
10237       CountElts++;
10238     }
10239     CountInits++;
10240   }
10241   return Success(Elements, E);
10242 }
10243 
10244 bool
10245 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
10246   const auto *VT = E->getType()->castAs<VectorType>();
10247   QualType EltTy = VT->getElementType();
10248   APValue ZeroElement;
10249   if (EltTy->isIntegerType())
10250     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
10251   else
10252     ZeroElement =
10253         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
10254 
10255   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
10256   return Success(Elements, E);
10257 }
10258 
10259 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
10260   VisitIgnoredValue(E->getSubExpr());
10261   return ZeroInitialization(E);
10262 }
10263 
10264 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10265   BinaryOperatorKind Op = E->getOpcode();
10266   assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
10267          "Operation not supported on vector types");
10268 
10269   if (Op == BO_Comma)
10270     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10271 
10272   Expr *LHS = E->getLHS();
10273   Expr *RHS = E->getRHS();
10274 
10275   assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
10276          "Must both be vector types");
10277   // Checking JUST the types are the same would be fine, except shifts don't
10278   // need to have their types be the same (since you always shift by an int).
10279   assert(LHS->getType()->getAs<VectorType>()->getNumElements() ==
10280              E->getType()->getAs<VectorType>()->getNumElements() &&
10281          RHS->getType()->getAs<VectorType>()->getNumElements() ==
10282              E->getType()->getAs<VectorType>()->getNumElements() &&
10283          "All operands must be the same size.");
10284 
10285   APValue LHSValue;
10286   APValue RHSValue;
10287   bool LHSOK = Evaluate(LHSValue, Info, LHS);
10288   if (!LHSOK && !Info.noteFailure())
10289     return false;
10290   if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
10291     return false;
10292 
10293   if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
10294     return false;
10295 
10296   return Success(LHSValue, E);
10297 }
10298 
10299 //===----------------------------------------------------------------------===//
10300 // Array Evaluation
10301 //===----------------------------------------------------------------------===//
10302 
10303 namespace {
10304   class ArrayExprEvaluator
10305   : public ExprEvaluatorBase<ArrayExprEvaluator> {
10306     const LValue &This;
10307     APValue &Result;
10308   public:
10309 
10310     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
10311       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
10312 
10313     bool Success(const APValue &V, const Expr *E) {
10314       assert(V.isArray() && "expected array");
10315       Result = V;
10316       return true;
10317     }
10318 
10319     bool ZeroInitialization(const Expr *E) {
10320       const ConstantArrayType *CAT =
10321           Info.Ctx.getAsConstantArrayType(E->getType());
10322       if (!CAT) {
10323         if (E->getType()->isIncompleteArrayType()) {
10324           // We can be asked to zero-initialize a flexible array member; this
10325           // is represented as an ImplicitValueInitExpr of incomplete array
10326           // type. In this case, the array has zero elements.
10327           Result = APValue(APValue::UninitArray(), 0, 0);
10328           return true;
10329         }
10330         // FIXME: We could handle VLAs here.
10331         return Error(E);
10332       }
10333 
10334       Result = APValue(APValue::UninitArray(), 0,
10335                        CAT->getSize().getZExtValue());
10336       if (!Result.hasArrayFiller()) return true;
10337 
10338       // Zero-initialize all elements.
10339       LValue Subobject = This;
10340       Subobject.addArray(Info, E, CAT);
10341       ImplicitValueInitExpr VIE(CAT->getElementType());
10342       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
10343     }
10344 
10345     bool VisitCallExpr(const CallExpr *E) {
10346       return handleCallExpr(E, Result, &This);
10347     }
10348     bool VisitInitListExpr(const InitListExpr *E,
10349                            QualType AllocType = QualType());
10350     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
10351     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
10352     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
10353                                const LValue &Subobject,
10354                                APValue *Value, QualType Type);
10355     bool VisitStringLiteral(const StringLiteral *E,
10356                             QualType AllocType = QualType()) {
10357       expandStringLiteral(Info, E, Result, AllocType);
10358       return true;
10359     }
10360   };
10361 } // end anonymous namespace
10362 
10363 static bool EvaluateArray(const Expr *E, const LValue &This,
10364                           APValue &Result, EvalInfo &Info) {
10365   assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
10366   return ArrayExprEvaluator(Info, This, Result).Visit(E);
10367 }
10368 
10369 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10370                                      APValue &Result, const InitListExpr *ILE,
10371                                      QualType AllocType) {
10372   assert(ILE->isRValue() && ILE->getType()->isArrayType() &&
10373          "not an array rvalue");
10374   return ArrayExprEvaluator(Info, This, Result)
10375       .VisitInitListExpr(ILE, AllocType);
10376 }
10377 
10378 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10379                                           APValue &Result,
10380                                           const CXXConstructExpr *CCE,
10381                                           QualType AllocType) {
10382   assert(CCE->isRValue() && CCE->getType()->isArrayType() &&
10383          "not an array rvalue");
10384   return ArrayExprEvaluator(Info, This, Result)
10385       .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
10386 }
10387 
10388 // Return true iff the given array filler may depend on the element index.
10389 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
10390   // For now, just allow non-class value-initialization and initialization
10391   // lists comprised of them.
10392   if (isa<ImplicitValueInitExpr>(FillerExpr))
10393     return false;
10394   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
10395     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
10396       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
10397         return true;
10398     }
10399     return false;
10400   }
10401   return true;
10402 }
10403 
10404 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
10405                                            QualType AllocType) {
10406   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
10407       AllocType.isNull() ? E->getType() : AllocType);
10408   if (!CAT)
10409     return Error(E);
10410 
10411   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
10412   // an appropriately-typed string literal enclosed in braces.
10413   if (E->isStringLiteralInit()) {
10414     auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens());
10415     // FIXME: Support ObjCEncodeExpr here once we support it in
10416     // ArrayExprEvaluator generally.
10417     if (!SL)
10418       return Error(E);
10419     return VisitStringLiteral(SL, AllocType);
10420   }
10421 
10422   bool Success = true;
10423 
10424   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
10425          "zero-initialized array shouldn't have any initialized elts");
10426   APValue Filler;
10427   if (Result.isArray() && Result.hasArrayFiller())
10428     Filler = Result.getArrayFiller();
10429 
10430   unsigned NumEltsToInit = E->getNumInits();
10431   unsigned NumElts = CAT->getSize().getZExtValue();
10432   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
10433 
10434   // If the initializer might depend on the array index, run it for each
10435   // array element.
10436   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
10437     NumEltsToInit = NumElts;
10438 
10439   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
10440                           << NumEltsToInit << ".\n");
10441 
10442   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
10443 
10444   // If the array was previously zero-initialized, preserve the
10445   // zero-initialized values.
10446   if (Filler.hasValue()) {
10447     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
10448       Result.getArrayInitializedElt(I) = Filler;
10449     if (Result.hasArrayFiller())
10450       Result.getArrayFiller() = Filler;
10451   }
10452 
10453   LValue Subobject = This;
10454   Subobject.addArray(Info, E, CAT);
10455   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
10456     const Expr *Init =
10457         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
10458     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10459                          Info, Subobject, Init) ||
10460         !HandleLValueArrayAdjustment(Info, Init, Subobject,
10461                                      CAT->getElementType(), 1)) {
10462       if (!Info.noteFailure())
10463         return false;
10464       Success = false;
10465     }
10466   }
10467 
10468   if (!Result.hasArrayFiller())
10469     return Success;
10470 
10471   // If we get here, we have a trivial filler, which we can just evaluate
10472   // once and splat over the rest of the array elements.
10473   assert(FillerExpr && "no array filler for incomplete init list");
10474   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
10475                          FillerExpr) && Success;
10476 }
10477 
10478 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
10479   LValue CommonLV;
10480   if (E->getCommonExpr() &&
10481       !Evaluate(Info.CurrentCall->createTemporary(
10482                     E->getCommonExpr(),
10483                     getStorageType(Info.Ctx, E->getCommonExpr()),
10484                     ScopeKind::FullExpression, CommonLV),
10485                 Info, E->getCommonExpr()->getSourceExpr()))
10486     return false;
10487 
10488   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
10489 
10490   uint64_t Elements = CAT->getSize().getZExtValue();
10491   Result = APValue(APValue::UninitArray(), Elements, Elements);
10492 
10493   LValue Subobject = This;
10494   Subobject.addArray(Info, E, CAT);
10495 
10496   bool Success = true;
10497   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
10498     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10499                          Info, Subobject, E->getSubExpr()) ||
10500         !HandleLValueArrayAdjustment(Info, E, Subobject,
10501                                      CAT->getElementType(), 1)) {
10502       if (!Info.noteFailure())
10503         return false;
10504       Success = false;
10505     }
10506   }
10507 
10508   return Success;
10509 }
10510 
10511 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
10512   return VisitCXXConstructExpr(E, This, &Result, E->getType());
10513 }
10514 
10515 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10516                                                const LValue &Subobject,
10517                                                APValue *Value,
10518                                                QualType Type) {
10519   bool HadZeroInit = Value->hasValue();
10520 
10521   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
10522     unsigned N = CAT->getSize().getZExtValue();
10523 
10524     // Preserve the array filler if we had prior zero-initialization.
10525     APValue Filler =
10526       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
10527                                              : APValue();
10528 
10529     *Value = APValue(APValue::UninitArray(), N, N);
10530 
10531     if (HadZeroInit)
10532       for (unsigned I = 0; I != N; ++I)
10533         Value->getArrayInitializedElt(I) = Filler;
10534 
10535     // Initialize the elements.
10536     LValue ArrayElt = Subobject;
10537     ArrayElt.addArray(Info, E, CAT);
10538     for (unsigned I = 0; I != N; ++I)
10539       if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
10540                                  CAT->getElementType()) ||
10541           !HandleLValueArrayAdjustment(Info, E, ArrayElt,
10542                                        CAT->getElementType(), 1))
10543         return false;
10544 
10545     return true;
10546   }
10547 
10548   if (!Type->isRecordType())
10549     return Error(E);
10550 
10551   return RecordExprEvaluator(Info, Subobject, *Value)
10552              .VisitCXXConstructExpr(E, Type);
10553 }
10554 
10555 //===----------------------------------------------------------------------===//
10556 // Integer Evaluation
10557 //
10558 // As a GNU extension, we support casting pointers to sufficiently-wide integer
10559 // types and back in constant folding. Integer values are thus represented
10560 // either as an integer-valued APValue, or as an lvalue-valued APValue.
10561 //===----------------------------------------------------------------------===//
10562 
10563 namespace {
10564 class IntExprEvaluator
10565         : public ExprEvaluatorBase<IntExprEvaluator> {
10566   APValue &Result;
10567 public:
10568   IntExprEvaluator(EvalInfo &info, APValue &result)
10569       : ExprEvaluatorBaseTy(info), Result(result) {}
10570 
10571   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
10572     assert(E->getType()->isIntegralOrEnumerationType() &&
10573            "Invalid evaluation result.");
10574     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
10575            "Invalid evaluation result.");
10576     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10577            "Invalid evaluation result.");
10578     Result = APValue(SI);
10579     return true;
10580   }
10581   bool Success(const llvm::APSInt &SI, const Expr *E) {
10582     return Success(SI, E, Result);
10583   }
10584 
10585   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
10586     assert(E->getType()->isIntegralOrEnumerationType() &&
10587            "Invalid evaluation result.");
10588     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10589            "Invalid evaluation result.");
10590     Result = APValue(APSInt(I));
10591     Result.getInt().setIsUnsigned(
10592                             E->getType()->isUnsignedIntegerOrEnumerationType());
10593     return true;
10594   }
10595   bool Success(const llvm::APInt &I, const Expr *E) {
10596     return Success(I, E, Result);
10597   }
10598 
10599   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
10600     assert(E->getType()->isIntegralOrEnumerationType() &&
10601            "Invalid evaluation result.");
10602     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
10603     return true;
10604   }
10605   bool Success(uint64_t Value, const Expr *E) {
10606     return Success(Value, E, Result);
10607   }
10608 
10609   bool Success(CharUnits Size, const Expr *E) {
10610     return Success(Size.getQuantity(), E);
10611   }
10612 
10613   bool Success(const APValue &V, const Expr *E) {
10614     if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
10615       Result = V;
10616       return true;
10617     }
10618     return Success(V.getInt(), E);
10619   }
10620 
10621   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
10622 
10623   //===--------------------------------------------------------------------===//
10624   //                            Visitor Methods
10625   //===--------------------------------------------------------------------===//
10626 
10627   bool VisitIntegerLiteral(const IntegerLiteral *E) {
10628     return Success(E->getValue(), E);
10629   }
10630   bool VisitCharacterLiteral(const CharacterLiteral *E) {
10631     return Success(E->getValue(), E);
10632   }
10633 
10634   bool CheckReferencedDecl(const Expr *E, const Decl *D);
10635   bool VisitDeclRefExpr(const DeclRefExpr *E) {
10636     if (CheckReferencedDecl(E, E->getDecl()))
10637       return true;
10638 
10639     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
10640   }
10641   bool VisitMemberExpr(const MemberExpr *E) {
10642     if (CheckReferencedDecl(E, E->getMemberDecl())) {
10643       VisitIgnoredBaseExpression(E->getBase());
10644       return true;
10645     }
10646 
10647     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
10648   }
10649 
10650   bool VisitCallExpr(const CallExpr *E);
10651   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
10652   bool VisitBinaryOperator(const BinaryOperator *E);
10653   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
10654   bool VisitUnaryOperator(const UnaryOperator *E);
10655 
10656   bool VisitCastExpr(const CastExpr* E);
10657   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
10658 
10659   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
10660     return Success(E->getValue(), E);
10661   }
10662 
10663   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
10664     return Success(E->getValue(), E);
10665   }
10666 
10667   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
10668     if (Info.ArrayInitIndex == uint64_t(-1)) {
10669       // We were asked to evaluate this subexpression independent of the
10670       // enclosing ArrayInitLoopExpr. We can't do that.
10671       Info.FFDiag(E);
10672       return false;
10673     }
10674     return Success(Info.ArrayInitIndex, E);
10675   }
10676 
10677   // Note, GNU defines __null as an integer, not a pointer.
10678   bool VisitGNUNullExpr(const GNUNullExpr *E) {
10679     return ZeroInitialization(E);
10680   }
10681 
10682   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
10683     return Success(E->getValue(), E);
10684   }
10685 
10686   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
10687     return Success(E->getValue(), E);
10688   }
10689 
10690   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
10691     return Success(E->getValue(), E);
10692   }
10693 
10694   bool VisitUnaryReal(const UnaryOperator *E);
10695   bool VisitUnaryImag(const UnaryOperator *E);
10696 
10697   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
10698   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
10699   bool VisitSourceLocExpr(const SourceLocExpr *E);
10700   bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
10701   bool VisitRequiresExpr(const RequiresExpr *E);
10702   // FIXME: Missing: array subscript of vector, member of vector
10703 };
10704 
10705 class FixedPointExprEvaluator
10706     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
10707   APValue &Result;
10708 
10709  public:
10710   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
10711       : ExprEvaluatorBaseTy(info), Result(result) {}
10712 
10713   bool Success(const llvm::APInt &I, const Expr *E) {
10714     return Success(
10715         APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10716   }
10717 
10718   bool Success(uint64_t Value, const Expr *E) {
10719     return Success(
10720         APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10721   }
10722 
10723   bool Success(const APValue &V, const Expr *E) {
10724     return Success(V.getFixedPoint(), E);
10725   }
10726 
10727   bool Success(const APFixedPoint &V, const Expr *E) {
10728     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
10729     assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10730            "Invalid evaluation result.");
10731     Result = APValue(V);
10732     return true;
10733   }
10734 
10735   //===--------------------------------------------------------------------===//
10736   //                            Visitor Methods
10737   //===--------------------------------------------------------------------===//
10738 
10739   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
10740     return Success(E->getValue(), E);
10741   }
10742 
10743   bool VisitCastExpr(const CastExpr *E);
10744   bool VisitUnaryOperator(const UnaryOperator *E);
10745   bool VisitBinaryOperator(const BinaryOperator *E);
10746 };
10747 } // end anonymous namespace
10748 
10749 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
10750 /// produce either the integer value or a pointer.
10751 ///
10752 /// GCC has a heinous extension which folds casts between pointer types and
10753 /// pointer-sized integral types. We support this by allowing the evaluation of
10754 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
10755 /// Some simple arithmetic on such values is supported (they are treated much
10756 /// like char*).
10757 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
10758                                     EvalInfo &Info) {
10759   assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
10760   return IntExprEvaluator(Info, Result).Visit(E);
10761 }
10762 
10763 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
10764   APValue Val;
10765   if (!EvaluateIntegerOrLValue(E, Val, Info))
10766     return false;
10767   if (!Val.isInt()) {
10768     // FIXME: It would be better to produce the diagnostic for casting
10769     //        a pointer to an integer.
10770     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10771     return false;
10772   }
10773   Result = Val.getInt();
10774   return true;
10775 }
10776 
10777 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
10778   APValue Evaluated = E->EvaluateInContext(
10779       Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
10780   return Success(Evaluated, E);
10781 }
10782 
10783 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
10784                                EvalInfo &Info) {
10785   if (E->getType()->isFixedPointType()) {
10786     APValue Val;
10787     if (!FixedPointExprEvaluator(Info, Val).Visit(E))
10788       return false;
10789     if (!Val.isFixedPoint())
10790       return false;
10791 
10792     Result = Val.getFixedPoint();
10793     return true;
10794   }
10795   return false;
10796 }
10797 
10798 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
10799                                         EvalInfo &Info) {
10800   if (E->getType()->isIntegerType()) {
10801     auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
10802     APSInt Val;
10803     if (!EvaluateInteger(E, Val, Info))
10804       return false;
10805     Result = APFixedPoint(Val, FXSema);
10806     return true;
10807   } else if (E->getType()->isFixedPointType()) {
10808     return EvaluateFixedPoint(E, Result, Info);
10809   }
10810   return false;
10811 }
10812 
10813 /// Check whether the given declaration can be directly converted to an integral
10814 /// rvalue. If not, no diagnostic is produced; there are other things we can
10815 /// try.
10816 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
10817   // Enums are integer constant exprs.
10818   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
10819     // Check for signedness/width mismatches between E type and ECD value.
10820     bool SameSign = (ECD->getInitVal().isSigned()
10821                      == E->getType()->isSignedIntegerOrEnumerationType());
10822     bool SameWidth = (ECD->getInitVal().getBitWidth()
10823                       == Info.Ctx.getIntWidth(E->getType()));
10824     if (SameSign && SameWidth)
10825       return Success(ECD->getInitVal(), E);
10826     else {
10827       // Get rid of mismatch (otherwise Success assertions will fail)
10828       // by computing a new value matching the type of E.
10829       llvm::APSInt Val = ECD->getInitVal();
10830       if (!SameSign)
10831         Val.setIsSigned(!ECD->getInitVal().isSigned());
10832       if (!SameWidth)
10833         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
10834       return Success(Val, E);
10835     }
10836   }
10837   return false;
10838 }
10839 
10840 /// Values returned by __builtin_classify_type, chosen to match the values
10841 /// produced by GCC's builtin.
10842 enum class GCCTypeClass {
10843   None = -1,
10844   Void = 0,
10845   Integer = 1,
10846   // GCC reserves 2 for character types, but instead classifies them as
10847   // integers.
10848   Enum = 3,
10849   Bool = 4,
10850   Pointer = 5,
10851   // GCC reserves 6 for references, but appears to never use it (because
10852   // expressions never have reference type, presumably).
10853   PointerToDataMember = 7,
10854   RealFloat = 8,
10855   Complex = 9,
10856   // GCC reserves 10 for functions, but does not use it since GCC version 6 due
10857   // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
10858   // GCC claims to reserve 11 for pointers to member functions, but *actually*
10859   // uses 12 for that purpose, same as for a class or struct. Maybe it
10860   // internally implements a pointer to member as a struct?  Who knows.
10861   PointerToMemberFunction = 12, // Not a bug, see above.
10862   ClassOrStruct = 12,
10863   Union = 13,
10864   // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
10865   // decay to pointer. (Prior to version 6 it was only used in C++ mode).
10866   // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
10867   // literals.
10868 };
10869 
10870 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
10871 /// as GCC.
10872 static GCCTypeClass
10873 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
10874   assert(!T->isDependentType() && "unexpected dependent type");
10875 
10876   QualType CanTy = T.getCanonicalType();
10877   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
10878 
10879   switch (CanTy->getTypeClass()) {
10880 #define TYPE(ID, BASE)
10881 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
10882 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
10883 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
10884 #include "clang/AST/TypeNodes.inc"
10885   case Type::Auto:
10886   case Type::DeducedTemplateSpecialization:
10887       llvm_unreachable("unexpected non-canonical or dependent type");
10888 
10889   case Type::Builtin:
10890     switch (BT->getKind()) {
10891 #define BUILTIN_TYPE(ID, SINGLETON_ID)
10892 #define SIGNED_TYPE(ID, SINGLETON_ID) \
10893     case BuiltinType::ID: return GCCTypeClass::Integer;
10894 #define FLOATING_TYPE(ID, SINGLETON_ID) \
10895     case BuiltinType::ID: return GCCTypeClass::RealFloat;
10896 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
10897     case BuiltinType::ID: break;
10898 #include "clang/AST/BuiltinTypes.def"
10899     case BuiltinType::Void:
10900       return GCCTypeClass::Void;
10901 
10902     case BuiltinType::Bool:
10903       return GCCTypeClass::Bool;
10904 
10905     case BuiltinType::Char_U:
10906     case BuiltinType::UChar:
10907     case BuiltinType::WChar_U:
10908     case BuiltinType::Char8:
10909     case BuiltinType::Char16:
10910     case BuiltinType::Char32:
10911     case BuiltinType::UShort:
10912     case BuiltinType::UInt:
10913     case BuiltinType::ULong:
10914     case BuiltinType::ULongLong:
10915     case BuiltinType::UInt128:
10916       return GCCTypeClass::Integer;
10917 
10918     case BuiltinType::UShortAccum:
10919     case BuiltinType::UAccum:
10920     case BuiltinType::ULongAccum:
10921     case BuiltinType::UShortFract:
10922     case BuiltinType::UFract:
10923     case BuiltinType::ULongFract:
10924     case BuiltinType::SatUShortAccum:
10925     case BuiltinType::SatUAccum:
10926     case BuiltinType::SatULongAccum:
10927     case BuiltinType::SatUShortFract:
10928     case BuiltinType::SatUFract:
10929     case BuiltinType::SatULongFract:
10930       return GCCTypeClass::None;
10931 
10932     case BuiltinType::NullPtr:
10933 
10934     case BuiltinType::ObjCId:
10935     case BuiltinType::ObjCClass:
10936     case BuiltinType::ObjCSel:
10937 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
10938     case BuiltinType::Id:
10939 #include "clang/Basic/OpenCLImageTypes.def"
10940 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
10941     case BuiltinType::Id:
10942 #include "clang/Basic/OpenCLExtensionTypes.def"
10943     case BuiltinType::OCLSampler:
10944     case BuiltinType::OCLEvent:
10945     case BuiltinType::OCLClkEvent:
10946     case BuiltinType::OCLQueue:
10947     case BuiltinType::OCLReserveID:
10948 #define SVE_TYPE(Name, Id, SingletonId) \
10949     case BuiltinType::Id:
10950 #include "clang/Basic/AArch64SVEACLETypes.def"
10951 #define PPC_MMA_VECTOR_TYPE(Name, Id, Size) \
10952     case BuiltinType::Id:
10953 #include "clang/Basic/PPCTypes.def"
10954       return GCCTypeClass::None;
10955 
10956     case BuiltinType::Dependent:
10957       llvm_unreachable("unexpected dependent type");
10958     };
10959     llvm_unreachable("unexpected placeholder type");
10960 
10961   case Type::Enum:
10962     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
10963 
10964   case Type::Pointer:
10965   case Type::ConstantArray:
10966   case Type::VariableArray:
10967   case Type::IncompleteArray:
10968   case Type::FunctionNoProto:
10969   case Type::FunctionProto:
10970     return GCCTypeClass::Pointer;
10971 
10972   case Type::MemberPointer:
10973     return CanTy->isMemberDataPointerType()
10974                ? GCCTypeClass::PointerToDataMember
10975                : GCCTypeClass::PointerToMemberFunction;
10976 
10977   case Type::Complex:
10978     return GCCTypeClass::Complex;
10979 
10980   case Type::Record:
10981     return CanTy->isUnionType() ? GCCTypeClass::Union
10982                                 : GCCTypeClass::ClassOrStruct;
10983 
10984   case Type::Atomic:
10985     // GCC classifies _Atomic T the same as T.
10986     return EvaluateBuiltinClassifyType(
10987         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
10988 
10989   case Type::BlockPointer:
10990   case Type::Vector:
10991   case Type::ExtVector:
10992   case Type::ConstantMatrix:
10993   case Type::ObjCObject:
10994   case Type::ObjCInterface:
10995   case Type::ObjCObjectPointer:
10996   case Type::Pipe:
10997   case Type::ExtInt:
10998     // GCC classifies vectors as None. We follow its lead and classify all
10999     // other types that don't fit into the regular classification the same way.
11000     return GCCTypeClass::None;
11001 
11002   case Type::LValueReference:
11003   case Type::RValueReference:
11004     llvm_unreachable("invalid type for expression");
11005   }
11006 
11007   llvm_unreachable("unexpected type class");
11008 }
11009 
11010 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11011 /// as GCC.
11012 static GCCTypeClass
11013 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
11014   // If no argument was supplied, default to None. This isn't
11015   // ideal, however it is what gcc does.
11016   if (E->getNumArgs() == 0)
11017     return GCCTypeClass::None;
11018 
11019   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
11020   // being an ICE, but still folds it to a constant using the type of the first
11021   // argument.
11022   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
11023 }
11024 
11025 /// EvaluateBuiltinConstantPForLValue - Determine the result of
11026 /// __builtin_constant_p when applied to the given pointer.
11027 ///
11028 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
11029 /// or it points to the first character of a string literal.
11030 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
11031   APValue::LValueBase Base = LV.getLValueBase();
11032   if (Base.isNull()) {
11033     // A null base is acceptable.
11034     return true;
11035   } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
11036     if (!isa<StringLiteral>(E))
11037       return false;
11038     return LV.getLValueOffset().isZero();
11039   } else if (Base.is<TypeInfoLValue>()) {
11040     // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
11041     // evaluate to true.
11042     return true;
11043   } else {
11044     // Any other base is not constant enough for GCC.
11045     return false;
11046   }
11047 }
11048 
11049 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
11050 /// GCC as we can manage.
11051 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
11052   // This evaluation is not permitted to have side-effects, so evaluate it in
11053   // a speculative evaluation context.
11054   SpeculativeEvaluationRAII SpeculativeEval(Info);
11055 
11056   // Constant-folding is always enabled for the operand of __builtin_constant_p
11057   // (even when the enclosing evaluation context otherwise requires a strict
11058   // language-specific constant expression).
11059   FoldConstant Fold(Info, true);
11060 
11061   QualType ArgType = Arg->getType();
11062 
11063   // __builtin_constant_p always has one operand. The rules which gcc follows
11064   // are not precisely documented, but are as follows:
11065   //
11066   //  - If the operand is of integral, floating, complex or enumeration type,
11067   //    and can be folded to a known value of that type, it returns 1.
11068   //  - If the operand can be folded to a pointer to the first character
11069   //    of a string literal (or such a pointer cast to an integral type)
11070   //    or to a null pointer or an integer cast to a pointer, it returns 1.
11071   //
11072   // Otherwise, it returns 0.
11073   //
11074   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
11075   // its support for this did not work prior to GCC 9 and is not yet well
11076   // understood.
11077   if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
11078       ArgType->isAnyComplexType() || ArgType->isPointerType() ||
11079       ArgType->isNullPtrType()) {
11080     APValue V;
11081     if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
11082       Fold.keepDiagnostics();
11083       return false;
11084     }
11085 
11086     // For a pointer (possibly cast to integer), there are special rules.
11087     if (V.getKind() == APValue::LValue)
11088       return EvaluateBuiltinConstantPForLValue(V);
11089 
11090     // Otherwise, any constant value is good enough.
11091     return V.hasValue();
11092   }
11093 
11094   // Anything else isn't considered to be sufficiently constant.
11095   return false;
11096 }
11097 
11098 /// Retrieves the "underlying object type" of the given expression,
11099 /// as used by __builtin_object_size.
11100 static QualType getObjectType(APValue::LValueBase B) {
11101   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
11102     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
11103       return VD->getType();
11104   } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
11105     if (isa<CompoundLiteralExpr>(E))
11106       return E->getType();
11107   } else if (B.is<TypeInfoLValue>()) {
11108     return B.getTypeInfoType();
11109   } else if (B.is<DynamicAllocLValue>()) {
11110     return B.getDynamicAllocType();
11111   }
11112 
11113   return QualType();
11114 }
11115 
11116 /// A more selective version of E->IgnoreParenCasts for
11117 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
11118 /// to change the type of E.
11119 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
11120 ///
11121 /// Always returns an RValue with a pointer representation.
11122 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
11123   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
11124 
11125   auto *NoParens = E->IgnoreParens();
11126   auto *Cast = dyn_cast<CastExpr>(NoParens);
11127   if (Cast == nullptr)
11128     return NoParens;
11129 
11130   // We only conservatively allow a few kinds of casts, because this code is
11131   // inherently a simple solution that seeks to support the common case.
11132   auto CastKind = Cast->getCastKind();
11133   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
11134       CastKind != CK_AddressSpaceConversion)
11135     return NoParens;
11136 
11137   auto *SubExpr = Cast->getSubExpr();
11138   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
11139     return NoParens;
11140   return ignorePointerCastsAndParens(SubExpr);
11141 }
11142 
11143 /// Checks to see if the given LValue's Designator is at the end of the LValue's
11144 /// record layout. e.g.
11145 ///   struct { struct { int a, b; } fst, snd; } obj;
11146 ///   obj.fst   // no
11147 ///   obj.snd   // yes
11148 ///   obj.fst.a // no
11149 ///   obj.fst.b // no
11150 ///   obj.snd.a // no
11151 ///   obj.snd.b // yes
11152 ///
11153 /// Please note: this function is specialized for how __builtin_object_size
11154 /// views "objects".
11155 ///
11156 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
11157 /// correct result, it will always return true.
11158 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
11159   assert(!LVal.Designator.Invalid);
11160 
11161   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
11162     const RecordDecl *Parent = FD->getParent();
11163     Invalid = Parent->isInvalidDecl();
11164     if (Invalid || Parent->isUnion())
11165       return true;
11166     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
11167     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
11168   };
11169 
11170   auto &Base = LVal.getLValueBase();
11171   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
11172     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
11173       bool Invalid;
11174       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11175         return Invalid;
11176     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
11177       for (auto *FD : IFD->chain()) {
11178         bool Invalid;
11179         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
11180           return Invalid;
11181       }
11182     }
11183   }
11184 
11185   unsigned I = 0;
11186   QualType BaseType = getType(Base);
11187   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
11188     // If we don't know the array bound, conservatively assume we're looking at
11189     // the final array element.
11190     ++I;
11191     if (BaseType->isIncompleteArrayType())
11192       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
11193     else
11194       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
11195   }
11196 
11197   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
11198     const auto &Entry = LVal.Designator.Entries[I];
11199     if (BaseType->isArrayType()) {
11200       // Because __builtin_object_size treats arrays as objects, we can ignore
11201       // the index iff this is the last array in the Designator.
11202       if (I + 1 == E)
11203         return true;
11204       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
11205       uint64_t Index = Entry.getAsArrayIndex();
11206       if (Index + 1 != CAT->getSize())
11207         return false;
11208       BaseType = CAT->getElementType();
11209     } else if (BaseType->isAnyComplexType()) {
11210       const auto *CT = BaseType->castAs<ComplexType>();
11211       uint64_t Index = Entry.getAsArrayIndex();
11212       if (Index != 1)
11213         return false;
11214       BaseType = CT->getElementType();
11215     } else if (auto *FD = getAsField(Entry)) {
11216       bool Invalid;
11217       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11218         return Invalid;
11219       BaseType = FD->getType();
11220     } else {
11221       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
11222       return false;
11223     }
11224   }
11225   return true;
11226 }
11227 
11228 /// Tests to see if the LValue has a user-specified designator (that isn't
11229 /// necessarily valid). Note that this always returns 'true' if the LValue has
11230 /// an unsized array as its first designator entry, because there's currently no
11231 /// way to tell if the user typed *foo or foo[0].
11232 static bool refersToCompleteObject(const LValue &LVal) {
11233   if (LVal.Designator.Invalid)
11234     return false;
11235 
11236   if (!LVal.Designator.Entries.empty())
11237     return LVal.Designator.isMostDerivedAnUnsizedArray();
11238 
11239   if (!LVal.InvalidBase)
11240     return true;
11241 
11242   // If `E` is a MemberExpr, then the first part of the designator is hiding in
11243   // the LValueBase.
11244   const auto *E = LVal.Base.dyn_cast<const Expr *>();
11245   return !E || !isa<MemberExpr>(E);
11246 }
11247 
11248 /// Attempts to detect a user writing into a piece of memory that's impossible
11249 /// to figure out the size of by just using types.
11250 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
11251   const SubobjectDesignator &Designator = LVal.Designator;
11252   // Notes:
11253   // - Users can only write off of the end when we have an invalid base. Invalid
11254   //   bases imply we don't know where the memory came from.
11255   // - We used to be a bit more aggressive here; we'd only be conservative if
11256   //   the array at the end was flexible, or if it had 0 or 1 elements. This
11257   //   broke some common standard library extensions (PR30346), but was
11258   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
11259   //   with some sort of list. OTOH, it seems that GCC is always
11260   //   conservative with the last element in structs (if it's an array), so our
11261   //   current behavior is more compatible than an explicit list approach would
11262   //   be.
11263   return LVal.InvalidBase &&
11264          Designator.Entries.size() == Designator.MostDerivedPathLength &&
11265          Designator.MostDerivedIsArrayElement &&
11266          isDesignatorAtObjectEnd(Ctx, LVal);
11267 }
11268 
11269 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
11270 /// Fails if the conversion would cause loss of precision.
11271 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
11272                                             CharUnits &Result) {
11273   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
11274   if (Int.ugt(CharUnitsMax))
11275     return false;
11276   Result = CharUnits::fromQuantity(Int.getZExtValue());
11277   return true;
11278 }
11279 
11280 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
11281 /// determine how many bytes exist from the beginning of the object to either
11282 /// the end of the current subobject, or the end of the object itself, depending
11283 /// on what the LValue looks like + the value of Type.
11284 ///
11285 /// If this returns false, the value of Result is undefined.
11286 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
11287                                unsigned Type, const LValue &LVal,
11288                                CharUnits &EndOffset) {
11289   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
11290 
11291   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
11292     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
11293       return false;
11294     return HandleSizeof(Info, ExprLoc, Ty, Result);
11295   };
11296 
11297   // We want to evaluate the size of the entire object. This is a valid fallback
11298   // for when Type=1 and the designator is invalid, because we're asked for an
11299   // upper-bound.
11300   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
11301     // Type=3 wants a lower bound, so we can't fall back to this.
11302     if (Type == 3 && !DetermineForCompleteObject)
11303       return false;
11304 
11305     llvm::APInt APEndOffset;
11306     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11307         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11308       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11309 
11310     if (LVal.InvalidBase)
11311       return false;
11312 
11313     QualType BaseTy = getObjectType(LVal.getLValueBase());
11314     return CheckedHandleSizeof(BaseTy, EndOffset);
11315   }
11316 
11317   // We want to evaluate the size of a subobject.
11318   const SubobjectDesignator &Designator = LVal.Designator;
11319 
11320   // The following is a moderately common idiom in C:
11321   //
11322   // struct Foo { int a; char c[1]; };
11323   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
11324   // strcpy(&F->c[0], Bar);
11325   //
11326   // In order to not break too much legacy code, we need to support it.
11327   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
11328     // If we can resolve this to an alloc_size call, we can hand that back,
11329     // because we know for certain how many bytes there are to write to.
11330     llvm::APInt APEndOffset;
11331     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11332         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11333       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11334 
11335     // If we cannot determine the size of the initial allocation, then we can't
11336     // given an accurate upper-bound. However, we are still able to give
11337     // conservative lower-bounds for Type=3.
11338     if (Type == 1)
11339       return false;
11340   }
11341 
11342   CharUnits BytesPerElem;
11343   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
11344     return false;
11345 
11346   // According to the GCC documentation, we want the size of the subobject
11347   // denoted by the pointer. But that's not quite right -- what we actually
11348   // want is the size of the immediately-enclosing array, if there is one.
11349   int64_t ElemsRemaining;
11350   if (Designator.MostDerivedIsArrayElement &&
11351       Designator.Entries.size() == Designator.MostDerivedPathLength) {
11352     uint64_t ArraySize = Designator.getMostDerivedArraySize();
11353     uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
11354     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
11355   } else {
11356     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
11357   }
11358 
11359   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
11360   return true;
11361 }
11362 
11363 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
11364 /// returns true and stores the result in @p Size.
11365 ///
11366 /// If @p WasError is non-null, this will report whether the failure to evaluate
11367 /// is to be treated as an Error in IntExprEvaluator.
11368 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
11369                                          EvalInfo &Info, uint64_t &Size) {
11370   // Determine the denoted object.
11371   LValue LVal;
11372   {
11373     // The operand of __builtin_object_size is never evaluated for side-effects.
11374     // If there are any, but we can determine the pointed-to object anyway, then
11375     // ignore the side-effects.
11376     SpeculativeEvaluationRAII SpeculativeEval(Info);
11377     IgnoreSideEffectsRAII Fold(Info);
11378 
11379     if (E->isGLValue()) {
11380       // It's possible for us to be given GLValues if we're called via
11381       // Expr::tryEvaluateObjectSize.
11382       APValue RVal;
11383       if (!EvaluateAsRValue(Info, E, RVal))
11384         return false;
11385       LVal.setFrom(Info.Ctx, RVal);
11386     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
11387                                 /*InvalidBaseOK=*/true))
11388       return false;
11389   }
11390 
11391   // If we point to before the start of the object, there are no accessible
11392   // bytes.
11393   if (LVal.getLValueOffset().isNegative()) {
11394     Size = 0;
11395     return true;
11396   }
11397 
11398   CharUnits EndOffset;
11399   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
11400     return false;
11401 
11402   // If we've fallen outside of the end offset, just pretend there's nothing to
11403   // write to/read from.
11404   if (EndOffset <= LVal.getLValueOffset())
11405     Size = 0;
11406   else
11407     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
11408   return true;
11409 }
11410 
11411 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
11412   if (unsigned BuiltinOp = E->getBuiltinCallee())
11413     return VisitBuiltinCallExpr(E, BuiltinOp);
11414 
11415   return ExprEvaluatorBaseTy::VisitCallExpr(E);
11416 }
11417 
11418 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
11419                                      APValue &Val, APSInt &Alignment) {
11420   QualType SrcTy = E->getArg(0)->getType();
11421   if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
11422     return false;
11423   // Even though we are evaluating integer expressions we could get a pointer
11424   // argument for the __builtin_is_aligned() case.
11425   if (SrcTy->isPointerType()) {
11426     LValue Ptr;
11427     if (!EvaluatePointer(E->getArg(0), Ptr, Info))
11428       return false;
11429     Ptr.moveInto(Val);
11430   } else if (!SrcTy->isIntegralOrEnumerationType()) {
11431     Info.FFDiag(E->getArg(0));
11432     return false;
11433   } else {
11434     APSInt SrcInt;
11435     if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
11436       return false;
11437     assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
11438            "Bit widths must be the same");
11439     Val = APValue(SrcInt);
11440   }
11441   assert(Val.hasValue());
11442   return true;
11443 }
11444 
11445 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
11446                                             unsigned BuiltinOp) {
11447   switch (BuiltinOp) {
11448   default:
11449     return ExprEvaluatorBaseTy::VisitCallExpr(E);
11450 
11451   case Builtin::BI__builtin_dynamic_object_size:
11452   case Builtin::BI__builtin_object_size: {
11453     // The type was checked when we built the expression.
11454     unsigned Type =
11455         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11456     assert(Type <= 3 && "unexpected type");
11457 
11458     uint64_t Size;
11459     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
11460       return Success(Size, E);
11461 
11462     if (E->getArg(0)->HasSideEffects(Info.Ctx))
11463       return Success((Type & 2) ? 0 : -1, E);
11464 
11465     // Expression had no side effects, but we couldn't statically determine the
11466     // size of the referenced object.
11467     switch (Info.EvalMode) {
11468     case EvalInfo::EM_ConstantExpression:
11469     case EvalInfo::EM_ConstantFold:
11470     case EvalInfo::EM_IgnoreSideEffects:
11471       // Leave it to IR generation.
11472       return Error(E);
11473     case EvalInfo::EM_ConstantExpressionUnevaluated:
11474       // Reduce it to a constant now.
11475       return Success((Type & 2) ? 0 : -1, E);
11476     }
11477 
11478     llvm_unreachable("unexpected EvalMode");
11479   }
11480 
11481   case Builtin::BI__builtin_os_log_format_buffer_size: {
11482     analyze_os_log::OSLogBufferLayout Layout;
11483     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
11484     return Success(Layout.size().getQuantity(), E);
11485   }
11486 
11487   case Builtin::BI__builtin_is_aligned: {
11488     APValue Src;
11489     APSInt Alignment;
11490     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11491       return false;
11492     if (Src.isLValue()) {
11493       // If we evaluated a pointer, check the minimum known alignment.
11494       LValue Ptr;
11495       Ptr.setFrom(Info.Ctx, Src);
11496       CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
11497       CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
11498       // We can return true if the known alignment at the computed offset is
11499       // greater than the requested alignment.
11500       assert(PtrAlign.isPowerOfTwo());
11501       assert(Alignment.isPowerOf2());
11502       if (PtrAlign.getQuantity() >= Alignment)
11503         return Success(1, E);
11504       // If the alignment is not known to be sufficient, some cases could still
11505       // be aligned at run time. However, if the requested alignment is less or
11506       // equal to the base alignment and the offset is not aligned, we know that
11507       // the run-time value can never be aligned.
11508       if (BaseAlignment.getQuantity() >= Alignment &&
11509           PtrAlign.getQuantity() < Alignment)
11510         return Success(0, E);
11511       // Otherwise we can't infer whether the value is sufficiently aligned.
11512       // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
11513       //  in cases where we can't fully evaluate the pointer.
11514       Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
11515           << Alignment;
11516       return false;
11517     }
11518     assert(Src.isInt());
11519     return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
11520   }
11521   case Builtin::BI__builtin_align_up: {
11522     APValue Src;
11523     APSInt Alignment;
11524     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11525       return false;
11526     if (!Src.isInt())
11527       return Error(E);
11528     APSInt AlignedVal =
11529         APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
11530                Src.getInt().isUnsigned());
11531     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11532     return Success(AlignedVal, E);
11533   }
11534   case Builtin::BI__builtin_align_down: {
11535     APValue Src;
11536     APSInt Alignment;
11537     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11538       return false;
11539     if (!Src.isInt())
11540       return Error(E);
11541     APSInt AlignedVal =
11542         APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
11543     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11544     return Success(AlignedVal, E);
11545   }
11546 
11547   case Builtin::BI__builtin_bitreverse8:
11548   case Builtin::BI__builtin_bitreverse16:
11549   case Builtin::BI__builtin_bitreverse32:
11550   case Builtin::BI__builtin_bitreverse64: {
11551     APSInt Val;
11552     if (!EvaluateInteger(E->getArg(0), Val, Info))
11553       return false;
11554 
11555     return Success(Val.reverseBits(), E);
11556   }
11557 
11558   case Builtin::BI__builtin_bswap16:
11559   case Builtin::BI__builtin_bswap32:
11560   case Builtin::BI__builtin_bswap64: {
11561     APSInt Val;
11562     if (!EvaluateInteger(E->getArg(0), Val, Info))
11563       return false;
11564 
11565     return Success(Val.byteSwap(), E);
11566   }
11567 
11568   case Builtin::BI__builtin_classify_type:
11569     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
11570 
11571   case Builtin::BI__builtin_clrsb:
11572   case Builtin::BI__builtin_clrsbl:
11573   case Builtin::BI__builtin_clrsbll: {
11574     APSInt Val;
11575     if (!EvaluateInteger(E->getArg(0), Val, Info))
11576       return false;
11577 
11578     return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
11579   }
11580 
11581   case Builtin::BI__builtin_clz:
11582   case Builtin::BI__builtin_clzl:
11583   case Builtin::BI__builtin_clzll:
11584   case Builtin::BI__builtin_clzs: {
11585     APSInt Val;
11586     if (!EvaluateInteger(E->getArg(0), Val, Info))
11587       return false;
11588     if (!Val)
11589       return Error(E);
11590 
11591     return Success(Val.countLeadingZeros(), E);
11592   }
11593 
11594   case Builtin::BI__builtin_constant_p: {
11595     const Expr *Arg = E->getArg(0);
11596     if (EvaluateBuiltinConstantP(Info, Arg))
11597       return Success(true, E);
11598     if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
11599       // Outside a constant context, eagerly evaluate to false in the presence
11600       // of side-effects in order to avoid -Wunsequenced false-positives in
11601       // a branch on __builtin_constant_p(expr).
11602       return Success(false, E);
11603     }
11604     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11605     return false;
11606   }
11607 
11608   case Builtin::BI__builtin_is_constant_evaluated: {
11609     const auto *Callee = Info.CurrentCall->getCallee();
11610     if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
11611         (Info.CallStackDepth == 1 ||
11612          (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
11613           Callee->getIdentifier() &&
11614           Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
11615       // FIXME: Find a better way to avoid duplicated diagnostics.
11616       if (Info.EvalStatus.Diag)
11617         Info.report((Info.CallStackDepth == 1) ? E->getExprLoc()
11618                                                : Info.CurrentCall->CallLoc,
11619                     diag::warn_is_constant_evaluated_always_true_constexpr)
11620             << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
11621                                          : "std::is_constant_evaluated");
11622     }
11623 
11624     return Success(Info.InConstantContext, E);
11625   }
11626 
11627   case Builtin::BI__builtin_ctz:
11628   case Builtin::BI__builtin_ctzl:
11629   case Builtin::BI__builtin_ctzll:
11630   case Builtin::BI__builtin_ctzs: {
11631     APSInt Val;
11632     if (!EvaluateInteger(E->getArg(0), Val, Info))
11633       return false;
11634     if (!Val)
11635       return Error(E);
11636 
11637     return Success(Val.countTrailingZeros(), E);
11638   }
11639 
11640   case Builtin::BI__builtin_eh_return_data_regno: {
11641     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11642     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
11643     return Success(Operand, E);
11644   }
11645 
11646   case Builtin::BI__builtin_expect:
11647   case Builtin::BI__builtin_expect_with_probability:
11648     return Visit(E->getArg(0));
11649 
11650   case Builtin::BI__builtin_ffs:
11651   case Builtin::BI__builtin_ffsl:
11652   case Builtin::BI__builtin_ffsll: {
11653     APSInt Val;
11654     if (!EvaluateInteger(E->getArg(0), Val, Info))
11655       return false;
11656 
11657     unsigned N = Val.countTrailingZeros();
11658     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
11659   }
11660 
11661   case Builtin::BI__builtin_fpclassify: {
11662     APFloat Val(0.0);
11663     if (!EvaluateFloat(E->getArg(5), Val, Info))
11664       return false;
11665     unsigned Arg;
11666     switch (Val.getCategory()) {
11667     case APFloat::fcNaN: Arg = 0; break;
11668     case APFloat::fcInfinity: Arg = 1; break;
11669     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
11670     case APFloat::fcZero: Arg = 4; break;
11671     }
11672     return Visit(E->getArg(Arg));
11673   }
11674 
11675   case Builtin::BI__builtin_isinf_sign: {
11676     APFloat Val(0.0);
11677     return EvaluateFloat(E->getArg(0), Val, Info) &&
11678            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
11679   }
11680 
11681   case Builtin::BI__builtin_isinf: {
11682     APFloat Val(0.0);
11683     return EvaluateFloat(E->getArg(0), Val, Info) &&
11684            Success(Val.isInfinity() ? 1 : 0, E);
11685   }
11686 
11687   case Builtin::BI__builtin_isfinite: {
11688     APFloat Val(0.0);
11689     return EvaluateFloat(E->getArg(0), Val, Info) &&
11690            Success(Val.isFinite() ? 1 : 0, E);
11691   }
11692 
11693   case Builtin::BI__builtin_isnan: {
11694     APFloat Val(0.0);
11695     return EvaluateFloat(E->getArg(0), Val, Info) &&
11696            Success(Val.isNaN() ? 1 : 0, E);
11697   }
11698 
11699   case Builtin::BI__builtin_isnormal: {
11700     APFloat Val(0.0);
11701     return EvaluateFloat(E->getArg(0), Val, Info) &&
11702            Success(Val.isNormal() ? 1 : 0, E);
11703   }
11704 
11705   case Builtin::BI__builtin_parity:
11706   case Builtin::BI__builtin_parityl:
11707   case Builtin::BI__builtin_parityll: {
11708     APSInt Val;
11709     if (!EvaluateInteger(E->getArg(0), Val, Info))
11710       return false;
11711 
11712     return Success(Val.countPopulation() % 2, E);
11713   }
11714 
11715   case Builtin::BI__builtin_popcount:
11716   case Builtin::BI__builtin_popcountl:
11717   case Builtin::BI__builtin_popcountll: {
11718     APSInt Val;
11719     if (!EvaluateInteger(E->getArg(0), Val, Info))
11720       return false;
11721 
11722     return Success(Val.countPopulation(), E);
11723   }
11724 
11725   case Builtin::BI__builtin_rotateleft8:
11726   case Builtin::BI__builtin_rotateleft16:
11727   case Builtin::BI__builtin_rotateleft32:
11728   case Builtin::BI__builtin_rotateleft64:
11729   case Builtin::BI_rotl8: // Microsoft variants of rotate right
11730   case Builtin::BI_rotl16:
11731   case Builtin::BI_rotl:
11732   case Builtin::BI_lrotl:
11733   case Builtin::BI_rotl64: {
11734     APSInt Val, Amt;
11735     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
11736         !EvaluateInteger(E->getArg(1), Amt, Info))
11737       return false;
11738 
11739     return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
11740   }
11741 
11742   case Builtin::BI__builtin_rotateright8:
11743   case Builtin::BI__builtin_rotateright16:
11744   case Builtin::BI__builtin_rotateright32:
11745   case Builtin::BI__builtin_rotateright64:
11746   case Builtin::BI_rotr8: // Microsoft variants of rotate right
11747   case Builtin::BI_rotr16:
11748   case Builtin::BI_rotr:
11749   case Builtin::BI_lrotr:
11750   case Builtin::BI_rotr64: {
11751     APSInt Val, Amt;
11752     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
11753         !EvaluateInteger(E->getArg(1), Amt, Info))
11754       return false;
11755 
11756     return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
11757   }
11758 
11759   case Builtin::BIstrlen:
11760   case Builtin::BIwcslen:
11761     // A call to strlen is not a constant expression.
11762     if (Info.getLangOpts().CPlusPlus11)
11763       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11764         << /*isConstexpr*/0 << /*isConstructor*/0
11765         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11766     else
11767       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11768     LLVM_FALLTHROUGH;
11769   case Builtin::BI__builtin_strlen:
11770   case Builtin::BI__builtin_wcslen: {
11771     // As an extension, we support __builtin_strlen() as a constant expression,
11772     // and support folding strlen() to a constant.
11773     LValue String;
11774     if (!EvaluatePointer(E->getArg(0), String, Info))
11775       return false;
11776 
11777     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
11778 
11779     // Fast path: if it's a string literal, search the string value.
11780     if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
11781             String.getLValueBase().dyn_cast<const Expr *>())) {
11782       // The string literal may have embedded null characters. Find the first
11783       // one and truncate there.
11784       StringRef Str = S->getBytes();
11785       int64_t Off = String.Offset.getQuantity();
11786       if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
11787           S->getCharByteWidth() == 1 &&
11788           // FIXME: Add fast-path for wchar_t too.
11789           Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
11790         Str = Str.substr(Off);
11791 
11792         StringRef::size_type Pos = Str.find(0);
11793         if (Pos != StringRef::npos)
11794           Str = Str.substr(0, Pos);
11795 
11796         return Success(Str.size(), E);
11797       }
11798 
11799       // Fall through to slow path to issue appropriate diagnostic.
11800     }
11801 
11802     // Slow path: scan the bytes of the string looking for the terminating 0.
11803     for (uint64_t Strlen = 0; /**/; ++Strlen) {
11804       APValue Char;
11805       if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
11806           !Char.isInt())
11807         return false;
11808       if (!Char.getInt())
11809         return Success(Strlen, E);
11810       if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
11811         return false;
11812     }
11813   }
11814 
11815   case Builtin::BIstrcmp:
11816   case Builtin::BIwcscmp:
11817   case Builtin::BIstrncmp:
11818   case Builtin::BIwcsncmp:
11819   case Builtin::BImemcmp:
11820   case Builtin::BIbcmp:
11821   case Builtin::BIwmemcmp:
11822     // A call to strlen is not a constant expression.
11823     if (Info.getLangOpts().CPlusPlus11)
11824       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11825         << /*isConstexpr*/0 << /*isConstructor*/0
11826         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11827     else
11828       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11829     LLVM_FALLTHROUGH;
11830   case Builtin::BI__builtin_strcmp:
11831   case Builtin::BI__builtin_wcscmp:
11832   case Builtin::BI__builtin_strncmp:
11833   case Builtin::BI__builtin_wcsncmp:
11834   case Builtin::BI__builtin_memcmp:
11835   case Builtin::BI__builtin_bcmp:
11836   case Builtin::BI__builtin_wmemcmp: {
11837     LValue String1, String2;
11838     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
11839         !EvaluatePointer(E->getArg(1), String2, Info))
11840       return false;
11841 
11842     uint64_t MaxLength = uint64_t(-1);
11843     if (BuiltinOp != Builtin::BIstrcmp &&
11844         BuiltinOp != Builtin::BIwcscmp &&
11845         BuiltinOp != Builtin::BI__builtin_strcmp &&
11846         BuiltinOp != Builtin::BI__builtin_wcscmp) {
11847       APSInt N;
11848       if (!EvaluateInteger(E->getArg(2), N, Info))
11849         return false;
11850       MaxLength = N.getExtValue();
11851     }
11852 
11853     // Empty substrings compare equal by definition.
11854     if (MaxLength == 0u)
11855       return Success(0, E);
11856 
11857     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11858         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11859         String1.Designator.Invalid || String2.Designator.Invalid)
11860       return false;
11861 
11862     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
11863     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
11864 
11865     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
11866                      BuiltinOp == Builtin::BIbcmp ||
11867                      BuiltinOp == Builtin::BI__builtin_memcmp ||
11868                      BuiltinOp == Builtin::BI__builtin_bcmp;
11869 
11870     assert(IsRawByte ||
11871            (Info.Ctx.hasSameUnqualifiedType(
11872                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
11873             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
11874 
11875     // For memcmp, allow comparing any arrays of '[[un]signed] char' or
11876     // 'char8_t', but no other types.
11877     if (IsRawByte &&
11878         !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
11879       // FIXME: Consider using our bit_cast implementation to support this.
11880       Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
11881           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
11882           << CharTy1 << CharTy2;
11883       return false;
11884     }
11885 
11886     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
11887       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
11888              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
11889              Char1.isInt() && Char2.isInt();
11890     };
11891     const auto &AdvanceElems = [&] {
11892       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
11893              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
11894     };
11895 
11896     bool StopAtNull =
11897         (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
11898          BuiltinOp != Builtin::BIwmemcmp &&
11899          BuiltinOp != Builtin::BI__builtin_memcmp &&
11900          BuiltinOp != Builtin::BI__builtin_bcmp &&
11901          BuiltinOp != Builtin::BI__builtin_wmemcmp);
11902     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
11903                   BuiltinOp == Builtin::BIwcsncmp ||
11904                   BuiltinOp == Builtin::BIwmemcmp ||
11905                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
11906                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
11907                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
11908 
11909     for (; MaxLength; --MaxLength) {
11910       APValue Char1, Char2;
11911       if (!ReadCurElems(Char1, Char2))
11912         return false;
11913       if (Char1.getInt().ne(Char2.getInt())) {
11914         if (IsWide) // wmemcmp compares with wchar_t signedness.
11915           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
11916         // memcmp always compares unsigned chars.
11917         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
11918       }
11919       if (StopAtNull && !Char1.getInt())
11920         return Success(0, E);
11921       assert(!(StopAtNull && !Char2.getInt()));
11922       if (!AdvanceElems())
11923         return false;
11924     }
11925     // We hit the strncmp / memcmp limit.
11926     return Success(0, E);
11927   }
11928 
11929   case Builtin::BI__atomic_always_lock_free:
11930   case Builtin::BI__atomic_is_lock_free:
11931   case Builtin::BI__c11_atomic_is_lock_free: {
11932     APSInt SizeVal;
11933     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
11934       return false;
11935 
11936     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
11937     // of two less than or equal to the maximum inline atomic width, we know it
11938     // is lock-free.  If the size isn't a power of two, or greater than the
11939     // maximum alignment where we promote atomics, we know it is not lock-free
11940     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
11941     // the answer can only be determined at runtime; for example, 16-byte
11942     // atomics have lock-free implementations on some, but not all,
11943     // x86-64 processors.
11944 
11945     // Check power-of-two.
11946     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
11947     if (Size.isPowerOfTwo()) {
11948       // Check against inlining width.
11949       unsigned InlineWidthBits =
11950           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
11951       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
11952         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
11953             Size == CharUnits::One() ||
11954             E->getArg(1)->isNullPointerConstant(Info.Ctx,
11955                                                 Expr::NPC_NeverValueDependent))
11956           // OK, we will inline appropriately-aligned operations of this size,
11957           // and _Atomic(T) is appropriately-aligned.
11958           return Success(1, E);
11959 
11960         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
11961           castAs<PointerType>()->getPointeeType();
11962         if (!PointeeType->isIncompleteType() &&
11963             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
11964           // OK, we will inline operations on this object.
11965           return Success(1, E);
11966         }
11967       }
11968     }
11969 
11970     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
11971         Success(0, E) : Error(E);
11972   }
11973   case Builtin::BIomp_is_initial_device:
11974     // We can decide statically which value the runtime would return if called.
11975     return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
11976   case Builtin::BI__builtin_add_overflow:
11977   case Builtin::BI__builtin_sub_overflow:
11978   case Builtin::BI__builtin_mul_overflow:
11979   case Builtin::BI__builtin_sadd_overflow:
11980   case Builtin::BI__builtin_uadd_overflow:
11981   case Builtin::BI__builtin_uaddl_overflow:
11982   case Builtin::BI__builtin_uaddll_overflow:
11983   case Builtin::BI__builtin_usub_overflow:
11984   case Builtin::BI__builtin_usubl_overflow:
11985   case Builtin::BI__builtin_usubll_overflow:
11986   case Builtin::BI__builtin_umul_overflow:
11987   case Builtin::BI__builtin_umull_overflow:
11988   case Builtin::BI__builtin_umulll_overflow:
11989   case Builtin::BI__builtin_saddl_overflow:
11990   case Builtin::BI__builtin_saddll_overflow:
11991   case Builtin::BI__builtin_ssub_overflow:
11992   case Builtin::BI__builtin_ssubl_overflow:
11993   case Builtin::BI__builtin_ssubll_overflow:
11994   case Builtin::BI__builtin_smul_overflow:
11995   case Builtin::BI__builtin_smull_overflow:
11996   case Builtin::BI__builtin_smulll_overflow: {
11997     LValue ResultLValue;
11998     APSInt LHS, RHS;
11999 
12000     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
12001     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
12002         !EvaluateInteger(E->getArg(1), RHS, Info) ||
12003         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
12004       return false;
12005 
12006     APSInt Result;
12007     bool DidOverflow = false;
12008 
12009     // If the types don't have to match, enlarge all 3 to the largest of them.
12010     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12011         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12012         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12013       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
12014                       ResultType->isSignedIntegerOrEnumerationType();
12015       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
12016                       ResultType->isSignedIntegerOrEnumerationType();
12017       uint64_t LHSSize = LHS.getBitWidth();
12018       uint64_t RHSSize = RHS.getBitWidth();
12019       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
12020       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
12021 
12022       // Add an additional bit if the signedness isn't uniformly agreed to. We
12023       // could do this ONLY if there is a signed and an unsigned that both have
12024       // MaxBits, but the code to check that is pretty nasty.  The issue will be
12025       // caught in the shrink-to-result later anyway.
12026       if (IsSigned && !AllSigned)
12027         ++MaxBits;
12028 
12029       LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
12030       RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
12031       Result = APSInt(MaxBits, !IsSigned);
12032     }
12033 
12034     // Find largest int.
12035     switch (BuiltinOp) {
12036     default:
12037       llvm_unreachable("Invalid value for BuiltinOp");
12038     case Builtin::BI__builtin_add_overflow:
12039     case Builtin::BI__builtin_sadd_overflow:
12040     case Builtin::BI__builtin_saddl_overflow:
12041     case Builtin::BI__builtin_saddll_overflow:
12042     case Builtin::BI__builtin_uadd_overflow:
12043     case Builtin::BI__builtin_uaddl_overflow:
12044     case Builtin::BI__builtin_uaddll_overflow:
12045       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
12046                               : LHS.uadd_ov(RHS, DidOverflow);
12047       break;
12048     case Builtin::BI__builtin_sub_overflow:
12049     case Builtin::BI__builtin_ssub_overflow:
12050     case Builtin::BI__builtin_ssubl_overflow:
12051     case Builtin::BI__builtin_ssubll_overflow:
12052     case Builtin::BI__builtin_usub_overflow:
12053     case Builtin::BI__builtin_usubl_overflow:
12054     case Builtin::BI__builtin_usubll_overflow:
12055       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
12056                               : LHS.usub_ov(RHS, DidOverflow);
12057       break;
12058     case Builtin::BI__builtin_mul_overflow:
12059     case Builtin::BI__builtin_smul_overflow:
12060     case Builtin::BI__builtin_smull_overflow:
12061     case Builtin::BI__builtin_smulll_overflow:
12062     case Builtin::BI__builtin_umul_overflow:
12063     case Builtin::BI__builtin_umull_overflow:
12064     case Builtin::BI__builtin_umulll_overflow:
12065       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
12066                               : LHS.umul_ov(RHS, DidOverflow);
12067       break;
12068     }
12069 
12070     // In the case where multiple sizes are allowed, truncate and see if
12071     // the values are the same.
12072     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12073         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12074         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12075       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
12076       // since it will give us the behavior of a TruncOrSelf in the case where
12077       // its parameter <= its size.  We previously set Result to be at least the
12078       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
12079       // will work exactly like TruncOrSelf.
12080       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
12081       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
12082 
12083       if (!APSInt::isSameValue(Temp, Result))
12084         DidOverflow = true;
12085       Result = Temp;
12086     }
12087 
12088     APValue APV{Result};
12089     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
12090       return false;
12091     return Success(DidOverflow, E);
12092   }
12093   }
12094 }
12095 
12096 /// Determine whether this is a pointer past the end of the complete
12097 /// object referred to by the lvalue.
12098 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
12099                                             const LValue &LV) {
12100   // A null pointer can be viewed as being "past the end" but we don't
12101   // choose to look at it that way here.
12102   if (!LV.getLValueBase())
12103     return false;
12104 
12105   // If the designator is valid and refers to a subobject, we're not pointing
12106   // past the end.
12107   if (!LV.getLValueDesignator().Invalid &&
12108       !LV.getLValueDesignator().isOnePastTheEnd())
12109     return false;
12110 
12111   // A pointer to an incomplete type might be past-the-end if the type's size is
12112   // zero.  We cannot tell because the type is incomplete.
12113   QualType Ty = getType(LV.getLValueBase());
12114   if (Ty->isIncompleteType())
12115     return true;
12116 
12117   // We're a past-the-end pointer if we point to the byte after the object,
12118   // no matter what our type or path is.
12119   auto Size = Ctx.getTypeSizeInChars(Ty);
12120   return LV.getLValueOffset() == Size;
12121 }
12122 
12123 namespace {
12124 
12125 /// Data recursive integer evaluator of certain binary operators.
12126 ///
12127 /// We use a data recursive algorithm for binary operators so that we are able
12128 /// to handle extreme cases of chained binary operators without causing stack
12129 /// overflow.
12130 class DataRecursiveIntBinOpEvaluator {
12131   struct EvalResult {
12132     APValue Val;
12133     bool Failed;
12134 
12135     EvalResult() : Failed(false) { }
12136 
12137     void swap(EvalResult &RHS) {
12138       Val.swap(RHS.Val);
12139       Failed = RHS.Failed;
12140       RHS.Failed = false;
12141     }
12142   };
12143 
12144   struct Job {
12145     const Expr *E;
12146     EvalResult LHSResult; // meaningful only for binary operator expression.
12147     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
12148 
12149     Job() = default;
12150     Job(Job &&) = default;
12151 
12152     void startSpeculativeEval(EvalInfo &Info) {
12153       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
12154     }
12155 
12156   private:
12157     SpeculativeEvaluationRAII SpecEvalRAII;
12158   };
12159 
12160   SmallVector<Job, 16> Queue;
12161 
12162   IntExprEvaluator &IntEval;
12163   EvalInfo &Info;
12164   APValue &FinalResult;
12165 
12166 public:
12167   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
12168     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
12169 
12170   /// True if \param E is a binary operator that we are going to handle
12171   /// data recursively.
12172   /// We handle binary operators that are comma, logical, or that have operands
12173   /// with integral or enumeration type.
12174   static bool shouldEnqueue(const BinaryOperator *E) {
12175     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
12176            (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
12177             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12178             E->getRHS()->getType()->isIntegralOrEnumerationType());
12179   }
12180 
12181   bool Traverse(const BinaryOperator *E) {
12182     enqueue(E);
12183     EvalResult PrevResult;
12184     while (!Queue.empty())
12185       process(PrevResult);
12186 
12187     if (PrevResult.Failed) return false;
12188 
12189     FinalResult.swap(PrevResult.Val);
12190     return true;
12191   }
12192 
12193 private:
12194   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
12195     return IntEval.Success(Value, E, Result);
12196   }
12197   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
12198     return IntEval.Success(Value, E, Result);
12199   }
12200   bool Error(const Expr *E) {
12201     return IntEval.Error(E);
12202   }
12203   bool Error(const Expr *E, diag::kind D) {
12204     return IntEval.Error(E, D);
12205   }
12206 
12207   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
12208     return Info.CCEDiag(E, D);
12209   }
12210 
12211   // Returns true if visiting the RHS is necessary, false otherwise.
12212   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12213                          bool &SuppressRHSDiags);
12214 
12215   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12216                   const BinaryOperator *E, APValue &Result);
12217 
12218   void EvaluateExpr(const Expr *E, EvalResult &Result) {
12219     Result.Failed = !Evaluate(Result.Val, Info, E);
12220     if (Result.Failed)
12221       Result.Val = APValue();
12222   }
12223 
12224   void process(EvalResult &Result);
12225 
12226   void enqueue(const Expr *E) {
12227     E = E->IgnoreParens();
12228     Queue.resize(Queue.size()+1);
12229     Queue.back().E = E;
12230     Queue.back().Kind = Job::AnyExprKind;
12231   }
12232 };
12233 
12234 }
12235 
12236 bool DataRecursiveIntBinOpEvaluator::
12237        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12238                          bool &SuppressRHSDiags) {
12239   if (E->getOpcode() == BO_Comma) {
12240     // Ignore LHS but note if we could not evaluate it.
12241     if (LHSResult.Failed)
12242       return Info.noteSideEffect();
12243     return true;
12244   }
12245 
12246   if (E->isLogicalOp()) {
12247     bool LHSAsBool;
12248     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
12249       // We were able to evaluate the LHS, see if we can get away with not
12250       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
12251       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
12252         Success(LHSAsBool, E, LHSResult.Val);
12253         return false; // Ignore RHS
12254       }
12255     } else {
12256       LHSResult.Failed = true;
12257 
12258       // Since we weren't able to evaluate the left hand side, it
12259       // might have had side effects.
12260       if (!Info.noteSideEffect())
12261         return false;
12262 
12263       // We can't evaluate the LHS; however, sometimes the result
12264       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12265       // Don't ignore RHS and suppress diagnostics from this arm.
12266       SuppressRHSDiags = true;
12267     }
12268 
12269     return true;
12270   }
12271 
12272   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12273          E->getRHS()->getType()->isIntegralOrEnumerationType());
12274 
12275   if (LHSResult.Failed && !Info.noteFailure())
12276     return false; // Ignore RHS;
12277 
12278   return true;
12279 }
12280 
12281 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
12282                                     bool IsSub) {
12283   // Compute the new offset in the appropriate width, wrapping at 64 bits.
12284   // FIXME: When compiling for a 32-bit target, we should use 32-bit
12285   // offsets.
12286   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
12287   CharUnits &Offset = LVal.getLValueOffset();
12288   uint64_t Offset64 = Offset.getQuantity();
12289   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
12290   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
12291                                          : Offset64 + Index64);
12292 }
12293 
12294 bool DataRecursiveIntBinOpEvaluator::
12295        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12296                   const BinaryOperator *E, APValue &Result) {
12297   if (E->getOpcode() == BO_Comma) {
12298     if (RHSResult.Failed)
12299       return false;
12300     Result = RHSResult.Val;
12301     return true;
12302   }
12303 
12304   if (E->isLogicalOp()) {
12305     bool lhsResult, rhsResult;
12306     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
12307     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
12308 
12309     if (LHSIsOK) {
12310       if (RHSIsOK) {
12311         if (E->getOpcode() == BO_LOr)
12312           return Success(lhsResult || rhsResult, E, Result);
12313         else
12314           return Success(lhsResult && rhsResult, E, Result);
12315       }
12316     } else {
12317       if (RHSIsOK) {
12318         // We can't evaluate the LHS; however, sometimes the result
12319         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12320         if (rhsResult == (E->getOpcode() == BO_LOr))
12321           return Success(rhsResult, E, Result);
12322       }
12323     }
12324 
12325     return false;
12326   }
12327 
12328   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12329          E->getRHS()->getType()->isIntegralOrEnumerationType());
12330 
12331   if (LHSResult.Failed || RHSResult.Failed)
12332     return false;
12333 
12334   const APValue &LHSVal = LHSResult.Val;
12335   const APValue &RHSVal = RHSResult.Val;
12336 
12337   // Handle cases like (unsigned long)&a + 4.
12338   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
12339     Result = LHSVal;
12340     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
12341     return true;
12342   }
12343 
12344   // Handle cases like 4 + (unsigned long)&a
12345   if (E->getOpcode() == BO_Add &&
12346       RHSVal.isLValue() && LHSVal.isInt()) {
12347     Result = RHSVal;
12348     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
12349     return true;
12350   }
12351 
12352   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
12353     // Handle (intptr_t)&&A - (intptr_t)&&B.
12354     if (!LHSVal.getLValueOffset().isZero() ||
12355         !RHSVal.getLValueOffset().isZero())
12356       return false;
12357     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
12358     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
12359     if (!LHSExpr || !RHSExpr)
12360       return false;
12361     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12362     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12363     if (!LHSAddrExpr || !RHSAddrExpr)
12364       return false;
12365     // Make sure both labels come from the same function.
12366     if (LHSAddrExpr->getLabel()->getDeclContext() !=
12367         RHSAddrExpr->getLabel()->getDeclContext())
12368       return false;
12369     Result = APValue(LHSAddrExpr, RHSAddrExpr);
12370     return true;
12371   }
12372 
12373   // All the remaining cases expect both operands to be an integer
12374   if (!LHSVal.isInt() || !RHSVal.isInt())
12375     return Error(E);
12376 
12377   // Set up the width and signedness manually, in case it can't be deduced
12378   // from the operation we're performing.
12379   // FIXME: Don't do this in the cases where we can deduce it.
12380   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
12381                E->getType()->isUnsignedIntegerOrEnumerationType());
12382   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
12383                          RHSVal.getInt(), Value))
12384     return false;
12385   return Success(Value, E, Result);
12386 }
12387 
12388 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
12389   Job &job = Queue.back();
12390 
12391   switch (job.Kind) {
12392     case Job::AnyExprKind: {
12393       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
12394         if (shouldEnqueue(Bop)) {
12395           job.Kind = Job::BinOpKind;
12396           enqueue(Bop->getLHS());
12397           return;
12398         }
12399       }
12400 
12401       EvaluateExpr(job.E, Result);
12402       Queue.pop_back();
12403       return;
12404     }
12405 
12406     case Job::BinOpKind: {
12407       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12408       bool SuppressRHSDiags = false;
12409       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
12410         Queue.pop_back();
12411         return;
12412       }
12413       if (SuppressRHSDiags)
12414         job.startSpeculativeEval(Info);
12415       job.LHSResult.swap(Result);
12416       job.Kind = Job::BinOpVisitedLHSKind;
12417       enqueue(Bop->getRHS());
12418       return;
12419     }
12420 
12421     case Job::BinOpVisitedLHSKind: {
12422       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12423       EvalResult RHS;
12424       RHS.swap(Result);
12425       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
12426       Queue.pop_back();
12427       return;
12428     }
12429   }
12430 
12431   llvm_unreachable("Invalid Job::Kind!");
12432 }
12433 
12434 namespace {
12435 /// Used when we determine that we should fail, but can keep evaluating prior to
12436 /// noting that we had a failure.
12437 class DelayedNoteFailureRAII {
12438   EvalInfo &Info;
12439   bool NoteFailure;
12440 
12441 public:
12442   DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
12443       : Info(Info), NoteFailure(NoteFailure) {}
12444   ~DelayedNoteFailureRAII() {
12445     if (NoteFailure) {
12446       bool ContinueAfterFailure = Info.noteFailure();
12447       (void)ContinueAfterFailure;
12448       assert(ContinueAfterFailure &&
12449              "Shouldn't have kept evaluating on failure.");
12450     }
12451   }
12452 };
12453 
12454 enum class CmpResult {
12455   Unequal,
12456   Less,
12457   Equal,
12458   Greater,
12459   Unordered,
12460 };
12461 }
12462 
12463 template <class SuccessCB, class AfterCB>
12464 static bool
12465 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
12466                                  SuccessCB &&Success, AfterCB &&DoAfter) {
12467   assert(E->isComparisonOp() && "expected comparison operator");
12468   assert((E->getOpcode() == BO_Cmp ||
12469           E->getType()->isIntegralOrEnumerationType()) &&
12470          "unsupported binary expression evaluation");
12471   auto Error = [&](const Expr *E) {
12472     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12473     return false;
12474   };
12475 
12476   bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
12477   bool IsEquality = E->isEqualityOp();
12478 
12479   QualType LHSTy = E->getLHS()->getType();
12480   QualType RHSTy = E->getRHS()->getType();
12481 
12482   if (LHSTy->isIntegralOrEnumerationType() &&
12483       RHSTy->isIntegralOrEnumerationType()) {
12484     APSInt LHS, RHS;
12485     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
12486     if (!LHSOK && !Info.noteFailure())
12487       return false;
12488     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
12489       return false;
12490     if (LHS < RHS)
12491       return Success(CmpResult::Less, E);
12492     if (LHS > RHS)
12493       return Success(CmpResult::Greater, E);
12494     return Success(CmpResult::Equal, E);
12495   }
12496 
12497   if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
12498     APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
12499     APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
12500 
12501     bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
12502     if (!LHSOK && !Info.noteFailure())
12503       return false;
12504     if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
12505       return false;
12506     if (LHSFX < RHSFX)
12507       return Success(CmpResult::Less, E);
12508     if (LHSFX > RHSFX)
12509       return Success(CmpResult::Greater, E);
12510     return Success(CmpResult::Equal, E);
12511   }
12512 
12513   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
12514     ComplexValue LHS, RHS;
12515     bool LHSOK;
12516     if (E->isAssignmentOp()) {
12517       LValue LV;
12518       EvaluateLValue(E->getLHS(), LV, Info);
12519       LHSOK = false;
12520     } else if (LHSTy->isRealFloatingType()) {
12521       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
12522       if (LHSOK) {
12523         LHS.makeComplexFloat();
12524         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
12525       }
12526     } else {
12527       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
12528     }
12529     if (!LHSOK && !Info.noteFailure())
12530       return false;
12531 
12532     if (E->getRHS()->getType()->isRealFloatingType()) {
12533       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
12534         return false;
12535       RHS.makeComplexFloat();
12536       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
12537     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
12538       return false;
12539 
12540     if (LHS.isComplexFloat()) {
12541       APFloat::cmpResult CR_r =
12542         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
12543       APFloat::cmpResult CR_i =
12544         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
12545       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
12546       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12547     } else {
12548       assert(IsEquality && "invalid complex comparison");
12549       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
12550                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
12551       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12552     }
12553   }
12554 
12555   if (LHSTy->isRealFloatingType() &&
12556       RHSTy->isRealFloatingType()) {
12557     APFloat RHS(0.0), LHS(0.0);
12558 
12559     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
12560     if (!LHSOK && !Info.noteFailure())
12561       return false;
12562 
12563     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
12564       return false;
12565 
12566     assert(E->isComparisonOp() && "Invalid binary operator!");
12567     llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
12568     if (!Info.InConstantContext &&
12569         APFloatCmpResult == APFloat::cmpUnordered &&
12570         E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
12571       // Note: Compares may raise invalid in some cases involving NaN or sNaN.
12572       Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
12573       return false;
12574     }
12575     auto GetCmpRes = [&]() {
12576       switch (APFloatCmpResult) {
12577       case APFloat::cmpEqual:
12578         return CmpResult::Equal;
12579       case APFloat::cmpLessThan:
12580         return CmpResult::Less;
12581       case APFloat::cmpGreaterThan:
12582         return CmpResult::Greater;
12583       case APFloat::cmpUnordered:
12584         return CmpResult::Unordered;
12585       }
12586       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
12587     };
12588     return Success(GetCmpRes(), E);
12589   }
12590 
12591   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
12592     LValue LHSValue, RHSValue;
12593 
12594     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12595     if (!LHSOK && !Info.noteFailure())
12596       return false;
12597 
12598     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12599       return false;
12600 
12601     // Reject differing bases from the normal codepath; we special-case
12602     // comparisons to null.
12603     if (!HasSameBase(LHSValue, RHSValue)) {
12604       // Inequalities and subtractions between unrelated pointers have
12605       // unspecified or undefined behavior.
12606       if (!IsEquality) {
12607         Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified);
12608         return false;
12609       }
12610       // A constant address may compare equal to the address of a symbol.
12611       // The one exception is that address of an object cannot compare equal
12612       // to a null pointer constant.
12613       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
12614           (!RHSValue.Base && !RHSValue.Offset.isZero()))
12615         return Error(E);
12616       // It's implementation-defined whether distinct literals will have
12617       // distinct addresses. In clang, the result of such a comparison is
12618       // unspecified, so it is not a constant expression. However, we do know
12619       // that the address of a literal will be non-null.
12620       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
12621           LHSValue.Base && RHSValue.Base)
12622         return Error(E);
12623       // We can't tell whether weak symbols will end up pointing to the same
12624       // object.
12625       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
12626         return Error(E);
12627       // We can't compare the address of the start of one object with the
12628       // past-the-end address of another object, per C++ DR1652.
12629       if ((LHSValue.Base && LHSValue.Offset.isZero() &&
12630            isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
12631           (RHSValue.Base && RHSValue.Offset.isZero() &&
12632            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
12633         return Error(E);
12634       // We can't tell whether an object is at the same address as another
12635       // zero sized object.
12636       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
12637           (LHSValue.Base && isZeroSized(RHSValue)))
12638         return Error(E);
12639       return Success(CmpResult::Unequal, E);
12640     }
12641 
12642     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12643     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12644 
12645     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12646     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12647 
12648     // C++11 [expr.rel]p3:
12649     //   Pointers to void (after pointer conversions) can be compared, with a
12650     //   result defined as follows: If both pointers represent the same
12651     //   address or are both the null pointer value, the result is true if the
12652     //   operator is <= or >= and false otherwise; otherwise the result is
12653     //   unspecified.
12654     // We interpret this as applying to pointers to *cv* void.
12655     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
12656       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
12657 
12658     // C++11 [expr.rel]p2:
12659     // - If two pointers point to non-static data members of the same object,
12660     //   or to subobjects or array elements fo such members, recursively, the
12661     //   pointer to the later declared member compares greater provided the
12662     //   two members have the same access control and provided their class is
12663     //   not a union.
12664     //   [...]
12665     // - Otherwise pointer comparisons are unspecified.
12666     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
12667       bool WasArrayIndex;
12668       unsigned Mismatch = FindDesignatorMismatch(
12669           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
12670       // At the point where the designators diverge, the comparison has a
12671       // specified value if:
12672       //  - we are comparing array indices
12673       //  - we are comparing fields of a union, or fields with the same access
12674       // Otherwise, the result is unspecified and thus the comparison is not a
12675       // constant expression.
12676       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
12677           Mismatch < RHSDesignator.Entries.size()) {
12678         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
12679         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
12680         if (!LF && !RF)
12681           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
12682         else if (!LF)
12683           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12684               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
12685               << RF->getParent() << RF;
12686         else if (!RF)
12687           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12688               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
12689               << LF->getParent() << LF;
12690         else if (!LF->getParent()->isUnion() &&
12691                  LF->getAccess() != RF->getAccess())
12692           Info.CCEDiag(E,
12693                        diag::note_constexpr_pointer_comparison_differing_access)
12694               << LF << LF->getAccess() << RF << RF->getAccess()
12695               << LF->getParent();
12696       }
12697     }
12698 
12699     // The comparison here must be unsigned, and performed with the same
12700     // width as the pointer.
12701     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
12702     uint64_t CompareLHS = LHSOffset.getQuantity();
12703     uint64_t CompareRHS = RHSOffset.getQuantity();
12704     assert(PtrSize <= 64 && "Unexpected pointer width");
12705     uint64_t Mask = ~0ULL >> (64 - PtrSize);
12706     CompareLHS &= Mask;
12707     CompareRHS &= Mask;
12708 
12709     // If there is a base and this is a relational operator, we can only
12710     // compare pointers within the object in question; otherwise, the result
12711     // depends on where the object is located in memory.
12712     if (!LHSValue.Base.isNull() && IsRelational) {
12713       QualType BaseTy = getType(LHSValue.Base);
12714       if (BaseTy->isIncompleteType())
12715         return Error(E);
12716       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
12717       uint64_t OffsetLimit = Size.getQuantity();
12718       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
12719         return Error(E);
12720     }
12721 
12722     if (CompareLHS < CompareRHS)
12723       return Success(CmpResult::Less, E);
12724     if (CompareLHS > CompareRHS)
12725       return Success(CmpResult::Greater, E);
12726     return Success(CmpResult::Equal, E);
12727   }
12728 
12729   if (LHSTy->isMemberPointerType()) {
12730     assert(IsEquality && "unexpected member pointer operation");
12731     assert(RHSTy->isMemberPointerType() && "invalid comparison");
12732 
12733     MemberPtr LHSValue, RHSValue;
12734 
12735     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
12736     if (!LHSOK && !Info.noteFailure())
12737       return false;
12738 
12739     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12740       return false;
12741 
12742     // C++11 [expr.eq]p2:
12743     //   If both operands are null, they compare equal. Otherwise if only one is
12744     //   null, they compare unequal.
12745     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
12746       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
12747       return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12748     }
12749 
12750     //   Otherwise if either is a pointer to a virtual member function, the
12751     //   result is unspecified.
12752     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
12753       if (MD->isVirtual())
12754         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12755     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
12756       if (MD->isVirtual())
12757         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12758 
12759     //   Otherwise they compare equal if and only if they would refer to the
12760     //   same member of the same most derived object or the same subobject if
12761     //   they were dereferenced with a hypothetical object of the associated
12762     //   class type.
12763     bool Equal = LHSValue == RHSValue;
12764     return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12765   }
12766 
12767   if (LHSTy->isNullPtrType()) {
12768     assert(E->isComparisonOp() && "unexpected nullptr operation");
12769     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
12770     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
12771     // are compared, the result is true of the operator is <=, >= or ==, and
12772     // false otherwise.
12773     return Success(CmpResult::Equal, E);
12774   }
12775 
12776   return DoAfter();
12777 }
12778 
12779 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
12780   if (!CheckLiteralType(Info, E))
12781     return false;
12782 
12783   auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12784     ComparisonCategoryResult CCR;
12785     switch (CR) {
12786     case CmpResult::Unequal:
12787       llvm_unreachable("should never produce Unequal for three-way comparison");
12788     case CmpResult::Less:
12789       CCR = ComparisonCategoryResult::Less;
12790       break;
12791     case CmpResult::Equal:
12792       CCR = ComparisonCategoryResult::Equal;
12793       break;
12794     case CmpResult::Greater:
12795       CCR = ComparisonCategoryResult::Greater;
12796       break;
12797     case CmpResult::Unordered:
12798       CCR = ComparisonCategoryResult::Unordered;
12799       break;
12800     }
12801     // Evaluation succeeded. Lookup the information for the comparison category
12802     // type and fetch the VarDecl for the result.
12803     const ComparisonCategoryInfo &CmpInfo =
12804         Info.Ctx.CompCategories.getInfoForType(E->getType());
12805     const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
12806     // Check and evaluate the result as a constant expression.
12807     LValue LV;
12808     LV.set(VD);
12809     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
12810       return false;
12811     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
12812                                    ConstantExprKind::Normal);
12813   };
12814   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12815     return ExprEvaluatorBaseTy::VisitBinCmp(E);
12816   });
12817 }
12818 
12819 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12820   // We don't call noteFailure immediately because the assignment happens after
12821   // we evaluate LHS and RHS.
12822   if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
12823     return Error(E);
12824 
12825   DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
12826   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
12827     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
12828 
12829   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
12830           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
12831          "DataRecursiveIntBinOpEvaluator should have handled integral types");
12832 
12833   if (E->isComparisonOp()) {
12834     // Evaluate builtin binary comparisons by evaluating them as three-way
12835     // comparisons and then translating the result.
12836     auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12837       assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
12838              "should only produce Unequal for equality comparisons");
12839       bool IsEqual   = CR == CmpResult::Equal,
12840            IsLess    = CR == CmpResult::Less,
12841            IsGreater = CR == CmpResult::Greater;
12842       auto Op = E->getOpcode();
12843       switch (Op) {
12844       default:
12845         llvm_unreachable("unsupported binary operator");
12846       case BO_EQ:
12847       case BO_NE:
12848         return Success(IsEqual == (Op == BO_EQ), E);
12849       case BO_LT:
12850         return Success(IsLess, E);
12851       case BO_GT:
12852         return Success(IsGreater, E);
12853       case BO_LE:
12854         return Success(IsEqual || IsLess, E);
12855       case BO_GE:
12856         return Success(IsEqual || IsGreater, E);
12857       }
12858     };
12859     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12860       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12861     });
12862   }
12863 
12864   QualType LHSTy = E->getLHS()->getType();
12865   QualType RHSTy = E->getRHS()->getType();
12866 
12867   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
12868       E->getOpcode() == BO_Sub) {
12869     LValue LHSValue, RHSValue;
12870 
12871     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12872     if (!LHSOK && !Info.noteFailure())
12873       return false;
12874 
12875     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12876       return false;
12877 
12878     // Reject differing bases from the normal codepath; we special-case
12879     // comparisons to null.
12880     if (!HasSameBase(LHSValue, RHSValue)) {
12881       // Handle &&A - &&B.
12882       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
12883         return Error(E);
12884       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
12885       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
12886       if (!LHSExpr || !RHSExpr)
12887         return Error(E);
12888       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12889       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12890       if (!LHSAddrExpr || !RHSAddrExpr)
12891         return Error(E);
12892       // Make sure both labels come from the same function.
12893       if (LHSAddrExpr->getLabel()->getDeclContext() !=
12894           RHSAddrExpr->getLabel()->getDeclContext())
12895         return Error(E);
12896       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
12897     }
12898     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12899     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12900 
12901     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12902     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12903 
12904     // C++11 [expr.add]p6:
12905     //   Unless both pointers point to elements of the same array object, or
12906     //   one past the last element of the array object, the behavior is
12907     //   undefined.
12908     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
12909         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
12910                                 RHSDesignator))
12911       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
12912 
12913     QualType Type = E->getLHS()->getType();
12914     QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
12915 
12916     CharUnits ElementSize;
12917     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
12918       return false;
12919 
12920     // As an extension, a type may have zero size (empty struct or union in
12921     // C, array of zero length). Pointer subtraction in such cases has
12922     // undefined behavior, so is not constant.
12923     if (ElementSize.isZero()) {
12924       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
12925           << ElementType;
12926       return false;
12927     }
12928 
12929     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
12930     // and produce incorrect results when it overflows. Such behavior
12931     // appears to be non-conforming, but is common, so perhaps we should
12932     // assume the standard intended for such cases to be undefined behavior
12933     // and check for them.
12934 
12935     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
12936     // overflow in the final conversion to ptrdiff_t.
12937     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
12938     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
12939     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
12940                     false);
12941     APSInt TrueResult = (LHS - RHS) / ElemSize;
12942     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
12943 
12944     if (Result.extend(65) != TrueResult &&
12945         !HandleOverflow(Info, E, TrueResult, E->getType()))
12946       return false;
12947     return Success(Result, E);
12948   }
12949 
12950   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12951 }
12952 
12953 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
12954 /// a result as the expression's type.
12955 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
12956                                     const UnaryExprOrTypeTraitExpr *E) {
12957   switch(E->getKind()) {
12958   case UETT_PreferredAlignOf:
12959   case UETT_AlignOf: {
12960     if (E->isArgumentType())
12961       return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
12962                      E);
12963     else
12964       return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
12965                      E);
12966   }
12967 
12968   case UETT_VecStep: {
12969     QualType Ty = E->getTypeOfArgument();
12970 
12971     if (Ty->isVectorType()) {
12972       unsigned n = Ty->castAs<VectorType>()->getNumElements();
12973 
12974       // The vec_step built-in functions that take a 3-component
12975       // vector return 4. (OpenCL 1.1 spec 6.11.12)
12976       if (n == 3)
12977         n = 4;
12978 
12979       return Success(n, E);
12980     } else
12981       return Success(1, E);
12982   }
12983 
12984   case UETT_SizeOf: {
12985     QualType SrcTy = E->getTypeOfArgument();
12986     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
12987     //   the result is the size of the referenced type."
12988     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
12989       SrcTy = Ref->getPointeeType();
12990 
12991     CharUnits Sizeof;
12992     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
12993       return false;
12994     return Success(Sizeof, E);
12995   }
12996   case UETT_OpenMPRequiredSimdAlign:
12997     assert(E->isArgumentType());
12998     return Success(
12999         Info.Ctx.toCharUnitsFromBits(
13000                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
13001             .getQuantity(),
13002         E);
13003   }
13004 
13005   llvm_unreachable("unknown expr/type trait");
13006 }
13007 
13008 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
13009   CharUnits Result;
13010   unsigned n = OOE->getNumComponents();
13011   if (n == 0)
13012     return Error(OOE);
13013   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
13014   for (unsigned i = 0; i != n; ++i) {
13015     OffsetOfNode ON = OOE->getComponent(i);
13016     switch (ON.getKind()) {
13017     case OffsetOfNode::Array: {
13018       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
13019       APSInt IdxResult;
13020       if (!EvaluateInteger(Idx, IdxResult, Info))
13021         return false;
13022       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
13023       if (!AT)
13024         return Error(OOE);
13025       CurrentType = AT->getElementType();
13026       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
13027       Result += IdxResult.getSExtValue() * ElementSize;
13028       break;
13029     }
13030 
13031     case OffsetOfNode::Field: {
13032       FieldDecl *MemberDecl = ON.getField();
13033       const RecordType *RT = CurrentType->getAs<RecordType>();
13034       if (!RT)
13035         return Error(OOE);
13036       RecordDecl *RD = RT->getDecl();
13037       if (RD->isInvalidDecl()) return false;
13038       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13039       unsigned i = MemberDecl->getFieldIndex();
13040       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
13041       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
13042       CurrentType = MemberDecl->getType().getNonReferenceType();
13043       break;
13044     }
13045 
13046     case OffsetOfNode::Identifier:
13047       llvm_unreachable("dependent __builtin_offsetof");
13048 
13049     case OffsetOfNode::Base: {
13050       CXXBaseSpecifier *BaseSpec = ON.getBase();
13051       if (BaseSpec->isVirtual())
13052         return Error(OOE);
13053 
13054       // Find the layout of the class whose base we are looking into.
13055       const RecordType *RT = CurrentType->getAs<RecordType>();
13056       if (!RT)
13057         return Error(OOE);
13058       RecordDecl *RD = RT->getDecl();
13059       if (RD->isInvalidDecl()) return false;
13060       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13061 
13062       // Find the base class itself.
13063       CurrentType = BaseSpec->getType();
13064       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
13065       if (!BaseRT)
13066         return Error(OOE);
13067 
13068       // Add the offset to the base.
13069       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
13070       break;
13071     }
13072     }
13073   }
13074   return Success(Result, OOE);
13075 }
13076 
13077 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13078   switch (E->getOpcode()) {
13079   default:
13080     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
13081     // See C99 6.6p3.
13082     return Error(E);
13083   case UO_Extension:
13084     // FIXME: Should extension allow i-c-e extension expressions in its scope?
13085     // If so, we could clear the diagnostic ID.
13086     return Visit(E->getSubExpr());
13087   case UO_Plus:
13088     // The result is just the value.
13089     return Visit(E->getSubExpr());
13090   case UO_Minus: {
13091     if (!Visit(E->getSubExpr()))
13092       return false;
13093     if (!Result.isInt()) return Error(E);
13094     const APSInt &Value = Result.getInt();
13095     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
13096         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
13097                         E->getType()))
13098       return false;
13099     return Success(-Value, E);
13100   }
13101   case UO_Not: {
13102     if (!Visit(E->getSubExpr()))
13103       return false;
13104     if (!Result.isInt()) return Error(E);
13105     return Success(~Result.getInt(), E);
13106   }
13107   case UO_LNot: {
13108     bool bres;
13109     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13110       return false;
13111     return Success(!bres, E);
13112   }
13113   }
13114 }
13115 
13116 /// HandleCast - This is used to evaluate implicit or explicit casts where the
13117 /// result type is integer.
13118 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
13119   const Expr *SubExpr = E->getSubExpr();
13120   QualType DestType = E->getType();
13121   QualType SrcType = SubExpr->getType();
13122 
13123   switch (E->getCastKind()) {
13124   case CK_BaseToDerived:
13125   case CK_DerivedToBase:
13126   case CK_UncheckedDerivedToBase:
13127   case CK_Dynamic:
13128   case CK_ToUnion:
13129   case CK_ArrayToPointerDecay:
13130   case CK_FunctionToPointerDecay:
13131   case CK_NullToPointer:
13132   case CK_NullToMemberPointer:
13133   case CK_BaseToDerivedMemberPointer:
13134   case CK_DerivedToBaseMemberPointer:
13135   case CK_ReinterpretMemberPointer:
13136   case CK_ConstructorConversion:
13137   case CK_IntegralToPointer:
13138   case CK_ToVoid:
13139   case CK_VectorSplat:
13140   case CK_IntegralToFloating:
13141   case CK_FloatingCast:
13142   case CK_CPointerToObjCPointerCast:
13143   case CK_BlockPointerToObjCPointerCast:
13144   case CK_AnyPointerToBlockPointerCast:
13145   case CK_ObjCObjectLValueCast:
13146   case CK_FloatingRealToComplex:
13147   case CK_FloatingComplexToReal:
13148   case CK_FloatingComplexCast:
13149   case CK_FloatingComplexToIntegralComplex:
13150   case CK_IntegralRealToComplex:
13151   case CK_IntegralComplexCast:
13152   case CK_IntegralComplexToFloatingComplex:
13153   case CK_BuiltinFnToFnPtr:
13154   case CK_ZeroToOCLOpaqueType:
13155   case CK_NonAtomicToAtomic:
13156   case CK_AddressSpaceConversion:
13157   case CK_IntToOCLSampler:
13158   case CK_FloatingToFixedPoint:
13159   case CK_FixedPointToFloating:
13160   case CK_FixedPointCast:
13161   case CK_IntegralToFixedPoint:
13162     llvm_unreachable("invalid cast kind for integral value");
13163 
13164   case CK_BitCast:
13165   case CK_Dependent:
13166   case CK_LValueBitCast:
13167   case CK_ARCProduceObject:
13168   case CK_ARCConsumeObject:
13169   case CK_ARCReclaimReturnedObject:
13170   case CK_ARCExtendBlockObject:
13171   case CK_CopyAndAutoreleaseBlockObject:
13172     return Error(E);
13173 
13174   case CK_UserDefinedConversion:
13175   case CK_LValueToRValue:
13176   case CK_AtomicToNonAtomic:
13177   case CK_NoOp:
13178   case CK_LValueToRValueBitCast:
13179     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13180 
13181   case CK_MemberPointerToBoolean:
13182   case CK_PointerToBoolean:
13183   case CK_IntegralToBoolean:
13184   case CK_FloatingToBoolean:
13185   case CK_BooleanToSignedIntegral:
13186   case CK_FloatingComplexToBoolean:
13187   case CK_IntegralComplexToBoolean: {
13188     bool BoolResult;
13189     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
13190       return false;
13191     uint64_t IntResult = BoolResult;
13192     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
13193       IntResult = (uint64_t)-1;
13194     return Success(IntResult, E);
13195   }
13196 
13197   case CK_FixedPointToIntegral: {
13198     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
13199     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13200       return false;
13201     bool Overflowed;
13202     llvm::APSInt Result = Src.convertToInt(
13203         Info.Ctx.getIntWidth(DestType),
13204         DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
13205     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
13206       return false;
13207     return Success(Result, E);
13208   }
13209 
13210   case CK_FixedPointToBoolean: {
13211     // Unsigned padding does not affect this.
13212     APValue Val;
13213     if (!Evaluate(Val, Info, SubExpr))
13214       return false;
13215     return Success(Val.getFixedPoint().getBoolValue(), E);
13216   }
13217 
13218   case CK_IntegralCast: {
13219     if (!Visit(SubExpr))
13220       return false;
13221 
13222     if (!Result.isInt()) {
13223       // Allow casts of address-of-label differences if they are no-ops
13224       // or narrowing.  (The narrowing case isn't actually guaranteed to
13225       // be constant-evaluatable except in some narrow cases which are hard
13226       // to detect here.  We let it through on the assumption the user knows
13227       // what they are doing.)
13228       if (Result.isAddrLabelDiff())
13229         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
13230       // Only allow casts of lvalues if they are lossless.
13231       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
13232     }
13233 
13234     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
13235                                       Result.getInt()), E);
13236   }
13237 
13238   case CK_PointerToIntegral: {
13239     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
13240 
13241     LValue LV;
13242     if (!EvaluatePointer(SubExpr, LV, Info))
13243       return false;
13244 
13245     if (LV.getLValueBase()) {
13246       // Only allow based lvalue casts if they are lossless.
13247       // FIXME: Allow a larger integer size than the pointer size, and allow
13248       // narrowing back down to pointer width in subsequent integral casts.
13249       // FIXME: Check integer type's active bits, not its type size.
13250       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
13251         return Error(E);
13252 
13253       LV.Designator.setInvalid();
13254       LV.moveInto(Result);
13255       return true;
13256     }
13257 
13258     APSInt AsInt;
13259     APValue V;
13260     LV.moveInto(V);
13261     if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
13262       llvm_unreachable("Can't cast this!");
13263 
13264     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
13265   }
13266 
13267   case CK_IntegralComplexToReal: {
13268     ComplexValue C;
13269     if (!EvaluateComplex(SubExpr, C, Info))
13270       return false;
13271     return Success(C.getComplexIntReal(), E);
13272   }
13273 
13274   case CK_FloatingToIntegral: {
13275     APFloat F(0.0);
13276     if (!EvaluateFloat(SubExpr, F, Info))
13277       return false;
13278 
13279     APSInt Value;
13280     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
13281       return false;
13282     return Success(Value, E);
13283   }
13284   }
13285 
13286   llvm_unreachable("unknown cast resulting in integral value");
13287 }
13288 
13289 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13290   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13291     ComplexValue LV;
13292     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13293       return false;
13294     if (!LV.isComplexInt())
13295       return Error(E);
13296     return Success(LV.getComplexIntReal(), E);
13297   }
13298 
13299   return Visit(E->getSubExpr());
13300 }
13301 
13302 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13303   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
13304     ComplexValue LV;
13305     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13306       return false;
13307     if (!LV.isComplexInt())
13308       return Error(E);
13309     return Success(LV.getComplexIntImag(), E);
13310   }
13311 
13312   VisitIgnoredValue(E->getSubExpr());
13313   return Success(0, E);
13314 }
13315 
13316 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
13317   return Success(E->getPackLength(), E);
13318 }
13319 
13320 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
13321   return Success(E->getValue(), E);
13322 }
13323 
13324 bool IntExprEvaluator::VisitConceptSpecializationExpr(
13325        const ConceptSpecializationExpr *E) {
13326   return Success(E->isSatisfied(), E);
13327 }
13328 
13329 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
13330   return Success(E->isSatisfied(), E);
13331 }
13332 
13333 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13334   switch (E->getOpcode()) {
13335     default:
13336       // Invalid unary operators
13337       return Error(E);
13338     case UO_Plus:
13339       // The result is just the value.
13340       return Visit(E->getSubExpr());
13341     case UO_Minus: {
13342       if (!Visit(E->getSubExpr())) return false;
13343       if (!Result.isFixedPoint())
13344         return Error(E);
13345       bool Overflowed;
13346       APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
13347       if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
13348         return false;
13349       return Success(Negated, E);
13350     }
13351     case UO_LNot: {
13352       bool bres;
13353       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13354         return false;
13355       return Success(!bres, E);
13356     }
13357   }
13358 }
13359 
13360 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
13361   const Expr *SubExpr = E->getSubExpr();
13362   QualType DestType = E->getType();
13363   assert(DestType->isFixedPointType() &&
13364          "Expected destination type to be a fixed point type");
13365   auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
13366 
13367   switch (E->getCastKind()) {
13368   case CK_FixedPointCast: {
13369     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13370     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13371       return false;
13372     bool Overflowed;
13373     APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
13374     if (Overflowed) {
13375       if (Info.checkingForUndefinedBehavior())
13376         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13377                                          diag::warn_fixedpoint_constant_overflow)
13378           << Result.toString() << E->getType();
13379       else if (!HandleOverflow(Info, E, Result, E->getType()))
13380         return false;
13381     }
13382     return Success(Result, E);
13383   }
13384   case CK_IntegralToFixedPoint: {
13385     APSInt Src;
13386     if (!EvaluateInteger(SubExpr, Src, Info))
13387       return false;
13388 
13389     bool Overflowed;
13390     APFixedPoint IntResult = APFixedPoint::getFromIntValue(
13391         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13392 
13393     if (Overflowed) {
13394       if (Info.checkingForUndefinedBehavior())
13395         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13396                                          diag::warn_fixedpoint_constant_overflow)
13397           << IntResult.toString() << E->getType();
13398       else if (!HandleOverflow(Info, E, IntResult, E->getType()))
13399         return false;
13400     }
13401 
13402     return Success(IntResult, E);
13403   }
13404   case CK_FloatingToFixedPoint: {
13405     APFloat Src(0.0);
13406     if (!EvaluateFloat(SubExpr, Src, Info))
13407       return false;
13408 
13409     bool Overflowed;
13410     APFixedPoint Result = APFixedPoint::getFromFloatValue(
13411         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13412 
13413     if (Overflowed) {
13414       if (Info.checkingForUndefinedBehavior())
13415         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13416                                          diag::warn_fixedpoint_constant_overflow)
13417           << Result.toString() << E->getType();
13418       else if (!HandleOverflow(Info, E, Result, E->getType()))
13419         return false;
13420     }
13421 
13422     return Success(Result, E);
13423   }
13424   case CK_NoOp:
13425   case CK_LValueToRValue:
13426     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13427   default:
13428     return Error(E);
13429   }
13430 }
13431 
13432 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13433   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13434     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13435 
13436   const Expr *LHS = E->getLHS();
13437   const Expr *RHS = E->getRHS();
13438   FixedPointSemantics ResultFXSema =
13439       Info.Ctx.getFixedPointSemantics(E->getType());
13440 
13441   APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
13442   if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
13443     return false;
13444   APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
13445   if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
13446     return false;
13447 
13448   bool OpOverflow = false, ConversionOverflow = false;
13449   APFixedPoint Result(LHSFX.getSemantics());
13450   switch (E->getOpcode()) {
13451   case BO_Add: {
13452     Result = LHSFX.add(RHSFX, &OpOverflow)
13453                   .convert(ResultFXSema, &ConversionOverflow);
13454     break;
13455   }
13456   case BO_Sub: {
13457     Result = LHSFX.sub(RHSFX, &OpOverflow)
13458                   .convert(ResultFXSema, &ConversionOverflow);
13459     break;
13460   }
13461   case BO_Mul: {
13462     Result = LHSFX.mul(RHSFX, &OpOverflow)
13463                   .convert(ResultFXSema, &ConversionOverflow);
13464     break;
13465   }
13466   case BO_Div: {
13467     if (RHSFX.getValue() == 0) {
13468       Info.FFDiag(E, diag::note_expr_divide_by_zero);
13469       return false;
13470     }
13471     Result = LHSFX.div(RHSFX, &OpOverflow)
13472                   .convert(ResultFXSema, &ConversionOverflow);
13473     break;
13474   }
13475   case BO_Shl:
13476   case BO_Shr: {
13477     FixedPointSemantics LHSSema = LHSFX.getSemantics();
13478     llvm::APSInt RHSVal = RHSFX.getValue();
13479 
13480     unsigned ShiftBW =
13481         LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
13482     unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
13483     // Embedded-C 4.1.6.2.2:
13484     //   The right operand must be nonnegative and less than the total number
13485     //   of (nonpadding) bits of the fixed-point operand ...
13486     if (RHSVal.isNegative())
13487       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
13488     else if (Amt != RHSVal)
13489       Info.CCEDiag(E, diag::note_constexpr_large_shift)
13490           << RHSVal << E->getType() << ShiftBW;
13491 
13492     if (E->getOpcode() == BO_Shl)
13493       Result = LHSFX.shl(Amt, &OpOverflow);
13494     else
13495       Result = LHSFX.shr(Amt, &OpOverflow);
13496     break;
13497   }
13498   default:
13499     return false;
13500   }
13501   if (OpOverflow || ConversionOverflow) {
13502     if (Info.checkingForUndefinedBehavior())
13503       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13504                                        diag::warn_fixedpoint_constant_overflow)
13505         << Result.toString() << E->getType();
13506     else if (!HandleOverflow(Info, E, Result, E->getType()))
13507       return false;
13508   }
13509   return Success(Result, E);
13510 }
13511 
13512 //===----------------------------------------------------------------------===//
13513 // Float Evaluation
13514 //===----------------------------------------------------------------------===//
13515 
13516 namespace {
13517 class FloatExprEvaluator
13518   : public ExprEvaluatorBase<FloatExprEvaluator> {
13519   APFloat &Result;
13520 public:
13521   FloatExprEvaluator(EvalInfo &info, APFloat &result)
13522     : ExprEvaluatorBaseTy(info), Result(result) {}
13523 
13524   bool Success(const APValue &V, const Expr *e) {
13525     Result = V.getFloat();
13526     return true;
13527   }
13528 
13529   bool ZeroInitialization(const Expr *E) {
13530     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
13531     return true;
13532   }
13533 
13534   bool VisitCallExpr(const CallExpr *E);
13535 
13536   bool VisitUnaryOperator(const UnaryOperator *E);
13537   bool VisitBinaryOperator(const BinaryOperator *E);
13538   bool VisitFloatingLiteral(const FloatingLiteral *E);
13539   bool VisitCastExpr(const CastExpr *E);
13540 
13541   bool VisitUnaryReal(const UnaryOperator *E);
13542   bool VisitUnaryImag(const UnaryOperator *E);
13543 
13544   // FIXME: Missing: array subscript of vector, member of vector
13545 };
13546 } // end anonymous namespace
13547 
13548 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
13549   assert(E->isRValue() && E->getType()->isRealFloatingType());
13550   return FloatExprEvaluator(Info, Result).Visit(E);
13551 }
13552 
13553 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
13554                                   QualType ResultTy,
13555                                   const Expr *Arg,
13556                                   bool SNaN,
13557                                   llvm::APFloat &Result) {
13558   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
13559   if (!S) return false;
13560 
13561   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
13562 
13563   llvm::APInt fill;
13564 
13565   // Treat empty strings as if they were zero.
13566   if (S->getString().empty())
13567     fill = llvm::APInt(32, 0);
13568   else if (S->getString().getAsInteger(0, fill))
13569     return false;
13570 
13571   if (Context.getTargetInfo().isNan2008()) {
13572     if (SNaN)
13573       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13574     else
13575       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13576   } else {
13577     // Prior to IEEE 754-2008, architectures were allowed to choose whether
13578     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
13579     // a different encoding to what became a standard in 2008, and for pre-
13580     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
13581     // sNaN. This is now known as "legacy NaN" encoding.
13582     if (SNaN)
13583       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13584     else
13585       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13586   }
13587 
13588   return true;
13589 }
13590 
13591 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
13592   switch (E->getBuiltinCallee()) {
13593   default:
13594     return ExprEvaluatorBaseTy::VisitCallExpr(E);
13595 
13596   case Builtin::BI__builtin_huge_val:
13597   case Builtin::BI__builtin_huge_valf:
13598   case Builtin::BI__builtin_huge_vall:
13599   case Builtin::BI__builtin_huge_valf128:
13600   case Builtin::BI__builtin_inf:
13601   case Builtin::BI__builtin_inff:
13602   case Builtin::BI__builtin_infl:
13603   case Builtin::BI__builtin_inff128: {
13604     const llvm::fltSemantics &Sem =
13605       Info.Ctx.getFloatTypeSemantics(E->getType());
13606     Result = llvm::APFloat::getInf(Sem);
13607     return true;
13608   }
13609 
13610   case Builtin::BI__builtin_nans:
13611   case Builtin::BI__builtin_nansf:
13612   case Builtin::BI__builtin_nansl:
13613   case Builtin::BI__builtin_nansf128:
13614     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13615                                true, Result))
13616       return Error(E);
13617     return true;
13618 
13619   case Builtin::BI__builtin_nan:
13620   case Builtin::BI__builtin_nanf:
13621   case Builtin::BI__builtin_nanl:
13622   case Builtin::BI__builtin_nanf128:
13623     // If this is __builtin_nan() turn this into a nan, otherwise we
13624     // can't constant fold it.
13625     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13626                                false, Result))
13627       return Error(E);
13628     return true;
13629 
13630   case Builtin::BI__builtin_fabs:
13631   case Builtin::BI__builtin_fabsf:
13632   case Builtin::BI__builtin_fabsl:
13633   case Builtin::BI__builtin_fabsf128:
13634     // The C standard says "fabs raises no floating-point exceptions,
13635     // even if x is a signaling NaN. The returned value is independent of
13636     // the current rounding direction mode."  Therefore constant folding can
13637     // proceed without regard to the floating point settings.
13638     // Reference, WG14 N2478 F.10.4.3
13639     if (!EvaluateFloat(E->getArg(0), Result, Info))
13640       return false;
13641 
13642     if (Result.isNegative())
13643       Result.changeSign();
13644     return true;
13645 
13646   // FIXME: Builtin::BI__builtin_powi
13647   // FIXME: Builtin::BI__builtin_powif
13648   // FIXME: Builtin::BI__builtin_powil
13649 
13650   case Builtin::BI__builtin_copysign:
13651   case Builtin::BI__builtin_copysignf:
13652   case Builtin::BI__builtin_copysignl:
13653   case Builtin::BI__builtin_copysignf128: {
13654     APFloat RHS(0.);
13655     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
13656         !EvaluateFloat(E->getArg(1), RHS, Info))
13657       return false;
13658     Result.copySign(RHS);
13659     return true;
13660   }
13661   }
13662 }
13663 
13664 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13665   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13666     ComplexValue CV;
13667     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13668       return false;
13669     Result = CV.FloatReal;
13670     return true;
13671   }
13672 
13673   return Visit(E->getSubExpr());
13674 }
13675 
13676 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13677   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13678     ComplexValue CV;
13679     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13680       return false;
13681     Result = CV.FloatImag;
13682     return true;
13683   }
13684 
13685   VisitIgnoredValue(E->getSubExpr());
13686   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
13687   Result = llvm::APFloat::getZero(Sem);
13688   return true;
13689 }
13690 
13691 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13692   switch (E->getOpcode()) {
13693   default: return Error(E);
13694   case UO_Plus:
13695     return EvaluateFloat(E->getSubExpr(), Result, Info);
13696   case UO_Minus:
13697     // In C standard, WG14 N2478 F.3 p4
13698     // "the unary - raises no floating point exceptions,
13699     // even if the operand is signalling."
13700     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
13701       return false;
13702     Result.changeSign();
13703     return true;
13704   }
13705 }
13706 
13707 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13708   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13709     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13710 
13711   APFloat RHS(0.0);
13712   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
13713   if (!LHSOK && !Info.noteFailure())
13714     return false;
13715   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
13716          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
13717 }
13718 
13719 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
13720   Result = E->getValue();
13721   return true;
13722 }
13723 
13724 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
13725   const Expr* SubExpr = E->getSubExpr();
13726 
13727   switch (E->getCastKind()) {
13728   default:
13729     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13730 
13731   case CK_IntegralToFloating: {
13732     APSInt IntResult;
13733     const FPOptions FPO = E->getFPFeaturesInEffect(
13734                                   Info.Ctx.getLangOpts());
13735     return EvaluateInteger(SubExpr, IntResult, Info) &&
13736            HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
13737                                 IntResult, E->getType(), Result);
13738   }
13739 
13740   case CK_FixedPointToFloating: {
13741     APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13742     if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
13743       return false;
13744     Result =
13745         FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
13746     return true;
13747   }
13748 
13749   case CK_FloatingCast: {
13750     if (!Visit(SubExpr))
13751       return false;
13752     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
13753                                   Result);
13754   }
13755 
13756   case CK_FloatingComplexToReal: {
13757     ComplexValue V;
13758     if (!EvaluateComplex(SubExpr, V, Info))
13759       return false;
13760     Result = V.getComplexFloatReal();
13761     return true;
13762   }
13763   }
13764 }
13765 
13766 //===----------------------------------------------------------------------===//
13767 // Complex Evaluation (for float and integer)
13768 //===----------------------------------------------------------------------===//
13769 
13770 namespace {
13771 class ComplexExprEvaluator
13772   : public ExprEvaluatorBase<ComplexExprEvaluator> {
13773   ComplexValue &Result;
13774 
13775 public:
13776   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
13777     : ExprEvaluatorBaseTy(info), Result(Result) {}
13778 
13779   bool Success(const APValue &V, const Expr *e) {
13780     Result.setFrom(V);
13781     return true;
13782   }
13783 
13784   bool ZeroInitialization(const Expr *E);
13785 
13786   //===--------------------------------------------------------------------===//
13787   //                            Visitor Methods
13788   //===--------------------------------------------------------------------===//
13789 
13790   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
13791   bool VisitCastExpr(const CastExpr *E);
13792   bool VisitBinaryOperator(const BinaryOperator *E);
13793   bool VisitUnaryOperator(const UnaryOperator *E);
13794   bool VisitInitListExpr(const InitListExpr *E);
13795   bool VisitCallExpr(const CallExpr *E);
13796 };
13797 } // end anonymous namespace
13798 
13799 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
13800                             EvalInfo &Info) {
13801   assert(E->isRValue() && E->getType()->isAnyComplexType());
13802   return ComplexExprEvaluator(Info, Result).Visit(E);
13803 }
13804 
13805 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
13806   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
13807   if (ElemTy->isRealFloatingType()) {
13808     Result.makeComplexFloat();
13809     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
13810     Result.FloatReal = Zero;
13811     Result.FloatImag = Zero;
13812   } else {
13813     Result.makeComplexInt();
13814     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
13815     Result.IntReal = Zero;
13816     Result.IntImag = Zero;
13817   }
13818   return true;
13819 }
13820 
13821 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
13822   const Expr* SubExpr = E->getSubExpr();
13823 
13824   if (SubExpr->getType()->isRealFloatingType()) {
13825     Result.makeComplexFloat();
13826     APFloat &Imag = Result.FloatImag;
13827     if (!EvaluateFloat(SubExpr, Imag, Info))
13828       return false;
13829 
13830     Result.FloatReal = APFloat(Imag.getSemantics());
13831     return true;
13832   } else {
13833     assert(SubExpr->getType()->isIntegerType() &&
13834            "Unexpected imaginary literal.");
13835 
13836     Result.makeComplexInt();
13837     APSInt &Imag = Result.IntImag;
13838     if (!EvaluateInteger(SubExpr, Imag, Info))
13839       return false;
13840 
13841     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
13842     return true;
13843   }
13844 }
13845 
13846 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
13847 
13848   switch (E->getCastKind()) {
13849   case CK_BitCast:
13850   case CK_BaseToDerived:
13851   case CK_DerivedToBase:
13852   case CK_UncheckedDerivedToBase:
13853   case CK_Dynamic:
13854   case CK_ToUnion:
13855   case CK_ArrayToPointerDecay:
13856   case CK_FunctionToPointerDecay:
13857   case CK_NullToPointer:
13858   case CK_NullToMemberPointer:
13859   case CK_BaseToDerivedMemberPointer:
13860   case CK_DerivedToBaseMemberPointer:
13861   case CK_MemberPointerToBoolean:
13862   case CK_ReinterpretMemberPointer:
13863   case CK_ConstructorConversion:
13864   case CK_IntegralToPointer:
13865   case CK_PointerToIntegral:
13866   case CK_PointerToBoolean:
13867   case CK_ToVoid:
13868   case CK_VectorSplat:
13869   case CK_IntegralCast:
13870   case CK_BooleanToSignedIntegral:
13871   case CK_IntegralToBoolean:
13872   case CK_IntegralToFloating:
13873   case CK_FloatingToIntegral:
13874   case CK_FloatingToBoolean:
13875   case CK_FloatingCast:
13876   case CK_CPointerToObjCPointerCast:
13877   case CK_BlockPointerToObjCPointerCast:
13878   case CK_AnyPointerToBlockPointerCast:
13879   case CK_ObjCObjectLValueCast:
13880   case CK_FloatingComplexToReal:
13881   case CK_FloatingComplexToBoolean:
13882   case CK_IntegralComplexToReal:
13883   case CK_IntegralComplexToBoolean:
13884   case CK_ARCProduceObject:
13885   case CK_ARCConsumeObject:
13886   case CK_ARCReclaimReturnedObject:
13887   case CK_ARCExtendBlockObject:
13888   case CK_CopyAndAutoreleaseBlockObject:
13889   case CK_BuiltinFnToFnPtr:
13890   case CK_ZeroToOCLOpaqueType:
13891   case CK_NonAtomicToAtomic:
13892   case CK_AddressSpaceConversion:
13893   case CK_IntToOCLSampler:
13894   case CK_FloatingToFixedPoint:
13895   case CK_FixedPointToFloating:
13896   case CK_FixedPointCast:
13897   case CK_FixedPointToBoolean:
13898   case CK_FixedPointToIntegral:
13899   case CK_IntegralToFixedPoint:
13900     llvm_unreachable("invalid cast kind for complex value");
13901 
13902   case CK_LValueToRValue:
13903   case CK_AtomicToNonAtomic:
13904   case CK_NoOp:
13905   case CK_LValueToRValueBitCast:
13906     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13907 
13908   case CK_Dependent:
13909   case CK_LValueBitCast:
13910   case CK_UserDefinedConversion:
13911     return Error(E);
13912 
13913   case CK_FloatingRealToComplex: {
13914     APFloat &Real = Result.FloatReal;
13915     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
13916       return false;
13917 
13918     Result.makeComplexFloat();
13919     Result.FloatImag = APFloat(Real.getSemantics());
13920     return true;
13921   }
13922 
13923   case CK_FloatingComplexCast: {
13924     if (!Visit(E->getSubExpr()))
13925       return false;
13926 
13927     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13928     QualType From
13929       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13930 
13931     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
13932            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
13933   }
13934 
13935   case CK_FloatingComplexToIntegralComplex: {
13936     if (!Visit(E->getSubExpr()))
13937       return false;
13938 
13939     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13940     QualType From
13941       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13942     Result.makeComplexInt();
13943     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
13944                                 To, Result.IntReal) &&
13945            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
13946                                 To, Result.IntImag);
13947   }
13948 
13949   case CK_IntegralRealToComplex: {
13950     APSInt &Real = Result.IntReal;
13951     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
13952       return false;
13953 
13954     Result.makeComplexInt();
13955     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
13956     return true;
13957   }
13958 
13959   case CK_IntegralComplexCast: {
13960     if (!Visit(E->getSubExpr()))
13961       return false;
13962 
13963     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13964     QualType From
13965       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13966 
13967     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
13968     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
13969     return true;
13970   }
13971 
13972   case CK_IntegralComplexToFloatingComplex: {
13973     if (!Visit(E->getSubExpr()))
13974       return false;
13975 
13976     const FPOptions FPO = E->getFPFeaturesInEffect(
13977                                   Info.Ctx.getLangOpts());
13978     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13979     QualType From
13980       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13981     Result.makeComplexFloat();
13982     return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
13983                                 To, Result.FloatReal) &&
13984            HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
13985                                 To, Result.FloatImag);
13986   }
13987   }
13988 
13989   llvm_unreachable("unknown cast resulting in complex value");
13990 }
13991 
13992 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13993   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13994     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13995 
13996   // Track whether the LHS or RHS is real at the type system level. When this is
13997   // the case we can simplify our evaluation strategy.
13998   bool LHSReal = false, RHSReal = false;
13999 
14000   bool LHSOK;
14001   if (E->getLHS()->getType()->isRealFloatingType()) {
14002     LHSReal = true;
14003     APFloat &Real = Result.FloatReal;
14004     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
14005     if (LHSOK) {
14006       Result.makeComplexFloat();
14007       Result.FloatImag = APFloat(Real.getSemantics());
14008     }
14009   } else {
14010     LHSOK = Visit(E->getLHS());
14011   }
14012   if (!LHSOK && !Info.noteFailure())
14013     return false;
14014 
14015   ComplexValue RHS;
14016   if (E->getRHS()->getType()->isRealFloatingType()) {
14017     RHSReal = true;
14018     APFloat &Real = RHS.FloatReal;
14019     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
14020       return false;
14021     RHS.makeComplexFloat();
14022     RHS.FloatImag = APFloat(Real.getSemantics());
14023   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
14024     return false;
14025 
14026   assert(!(LHSReal && RHSReal) &&
14027          "Cannot have both operands of a complex operation be real.");
14028   switch (E->getOpcode()) {
14029   default: return Error(E);
14030   case BO_Add:
14031     if (Result.isComplexFloat()) {
14032       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
14033                                        APFloat::rmNearestTiesToEven);
14034       if (LHSReal)
14035         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14036       else if (!RHSReal)
14037         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
14038                                          APFloat::rmNearestTiesToEven);
14039     } else {
14040       Result.getComplexIntReal() += RHS.getComplexIntReal();
14041       Result.getComplexIntImag() += RHS.getComplexIntImag();
14042     }
14043     break;
14044   case BO_Sub:
14045     if (Result.isComplexFloat()) {
14046       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
14047                                             APFloat::rmNearestTiesToEven);
14048       if (LHSReal) {
14049         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14050         Result.getComplexFloatImag().changeSign();
14051       } else if (!RHSReal) {
14052         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
14053                                               APFloat::rmNearestTiesToEven);
14054       }
14055     } else {
14056       Result.getComplexIntReal() -= RHS.getComplexIntReal();
14057       Result.getComplexIntImag() -= RHS.getComplexIntImag();
14058     }
14059     break;
14060   case BO_Mul:
14061     if (Result.isComplexFloat()) {
14062       // This is an implementation of complex multiplication according to the
14063       // constraints laid out in C11 Annex G. The implementation uses the
14064       // following naming scheme:
14065       //   (a + ib) * (c + id)
14066       ComplexValue LHS = Result;
14067       APFloat &A = LHS.getComplexFloatReal();
14068       APFloat &B = LHS.getComplexFloatImag();
14069       APFloat &C = RHS.getComplexFloatReal();
14070       APFloat &D = RHS.getComplexFloatImag();
14071       APFloat &ResR = Result.getComplexFloatReal();
14072       APFloat &ResI = Result.getComplexFloatImag();
14073       if (LHSReal) {
14074         assert(!RHSReal && "Cannot have two real operands for a complex op!");
14075         ResR = A * C;
14076         ResI = A * D;
14077       } else if (RHSReal) {
14078         ResR = C * A;
14079         ResI = C * B;
14080       } else {
14081         // In the fully general case, we need to handle NaNs and infinities
14082         // robustly.
14083         APFloat AC = A * C;
14084         APFloat BD = B * D;
14085         APFloat AD = A * D;
14086         APFloat BC = B * C;
14087         ResR = AC - BD;
14088         ResI = AD + BC;
14089         if (ResR.isNaN() && ResI.isNaN()) {
14090           bool Recalc = false;
14091           if (A.isInfinity() || B.isInfinity()) {
14092             A = APFloat::copySign(
14093                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14094             B = APFloat::copySign(
14095                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14096             if (C.isNaN())
14097               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14098             if (D.isNaN())
14099               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14100             Recalc = true;
14101           }
14102           if (C.isInfinity() || D.isInfinity()) {
14103             C = APFloat::copySign(
14104                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14105             D = APFloat::copySign(
14106                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14107             if (A.isNaN())
14108               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14109             if (B.isNaN())
14110               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14111             Recalc = true;
14112           }
14113           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
14114                           AD.isInfinity() || BC.isInfinity())) {
14115             if (A.isNaN())
14116               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14117             if (B.isNaN())
14118               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14119             if (C.isNaN())
14120               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14121             if (D.isNaN())
14122               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14123             Recalc = true;
14124           }
14125           if (Recalc) {
14126             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
14127             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
14128           }
14129         }
14130       }
14131     } else {
14132       ComplexValue LHS = Result;
14133       Result.getComplexIntReal() =
14134         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
14135          LHS.getComplexIntImag() * RHS.getComplexIntImag());
14136       Result.getComplexIntImag() =
14137         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
14138          LHS.getComplexIntImag() * RHS.getComplexIntReal());
14139     }
14140     break;
14141   case BO_Div:
14142     if (Result.isComplexFloat()) {
14143       // This is an implementation of complex division according to the
14144       // constraints laid out in C11 Annex G. The implementation uses the
14145       // following naming scheme:
14146       //   (a + ib) / (c + id)
14147       ComplexValue LHS = Result;
14148       APFloat &A = LHS.getComplexFloatReal();
14149       APFloat &B = LHS.getComplexFloatImag();
14150       APFloat &C = RHS.getComplexFloatReal();
14151       APFloat &D = RHS.getComplexFloatImag();
14152       APFloat &ResR = Result.getComplexFloatReal();
14153       APFloat &ResI = Result.getComplexFloatImag();
14154       if (RHSReal) {
14155         ResR = A / C;
14156         ResI = B / C;
14157       } else {
14158         if (LHSReal) {
14159           // No real optimizations we can do here, stub out with zero.
14160           B = APFloat::getZero(A.getSemantics());
14161         }
14162         int DenomLogB = 0;
14163         APFloat MaxCD = maxnum(abs(C), abs(D));
14164         if (MaxCD.isFinite()) {
14165           DenomLogB = ilogb(MaxCD);
14166           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
14167           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
14168         }
14169         APFloat Denom = C * C + D * D;
14170         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
14171                       APFloat::rmNearestTiesToEven);
14172         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
14173                       APFloat::rmNearestTiesToEven);
14174         if (ResR.isNaN() && ResI.isNaN()) {
14175           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
14176             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
14177             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
14178           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
14179                      D.isFinite()) {
14180             A = APFloat::copySign(
14181                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14182             B = APFloat::copySign(
14183                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14184             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
14185             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
14186           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
14187             C = APFloat::copySign(
14188                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14189             D = APFloat::copySign(
14190                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14191             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
14192             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
14193           }
14194         }
14195       }
14196     } else {
14197       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
14198         return Error(E, diag::note_expr_divide_by_zero);
14199 
14200       ComplexValue LHS = Result;
14201       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
14202         RHS.getComplexIntImag() * RHS.getComplexIntImag();
14203       Result.getComplexIntReal() =
14204         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
14205          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
14206       Result.getComplexIntImag() =
14207         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
14208          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
14209     }
14210     break;
14211   }
14212 
14213   return true;
14214 }
14215 
14216 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14217   // Get the operand value into 'Result'.
14218   if (!Visit(E->getSubExpr()))
14219     return false;
14220 
14221   switch (E->getOpcode()) {
14222   default:
14223     return Error(E);
14224   case UO_Extension:
14225     return true;
14226   case UO_Plus:
14227     // The result is always just the subexpr.
14228     return true;
14229   case UO_Minus:
14230     if (Result.isComplexFloat()) {
14231       Result.getComplexFloatReal().changeSign();
14232       Result.getComplexFloatImag().changeSign();
14233     }
14234     else {
14235       Result.getComplexIntReal() = -Result.getComplexIntReal();
14236       Result.getComplexIntImag() = -Result.getComplexIntImag();
14237     }
14238     return true;
14239   case UO_Not:
14240     if (Result.isComplexFloat())
14241       Result.getComplexFloatImag().changeSign();
14242     else
14243       Result.getComplexIntImag() = -Result.getComplexIntImag();
14244     return true;
14245   }
14246 }
14247 
14248 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
14249   if (E->getNumInits() == 2) {
14250     if (E->getType()->isComplexType()) {
14251       Result.makeComplexFloat();
14252       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
14253         return false;
14254       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
14255         return false;
14256     } else {
14257       Result.makeComplexInt();
14258       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
14259         return false;
14260       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
14261         return false;
14262     }
14263     return true;
14264   }
14265   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
14266 }
14267 
14268 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
14269   switch (E->getBuiltinCallee()) {
14270   case Builtin::BI__builtin_complex:
14271     Result.makeComplexFloat();
14272     if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
14273       return false;
14274     if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
14275       return false;
14276     return true;
14277 
14278   default:
14279     break;
14280   }
14281 
14282   return ExprEvaluatorBaseTy::VisitCallExpr(E);
14283 }
14284 
14285 //===----------------------------------------------------------------------===//
14286 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
14287 // implicit conversion.
14288 //===----------------------------------------------------------------------===//
14289 
14290 namespace {
14291 class AtomicExprEvaluator :
14292     public ExprEvaluatorBase<AtomicExprEvaluator> {
14293   const LValue *This;
14294   APValue &Result;
14295 public:
14296   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
14297       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
14298 
14299   bool Success(const APValue &V, const Expr *E) {
14300     Result = V;
14301     return true;
14302   }
14303 
14304   bool ZeroInitialization(const Expr *E) {
14305     ImplicitValueInitExpr VIE(
14306         E->getType()->castAs<AtomicType>()->getValueType());
14307     // For atomic-qualified class (and array) types in C++, initialize the
14308     // _Atomic-wrapped subobject directly, in-place.
14309     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
14310                 : Evaluate(Result, Info, &VIE);
14311   }
14312 
14313   bool VisitCastExpr(const CastExpr *E) {
14314     switch (E->getCastKind()) {
14315     default:
14316       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14317     case CK_NonAtomicToAtomic:
14318       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
14319                   : Evaluate(Result, Info, E->getSubExpr());
14320     }
14321   }
14322 };
14323 } // end anonymous namespace
14324 
14325 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
14326                            EvalInfo &Info) {
14327   assert(E->isRValue() && E->getType()->isAtomicType());
14328   return AtomicExprEvaluator(Info, This, Result).Visit(E);
14329 }
14330 
14331 //===----------------------------------------------------------------------===//
14332 // Void expression evaluation, primarily for a cast to void on the LHS of a
14333 // comma operator
14334 //===----------------------------------------------------------------------===//
14335 
14336 namespace {
14337 class VoidExprEvaluator
14338   : public ExprEvaluatorBase<VoidExprEvaluator> {
14339 public:
14340   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
14341 
14342   bool Success(const APValue &V, const Expr *e) { return true; }
14343 
14344   bool ZeroInitialization(const Expr *E) { return true; }
14345 
14346   bool VisitCastExpr(const CastExpr *E) {
14347     switch (E->getCastKind()) {
14348     default:
14349       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14350     case CK_ToVoid:
14351       VisitIgnoredValue(E->getSubExpr());
14352       return true;
14353     }
14354   }
14355 
14356   bool VisitCallExpr(const CallExpr *E) {
14357     switch (E->getBuiltinCallee()) {
14358     case Builtin::BI__assume:
14359     case Builtin::BI__builtin_assume:
14360       // The argument is not evaluated!
14361       return true;
14362 
14363     case Builtin::BI__builtin_operator_delete:
14364       return HandleOperatorDeleteCall(Info, E);
14365 
14366     default:
14367       break;
14368     }
14369 
14370     return ExprEvaluatorBaseTy::VisitCallExpr(E);
14371   }
14372 
14373   bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
14374 };
14375 } // end anonymous namespace
14376 
14377 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
14378   // We cannot speculatively evaluate a delete expression.
14379   if (Info.SpeculativeEvaluationDepth)
14380     return false;
14381 
14382   FunctionDecl *OperatorDelete = E->getOperatorDelete();
14383   if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
14384     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14385         << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
14386     return false;
14387   }
14388 
14389   const Expr *Arg = E->getArgument();
14390 
14391   LValue Pointer;
14392   if (!EvaluatePointer(Arg, Pointer, Info))
14393     return false;
14394   if (Pointer.Designator.Invalid)
14395     return false;
14396 
14397   // Deleting a null pointer has no effect.
14398   if (Pointer.isNullPointer()) {
14399     // This is the only case where we need to produce an extension warning:
14400     // the only other way we can succeed is if we find a dynamic allocation,
14401     // and we will have warned when we allocated it in that case.
14402     if (!Info.getLangOpts().CPlusPlus20)
14403       Info.CCEDiag(E, diag::note_constexpr_new);
14404     return true;
14405   }
14406 
14407   Optional<DynAlloc *> Alloc = CheckDeleteKind(
14408       Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
14409   if (!Alloc)
14410     return false;
14411   QualType AllocType = Pointer.Base.getDynamicAllocType();
14412 
14413   // For the non-array case, the designator must be empty if the static type
14414   // does not have a virtual destructor.
14415   if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
14416       !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
14417     Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
14418         << Arg->getType()->getPointeeType() << AllocType;
14419     return false;
14420   }
14421 
14422   // For a class type with a virtual destructor, the selected operator delete
14423   // is the one looked up when building the destructor.
14424   if (!E->isArrayForm() && !E->isGlobalDelete()) {
14425     const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
14426     if (VirtualDelete &&
14427         !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
14428       Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14429           << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
14430       return false;
14431     }
14432   }
14433 
14434   if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
14435                          (*Alloc)->Value, AllocType))
14436     return false;
14437 
14438   if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
14439     // The element was already erased. This means the destructor call also
14440     // deleted the object.
14441     // FIXME: This probably results in undefined behavior before we get this
14442     // far, and should be diagnosed elsewhere first.
14443     Info.FFDiag(E, diag::note_constexpr_double_delete);
14444     return false;
14445   }
14446 
14447   return true;
14448 }
14449 
14450 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
14451   assert(E->isRValue() && E->getType()->isVoidType());
14452   return VoidExprEvaluator(Info).Visit(E);
14453 }
14454 
14455 //===----------------------------------------------------------------------===//
14456 // Top level Expr::EvaluateAsRValue method.
14457 //===----------------------------------------------------------------------===//
14458 
14459 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
14460   // In C, function designators are not lvalues, but we evaluate them as if they
14461   // are.
14462   QualType T = E->getType();
14463   if (E->isGLValue() || T->isFunctionType()) {
14464     LValue LV;
14465     if (!EvaluateLValue(E, LV, Info))
14466       return false;
14467     LV.moveInto(Result);
14468   } else if (T->isVectorType()) {
14469     if (!EvaluateVector(E, Result, Info))
14470       return false;
14471   } else if (T->isIntegralOrEnumerationType()) {
14472     if (!IntExprEvaluator(Info, Result).Visit(E))
14473       return false;
14474   } else if (T->hasPointerRepresentation()) {
14475     LValue LV;
14476     if (!EvaluatePointer(E, LV, Info))
14477       return false;
14478     LV.moveInto(Result);
14479   } else if (T->isRealFloatingType()) {
14480     llvm::APFloat F(0.0);
14481     if (!EvaluateFloat(E, F, Info))
14482       return false;
14483     Result = APValue(F);
14484   } else if (T->isAnyComplexType()) {
14485     ComplexValue C;
14486     if (!EvaluateComplex(E, C, Info))
14487       return false;
14488     C.moveInto(Result);
14489   } else if (T->isFixedPointType()) {
14490     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
14491   } else if (T->isMemberPointerType()) {
14492     MemberPtr P;
14493     if (!EvaluateMemberPointer(E, P, Info))
14494       return false;
14495     P.moveInto(Result);
14496     return true;
14497   } else if (T->isArrayType()) {
14498     LValue LV;
14499     APValue &Value =
14500         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14501     if (!EvaluateArray(E, LV, Value, Info))
14502       return false;
14503     Result = Value;
14504   } else if (T->isRecordType()) {
14505     LValue LV;
14506     APValue &Value =
14507         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14508     if (!EvaluateRecord(E, LV, Value, Info))
14509       return false;
14510     Result = Value;
14511   } else if (T->isVoidType()) {
14512     if (!Info.getLangOpts().CPlusPlus11)
14513       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
14514         << E->getType();
14515     if (!EvaluateVoid(E, Info))
14516       return false;
14517   } else if (T->isAtomicType()) {
14518     QualType Unqual = T.getAtomicUnqualifiedType();
14519     if (Unqual->isArrayType() || Unqual->isRecordType()) {
14520       LValue LV;
14521       APValue &Value = Info.CurrentCall->createTemporary(
14522           E, Unqual, ScopeKind::FullExpression, LV);
14523       if (!EvaluateAtomic(E, &LV, Value, Info))
14524         return false;
14525     } else {
14526       if (!EvaluateAtomic(E, nullptr, Result, Info))
14527         return false;
14528     }
14529   } else if (Info.getLangOpts().CPlusPlus11) {
14530     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
14531     return false;
14532   } else {
14533     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
14534     return false;
14535   }
14536 
14537   return true;
14538 }
14539 
14540 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
14541 /// cases, the in-place evaluation is essential, since later initializers for
14542 /// an object can indirectly refer to subobjects which were initialized earlier.
14543 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
14544                             const Expr *E, bool AllowNonLiteralTypes) {
14545   assert(!E->isValueDependent());
14546 
14547   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
14548     return false;
14549 
14550   if (E->isRValue()) {
14551     // Evaluate arrays and record types in-place, so that later initializers can
14552     // refer to earlier-initialized members of the object.
14553     QualType T = E->getType();
14554     if (T->isArrayType())
14555       return EvaluateArray(E, This, Result, Info);
14556     else if (T->isRecordType())
14557       return EvaluateRecord(E, This, Result, Info);
14558     else if (T->isAtomicType()) {
14559       QualType Unqual = T.getAtomicUnqualifiedType();
14560       if (Unqual->isArrayType() || Unqual->isRecordType())
14561         return EvaluateAtomic(E, &This, Result, Info);
14562     }
14563   }
14564 
14565   // For any other type, in-place evaluation is unimportant.
14566   return Evaluate(Result, Info, E);
14567 }
14568 
14569 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
14570 /// lvalue-to-rvalue cast if it is an lvalue.
14571 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
14572   if (Info.EnableNewConstInterp) {
14573     if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
14574       return false;
14575   } else {
14576     if (E->getType().isNull())
14577       return false;
14578 
14579     if (!CheckLiteralType(Info, E))
14580       return false;
14581 
14582     if (!::Evaluate(Result, Info, E))
14583       return false;
14584 
14585     if (E->isGLValue()) {
14586       LValue LV;
14587       LV.setFrom(Info.Ctx, Result);
14588       if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
14589         return false;
14590     }
14591   }
14592 
14593   // Check this core constant expression is a constant expression.
14594   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
14595                                  ConstantExprKind::Normal) &&
14596          CheckMemoryLeaks(Info);
14597 }
14598 
14599 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
14600                                  const ASTContext &Ctx, bool &IsConst) {
14601   // Fast-path evaluations of integer literals, since we sometimes see files
14602   // containing vast quantities of these.
14603   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
14604     Result.Val = APValue(APSInt(L->getValue(),
14605                                 L->getType()->isUnsignedIntegerType()));
14606     IsConst = true;
14607     return true;
14608   }
14609 
14610   // This case should be rare, but we need to check it before we check on
14611   // the type below.
14612   if (Exp->getType().isNull()) {
14613     IsConst = false;
14614     return true;
14615   }
14616 
14617   // FIXME: Evaluating values of large array and record types can cause
14618   // performance problems. Only do so in C++11 for now.
14619   if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
14620                           Exp->getType()->isRecordType()) &&
14621       !Ctx.getLangOpts().CPlusPlus11) {
14622     IsConst = false;
14623     return true;
14624   }
14625   return false;
14626 }
14627 
14628 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
14629                                       Expr::SideEffectsKind SEK) {
14630   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
14631          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
14632 }
14633 
14634 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
14635                              const ASTContext &Ctx, EvalInfo &Info) {
14636   bool IsConst;
14637   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
14638     return IsConst;
14639 
14640   return EvaluateAsRValue(Info, E, Result.Val);
14641 }
14642 
14643 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
14644                           const ASTContext &Ctx,
14645                           Expr::SideEffectsKind AllowSideEffects,
14646                           EvalInfo &Info) {
14647   if (!E->getType()->isIntegralOrEnumerationType())
14648     return false;
14649 
14650   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
14651       !ExprResult.Val.isInt() ||
14652       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14653     return false;
14654 
14655   return true;
14656 }
14657 
14658 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
14659                                  const ASTContext &Ctx,
14660                                  Expr::SideEffectsKind AllowSideEffects,
14661                                  EvalInfo &Info) {
14662   if (!E->getType()->isFixedPointType())
14663     return false;
14664 
14665   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
14666     return false;
14667 
14668   if (!ExprResult.Val.isFixedPoint() ||
14669       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14670     return false;
14671 
14672   return true;
14673 }
14674 
14675 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
14676 /// any crazy technique (that has nothing to do with language standards) that
14677 /// we want to.  If this function returns true, it returns the folded constant
14678 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
14679 /// will be applied to the result.
14680 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
14681                             bool InConstantContext) const {
14682   assert(!isValueDependent() &&
14683          "Expression evaluator can't be called on a dependent expression.");
14684   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14685   Info.InConstantContext = InConstantContext;
14686   return ::EvaluateAsRValue(this, Result, Ctx, Info);
14687 }
14688 
14689 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
14690                                       bool InConstantContext) const {
14691   assert(!isValueDependent() &&
14692          "Expression evaluator can't be called on a dependent expression.");
14693   EvalResult Scratch;
14694   return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
14695          HandleConversionToBool(Scratch.Val, Result);
14696 }
14697 
14698 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
14699                          SideEffectsKind AllowSideEffects,
14700                          bool InConstantContext) const {
14701   assert(!isValueDependent() &&
14702          "Expression evaluator can't be called on a dependent expression.");
14703   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14704   Info.InConstantContext = InConstantContext;
14705   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
14706 }
14707 
14708 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
14709                                 SideEffectsKind AllowSideEffects,
14710                                 bool InConstantContext) const {
14711   assert(!isValueDependent() &&
14712          "Expression evaluator can't be called on a dependent expression.");
14713   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14714   Info.InConstantContext = InConstantContext;
14715   return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
14716 }
14717 
14718 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
14719                            SideEffectsKind AllowSideEffects,
14720                            bool InConstantContext) const {
14721   assert(!isValueDependent() &&
14722          "Expression evaluator can't be called on a dependent expression.");
14723 
14724   if (!getType()->isRealFloatingType())
14725     return false;
14726 
14727   EvalResult ExprResult;
14728   if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
14729       !ExprResult.Val.isFloat() ||
14730       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14731     return false;
14732 
14733   Result = ExprResult.Val.getFloat();
14734   return true;
14735 }
14736 
14737 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
14738                             bool InConstantContext) const {
14739   assert(!isValueDependent() &&
14740          "Expression evaluator can't be called on a dependent expression.");
14741 
14742   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
14743   Info.InConstantContext = InConstantContext;
14744   LValue LV;
14745   CheckedTemporaries CheckedTemps;
14746   if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
14747       Result.HasSideEffects ||
14748       !CheckLValueConstantExpression(Info, getExprLoc(),
14749                                      Ctx.getLValueReferenceType(getType()), LV,
14750                                      ConstantExprKind::Normal, CheckedTemps))
14751     return false;
14752 
14753   LV.moveInto(Result.Val);
14754   return true;
14755 }
14756 
14757 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base,
14758                                 APValue DestroyedValue, QualType Type,
14759                                 SourceLocation Loc, Expr::EvalStatus &EStatus) {
14760   EvalInfo Info(Ctx, EStatus, EvalInfo::EM_ConstantExpression);
14761   Info.setEvaluatingDecl(Base, DestroyedValue,
14762                          EvalInfo::EvaluatingDeclKind::Dtor);
14763   Info.InConstantContext = true;
14764 
14765   LValue LVal;
14766   LVal.set(Base);
14767 
14768   if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
14769       EStatus.HasSideEffects)
14770     return false;
14771 
14772   if (!Info.discardCleanups())
14773     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14774 
14775   return true;
14776 }
14777 
14778 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx,
14779                                   ConstantExprKind Kind) const {
14780   assert(!isValueDependent() &&
14781          "Expression evaluator can't be called on a dependent expression.");
14782 
14783   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
14784   EvalInfo Info(Ctx, Result, EM);
14785   Info.InConstantContext = true;
14786 
14787   // The type of the object we're initializing is 'const T' for a class NTTP.
14788   QualType T = getType();
14789   if (Kind == ConstantExprKind::ClassTemplateArgument)
14790     T.addConst();
14791 
14792   // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
14793   // represent the result of the evaluation. CheckConstantExpression ensures
14794   // this doesn't escape.
14795   MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
14796   APValue::LValueBase Base(&BaseMTE);
14797 
14798   Info.setEvaluatingDecl(Base, Result.Val);
14799   LValue LVal;
14800   LVal.set(Base);
14801 
14802   if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || Result.HasSideEffects)
14803     return false;
14804 
14805   if (!Info.discardCleanups())
14806     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14807 
14808   if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
14809                                Result.Val, Kind))
14810     return false;
14811   if (!CheckMemoryLeaks(Info))
14812     return false;
14813 
14814   // If this is a class template argument, it's required to have constant
14815   // destruction too.
14816   if (Kind == ConstantExprKind::ClassTemplateArgument &&
14817       (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result) ||
14818        Result.HasSideEffects)) {
14819     // FIXME: Prefix a note to indicate that the problem is lack of constant
14820     // destruction.
14821     return false;
14822   }
14823 
14824   return true;
14825 }
14826 
14827 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
14828                                  const VarDecl *VD,
14829                                  SmallVectorImpl<PartialDiagnosticAt> &Notes,
14830                                  bool IsConstantInitialization) const {
14831   assert(!isValueDependent() &&
14832          "Expression evaluator can't be called on a dependent expression.");
14833 
14834   // FIXME: Evaluating initializers for large array and record types can cause
14835   // performance problems. Only do so in C++11 for now.
14836   if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
14837       !Ctx.getLangOpts().CPlusPlus11)
14838     return false;
14839 
14840   Expr::EvalStatus EStatus;
14841   EStatus.Diag = &Notes;
14842 
14843   EvalInfo Info(Ctx, EStatus,
14844                 (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11)
14845                     ? EvalInfo::EM_ConstantExpression
14846                     : EvalInfo::EM_ConstantFold);
14847   Info.setEvaluatingDecl(VD, Value);
14848   Info.InConstantContext = IsConstantInitialization;
14849 
14850   SourceLocation DeclLoc = VD->getLocation();
14851   QualType DeclTy = VD->getType();
14852 
14853   if (Info.EnableNewConstInterp) {
14854     auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
14855     if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
14856       return false;
14857   } else {
14858     LValue LVal;
14859     LVal.set(VD);
14860 
14861     if (!EvaluateInPlace(Value, Info, LVal, this,
14862                          /*AllowNonLiteralTypes=*/true) ||
14863         EStatus.HasSideEffects)
14864       return false;
14865 
14866     // At this point, any lifetime-extended temporaries are completely
14867     // initialized.
14868     Info.performLifetimeExtension();
14869 
14870     if (!Info.discardCleanups())
14871       llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14872   }
14873   return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
14874                                  ConstantExprKind::Normal) &&
14875          CheckMemoryLeaks(Info);
14876 }
14877 
14878 bool VarDecl::evaluateDestruction(
14879     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
14880   Expr::EvalStatus EStatus;
14881   EStatus.Diag = &Notes;
14882 
14883   // Make a copy of the value for the destructor to mutate, if we know it.
14884   // Otherwise, treat the value as default-initialized; if the destructor works
14885   // anyway, then the destruction is constant (and must be essentially empty).
14886   APValue DestroyedValue;
14887   if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
14888     DestroyedValue = *getEvaluatedValue();
14889   else if (!getDefaultInitValue(getType(), DestroyedValue))
14890     return false;
14891 
14892   if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
14893                            getType(), getLocation(), EStatus) ||
14894       EStatus.HasSideEffects)
14895     return false;
14896 
14897   ensureEvaluatedStmt()->HasConstantDestruction = true;
14898   return true;
14899 }
14900 
14901 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
14902 /// constant folded, but discard the result.
14903 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
14904   assert(!isValueDependent() &&
14905          "Expression evaluator can't be called on a dependent expression.");
14906 
14907   EvalResult Result;
14908   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
14909          !hasUnacceptableSideEffect(Result, SEK);
14910 }
14911 
14912 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
14913                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
14914   assert(!isValueDependent() &&
14915          "Expression evaluator can't be called on a dependent expression.");
14916 
14917   EvalResult EVResult;
14918   EVResult.Diag = Diag;
14919   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14920   Info.InConstantContext = true;
14921 
14922   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
14923   (void)Result;
14924   assert(Result && "Could not evaluate expression");
14925   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
14926 
14927   return EVResult.Val.getInt();
14928 }
14929 
14930 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
14931     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
14932   assert(!isValueDependent() &&
14933          "Expression evaluator can't be called on a dependent expression.");
14934 
14935   EvalResult EVResult;
14936   EVResult.Diag = Diag;
14937   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14938   Info.InConstantContext = true;
14939   Info.CheckingForUndefinedBehavior = true;
14940 
14941   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
14942   (void)Result;
14943   assert(Result && "Could not evaluate expression");
14944   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
14945 
14946   return EVResult.Val.getInt();
14947 }
14948 
14949 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
14950   assert(!isValueDependent() &&
14951          "Expression evaluator can't be called on a dependent expression.");
14952 
14953   bool IsConst;
14954   EvalResult EVResult;
14955   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
14956     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14957     Info.CheckingForUndefinedBehavior = true;
14958     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
14959   }
14960 }
14961 
14962 bool Expr::EvalResult::isGlobalLValue() const {
14963   assert(Val.isLValue());
14964   return IsGlobalLValue(Val.getLValueBase());
14965 }
14966 
14967 /// isIntegerConstantExpr - this recursive routine will test if an expression is
14968 /// an integer constant expression.
14969 
14970 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
14971 /// comma, etc
14972 
14973 // CheckICE - This function does the fundamental ICE checking: the returned
14974 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
14975 // and a (possibly null) SourceLocation indicating the location of the problem.
14976 //
14977 // Note that to reduce code duplication, this helper does no evaluation
14978 // itself; the caller checks whether the expression is evaluatable, and
14979 // in the rare cases where CheckICE actually cares about the evaluated
14980 // value, it calls into Evaluate.
14981 
14982 namespace {
14983 
14984 enum ICEKind {
14985   /// This expression is an ICE.
14986   IK_ICE,
14987   /// This expression is not an ICE, but if it isn't evaluated, it's
14988   /// a legal subexpression for an ICE. This return value is used to handle
14989   /// the comma operator in C99 mode, and non-constant subexpressions.
14990   IK_ICEIfUnevaluated,
14991   /// This expression is not an ICE, and is not a legal subexpression for one.
14992   IK_NotICE
14993 };
14994 
14995 struct ICEDiag {
14996   ICEKind Kind;
14997   SourceLocation Loc;
14998 
14999   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
15000 };
15001 
15002 }
15003 
15004 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
15005 
15006 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
15007 
15008 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
15009   Expr::EvalResult EVResult;
15010   Expr::EvalStatus Status;
15011   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15012 
15013   Info.InConstantContext = true;
15014   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
15015       !EVResult.Val.isInt())
15016     return ICEDiag(IK_NotICE, E->getBeginLoc());
15017 
15018   return NoDiag();
15019 }
15020 
15021 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
15022   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
15023   if (!E->getType()->isIntegralOrEnumerationType())
15024     return ICEDiag(IK_NotICE, E->getBeginLoc());
15025 
15026   switch (E->getStmtClass()) {
15027 #define ABSTRACT_STMT(Node)
15028 #define STMT(Node, Base) case Expr::Node##Class:
15029 #define EXPR(Node, Base)
15030 #include "clang/AST/StmtNodes.inc"
15031   case Expr::PredefinedExprClass:
15032   case Expr::FloatingLiteralClass:
15033   case Expr::ImaginaryLiteralClass:
15034   case Expr::StringLiteralClass:
15035   case Expr::ArraySubscriptExprClass:
15036   case Expr::MatrixSubscriptExprClass:
15037   case Expr::OMPArraySectionExprClass:
15038   case Expr::OMPArrayShapingExprClass:
15039   case Expr::OMPIteratorExprClass:
15040   case Expr::MemberExprClass:
15041   case Expr::CompoundAssignOperatorClass:
15042   case Expr::CompoundLiteralExprClass:
15043   case Expr::ExtVectorElementExprClass:
15044   case Expr::DesignatedInitExprClass:
15045   case Expr::ArrayInitLoopExprClass:
15046   case Expr::ArrayInitIndexExprClass:
15047   case Expr::NoInitExprClass:
15048   case Expr::DesignatedInitUpdateExprClass:
15049   case Expr::ImplicitValueInitExprClass:
15050   case Expr::ParenListExprClass:
15051   case Expr::VAArgExprClass:
15052   case Expr::AddrLabelExprClass:
15053   case Expr::StmtExprClass:
15054   case Expr::CXXMemberCallExprClass:
15055   case Expr::CUDAKernelCallExprClass:
15056   case Expr::CXXAddrspaceCastExprClass:
15057   case Expr::CXXDynamicCastExprClass:
15058   case Expr::CXXTypeidExprClass:
15059   case Expr::CXXUuidofExprClass:
15060   case Expr::MSPropertyRefExprClass:
15061   case Expr::MSPropertySubscriptExprClass:
15062   case Expr::CXXNullPtrLiteralExprClass:
15063   case Expr::UserDefinedLiteralClass:
15064   case Expr::CXXThisExprClass:
15065   case Expr::CXXThrowExprClass:
15066   case Expr::CXXNewExprClass:
15067   case Expr::CXXDeleteExprClass:
15068   case Expr::CXXPseudoDestructorExprClass:
15069   case Expr::UnresolvedLookupExprClass:
15070   case Expr::TypoExprClass:
15071   case Expr::RecoveryExprClass:
15072   case Expr::DependentScopeDeclRefExprClass:
15073   case Expr::CXXConstructExprClass:
15074   case Expr::CXXInheritedCtorInitExprClass:
15075   case Expr::CXXStdInitializerListExprClass:
15076   case Expr::CXXBindTemporaryExprClass:
15077   case Expr::ExprWithCleanupsClass:
15078   case Expr::CXXTemporaryObjectExprClass:
15079   case Expr::CXXUnresolvedConstructExprClass:
15080   case Expr::CXXDependentScopeMemberExprClass:
15081   case Expr::UnresolvedMemberExprClass:
15082   case Expr::ObjCStringLiteralClass:
15083   case Expr::ObjCBoxedExprClass:
15084   case Expr::ObjCArrayLiteralClass:
15085   case Expr::ObjCDictionaryLiteralClass:
15086   case Expr::ObjCEncodeExprClass:
15087   case Expr::ObjCMessageExprClass:
15088   case Expr::ObjCSelectorExprClass:
15089   case Expr::ObjCProtocolExprClass:
15090   case Expr::ObjCIvarRefExprClass:
15091   case Expr::ObjCPropertyRefExprClass:
15092   case Expr::ObjCSubscriptRefExprClass:
15093   case Expr::ObjCIsaExprClass:
15094   case Expr::ObjCAvailabilityCheckExprClass:
15095   case Expr::ShuffleVectorExprClass:
15096   case Expr::ConvertVectorExprClass:
15097   case Expr::BlockExprClass:
15098   case Expr::NoStmtClass:
15099   case Expr::OpaqueValueExprClass:
15100   case Expr::PackExpansionExprClass:
15101   case Expr::SubstNonTypeTemplateParmPackExprClass:
15102   case Expr::FunctionParmPackExprClass:
15103   case Expr::AsTypeExprClass:
15104   case Expr::ObjCIndirectCopyRestoreExprClass:
15105   case Expr::MaterializeTemporaryExprClass:
15106   case Expr::PseudoObjectExprClass:
15107   case Expr::AtomicExprClass:
15108   case Expr::LambdaExprClass:
15109   case Expr::CXXFoldExprClass:
15110   case Expr::CoawaitExprClass:
15111   case Expr::DependentCoawaitExprClass:
15112   case Expr::CoyieldExprClass:
15113     return ICEDiag(IK_NotICE, E->getBeginLoc());
15114 
15115   case Expr::InitListExprClass: {
15116     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
15117     // form "T x = { a };" is equivalent to "T x = a;".
15118     // Unless we're initializing a reference, T is a scalar as it is known to be
15119     // of integral or enumeration type.
15120     if (E->isRValue())
15121       if (cast<InitListExpr>(E)->getNumInits() == 1)
15122         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
15123     return ICEDiag(IK_NotICE, E->getBeginLoc());
15124   }
15125 
15126   case Expr::SizeOfPackExprClass:
15127   case Expr::GNUNullExprClass:
15128   case Expr::SourceLocExprClass:
15129     return NoDiag();
15130 
15131   case Expr::SubstNonTypeTemplateParmExprClass:
15132     return
15133       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
15134 
15135   case Expr::ConstantExprClass:
15136     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
15137 
15138   case Expr::ParenExprClass:
15139     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
15140   case Expr::GenericSelectionExprClass:
15141     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
15142   case Expr::IntegerLiteralClass:
15143   case Expr::FixedPointLiteralClass:
15144   case Expr::CharacterLiteralClass:
15145   case Expr::ObjCBoolLiteralExprClass:
15146   case Expr::CXXBoolLiteralExprClass:
15147   case Expr::CXXScalarValueInitExprClass:
15148   case Expr::TypeTraitExprClass:
15149   case Expr::ConceptSpecializationExprClass:
15150   case Expr::RequiresExprClass:
15151   case Expr::ArrayTypeTraitExprClass:
15152   case Expr::ExpressionTraitExprClass:
15153   case Expr::CXXNoexceptExprClass:
15154     return NoDiag();
15155   case Expr::CallExprClass:
15156   case Expr::CXXOperatorCallExprClass: {
15157     // C99 6.6/3 allows function calls within unevaluated subexpressions of
15158     // constant expressions, but they can never be ICEs because an ICE cannot
15159     // contain an operand of (pointer to) function type.
15160     const CallExpr *CE = cast<CallExpr>(E);
15161     if (CE->getBuiltinCallee())
15162       return CheckEvalInICE(E, Ctx);
15163     return ICEDiag(IK_NotICE, E->getBeginLoc());
15164   }
15165   case Expr::CXXRewrittenBinaryOperatorClass:
15166     return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
15167                     Ctx);
15168   case Expr::DeclRefExprClass: {
15169     const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
15170     if (isa<EnumConstantDecl>(D))
15171       return NoDiag();
15172 
15173     // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
15174     // integer variables in constant expressions:
15175     //
15176     // C++ 7.1.5.1p2
15177     //   A variable of non-volatile const-qualified integral or enumeration
15178     //   type initialized by an ICE can be used in ICEs.
15179     //
15180     // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
15181     // that mode, use of reference variables should not be allowed.
15182     const VarDecl *VD = dyn_cast<VarDecl>(D);
15183     if (VD && VD->isUsableInConstantExpressions(Ctx) &&
15184         !VD->getType()->isReferenceType())
15185       return NoDiag();
15186 
15187     return ICEDiag(IK_NotICE, E->getBeginLoc());
15188   }
15189   case Expr::UnaryOperatorClass: {
15190     const UnaryOperator *Exp = cast<UnaryOperator>(E);
15191     switch (Exp->getOpcode()) {
15192     case UO_PostInc:
15193     case UO_PostDec:
15194     case UO_PreInc:
15195     case UO_PreDec:
15196     case UO_AddrOf:
15197     case UO_Deref:
15198     case UO_Coawait:
15199       // C99 6.6/3 allows increment and decrement within unevaluated
15200       // subexpressions of constant expressions, but they can never be ICEs
15201       // because an ICE cannot contain an lvalue operand.
15202       return ICEDiag(IK_NotICE, E->getBeginLoc());
15203     case UO_Extension:
15204     case UO_LNot:
15205     case UO_Plus:
15206     case UO_Minus:
15207     case UO_Not:
15208     case UO_Real:
15209     case UO_Imag:
15210       return CheckICE(Exp->getSubExpr(), Ctx);
15211     }
15212     llvm_unreachable("invalid unary operator class");
15213   }
15214   case Expr::OffsetOfExprClass: {
15215     // Note that per C99, offsetof must be an ICE. And AFAIK, using
15216     // EvaluateAsRValue matches the proposed gcc behavior for cases like
15217     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
15218     // compliance: we should warn earlier for offsetof expressions with
15219     // array subscripts that aren't ICEs, and if the array subscripts
15220     // are ICEs, the value of the offsetof must be an integer constant.
15221     return CheckEvalInICE(E, Ctx);
15222   }
15223   case Expr::UnaryExprOrTypeTraitExprClass: {
15224     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
15225     if ((Exp->getKind() ==  UETT_SizeOf) &&
15226         Exp->getTypeOfArgument()->isVariableArrayType())
15227       return ICEDiag(IK_NotICE, E->getBeginLoc());
15228     return NoDiag();
15229   }
15230   case Expr::BinaryOperatorClass: {
15231     const BinaryOperator *Exp = cast<BinaryOperator>(E);
15232     switch (Exp->getOpcode()) {
15233     case BO_PtrMemD:
15234     case BO_PtrMemI:
15235     case BO_Assign:
15236     case BO_MulAssign:
15237     case BO_DivAssign:
15238     case BO_RemAssign:
15239     case BO_AddAssign:
15240     case BO_SubAssign:
15241     case BO_ShlAssign:
15242     case BO_ShrAssign:
15243     case BO_AndAssign:
15244     case BO_XorAssign:
15245     case BO_OrAssign:
15246       // C99 6.6/3 allows assignments within unevaluated subexpressions of
15247       // constant expressions, but they can never be ICEs because an ICE cannot
15248       // contain an lvalue operand.
15249       return ICEDiag(IK_NotICE, E->getBeginLoc());
15250 
15251     case BO_Mul:
15252     case BO_Div:
15253     case BO_Rem:
15254     case BO_Add:
15255     case BO_Sub:
15256     case BO_Shl:
15257     case BO_Shr:
15258     case BO_LT:
15259     case BO_GT:
15260     case BO_LE:
15261     case BO_GE:
15262     case BO_EQ:
15263     case BO_NE:
15264     case BO_And:
15265     case BO_Xor:
15266     case BO_Or:
15267     case BO_Comma:
15268     case BO_Cmp: {
15269       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15270       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15271       if (Exp->getOpcode() == BO_Div ||
15272           Exp->getOpcode() == BO_Rem) {
15273         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
15274         // we don't evaluate one.
15275         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
15276           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
15277           if (REval == 0)
15278             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15279           if (REval.isSigned() && REval.isAllOnesValue()) {
15280             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
15281             if (LEval.isMinSignedValue())
15282               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15283           }
15284         }
15285       }
15286       if (Exp->getOpcode() == BO_Comma) {
15287         if (Ctx.getLangOpts().C99) {
15288           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
15289           // if it isn't evaluated.
15290           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
15291             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15292         } else {
15293           // In both C89 and C++, commas in ICEs are illegal.
15294           return ICEDiag(IK_NotICE, E->getBeginLoc());
15295         }
15296       }
15297       return Worst(LHSResult, RHSResult);
15298     }
15299     case BO_LAnd:
15300     case BO_LOr: {
15301       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15302       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15303       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
15304         // Rare case where the RHS has a comma "side-effect"; we need
15305         // to actually check the condition to see whether the side
15306         // with the comma is evaluated.
15307         if ((Exp->getOpcode() == BO_LAnd) !=
15308             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
15309           return RHSResult;
15310         return NoDiag();
15311       }
15312 
15313       return Worst(LHSResult, RHSResult);
15314     }
15315     }
15316     llvm_unreachable("invalid binary operator kind");
15317   }
15318   case Expr::ImplicitCastExprClass:
15319   case Expr::CStyleCastExprClass:
15320   case Expr::CXXFunctionalCastExprClass:
15321   case Expr::CXXStaticCastExprClass:
15322   case Expr::CXXReinterpretCastExprClass:
15323   case Expr::CXXConstCastExprClass:
15324   case Expr::ObjCBridgedCastExprClass: {
15325     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
15326     if (isa<ExplicitCastExpr>(E)) {
15327       if (const FloatingLiteral *FL
15328             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
15329         unsigned DestWidth = Ctx.getIntWidth(E->getType());
15330         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
15331         APSInt IgnoredVal(DestWidth, !DestSigned);
15332         bool Ignored;
15333         // If the value does not fit in the destination type, the behavior is
15334         // undefined, so we are not required to treat it as a constant
15335         // expression.
15336         if (FL->getValue().convertToInteger(IgnoredVal,
15337                                             llvm::APFloat::rmTowardZero,
15338                                             &Ignored) & APFloat::opInvalidOp)
15339           return ICEDiag(IK_NotICE, E->getBeginLoc());
15340         return NoDiag();
15341       }
15342     }
15343     switch (cast<CastExpr>(E)->getCastKind()) {
15344     case CK_LValueToRValue:
15345     case CK_AtomicToNonAtomic:
15346     case CK_NonAtomicToAtomic:
15347     case CK_NoOp:
15348     case CK_IntegralToBoolean:
15349     case CK_IntegralCast:
15350       return CheckICE(SubExpr, Ctx);
15351     default:
15352       return ICEDiag(IK_NotICE, E->getBeginLoc());
15353     }
15354   }
15355   case Expr::BinaryConditionalOperatorClass: {
15356     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
15357     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
15358     if (CommonResult.Kind == IK_NotICE) return CommonResult;
15359     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15360     if (FalseResult.Kind == IK_NotICE) return FalseResult;
15361     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
15362     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
15363         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
15364     return FalseResult;
15365   }
15366   case Expr::ConditionalOperatorClass: {
15367     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
15368     // If the condition (ignoring parens) is a __builtin_constant_p call,
15369     // then only the true side is actually considered in an integer constant
15370     // expression, and it is fully evaluated.  This is an important GNU
15371     // extension.  See GCC PR38377 for discussion.
15372     if (const CallExpr *CallCE
15373         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
15374       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
15375         return CheckEvalInICE(E, Ctx);
15376     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
15377     if (CondResult.Kind == IK_NotICE)
15378       return CondResult;
15379 
15380     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
15381     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15382 
15383     if (TrueResult.Kind == IK_NotICE)
15384       return TrueResult;
15385     if (FalseResult.Kind == IK_NotICE)
15386       return FalseResult;
15387     if (CondResult.Kind == IK_ICEIfUnevaluated)
15388       return CondResult;
15389     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
15390       return NoDiag();
15391     // Rare case where the diagnostics depend on which side is evaluated
15392     // Note that if we get here, CondResult is 0, and at least one of
15393     // TrueResult and FalseResult is non-zero.
15394     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
15395       return FalseResult;
15396     return TrueResult;
15397   }
15398   case Expr::CXXDefaultArgExprClass:
15399     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
15400   case Expr::CXXDefaultInitExprClass:
15401     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
15402   case Expr::ChooseExprClass: {
15403     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
15404   }
15405   case Expr::BuiltinBitCastExprClass: {
15406     if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
15407       return ICEDiag(IK_NotICE, E->getBeginLoc());
15408     return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
15409   }
15410   }
15411 
15412   llvm_unreachable("Invalid StmtClass!");
15413 }
15414 
15415 /// Evaluate an expression as a C++11 integral constant expression.
15416 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
15417                                                     const Expr *E,
15418                                                     llvm::APSInt *Value,
15419                                                     SourceLocation *Loc) {
15420   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15421     if (Loc) *Loc = E->getExprLoc();
15422     return false;
15423   }
15424 
15425   APValue Result;
15426   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
15427     return false;
15428 
15429   if (!Result.isInt()) {
15430     if (Loc) *Loc = E->getExprLoc();
15431     return false;
15432   }
15433 
15434   if (Value) *Value = Result.getInt();
15435   return true;
15436 }
15437 
15438 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
15439                                  SourceLocation *Loc) const {
15440   assert(!isValueDependent() &&
15441          "Expression evaluator can't be called on a dependent expression.");
15442 
15443   if (Ctx.getLangOpts().CPlusPlus11)
15444     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
15445 
15446   ICEDiag D = CheckICE(this, Ctx);
15447   if (D.Kind != IK_ICE) {
15448     if (Loc) *Loc = D.Loc;
15449     return false;
15450   }
15451   return true;
15452 }
15453 
15454 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx,
15455                                                     SourceLocation *Loc,
15456                                                     bool isEvaluated) const {
15457   assert(!isValueDependent() &&
15458          "Expression evaluator can't be called on a dependent expression.");
15459 
15460   APSInt Value;
15461 
15462   if (Ctx.getLangOpts().CPlusPlus11) {
15463     if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc))
15464       return Value;
15465     return None;
15466   }
15467 
15468   if (!isIntegerConstantExpr(Ctx, Loc))
15469     return None;
15470 
15471   // The only possible side-effects here are due to UB discovered in the
15472   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
15473   // required to treat the expression as an ICE, so we produce the folded
15474   // value.
15475   EvalResult ExprResult;
15476   Expr::EvalStatus Status;
15477   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
15478   Info.InConstantContext = true;
15479 
15480   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
15481     llvm_unreachable("ICE cannot be evaluated!");
15482 
15483   return ExprResult.Val.getInt();
15484 }
15485 
15486 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
15487   assert(!isValueDependent() &&
15488          "Expression evaluator can't be called on a dependent expression.");
15489 
15490   return CheckICE(this, Ctx).Kind == IK_ICE;
15491 }
15492 
15493 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
15494                                SourceLocation *Loc) const {
15495   assert(!isValueDependent() &&
15496          "Expression evaluator can't be called on a dependent expression.");
15497 
15498   // We support this checking in C++98 mode in order to diagnose compatibility
15499   // issues.
15500   assert(Ctx.getLangOpts().CPlusPlus);
15501 
15502   // Build evaluation settings.
15503   Expr::EvalStatus Status;
15504   SmallVector<PartialDiagnosticAt, 8> Diags;
15505   Status.Diag = &Diags;
15506   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15507 
15508   APValue Scratch;
15509   bool IsConstExpr =
15510       ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
15511       // FIXME: We don't produce a diagnostic for this, but the callers that
15512       // call us on arbitrary full-expressions should generally not care.
15513       Info.discardCleanups() && !Status.HasSideEffects;
15514 
15515   if (!Diags.empty()) {
15516     IsConstExpr = false;
15517     if (Loc) *Loc = Diags[0].first;
15518   } else if (!IsConstExpr) {
15519     // FIXME: This shouldn't happen.
15520     if (Loc) *Loc = getExprLoc();
15521   }
15522 
15523   return IsConstExpr;
15524 }
15525 
15526 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
15527                                     const FunctionDecl *Callee,
15528                                     ArrayRef<const Expr*> Args,
15529                                     const Expr *This) const {
15530   assert(!isValueDependent() &&
15531          "Expression evaluator can't be called on a dependent expression.");
15532 
15533   Expr::EvalStatus Status;
15534   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
15535   Info.InConstantContext = true;
15536 
15537   LValue ThisVal;
15538   const LValue *ThisPtr = nullptr;
15539   if (This) {
15540 #ifndef NDEBUG
15541     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
15542     assert(MD && "Don't provide `this` for non-methods.");
15543     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
15544 #endif
15545     if (!This->isValueDependent() &&
15546         EvaluateObjectArgument(Info, This, ThisVal) &&
15547         !Info.EvalStatus.HasSideEffects)
15548       ThisPtr = &ThisVal;
15549 
15550     // Ignore any side-effects from a failed evaluation. This is safe because
15551     // they can't interfere with any other argument evaluation.
15552     Info.EvalStatus.HasSideEffects = false;
15553   }
15554 
15555   CallRef Call = Info.CurrentCall->createCall(Callee);
15556   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
15557        I != E; ++I) {
15558     unsigned Idx = I - Args.begin();
15559     if (Idx >= Callee->getNumParams())
15560       break;
15561     const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
15562     if ((*I)->isValueDependent() ||
15563         !EvaluateCallArg(PVD, *I, Call, Info) ||
15564         Info.EvalStatus.HasSideEffects) {
15565       // If evaluation fails, throw away the argument entirely.
15566       if (APValue *Slot = Info.getParamSlot(Call, PVD))
15567         *Slot = APValue();
15568     }
15569 
15570     // Ignore any side-effects from a failed evaluation. This is safe because
15571     // they can't interfere with any other argument evaluation.
15572     Info.EvalStatus.HasSideEffects = false;
15573   }
15574 
15575   // Parameter cleanups happen in the caller and are not part of this
15576   // evaluation.
15577   Info.discardCleanups();
15578   Info.EvalStatus.HasSideEffects = false;
15579 
15580   // Build fake call to Callee.
15581   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call);
15582   // FIXME: Missing ExprWithCleanups in enable_if conditions?
15583   FullExpressionRAII Scope(Info);
15584   return Evaluate(Value, Info, this) && Scope.destroy() &&
15585          !Info.EvalStatus.HasSideEffects;
15586 }
15587 
15588 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
15589                                    SmallVectorImpl<
15590                                      PartialDiagnosticAt> &Diags) {
15591   // FIXME: It would be useful to check constexpr function templates, but at the
15592   // moment the constant expression evaluator cannot cope with the non-rigorous
15593   // ASTs which we build for dependent expressions.
15594   if (FD->isDependentContext())
15595     return true;
15596 
15597   // Bail out if a constexpr constructor has an initializer that contains an
15598   // error. We deliberately don't produce a diagnostic, as we have produced a
15599   // relevant diagnostic when parsing the error initializer.
15600   if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
15601     for (const auto *InitExpr : Ctor->inits()) {
15602       if (InitExpr->getInit() && InitExpr->getInit()->containsErrors())
15603         return false;
15604     }
15605   }
15606   Expr::EvalStatus Status;
15607   Status.Diag = &Diags;
15608 
15609   EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
15610   Info.InConstantContext = true;
15611   Info.CheckingPotentialConstantExpression = true;
15612 
15613   // The constexpr VM attempts to compile all methods to bytecode here.
15614   if (Info.EnableNewConstInterp) {
15615     Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
15616     return Diags.empty();
15617   }
15618 
15619   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
15620   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
15621 
15622   // Fabricate an arbitrary expression on the stack and pretend that it
15623   // is a temporary being used as the 'this' pointer.
15624   LValue This;
15625   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
15626   This.set({&VIE, Info.CurrentCall->Index});
15627 
15628   ArrayRef<const Expr*> Args;
15629 
15630   APValue Scratch;
15631   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
15632     // Evaluate the call as a constant initializer, to allow the construction
15633     // of objects of non-literal types.
15634     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
15635     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
15636   } else {
15637     SourceLocation Loc = FD->getLocation();
15638     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
15639                        Args, CallRef(), FD->getBody(), Info, Scratch, nullptr);
15640   }
15641 
15642   return Diags.empty();
15643 }
15644 
15645 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
15646                                               const FunctionDecl *FD,
15647                                               SmallVectorImpl<
15648                                                 PartialDiagnosticAt> &Diags) {
15649   assert(!E->isValueDependent() &&
15650          "Expression evaluator can't be called on a dependent expression.");
15651 
15652   Expr::EvalStatus Status;
15653   Status.Diag = &Diags;
15654 
15655   EvalInfo Info(FD->getASTContext(), Status,
15656                 EvalInfo::EM_ConstantExpressionUnevaluated);
15657   Info.InConstantContext = true;
15658   Info.CheckingPotentialConstantExpression = true;
15659 
15660   // Fabricate a call stack frame to give the arguments a plausible cover story.
15661   CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef());
15662 
15663   APValue ResultScratch;
15664   Evaluate(ResultScratch, Info, E);
15665   return Diags.empty();
15666 }
15667 
15668 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
15669                                  unsigned Type) const {
15670   if (!getType()->isPointerType())
15671     return false;
15672 
15673   Expr::EvalStatus Status;
15674   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
15675   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
15676 }
15677