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     return B.getType();
83   }
84 
85   /// Get an LValue path entry, which is known to not be an array index, as a
86   /// field declaration.
87   static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
88     return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
89   }
90   /// Get an LValue path entry, which is known to not be an array index, as a
91   /// base class declaration.
92   static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
93     return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
94   }
95   /// Determine whether this LValue path entry for a base class names a virtual
96   /// base class.
97   static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
98     return E.getAsBaseOrMember().getInt();
99   }
100 
101   /// Given an expression, determine the type used to store the result of
102   /// evaluating that expression.
103   static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
104     if (E->isPRValue())
105       return E->getType();
106     return Ctx.getLValueReferenceType(E->getType());
107   }
108 
109   /// Given a CallExpr, try to get the alloc_size attribute. May return null.
110   static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
111     if (const FunctionDecl *DirectCallee = CE->getDirectCallee())
112       return DirectCallee->getAttr<AllocSizeAttr>();
113     if (const Decl *IndirectCallee = CE->getCalleeDecl())
114       return IndirectCallee->getAttr<AllocSizeAttr>();
115     return nullptr;
116   }
117 
118   /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
119   /// This will look through a single cast.
120   ///
121   /// Returns null if we couldn't unwrap a function with alloc_size.
122   static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
123     if (!E->getType()->isPointerType())
124       return nullptr;
125 
126     E = E->IgnoreParens();
127     // If we're doing a variable assignment from e.g. malloc(N), there will
128     // probably be a cast of some kind. In exotic cases, we might also see a
129     // top-level ExprWithCleanups. Ignore them either way.
130     if (const auto *FE = dyn_cast<FullExpr>(E))
131       E = FE->getSubExpr()->IgnoreParens();
132 
133     if (const auto *Cast = dyn_cast<CastExpr>(E))
134       E = Cast->getSubExpr()->IgnoreParens();
135 
136     if (const auto *CE = dyn_cast<CallExpr>(E))
137       return getAllocSizeAttr(CE) ? CE : nullptr;
138     return nullptr;
139   }
140 
141   /// Determines whether or not the given Base contains a call to a function
142   /// with the alloc_size attribute.
143   static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
144     const auto *E = Base.dyn_cast<const Expr *>();
145     return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
146   }
147 
148   /// Determines whether the given kind of constant expression is only ever
149   /// used for name mangling. If so, it's permitted to reference things that we
150   /// can't generate code for (in particular, dllimported functions).
151   static bool isForManglingOnly(ConstantExprKind Kind) {
152     switch (Kind) {
153     case ConstantExprKind::Normal:
154     case ConstantExprKind::ClassTemplateArgument:
155     case ConstantExprKind::ImmediateInvocation:
156       // Note that non-type template arguments of class type are emitted as
157       // template parameter objects.
158       return false;
159 
160     case ConstantExprKind::NonClassTemplateArgument:
161       return true;
162     }
163     llvm_unreachable("unknown ConstantExprKind");
164   }
165 
166   static bool isTemplateArgument(ConstantExprKind Kind) {
167     switch (Kind) {
168     case ConstantExprKind::Normal:
169     case ConstantExprKind::ImmediateInvocation:
170       return false;
171 
172     case ConstantExprKind::ClassTemplateArgument:
173     case ConstantExprKind::NonClassTemplateArgument:
174       return true;
175     }
176     llvm_unreachable("unknown ConstantExprKind");
177   }
178 
179   /// The bound to claim that an array of unknown bound has.
180   /// The value in MostDerivedArraySize is undefined in this case. So, set it
181   /// to an arbitrary value that's likely to loudly break things if it's used.
182   static const uint64_t AssumedSizeForUnsizedArray =
183       std::numeric_limits<uint64_t>::max() / 2;
184 
185   /// Determines if an LValue with the given LValueBase will have an unsized
186   /// array in its designator.
187   /// Find the path length and type of the most-derived subobject in the given
188   /// path, and find the size of the containing array, if any.
189   static unsigned
190   findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
191                            ArrayRef<APValue::LValuePathEntry> Path,
192                            uint64_t &ArraySize, QualType &Type, bool &IsArray,
193                            bool &FirstEntryIsUnsizedArray) {
194     // This only accepts LValueBases from APValues, and APValues don't support
195     // arrays that lack size info.
196     assert(!isBaseAnAllocSizeCall(Base) &&
197            "Unsized arrays shouldn't appear here");
198     unsigned MostDerivedLength = 0;
199     Type = getType(Base);
200 
201     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
202       if (Type->isArrayType()) {
203         const ArrayType *AT = Ctx.getAsArrayType(Type);
204         Type = AT->getElementType();
205         MostDerivedLength = I + 1;
206         IsArray = true;
207 
208         if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
209           ArraySize = CAT->getSize().getZExtValue();
210         } else {
211           assert(I == 0 && "unexpected unsized array designator");
212           FirstEntryIsUnsizedArray = true;
213           ArraySize = AssumedSizeForUnsizedArray;
214         }
215       } else if (Type->isAnyComplexType()) {
216         const ComplexType *CT = Type->castAs<ComplexType>();
217         Type = CT->getElementType();
218         ArraySize = 2;
219         MostDerivedLength = I + 1;
220         IsArray = true;
221       } else if (const FieldDecl *FD = getAsField(Path[I])) {
222         Type = FD->getType();
223         ArraySize = 0;
224         MostDerivedLength = I + 1;
225         IsArray = false;
226       } else {
227         // Path[I] describes a base class.
228         ArraySize = 0;
229         IsArray = false;
230       }
231     }
232     return MostDerivedLength;
233   }
234 
235   /// A path from a glvalue to a subobject of that glvalue.
236   struct SubobjectDesignator {
237     /// True if the subobject was named in a manner not supported by C++11. Such
238     /// lvalues can still be folded, but they are not core constant expressions
239     /// and we cannot perform lvalue-to-rvalue conversions on them.
240     unsigned Invalid : 1;
241 
242     /// Is this a pointer one past the end of an object?
243     unsigned IsOnePastTheEnd : 1;
244 
245     /// Indicator of whether the first entry is an unsized array.
246     unsigned FirstEntryIsAnUnsizedArray : 1;
247 
248     /// Indicator of whether the most-derived object is an array element.
249     unsigned MostDerivedIsArrayElement : 1;
250 
251     /// The length of the path to the most-derived object of which this is a
252     /// subobject.
253     unsigned MostDerivedPathLength : 28;
254 
255     /// The size of the array of which the most-derived object is an element.
256     /// This will always be 0 if the most-derived object is not an array
257     /// element. 0 is not an indicator of whether or not the most-derived object
258     /// is an array, however, because 0-length arrays are allowed.
259     ///
260     /// If the current array is an unsized array, the value of this is
261     /// undefined.
262     uint64_t MostDerivedArraySize;
263 
264     /// The type of the most derived object referred to by this address.
265     QualType MostDerivedType;
266 
267     typedef APValue::LValuePathEntry PathEntry;
268 
269     /// The entries on the path from the glvalue to the designated subobject.
270     SmallVector<PathEntry, 8> Entries;
271 
272     SubobjectDesignator() : Invalid(true) {}
273 
274     explicit SubobjectDesignator(QualType T)
275         : Invalid(false), IsOnePastTheEnd(false),
276           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
277           MostDerivedPathLength(0), MostDerivedArraySize(0),
278           MostDerivedType(T) {}
279 
280     SubobjectDesignator(ASTContext &Ctx, const APValue &V)
281         : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
282           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
283           MostDerivedPathLength(0), MostDerivedArraySize(0) {
284       assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
285       if (!Invalid) {
286         IsOnePastTheEnd = V.isLValueOnePastTheEnd();
287         ArrayRef<PathEntry> VEntries = V.getLValuePath();
288         Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
289         if (V.getLValueBase()) {
290           bool IsArray = false;
291           bool FirstIsUnsizedArray = false;
292           MostDerivedPathLength = findMostDerivedSubobject(
293               Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
294               MostDerivedType, IsArray, FirstIsUnsizedArray);
295           MostDerivedIsArrayElement = IsArray;
296           FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
297         }
298       }
299     }
300 
301     void truncate(ASTContext &Ctx, APValue::LValueBase Base,
302                   unsigned NewLength) {
303       if (Invalid)
304         return;
305 
306       assert(Base && "cannot truncate path for null pointer");
307       assert(NewLength <= Entries.size() && "not a truncation");
308 
309       if (NewLength == Entries.size())
310         return;
311       Entries.resize(NewLength);
312 
313       bool IsArray = false;
314       bool FirstIsUnsizedArray = false;
315       MostDerivedPathLength = findMostDerivedSubobject(
316           Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
317           FirstIsUnsizedArray);
318       MostDerivedIsArrayElement = IsArray;
319       FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
320     }
321 
322     void setInvalid() {
323       Invalid = true;
324       Entries.clear();
325     }
326 
327     /// Determine whether the most derived subobject is an array without a
328     /// known bound.
329     bool isMostDerivedAnUnsizedArray() const {
330       assert(!Invalid && "Calling this makes no sense on invalid designators");
331       return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
332     }
333 
334     /// Determine what the most derived array's size is. Results in an assertion
335     /// failure if the most derived array lacks a size.
336     uint64_t getMostDerivedArraySize() const {
337       assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
338       return MostDerivedArraySize;
339     }
340 
341     /// Determine whether this is a one-past-the-end pointer.
342     bool isOnePastTheEnd() const {
343       assert(!Invalid);
344       if (IsOnePastTheEnd)
345         return true;
346       if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
347           Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
348               MostDerivedArraySize)
349         return true;
350       return false;
351     }
352 
353     /// Get the range of valid index adjustments in the form
354     ///   {maximum value that can be subtracted from this pointer,
355     ///    maximum value that can be added to this pointer}
356     std::pair<uint64_t, uint64_t> validIndexAdjustments() {
357       if (Invalid || isMostDerivedAnUnsizedArray())
358         return {0, 0};
359 
360       // [expr.add]p4: For the purposes of these operators, a pointer to a
361       // nonarray object behaves the same as a pointer to the first element of
362       // an array of length one with the type of the object as its element type.
363       bool IsArray = MostDerivedPathLength == Entries.size() &&
364                      MostDerivedIsArrayElement;
365       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
366                                     : (uint64_t)IsOnePastTheEnd;
367       uint64_t ArraySize =
368           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
369       return {ArrayIndex, ArraySize - ArrayIndex};
370     }
371 
372     /// Check that this refers to a valid subobject.
373     bool isValidSubobject() const {
374       if (Invalid)
375         return false;
376       return !isOnePastTheEnd();
377     }
378     /// Check that this refers to a valid subobject, and if not, produce a
379     /// relevant diagnostic and set the designator as invalid.
380     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
381 
382     /// Get the type of the designated object.
383     QualType getType(ASTContext &Ctx) const {
384       assert(!Invalid && "invalid designator has no subobject type");
385       return MostDerivedPathLength == Entries.size()
386                  ? MostDerivedType
387                  : Ctx.getRecordType(getAsBaseClass(Entries.back()));
388     }
389 
390     /// Update this designator to refer to the first element within this array.
391     void addArrayUnchecked(const ConstantArrayType *CAT) {
392       Entries.push_back(PathEntry::ArrayIndex(0));
393 
394       // This is a most-derived object.
395       MostDerivedType = CAT->getElementType();
396       MostDerivedIsArrayElement = true;
397       MostDerivedArraySize = CAT->getSize().getZExtValue();
398       MostDerivedPathLength = Entries.size();
399     }
400     /// Update this designator to refer to the first element within the array of
401     /// elements of type T. This is an array of unknown size.
402     void addUnsizedArrayUnchecked(QualType ElemTy) {
403       Entries.push_back(PathEntry::ArrayIndex(0));
404 
405       MostDerivedType = ElemTy;
406       MostDerivedIsArrayElement = true;
407       // The value in MostDerivedArraySize is undefined in this case. So, set it
408       // to an arbitrary value that's likely to loudly break things if it's
409       // used.
410       MostDerivedArraySize = AssumedSizeForUnsizedArray;
411       MostDerivedPathLength = Entries.size();
412     }
413     /// Update this designator to refer to the given base or member of this
414     /// object.
415     void addDeclUnchecked(const Decl *D, bool Virtual = false) {
416       Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
417 
418       // If this isn't a base class, it's a new most-derived object.
419       if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
420         MostDerivedType = FD->getType();
421         MostDerivedIsArrayElement = false;
422         MostDerivedArraySize = 0;
423         MostDerivedPathLength = Entries.size();
424       }
425     }
426     /// Update this designator to refer to the given complex component.
427     void addComplexUnchecked(QualType EltTy, bool Imag) {
428       Entries.push_back(PathEntry::ArrayIndex(Imag));
429 
430       // This is technically a most-derived object, though in practice this
431       // is unlikely to matter.
432       MostDerivedType = EltTy;
433       MostDerivedIsArrayElement = true;
434       MostDerivedArraySize = 2;
435       MostDerivedPathLength = Entries.size();
436     }
437     void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
438     void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
439                                    const APSInt &N);
440     /// Add N to the address of this subobject.
441     void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
442       if (Invalid || !N) return;
443       uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
444       if (isMostDerivedAnUnsizedArray()) {
445         diagnoseUnsizedArrayPointerArithmetic(Info, E);
446         // Can't verify -- trust that the user is doing the right thing (or if
447         // not, trust that the caller will catch the bad behavior).
448         // FIXME: Should we reject if this overflows, at least?
449         Entries.back() = PathEntry::ArrayIndex(
450             Entries.back().getAsArrayIndex() + TruncatedN);
451         return;
452       }
453 
454       // [expr.add]p4: For the purposes of these operators, a pointer to a
455       // nonarray object behaves the same as a pointer to the first element of
456       // an array of length one with the type of the object as its element type.
457       bool IsArray = MostDerivedPathLength == Entries.size() &&
458                      MostDerivedIsArrayElement;
459       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
460                                     : (uint64_t)IsOnePastTheEnd;
461       uint64_t ArraySize =
462           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
463 
464       if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
465         // Calculate the actual index in a wide enough type, so we can include
466         // it in the note.
467         N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
468         (llvm::APInt&)N += ArrayIndex;
469         assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
470         diagnosePointerArithmetic(Info, E, N);
471         setInvalid();
472         return;
473       }
474 
475       ArrayIndex += TruncatedN;
476       assert(ArrayIndex <= ArraySize &&
477              "bounds check succeeded for out-of-bounds index");
478 
479       if (IsArray)
480         Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
481       else
482         IsOnePastTheEnd = (ArrayIndex != 0);
483     }
484   };
485 
486   /// A scope at the end of which an object can need to be destroyed.
487   enum class ScopeKind {
488     Block,
489     FullExpression,
490     Call
491   };
492 
493   /// A reference to a particular call and its arguments.
494   struct CallRef {
495     CallRef() : OrigCallee(), CallIndex(0), Version() {}
496     CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
497         : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
498 
499     explicit operator bool() const { return OrigCallee; }
500 
501     /// Get the parameter that the caller initialized, corresponding to the
502     /// given parameter in the callee.
503     const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
504       return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
505                         : PVD;
506     }
507 
508     /// The callee at the point where the arguments were evaluated. This might
509     /// be different from the actual callee (a different redeclaration, or a
510     /// virtual override), but this function's parameters are the ones that
511     /// appear in the parameter map.
512     const FunctionDecl *OrigCallee;
513     /// The call index of the frame that holds the argument values.
514     unsigned CallIndex;
515     /// The version of the parameters corresponding to this call.
516     unsigned Version;
517   };
518 
519   /// A stack frame in the constexpr call stack.
520   class CallStackFrame : public interp::Frame {
521   public:
522     EvalInfo &Info;
523 
524     /// Parent - The caller of this stack frame.
525     CallStackFrame *Caller;
526 
527     /// Callee - The function which was called.
528     const FunctionDecl *Callee;
529 
530     /// This - The binding for the this pointer in this call, if any.
531     const LValue *This;
532 
533     /// Information on how to find the arguments to this call. Our arguments
534     /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
535     /// key and this value as the version.
536     CallRef Arguments;
537 
538     /// Source location information about the default argument or default
539     /// initializer expression we're evaluating, if any.
540     CurrentSourceLocExprScope CurSourceLocExprScope;
541 
542     // Note that we intentionally use std::map here so that references to
543     // values are stable.
544     typedef std::pair<const void *, unsigned> MapKeyTy;
545     typedef std::map<MapKeyTy, APValue> MapTy;
546     /// Temporaries - Temporary lvalues materialized within this stack frame.
547     MapTy Temporaries;
548 
549     /// CallLoc - The location of the call expression for this call.
550     SourceLocation CallLoc;
551 
552     /// Index - The call index of this call.
553     unsigned Index;
554 
555     /// The stack of integers for tracking version numbers for temporaries.
556     SmallVector<unsigned, 2> TempVersionStack = {1};
557     unsigned CurTempVersion = TempVersionStack.back();
558 
559     unsigned getTempVersion() const { return TempVersionStack.back(); }
560 
561     void pushTempVersion() {
562       TempVersionStack.push_back(++CurTempVersion);
563     }
564 
565     void popTempVersion() {
566       TempVersionStack.pop_back();
567     }
568 
569     CallRef createCall(const FunctionDecl *Callee) {
570       return {Callee, Index, ++CurTempVersion};
571     }
572 
573     // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
574     // on the overall stack usage of deeply-recursing constexpr evaluations.
575     // (We should cache this map rather than recomputing it repeatedly.)
576     // But let's try this and see how it goes; we can look into caching the map
577     // as a later change.
578 
579     /// LambdaCaptureFields - Mapping from captured variables/this to
580     /// corresponding data members in the closure class.
581     llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
582     FieldDecl *LambdaThisCaptureField;
583 
584     CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
585                    const FunctionDecl *Callee, const LValue *This,
586                    CallRef Arguments);
587     ~CallStackFrame();
588 
589     // Return the temporary for Key whose version number is Version.
590     APValue *getTemporary(const void *Key, unsigned Version) {
591       MapKeyTy KV(Key, Version);
592       auto LB = Temporaries.lower_bound(KV);
593       if (LB != Temporaries.end() && LB->first == KV)
594         return &LB->second;
595       // Pair (Key,Version) wasn't found in the map. Check that no elements
596       // in the map have 'Key' as their key.
597       assert((LB == Temporaries.end() || LB->first.first != Key) &&
598              (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
599              "Element with key 'Key' found in map");
600       return nullptr;
601     }
602 
603     // Return the current temporary for Key in the map.
604     APValue *getCurrentTemporary(const void *Key) {
605       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
606       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
607         return &std::prev(UB)->second;
608       return nullptr;
609     }
610 
611     // Return the version number of the current temporary for Key.
612     unsigned getCurrentTemporaryVersion(const void *Key) const {
613       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
614       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
615         return std::prev(UB)->first.second;
616       return 0;
617     }
618 
619     /// Allocate storage for an object of type T in this stack frame.
620     /// Populates LV with a handle to the created object. Key identifies
621     /// the temporary within the stack frame, and must not be reused without
622     /// bumping the temporary version number.
623     template<typename KeyT>
624     APValue &createTemporary(const KeyT *Key, QualType T,
625                              ScopeKind Scope, LValue &LV);
626 
627     /// Allocate storage for a parameter of a function call made in this frame.
628     APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
629 
630     void describe(llvm::raw_ostream &OS) override;
631 
632     Frame *getCaller() const override { return Caller; }
633     SourceLocation getCallLocation() const override { return CallLoc; }
634     const FunctionDecl *getCallee() const override { return Callee; }
635 
636     bool isStdFunction() const {
637       for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
638         if (DC->isStdNamespace())
639           return true;
640       return false;
641     }
642 
643   private:
644     APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
645                          ScopeKind Scope);
646   };
647 
648   /// Temporarily override 'this'.
649   class ThisOverrideRAII {
650   public:
651     ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
652         : Frame(Frame), OldThis(Frame.This) {
653       if (Enable)
654         Frame.This = NewThis;
655     }
656     ~ThisOverrideRAII() {
657       Frame.This = OldThis;
658     }
659   private:
660     CallStackFrame &Frame;
661     const LValue *OldThis;
662   };
663 }
664 
665 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
666                               const LValue &This, QualType ThisType);
667 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
668                               APValue::LValueBase LVBase, APValue &Value,
669                               QualType T);
670 
671 namespace {
672   /// A cleanup, and a flag indicating whether it is lifetime-extended.
673   class Cleanup {
674     llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
675     APValue::LValueBase Base;
676     QualType T;
677 
678   public:
679     Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
680             ScopeKind Scope)
681         : Value(Val, Scope), Base(Base), T(T) {}
682 
683     /// Determine whether this cleanup should be performed at the end of the
684     /// given kind of scope.
685     bool isDestroyedAtEndOf(ScopeKind K) const {
686       return (int)Value.getInt() >= (int)K;
687     }
688     bool endLifetime(EvalInfo &Info, bool RunDestructors) {
689       if (RunDestructors) {
690         SourceLocation Loc;
691         if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
692           Loc = VD->getLocation();
693         else if (const Expr *E = Base.dyn_cast<const Expr*>())
694           Loc = E->getExprLoc();
695         return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
696       }
697       *Value.getPointer() = APValue();
698       return true;
699     }
700 
701     bool hasSideEffect() {
702       return T.isDestructedType();
703     }
704   };
705 
706   /// A reference to an object whose construction we are currently evaluating.
707   struct ObjectUnderConstruction {
708     APValue::LValueBase Base;
709     ArrayRef<APValue::LValuePathEntry> Path;
710     friend bool operator==(const ObjectUnderConstruction &LHS,
711                            const ObjectUnderConstruction &RHS) {
712       return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
713     }
714     friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
715       return llvm::hash_combine(Obj.Base, Obj.Path);
716     }
717   };
718   enum class ConstructionPhase {
719     None,
720     Bases,
721     AfterBases,
722     AfterFields,
723     Destroying,
724     DestroyingBases
725   };
726 }
727 
728 namespace llvm {
729 template<> struct DenseMapInfo<ObjectUnderConstruction> {
730   using Base = DenseMapInfo<APValue::LValueBase>;
731   static ObjectUnderConstruction getEmptyKey() {
732     return {Base::getEmptyKey(), {}}; }
733   static ObjectUnderConstruction getTombstoneKey() {
734     return {Base::getTombstoneKey(), {}};
735   }
736   static unsigned getHashValue(const ObjectUnderConstruction &Object) {
737     return hash_value(Object);
738   }
739   static bool isEqual(const ObjectUnderConstruction &LHS,
740                       const ObjectUnderConstruction &RHS) {
741     return LHS == RHS;
742   }
743 };
744 }
745 
746 namespace {
747   /// A dynamically-allocated heap object.
748   struct DynAlloc {
749     /// The value of this heap-allocated object.
750     APValue Value;
751     /// The allocating expression; used for diagnostics. Either a CXXNewExpr
752     /// or a CallExpr (the latter is for direct calls to operator new inside
753     /// std::allocator<T>::allocate).
754     const Expr *AllocExpr = nullptr;
755 
756     enum Kind {
757       New,
758       ArrayNew,
759       StdAllocator
760     };
761 
762     /// Get the kind of the allocation. This must match between allocation
763     /// and deallocation.
764     Kind getKind() const {
765       if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
766         return NE->isArray() ? ArrayNew : New;
767       assert(isa<CallExpr>(AllocExpr));
768       return StdAllocator;
769     }
770   };
771 
772   struct DynAllocOrder {
773     bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
774       return L.getIndex() < R.getIndex();
775     }
776   };
777 
778   /// EvalInfo - This is a private struct used by the evaluator to capture
779   /// information about a subexpression as it is folded.  It retains information
780   /// about the AST context, but also maintains information about the folded
781   /// expression.
782   ///
783   /// If an expression could be evaluated, it is still possible it is not a C
784   /// "integer constant expression" or constant expression.  If not, this struct
785   /// captures information about how and why not.
786   ///
787   /// One bit of information passed *into* the request for constant folding
788   /// indicates whether the subexpression is "evaluated" or not according to C
789   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
790   /// evaluate the expression regardless of what the RHS is, but C only allows
791   /// certain things in certain situations.
792   class EvalInfo : public interp::State {
793   public:
794     ASTContext &Ctx;
795 
796     /// EvalStatus - Contains information about the evaluation.
797     Expr::EvalStatus &EvalStatus;
798 
799     /// CurrentCall - The top of the constexpr call stack.
800     CallStackFrame *CurrentCall;
801 
802     /// CallStackDepth - The number of calls in the call stack right now.
803     unsigned CallStackDepth;
804 
805     /// NextCallIndex - The next call index to assign.
806     unsigned NextCallIndex;
807 
808     /// StepsLeft - The remaining number of evaluation steps we're permitted
809     /// to perform. This is essentially a limit for the number of statements
810     /// we will evaluate.
811     unsigned StepsLeft;
812 
813     /// Enable the experimental new constant interpreter. If an expression is
814     /// not supported by the interpreter, an error is triggered.
815     bool EnableNewConstInterp;
816 
817     /// BottomFrame - The frame in which evaluation started. This must be
818     /// initialized after CurrentCall and CallStackDepth.
819     CallStackFrame BottomFrame;
820 
821     /// A stack of values whose lifetimes end at the end of some surrounding
822     /// evaluation frame.
823     llvm::SmallVector<Cleanup, 16> CleanupStack;
824 
825     /// EvaluatingDecl - This is the declaration whose initializer is being
826     /// evaluated, if any.
827     APValue::LValueBase EvaluatingDecl;
828 
829     enum class EvaluatingDeclKind {
830       None,
831       /// We're evaluating the construction of EvaluatingDecl.
832       Ctor,
833       /// We're evaluating the destruction of EvaluatingDecl.
834       Dtor,
835     };
836     EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
837 
838     /// EvaluatingDeclValue - This is the value being constructed for the
839     /// declaration whose initializer is being evaluated, if any.
840     APValue *EvaluatingDeclValue;
841 
842     /// Set of objects that are currently being constructed.
843     llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
844         ObjectsUnderConstruction;
845 
846     /// Current heap allocations, along with the location where each was
847     /// allocated. We use std::map here because we need stable addresses
848     /// for the stored APValues.
849     std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
850 
851     /// The number of heap allocations performed so far in this evaluation.
852     unsigned NumHeapAllocs = 0;
853 
854     struct EvaluatingConstructorRAII {
855       EvalInfo &EI;
856       ObjectUnderConstruction Object;
857       bool DidInsert;
858       EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
859                                 bool HasBases)
860           : EI(EI), Object(Object) {
861         DidInsert =
862             EI.ObjectsUnderConstruction
863                 .insert({Object, HasBases ? ConstructionPhase::Bases
864                                           : ConstructionPhase::AfterBases})
865                 .second;
866       }
867       void finishedConstructingBases() {
868         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
869       }
870       void finishedConstructingFields() {
871         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
872       }
873       ~EvaluatingConstructorRAII() {
874         if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
875       }
876     };
877 
878     struct EvaluatingDestructorRAII {
879       EvalInfo &EI;
880       ObjectUnderConstruction Object;
881       bool DidInsert;
882       EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
883           : EI(EI), Object(Object) {
884         DidInsert = EI.ObjectsUnderConstruction
885                         .insert({Object, ConstructionPhase::Destroying})
886                         .second;
887       }
888       void startedDestroyingBases() {
889         EI.ObjectsUnderConstruction[Object] =
890             ConstructionPhase::DestroyingBases;
891       }
892       ~EvaluatingDestructorRAII() {
893         if (DidInsert)
894           EI.ObjectsUnderConstruction.erase(Object);
895       }
896     };
897 
898     ConstructionPhase
899     isEvaluatingCtorDtor(APValue::LValueBase Base,
900                          ArrayRef<APValue::LValuePathEntry> Path) {
901       return ObjectsUnderConstruction.lookup({Base, Path});
902     }
903 
904     /// If we're currently speculatively evaluating, the outermost call stack
905     /// depth at which we can mutate state, otherwise 0.
906     unsigned SpeculativeEvaluationDepth = 0;
907 
908     /// The current array initialization index, if we're performing array
909     /// initialization.
910     uint64_t ArrayInitIndex = -1;
911 
912     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
913     /// notes attached to it will also be stored, otherwise they will not be.
914     bool HasActiveDiagnostic;
915 
916     /// Have we emitted a diagnostic explaining why we couldn't constant
917     /// fold (not just why it's not strictly a constant expression)?
918     bool HasFoldFailureDiagnostic;
919 
920     /// Whether or not we're in a context where the front end requires a
921     /// constant value.
922     bool InConstantContext;
923 
924     /// Whether we're checking that an expression is a potential constant
925     /// expression. If so, do not fail on constructs that could become constant
926     /// later on (such as a use of an undefined global).
927     bool CheckingPotentialConstantExpression = false;
928 
929     /// Whether we're checking for an expression that has undefined behavior.
930     /// If so, we will produce warnings if we encounter an operation that is
931     /// always undefined.
932     ///
933     /// Note that we still need to evaluate the expression normally when this
934     /// is set; this is used when evaluating ICEs in C.
935     bool CheckingForUndefinedBehavior = false;
936 
937     enum EvaluationMode {
938       /// Evaluate as a constant expression. Stop if we find that the expression
939       /// is not a constant expression.
940       EM_ConstantExpression,
941 
942       /// Evaluate as a constant expression. Stop if we find that the expression
943       /// is not a constant expression. Some expressions can be retried in the
944       /// optimizer if we don't constant fold them here, but in an unevaluated
945       /// context we try to fold them immediately since the optimizer never
946       /// gets a chance to look at it.
947       EM_ConstantExpressionUnevaluated,
948 
949       /// Fold the expression to a constant. Stop if we hit a side-effect that
950       /// we can't model.
951       EM_ConstantFold,
952 
953       /// Evaluate in any way we know how. Don't worry about side-effects that
954       /// can't be modeled.
955       EM_IgnoreSideEffects,
956     } EvalMode;
957 
958     /// Are we checking whether the expression is a potential constant
959     /// expression?
960     bool checkingPotentialConstantExpression() const override  {
961       return CheckingPotentialConstantExpression;
962     }
963 
964     /// Are we checking an expression for overflow?
965     // FIXME: We should check for any kind of undefined or suspicious behavior
966     // in such constructs, not just overflow.
967     bool checkingForUndefinedBehavior() const override {
968       return CheckingForUndefinedBehavior;
969     }
970 
971     EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
972         : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
973           CallStackDepth(0), NextCallIndex(1),
974           StepsLeft(C.getLangOpts().ConstexprStepLimit),
975           EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
976           BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()),
977           EvaluatingDecl((const ValueDecl *)nullptr),
978           EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
979           HasFoldFailureDiagnostic(false), InConstantContext(false),
980           EvalMode(Mode) {}
981 
982     ~EvalInfo() {
983       discardCleanups();
984     }
985 
986     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
987                            EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
988       EvaluatingDecl = Base;
989       IsEvaluatingDecl = EDK;
990       EvaluatingDeclValue = &Value;
991     }
992 
993     bool CheckCallLimit(SourceLocation Loc) {
994       // Don't perform any constexpr calls (other than the call we're checking)
995       // when checking a potential constant expression.
996       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
997         return false;
998       if (NextCallIndex == 0) {
999         // NextCallIndex has wrapped around.
1000         FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
1001         return false;
1002       }
1003       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
1004         return true;
1005       FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
1006         << getLangOpts().ConstexprCallDepth;
1007       return false;
1008     }
1009 
1010     std::pair<CallStackFrame *, unsigned>
1011     getCallFrameAndDepth(unsigned CallIndex) {
1012       assert(CallIndex && "no call index in getCallFrameAndDepth");
1013       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1014       // be null in this loop.
1015       unsigned Depth = CallStackDepth;
1016       CallStackFrame *Frame = CurrentCall;
1017       while (Frame->Index > CallIndex) {
1018         Frame = Frame->Caller;
1019         --Depth;
1020       }
1021       if (Frame->Index == CallIndex)
1022         return {Frame, Depth};
1023       return {nullptr, 0};
1024     }
1025 
1026     bool nextStep(const Stmt *S) {
1027       if (!StepsLeft) {
1028         FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1029         return false;
1030       }
1031       --StepsLeft;
1032       return true;
1033     }
1034 
1035     APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1036 
1037     Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) {
1038       Optional<DynAlloc*> Result;
1039       auto It = HeapAllocs.find(DA);
1040       if (It != HeapAllocs.end())
1041         Result = &It->second;
1042       return Result;
1043     }
1044 
1045     /// Get the allocated storage for the given parameter of the given call.
1046     APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1047       CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1048       return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1049                    : nullptr;
1050     }
1051 
1052     /// Information about a stack frame for std::allocator<T>::[de]allocate.
1053     struct StdAllocatorCaller {
1054       unsigned FrameIndex;
1055       QualType ElemType;
1056       explicit operator bool() const { return FrameIndex != 0; };
1057     };
1058 
1059     StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1060       for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1061            Call = Call->Caller) {
1062         const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1063         if (!MD)
1064           continue;
1065         const IdentifierInfo *FnII = MD->getIdentifier();
1066         if (!FnII || !FnII->isStr(FnName))
1067           continue;
1068 
1069         const auto *CTSD =
1070             dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1071         if (!CTSD)
1072           continue;
1073 
1074         const IdentifierInfo *ClassII = CTSD->getIdentifier();
1075         const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1076         if (CTSD->isInStdNamespace() && ClassII &&
1077             ClassII->isStr("allocator") && TAL.size() >= 1 &&
1078             TAL[0].getKind() == TemplateArgument::Type)
1079           return {Call->Index, TAL[0].getAsType()};
1080       }
1081 
1082       return {};
1083     }
1084 
1085     void performLifetimeExtension() {
1086       // Disable the cleanups for lifetime-extended temporaries.
1087       llvm::erase_if(CleanupStack, [](Cleanup &C) {
1088         return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1089       });
1090     }
1091 
1092     /// Throw away any remaining cleanups at the end of evaluation. If any
1093     /// cleanups would have had a side-effect, note that as an unmodeled
1094     /// side-effect and return false. Otherwise, return true.
1095     bool discardCleanups() {
1096       for (Cleanup &C : CleanupStack) {
1097         if (C.hasSideEffect() && !noteSideEffect()) {
1098           CleanupStack.clear();
1099           return false;
1100         }
1101       }
1102       CleanupStack.clear();
1103       return true;
1104     }
1105 
1106   private:
1107     interp::Frame *getCurrentFrame() override { return CurrentCall; }
1108     const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1109 
1110     bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1111     void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1112 
1113     void setFoldFailureDiagnostic(bool Flag) override {
1114       HasFoldFailureDiagnostic = Flag;
1115     }
1116 
1117     Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1118 
1119     ASTContext &getCtx() const override { return Ctx; }
1120 
1121     // If we have a prior diagnostic, it will be noting that the expression
1122     // isn't a constant expression. This diagnostic is more important,
1123     // unless we require this evaluation to produce a constant expression.
1124     //
1125     // FIXME: We might want to show both diagnostics to the user in
1126     // EM_ConstantFold mode.
1127     bool hasPriorDiagnostic() override {
1128       if (!EvalStatus.Diag->empty()) {
1129         switch (EvalMode) {
1130         case EM_ConstantFold:
1131         case EM_IgnoreSideEffects:
1132           if (!HasFoldFailureDiagnostic)
1133             break;
1134           // We've already failed to fold something. Keep that diagnostic.
1135           LLVM_FALLTHROUGH;
1136         case EM_ConstantExpression:
1137         case EM_ConstantExpressionUnevaluated:
1138           setActiveDiagnostic(false);
1139           return true;
1140         }
1141       }
1142       return false;
1143     }
1144 
1145     unsigned getCallStackDepth() override { return CallStackDepth; }
1146 
1147   public:
1148     /// Should we continue evaluation after encountering a side-effect that we
1149     /// couldn't model?
1150     bool keepEvaluatingAfterSideEffect() {
1151       switch (EvalMode) {
1152       case EM_IgnoreSideEffects:
1153         return true;
1154 
1155       case EM_ConstantExpression:
1156       case EM_ConstantExpressionUnevaluated:
1157       case EM_ConstantFold:
1158         // By default, assume any side effect might be valid in some other
1159         // evaluation of this expression from a different context.
1160         return checkingPotentialConstantExpression() ||
1161                checkingForUndefinedBehavior();
1162       }
1163       llvm_unreachable("Missed EvalMode case");
1164     }
1165 
1166     /// Note that we have had a side-effect, and determine whether we should
1167     /// keep evaluating.
1168     bool noteSideEffect() {
1169       EvalStatus.HasSideEffects = true;
1170       return keepEvaluatingAfterSideEffect();
1171     }
1172 
1173     /// Should we continue evaluation after encountering undefined behavior?
1174     bool keepEvaluatingAfterUndefinedBehavior() {
1175       switch (EvalMode) {
1176       case EM_IgnoreSideEffects:
1177       case EM_ConstantFold:
1178         return true;
1179 
1180       case EM_ConstantExpression:
1181       case EM_ConstantExpressionUnevaluated:
1182         return checkingForUndefinedBehavior();
1183       }
1184       llvm_unreachable("Missed EvalMode case");
1185     }
1186 
1187     /// Note that we hit something that was technically undefined behavior, but
1188     /// that we can evaluate past it (such as signed overflow or floating-point
1189     /// division by zero.)
1190     bool noteUndefinedBehavior() override {
1191       EvalStatus.HasUndefinedBehavior = true;
1192       return keepEvaluatingAfterUndefinedBehavior();
1193     }
1194 
1195     /// Should we continue evaluation as much as possible after encountering a
1196     /// construct which can't be reduced to a value?
1197     bool keepEvaluatingAfterFailure() const override {
1198       if (!StepsLeft)
1199         return false;
1200 
1201       switch (EvalMode) {
1202       case EM_ConstantExpression:
1203       case EM_ConstantExpressionUnevaluated:
1204       case EM_ConstantFold:
1205       case EM_IgnoreSideEffects:
1206         return checkingPotentialConstantExpression() ||
1207                checkingForUndefinedBehavior();
1208       }
1209       llvm_unreachable("Missed EvalMode case");
1210     }
1211 
1212     /// Notes that we failed to evaluate an expression that other expressions
1213     /// directly depend on, and determine if we should keep evaluating. This
1214     /// should only be called if we actually intend to keep evaluating.
1215     ///
1216     /// Call noteSideEffect() instead if we may be able to ignore the value that
1217     /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1218     ///
1219     /// (Foo(), 1)      // use noteSideEffect
1220     /// (Foo() || true) // use noteSideEffect
1221     /// Foo() + 1       // use noteFailure
1222     LLVM_NODISCARD bool noteFailure() {
1223       // Failure when evaluating some expression often means there is some
1224       // subexpression whose evaluation was skipped. Therefore, (because we
1225       // don't track whether we skipped an expression when unwinding after an
1226       // evaluation failure) every evaluation failure that bubbles up from a
1227       // subexpression implies that a side-effect has potentially happened. We
1228       // skip setting the HasSideEffects flag to true until we decide to
1229       // continue evaluating after that point, which happens here.
1230       bool KeepGoing = keepEvaluatingAfterFailure();
1231       EvalStatus.HasSideEffects |= KeepGoing;
1232       return KeepGoing;
1233     }
1234 
1235     class ArrayInitLoopIndex {
1236       EvalInfo &Info;
1237       uint64_t OuterIndex;
1238 
1239     public:
1240       ArrayInitLoopIndex(EvalInfo &Info)
1241           : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1242         Info.ArrayInitIndex = 0;
1243       }
1244       ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1245 
1246       operator uint64_t&() { return Info.ArrayInitIndex; }
1247     };
1248   };
1249 
1250   /// Object used to treat all foldable expressions as constant expressions.
1251   struct FoldConstant {
1252     EvalInfo &Info;
1253     bool Enabled;
1254     bool HadNoPriorDiags;
1255     EvalInfo::EvaluationMode OldMode;
1256 
1257     explicit FoldConstant(EvalInfo &Info, bool Enabled)
1258       : Info(Info),
1259         Enabled(Enabled),
1260         HadNoPriorDiags(Info.EvalStatus.Diag &&
1261                         Info.EvalStatus.Diag->empty() &&
1262                         !Info.EvalStatus.HasSideEffects),
1263         OldMode(Info.EvalMode) {
1264       if (Enabled)
1265         Info.EvalMode = EvalInfo::EM_ConstantFold;
1266     }
1267     void keepDiagnostics() { Enabled = false; }
1268     ~FoldConstant() {
1269       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1270           !Info.EvalStatus.HasSideEffects)
1271         Info.EvalStatus.Diag->clear();
1272       Info.EvalMode = OldMode;
1273     }
1274   };
1275 
1276   /// RAII object used to set the current evaluation mode to ignore
1277   /// side-effects.
1278   struct IgnoreSideEffectsRAII {
1279     EvalInfo &Info;
1280     EvalInfo::EvaluationMode OldMode;
1281     explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1282         : Info(Info), OldMode(Info.EvalMode) {
1283       Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1284     }
1285 
1286     ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1287   };
1288 
1289   /// RAII object used to optionally suppress diagnostics and side-effects from
1290   /// a speculative evaluation.
1291   class SpeculativeEvaluationRAII {
1292     EvalInfo *Info = nullptr;
1293     Expr::EvalStatus OldStatus;
1294     unsigned OldSpeculativeEvaluationDepth;
1295 
1296     void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1297       Info = Other.Info;
1298       OldStatus = Other.OldStatus;
1299       OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1300       Other.Info = nullptr;
1301     }
1302 
1303     void maybeRestoreState() {
1304       if (!Info)
1305         return;
1306 
1307       Info->EvalStatus = OldStatus;
1308       Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1309     }
1310 
1311   public:
1312     SpeculativeEvaluationRAII() = default;
1313 
1314     SpeculativeEvaluationRAII(
1315         EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1316         : Info(&Info), OldStatus(Info.EvalStatus),
1317           OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1318       Info.EvalStatus.Diag = NewDiag;
1319       Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1320     }
1321 
1322     SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1323     SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1324       moveFromAndCancel(std::move(Other));
1325     }
1326 
1327     SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1328       maybeRestoreState();
1329       moveFromAndCancel(std::move(Other));
1330       return *this;
1331     }
1332 
1333     ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1334   };
1335 
1336   /// RAII object wrapping a full-expression or block scope, and handling
1337   /// the ending of the lifetime of temporaries created within it.
1338   template<ScopeKind Kind>
1339   class ScopeRAII {
1340     EvalInfo &Info;
1341     unsigned OldStackSize;
1342   public:
1343     ScopeRAII(EvalInfo &Info)
1344         : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1345       // Push a new temporary version. This is needed to distinguish between
1346       // temporaries created in different iterations of a loop.
1347       Info.CurrentCall->pushTempVersion();
1348     }
1349     bool destroy(bool RunDestructors = true) {
1350       bool OK = cleanup(Info, RunDestructors, OldStackSize);
1351       OldStackSize = -1U;
1352       return OK;
1353     }
1354     ~ScopeRAII() {
1355       if (OldStackSize != -1U)
1356         destroy(false);
1357       // Body moved to a static method to encourage the compiler to inline away
1358       // instances of this class.
1359       Info.CurrentCall->popTempVersion();
1360     }
1361   private:
1362     static bool cleanup(EvalInfo &Info, bool RunDestructors,
1363                         unsigned OldStackSize) {
1364       assert(OldStackSize <= Info.CleanupStack.size() &&
1365              "running cleanups out of order?");
1366 
1367       // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1368       // for a full-expression scope.
1369       bool Success = true;
1370       for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1371         if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1372           if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1373             Success = false;
1374             break;
1375           }
1376         }
1377       }
1378 
1379       // Compact any retained cleanups.
1380       auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1381       if (Kind != ScopeKind::Block)
1382         NewEnd =
1383             std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1384               return C.isDestroyedAtEndOf(Kind);
1385             });
1386       Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1387       return Success;
1388     }
1389   };
1390   typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1391   typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1392   typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1393 }
1394 
1395 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1396                                          CheckSubobjectKind CSK) {
1397   if (Invalid)
1398     return false;
1399   if (isOnePastTheEnd()) {
1400     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1401       << CSK;
1402     setInvalid();
1403     return false;
1404   }
1405   // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1406   // must actually be at least one array element; even a VLA cannot have a
1407   // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1408   return true;
1409 }
1410 
1411 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1412                                                                 const Expr *E) {
1413   Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1414   // Do not set the designator as invalid: we can represent this situation,
1415   // and correct handling of __builtin_object_size requires us to do so.
1416 }
1417 
1418 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1419                                                     const Expr *E,
1420                                                     const APSInt &N) {
1421   // If we're complaining, we must be able to statically determine the size of
1422   // the most derived array.
1423   if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1424     Info.CCEDiag(E, diag::note_constexpr_array_index)
1425       << N << /*array*/ 0
1426       << static_cast<unsigned>(getMostDerivedArraySize());
1427   else
1428     Info.CCEDiag(E, diag::note_constexpr_array_index)
1429       << N << /*non-array*/ 1;
1430   setInvalid();
1431 }
1432 
1433 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1434                                const FunctionDecl *Callee, const LValue *This,
1435                                CallRef Call)
1436     : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1437       Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1438   Info.CurrentCall = this;
1439   ++Info.CallStackDepth;
1440 }
1441 
1442 CallStackFrame::~CallStackFrame() {
1443   assert(Info.CurrentCall == this && "calls retired out of order");
1444   --Info.CallStackDepth;
1445   Info.CurrentCall = Caller;
1446 }
1447 
1448 static bool isRead(AccessKinds AK) {
1449   return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1450 }
1451 
1452 static bool isModification(AccessKinds AK) {
1453   switch (AK) {
1454   case AK_Read:
1455   case AK_ReadObjectRepresentation:
1456   case AK_MemberCall:
1457   case AK_DynamicCast:
1458   case AK_TypeId:
1459     return false;
1460   case AK_Assign:
1461   case AK_Increment:
1462   case AK_Decrement:
1463   case AK_Construct:
1464   case AK_Destroy:
1465     return true;
1466   }
1467   llvm_unreachable("unknown access kind");
1468 }
1469 
1470 static bool isAnyAccess(AccessKinds AK) {
1471   return isRead(AK) || isModification(AK);
1472 }
1473 
1474 /// Is this an access per the C++ definition?
1475 static bool isFormalAccess(AccessKinds AK) {
1476   return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
1477 }
1478 
1479 /// Is this kind of axcess valid on an indeterminate object value?
1480 static bool isValidIndeterminateAccess(AccessKinds AK) {
1481   switch (AK) {
1482   case AK_Read:
1483   case AK_Increment:
1484   case AK_Decrement:
1485     // These need the object's value.
1486     return false;
1487 
1488   case AK_ReadObjectRepresentation:
1489   case AK_Assign:
1490   case AK_Construct:
1491   case AK_Destroy:
1492     // Construction and destruction don't need the value.
1493     return true;
1494 
1495   case AK_MemberCall:
1496   case AK_DynamicCast:
1497   case AK_TypeId:
1498     // These aren't really meaningful on scalars.
1499     return true;
1500   }
1501   llvm_unreachable("unknown access kind");
1502 }
1503 
1504 namespace {
1505   struct ComplexValue {
1506   private:
1507     bool IsInt;
1508 
1509   public:
1510     APSInt IntReal, IntImag;
1511     APFloat FloatReal, FloatImag;
1512 
1513     ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1514 
1515     void makeComplexFloat() { IsInt = false; }
1516     bool isComplexFloat() const { return !IsInt; }
1517     APFloat &getComplexFloatReal() { return FloatReal; }
1518     APFloat &getComplexFloatImag() { return FloatImag; }
1519 
1520     void makeComplexInt() { IsInt = true; }
1521     bool isComplexInt() const { return IsInt; }
1522     APSInt &getComplexIntReal() { return IntReal; }
1523     APSInt &getComplexIntImag() { return IntImag; }
1524 
1525     void moveInto(APValue &v) const {
1526       if (isComplexFloat())
1527         v = APValue(FloatReal, FloatImag);
1528       else
1529         v = APValue(IntReal, IntImag);
1530     }
1531     void setFrom(const APValue &v) {
1532       assert(v.isComplexFloat() || v.isComplexInt());
1533       if (v.isComplexFloat()) {
1534         makeComplexFloat();
1535         FloatReal = v.getComplexFloatReal();
1536         FloatImag = v.getComplexFloatImag();
1537       } else {
1538         makeComplexInt();
1539         IntReal = v.getComplexIntReal();
1540         IntImag = v.getComplexIntImag();
1541       }
1542     }
1543   };
1544 
1545   struct LValue {
1546     APValue::LValueBase Base;
1547     CharUnits Offset;
1548     SubobjectDesignator Designator;
1549     bool IsNullPtr : 1;
1550     bool InvalidBase : 1;
1551 
1552     const APValue::LValueBase getLValueBase() const { return Base; }
1553     CharUnits &getLValueOffset() { return Offset; }
1554     const CharUnits &getLValueOffset() const { return Offset; }
1555     SubobjectDesignator &getLValueDesignator() { return Designator; }
1556     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1557     bool isNullPointer() const { return IsNullPtr;}
1558 
1559     unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1560     unsigned getLValueVersion() const { return Base.getVersion(); }
1561 
1562     void moveInto(APValue &V) const {
1563       if (Designator.Invalid)
1564         V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1565       else {
1566         assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1567         V = APValue(Base, Offset, Designator.Entries,
1568                     Designator.IsOnePastTheEnd, IsNullPtr);
1569       }
1570     }
1571     void setFrom(ASTContext &Ctx, const APValue &V) {
1572       assert(V.isLValue() && "Setting LValue from a non-LValue?");
1573       Base = V.getLValueBase();
1574       Offset = V.getLValueOffset();
1575       InvalidBase = false;
1576       Designator = SubobjectDesignator(Ctx, V);
1577       IsNullPtr = V.isNullPointer();
1578     }
1579 
1580     void set(APValue::LValueBase B, bool BInvalid = false) {
1581 #ifndef NDEBUG
1582       // We only allow a few types of invalid bases. Enforce that here.
1583       if (BInvalid) {
1584         const auto *E = B.get<const Expr *>();
1585         assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1586                "Unexpected type of invalid base");
1587       }
1588 #endif
1589 
1590       Base = B;
1591       Offset = CharUnits::fromQuantity(0);
1592       InvalidBase = BInvalid;
1593       Designator = SubobjectDesignator(getType(B));
1594       IsNullPtr = false;
1595     }
1596 
1597     void setNull(ASTContext &Ctx, QualType PointerTy) {
1598       Base = (const ValueDecl *)nullptr;
1599       Offset =
1600           CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
1601       InvalidBase = false;
1602       Designator = SubobjectDesignator(PointerTy->getPointeeType());
1603       IsNullPtr = true;
1604     }
1605 
1606     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1607       set(B, true);
1608     }
1609 
1610     std::string toString(ASTContext &Ctx, QualType T) const {
1611       APValue Printable;
1612       moveInto(Printable);
1613       return Printable.getAsString(Ctx, T);
1614     }
1615 
1616   private:
1617     // Check that this LValue is not based on a null pointer. If it is, produce
1618     // a diagnostic and mark the designator as invalid.
1619     template <typename GenDiagType>
1620     bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1621       if (Designator.Invalid)
1622         return false;
1623       if (IsNullPtr) {
1624         GenDiag();
1625         Designator.setInvalid();
1626         return false;
1627       }
1628       return true;
1629     }
1630 
1631   public:
1632     bool checkNullPointer(EvalInfo &Info, const Expr *E,
1633                           CheckSubobjectKind CSK) {
1634       return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1635         Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1636       });
1637     }
1638 
1639     bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1640                                        AccessKinds AK) {
1641       return checkNullPointerDiagnosingWith([&Info, E, AK] {
1642         Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1643       });
1644     }
1645 
1646     // Check this LValue refers to an object. If not, set the designator to be
1647     // invalid and emit a diagnostic.
1648     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1649       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1650              Designator.checkSubobject(Info, E, CSK);
1651     }
1652 
1653     void addDecl(EvalInfo &Info, const Expr *E,
1654                  const Decl *D, bool Virtual = false) {
1655       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1656         Designator.addDeclUnchecked(D, Virtual);
1657     }
1658     void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1659       if (!Designator.Entries.empty()) {
1660         Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1661         Designator.setInvalid();
1662         return;
1663       }
1664       if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1665         assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1666         Designator.FirstEntryIsAnUnsizedArray = true;
1667         Designator.addUnsizedArrayUnchecked(ElemTy);
1668       }
1669     }
1670     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1671       if (checkSubobject(Info, E, CSK_ArrayToPointer))
1672         Designator.addArrayUnchecked(CAT);
1673     }
1674     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1675       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1676         Designator.addComplexUnchecked(EltTy, Imag);
1677     }
1678     void clearIsNullPointer() {
1679       IsNullPtr = false;
1680     }
1681     void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1682                               const APSInt &Index, CharUnits ElementSize) {
1683       // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1684       // but we're not required to diagnose it and it's valid in C++.)
1685       if (!Index)
1686         return;
1687 
1688       // Compute the new offset in the appropriate width, wrapping at 64 bits.
1689       // FIXME: When compiling for a 32-bit target, we should use 32-bit
1690       // offsets.
1691       uint64_t Offset64 = Offset.getQuantity();
1692       uint64_t ElemSize64 = ElementSize.getQuantity();
1693       uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1694       Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1695 
1696       if (checkNullPointer(Info, E, CSK_ArrayIndex))
1697         Designator.adjustIndex(Info, E, Index);
1698       clearIsNullPointer();
1699     }
1700     void adjustOffset(CharUnits N) {
1701       Offset += N;
1702       if (N.getQuantity())
1703         clearIsNullPointer();
1704     }
1705   };
1706 
1707   struct MemberPtr {
1708     MemberPtr() {}
1709     explicit MemberPtr(const ValueDecl *Decl)
1710         : DeclAndIsDerivedMember(Decl, false) {}
1711 
1712     /// The member or (direct or indirect) field referred to by this member
1713     /// pointer, or 0 if this is a null member pointer.
1714     const ValueDecl *getDecl() const {
1715       return DeclAndIsDerivedMember.getPointer();
1716     }
1717     /// Is this actually a member of some type derived from the relevant class?
1718     bool isDerivedMember() const {
1719       return DeclAndIsDerivedMember.getInt();
1720     }
1721     /// Get the class which the declaration actually lives in.
1722     const CXXRecordDecl *getContainingRecord() const {
1723       return cast<CXXRecordDecl>(
1724           DeclAndIsDerivedMember.getPointer()->getDeclContext());
1725     }
1726 
1727     void moveInto(APValue &V) const {
1728       V = APValue(getDecl(), isDerivedMember(), Path);
1729     }
1730     void setFrom(const APValue &V) {
1731       assert(V.isMemberPointer());
1732       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1733       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1734       Path.clear();
1735       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1736       Path.insert(Path.end(), P.begin(), P.end());
1737     }
1738 
1739     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1740     /// whether the member is a member of some class derived from the class type
1741     /// of the member pointer.
1742     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1743     /// Path - The path of base/derived classes from the member declaration's
1744     /// class (exclusive) to the class type of the member pointer (inclusive).
1745     SmallVector<const CXXRecordDecl*, 4> Path;
1746 
1747     /// Perform a cast towards the class of the Decl (either up or down the
1748     /// hierarchy).
1749     bool castBack(const CXXRecordDecl *Class) {
1750       assert(!Path.empty());
1751       const CXXRecordDecl *Expected;
1752       if (Path.size() >= 2)
1753         Expected = Path[Path.size() - 2];
1754       else
1755         Expected = getContainingRecord();
1756       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1757         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1758         // if B does not contain the original member and is not a base or
1759         // derived class of the class containing the original member, the result
1760         // of the cast is undefined.
1761         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1762         // (D::*). We consider that to be a language defect.
1763         return false;
1764       }
1765       Path.pop_back();
1766       return true;
1767     }
1768     /// Perform a base-to-derived member pointer cast.
1769     bool castToDerived(const CXXRecordDecl *Derived) {
1770       if (!getDecl())
1771         return true;
1772       if (!isDerivedMember()) {
1773         Path.push_back(Derived);
1774         return true;
1775       }
1776       if (!castBack(Derived))
1777         return false;
1778       if (Path.empty())
1779         DeclAndIsDerivedMember.setInt(false);
1780       return true;
1781     }
1782     /// Perform a derived-to-base member pointer cast.
1783     bool castToBase(const CXXRecordDecl *Base) {
1784       if (!getDecl())
1785         return true;
1786       if (Path.empty())
1787         DeclAndIsDerivedMember.setInt(true);
1788       if (isDerivedMember()) {
1789         Path.push_back(Base);
1790         return true;
1791       }
1792       return castBack(Base);
1793     }
1794   };
1795 
1796   /// Compare two member pointers, which are assumed to be of the same type.
1797   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1798     if (!LHS.getDecl() || !RHS.getDecl())
1799       return !LHS.getDecl() && !RHS.getDecl();
1800     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1801       return false;
1802     return LHS.Path == RHS.Path;
1803   }
1804 }
1805 
1806 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1807 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1808                             const LValue &This, const Expr *E,
1809                             bool AllowNonLiteralTypes = false);
1810 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1811                            bool InvalidBaseOK = false);
1812 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1813                             bool InvalidBaseOK = false);
1814 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1815                                   EvalInfo &Info);
1816 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1817 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1818 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1819                                     EvalInfo &Info);
1820 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1821 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1822 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1823                            EvalInfo &Info);
1824 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1825 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
1826                                   EvalInfo &Info);
1827 
1828 /// Evaluate an integer or fixed point expression into an APResult.
1829 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1830                                         EvalInfo &Info);
1831 
1832 /// Evaluate only a fixed point expression into an APResult.
1833 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1834                                EvalInfo &Info);
1835 
1836 //===----------------------------------------------------------------------===//
1837 // Misc utilities
1838 //===----------------------------------------------------------------------===//
1839 
1840 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1841 /// preserving its value (by extending by up to one bit as needed).
1842 static void negateAsSigned(APSInt &Int) {
1843   if (Int.isUnsigned() || Int.isMinSignedValue()) {
1844     Int = Int.extend(Int.getBitWidth() + 1);
1845     Int.setIsSigned(true);
1846   }
1847   Int = -Int;
1848 }
1849 
1850 template<typename KeyT>
1851 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1852                                          ScopeKind Scope, LValue &LV) {
1853   unsigned Version = getTempVersion();
1854   APValue::LValueBase Base(Key, Index, Version);
1855   LV.set(Base);
1856   return createLocal(Base, Key, T, Scope);
1857 }
1858 
1859 /// Allocate storage for a parameter of a function call made in this frame.
1860 APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1861                                      LValue &LV) {
1862   assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1863   APValue::LValueBase Base(PVD, Index, Args.Version);
1864   LV.set(Base);
1865   // We always destroy parameters at the end of the call, even if we'd allow
1866   // them to live to the end of the full-expression at runtime, in order to
1867   // give portable results and match other compilers.
1868   return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1869 }
1870 
1871 APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1872                                      QualType T, ScopeKind Scope) {
1873   assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1874   unsigned Version = Base.getVersion();
1875   APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1876   assert(Result.isAbsent() && "local created multiple times");
1877 
1878   // If we're creating a local immediately in the operand of a speculative
1879   // evaluation, don't register a cleanup to be run outside the speculative
1880   // evaluation context, since we won't actually be able to initialize this
1881   // object.
1882   if (Index <= Info.SpeculativeEvaluationDepth) {
1883     if (T.isDestructedType())
1884       Info.noteSideEffect();
1885   } else {
1886     Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1887   }
1888   return Result;
1889 }
1890 
1891 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1892   if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1893     FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1894     return nullptr;
1895   }
1896 
1897   DynamicAllocLValue DA(NumHeapAllocs++);
1898   LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1899   auto Result = HeapAllocs.emplace(std::piecewise_construct,
1900                                    std::forward_as_tuple(DA), std::tuple<>());
1901   assert(Result.second && "reused a heap alloc index?");
1902   Result.first->second.AllocExpr = E;
1903   return &Result.first->second.Value;
1904 }
1905 
1906 /// Produce a string describing the given constexpr call.
1907 void CallStackFrame::describe(raw_ostream &Out) {
1908   unsigned ArgIndex = 0;
1909   bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1910                       !isa<CXXConstructorDecl>(Callee) &&
1911                       cast<CXXMethodDecl>(Callee)->isInstance();
1912 
1913   if (!IsMemberCall)
1914     Out << *Callee << '(';
1915 
1916   if (This && IsMemberCall) {
1917     APValue Val;
1918     This->moveInto(Val);
1919     Val.printPretty(Out, Info.Ctx,
1920                     This->Designator.MostDerivedType);
1921     // FIXME: Add parens around Val if needed.
1922     Out << "->" << *Callee << '(';
1923     IsMemberCall = false;
1924   }
1925 
1926   for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1927        E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
1928     if (ArgIndex > (unsigned)IsMemberCall)
1929       Out << ", ";
1930 
1931     const ParmVarDecl *Param = *I;
1932     APValue *V = Info.getParamSlot(Arguments, Param);
1933     if (V)
1934       V->printPretty(Out, Info.Ctx, Param->getType());
1935     else
1936       Out << "<...>";
1937 
1938     if (ArgIndex == 0 && IsMemberCall)
1939       Out << "->" << *Callee << '(';
1940   }
1941 
1942   Out << ')';
1943 }
1944 
1945 /// Evaluate an expression to see if it had side-effects, and discard its
1946 /// result.
1947 /// \return \c true if the caller should keep evaluating.
1948 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1949   assert(!E->isValueDependent());
1950   APValue Scratch;
1951   if (!Evaluate(Scratch, Info, E))
1952     // We don't need the value, but we might have skipped a side effect here.
1953     return Info.noteSideEffect();
1954   return true;
1955 }
1956 
1957 /// Should this call expression be treated as a constant?
1958 static bool IsConstantCall(const CallExpr *E) {
1959   unsigned Builtin = E->getBuiltinCallee();
1960   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1961           Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
1962           Builtin == Builtin::BI__builtin_function_start);
1963 }
1964 
1965 static bool IsGlobalLValue(APValue::LValueBase B) {
1966   // C++11 [expr.const]p3 An address constant expression is a prvalue core
1967   // constant expression of pointer type that evaluates to...
1968 
1969   // ... a null pointer value, or a prvalue core constant expression of type
1970   // std::nullptr_t.
1971   if (!B) return true;
1972 
1973   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1974     // ... the address of an object with static storage duration,
1975     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1976       return VD->hasGlobalStorage();
1977     if (isa<TemplateParamObjectDecl>(D))
1978       return true;
1979     // ... the address of a function,
1980     // ... the address of a GUID [MS extension],
1981     return isa<FunctionDecl>(D) || isa<MSGuidDecl>(D);
1982   }
1983 
1984   if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
1985     return true;
1986 
1987   const Expr *E = B.get<const Expr*>();
1988   switch (E->getStmtClass()) {
1989   default:
1990     return false;
1991   case Expr::CompoundLiteralExprClass: {
1992     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1993     return CLE->isFileScope() && CLE->isLValue();
1994   }
1995   case Expr::MaterializeTemporaryExprClass:
1996     // A materialized temporary might have been lifetime-extended to static
1997     // storage duration.
1998     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1999   // A string literal has static storage duration.
2000   case Expr::StringLiteralClass:
2001   case Expr::PredefinedExprClass:
2002   case Expr::ObjCStringLiteralClass:
2003   case Expr::ObjCEncodeExprClass:
2004     return true;
2005   case Expr::ObjCBoxedExprClass:
2006     return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2007   case Expr::CallExprClass:
2008     return IsConstantCall(cast<CallExpr>(E));
2009   // For GCC compatibility, &&label has static storage duration.
2010   case Expr::AddrLabelExprClass:
2011     return true;
2012   // A Block literal expression may be used as the initialization value for
2013   // Block variables at global or local static scope.
2014   case Expr::BlockExprClass:
2015     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2016   case Expr::ImplicitValueInitExprClass:
2017     // FIXME:
2018     // We can never form an lvalue with an implicit value initialization as its
2019     // base through expression evaluation, so these only appear in one case: the
2020     // implicit variable declaration we invent when checking whether a constexpr
2021     // constructor can produce a constant expression. We must assume that such
2022     // an expression might be a global lvalue.
2023     return true;
2024   }
2025 }
2026 
2027 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2028   return LVal.Base.dyn_cast<const ValueDecl*>();
2029 }
2030 
2031 static bool IsLiteralLValue(const LValue &Value) {
2032   if (Value.getLValueCallIndex())
2033     return false;
2034   const Expr *E = Value.Base.dyn_cast<const Expr*>();
2035   return E && !isa<MaterializeTemporaryExpr>(E);
2036 }
2037 
2038 static bool IsWeakLValue(const LValue &Value) {
2039   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2040   return Decl && Decl->isWeak();
2041 }
2042 
2043 static bool isZeroSized(const LValue &Value) {
2044   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2045   if (Decl && isa<VarDecl>(Decl)) {
2046     QualType Ty = Decl->getType();
2047     if (Ty->isArrayType())
2048       return Ty->isIncompleteType() ||
2049              Decl->getASTContext().getTypeSize(Ty) == 0;
2050   }
2051   return false;
2052 }
2053 
2054 static bool HasSameBase(const LValue &A, const LValue &B) {
2055   if (!A.getLValueBase())
2056     return !B.getLValueBase();
2057   if (!B.getLValueBase())
2058     return false;
2059 
2060   if (A.getLValueBase().getOpaqueValue() !=
2061       B.getLValueBase().getOpaqueValue())
2062     return false;
2063 
2064   return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2065          A.getLValueVersion() == B.getLValueVersion();
2066 }
2067 
2068 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2069   assert(Base && "no location for a null lvalue");
2070   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2071 
2072   // For a parameter, find the corresponding call stack frame (if it still
2073   // exists), and point at the parameter of the function definition we actually
2074   // invoked.
2075   if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2076     unsigned Idx = PVD->getFunctionScopeIndex();
2077     for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2078       if (F->Arguments.CallIndex == Base.getCallIndex() &&
2079           F->Arguments.Version == Base.getVersion() && F->Callee &&
2080           Idx < F->Callee->getNumParams()) {
2081         VD = F->Callee->getParamDecl(Idx);
2082         break;
2083       }
2084     }
2085   }
2086 
2087   if (VD)
2088     Info.Note(VD->getLocation(), diag::note_declared_at);
2089   else if (const Expr *E = Base.dyn_cast<const Expr*>())
2090     Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2091   else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2092     // FIXME: Produce a note for dangling pointers too.
2093     if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA))
2094       Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2095                 diag::note_constexpr_dynamic_alloc_here);
2096   }
2097   // We have no information to show for a typeid(T) object.
2098 }
2099 
2100 enum class CheckEvaluationResultKind {
2101   ConstantExpression,
2102   FullyInitialized,
2103 };
2104 
2105 /// Materialized temporaries that we've already checked to determine if they're
2106 /// initializsed by a constant expression.
2107 using CheckedTemporaries =
2108     llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
2109 
2110 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2111                                   EvalInfo &Info, SourceLocation DiagLoc,
2112                                   QualType Type, const APValue &Value,
2113                                   ConstantExprKind Kind,
2114                                   SourceLocation SubobjectLoc,
2115                                   CheckedTemporaries &CheckedTemps);
2116 
2117 /// Check that this reference or pointer core constant expression is a valid
2118 /// value for an address or reference constant expression. Return true if we
2119 /// can fold this expression, whether or not it's a constant expression.
2120 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2121                                           QualType Type, const LValue &LVal,
2122                                           ConstantExprKind Kind,
2123                                           CheckedTemporaries &CheckedTemps) {
2124   bool IsReferenceType = Type->isReferenceType();
2125 
2126   APValue::LValueBase Base = LVal.getLValueBase();
2127   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2128 
2129   const Expr *BaseE = Base.dyn_cast<const Expr *>();
2130   const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2131 
2132   // Additional restrictions apply in a template argument. We only enforce the
2133   // C++20 restrictions here; additional syntactic and semantic restrictions
2134   // are applied elsewhere.
2135   if (isTemplateArgument(Kind)) {
2136     int InvalidBaseKind = -1;
2137     StringRef Ident;
2138     if (Base.is<TypeInfoLValue>())
2139       InvalidBaseKind = 0;
2140     else if (isa_and_nonnull<StringLiteral>(BaseE))
2141       InvalidBaseKind = 1;
2142     else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2143              isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2144       InvalidBaseKind = 2;
2145     else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2146       InvalidBaseKind = 3;
2147       Ident = PE->getIdentKindName();
2148     }
2149 
2150     if (InvalidBaseKind != -1) {
2151       Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2152           << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2153           << Ident;
2154       return false;
2155     }
2156   }
2157 
2158   if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD)) {
2159     if (FD->isConsteval()) {
2160       Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2161           << !Type->isAnyPointerType();
2162       Info.Note(FD->getLocation(), diag::note_declared_at);
2163       return false;
2164     }
2165   }
2166 
2167   // Check that the object is a global. Note that the fake 'this' object we
2168   // manufacture when checking potential constant expressions is conservatively
2169   // assumed to be global here.
2170   if (!IsGlobalLValue(Base)) {
2171     if (Info.getLangOpts().CPlusPlus11) {
2172       const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2173       Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2174         << IsReferenceType << !Designator.Entries.empty()
2175         << !!VD << VD;
2176 
2177       auto *VarD = dyn_cast_or_null<VarDecl>(VD);
2178       if (VarD && VarD->isConstexpr()) {
2179         // Non-static local constexpr variables have unintuitive semantics:
2180         //   constexpr int a = 1;
2181         //   constexpr const int *p = &a;
2182         // ... is invalid because the address of 'a' is not constant. Suggest
2183         // adding a 'static' in this case.
2184         Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2185             << VarD
2186             << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2187       } else {
2188         NoteLValueLocation(Info, Base);
2189       }
2190     } else {
2191       Info.FFDiag(Loc);
2192     }
2193     // Don't allow references to temporaries to escape.
2194     return false;
2195   }
2196   assert((Info.checkingPotentialConstantExpression() ||
2197           LVal.getLValueCallIndex() == 0) &&
2198          "have call index for global lvalue");
2199 
2200   if (Base.is<DynamicAllocLValue>()) {
2201     Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2202         << IsReferenceType << !Designator.Entries.empty();
2203     NoteLValueLocation(Info, Base);
2204     return false;
2205   }
2206 
2207   if (BaseVD) {
2208     if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2209       // Check if this is a thread-local variable.
2210       if (Var->getTLSKind())
2211         // FIXME: Diagnostic!
2212         return false;
2213 
2214       // A dllimport variable never acts like a constant, unless we're
2215       // evaluating a value for use only in name mangling.
2216       if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2217         // FIXME: Diagnostic!
2218         return false;
2219     }
2220     if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2221       // __declspec(dllimport) must be handled very carefully:
2222       // We must never initialize an expression with the thunk in C++.
2223       // Doing otherwise would allow the same id-expression to yield
2224       // different addresses for the same function in different translation
2225       // units.  However, this means that we must dynamically initialize the
2226       // expression with the contents of the import address table at runtime.
2227       //
2228       // The C language has no notion of ODR; furthermore, it has no notion of
2229       // dynamic initialization.  This means that we are permitted to
2230       // perform initialization with the address of the thunk.
2231       if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2232           FD->hasAttr<DLLImportAttr>())
2233         // FIXME: Diagnostic!
2234         return false;
2235     }
2236   } else if (const auto *MTE =
2237                  dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2238     if (CheckedTemps.insert(MTE).second) {
2239       QualType TempType = getType(Base);
2240       if (TempType.isDestructedType()) {
2241         Info.FFDiag(MTE->getExprLoc(),
2242                     diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2243             << TempType;
2244         return false;
2245       }
2246 
2247       APValue *V = MTE->getOrCreateValue(false);
2248       assert(V && "evasluation result refers to uninitialised temporary");
2249       if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2250                                  Info, MTE->getExprLoc(), TempType, *V,
2251                                  Kind, SourceLocation(), CheckedTemps))
2252         return false;
2253     }
2254   }
2255 
2256   // Allow address constant expressions to be past-the-end pointers. This is
2257   // an extension: the standard requires them to point to an object.
2258   if (!IsReferenceType)
2259     return true;
2260 
2261   // A reference constant expression must refer to an object.
2262   if (!Base) {
2263     // FIXME: diagnostic
2264     Info.CCEDiag(Loc);
2265     return true;
2266   }
2267 
2268   // Does this refer one past the end of some object?
2269   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2270     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2271       << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2272     NoteLValueLocation(Info, Base);
2273   }
2274 
2275   return true;
2276 }
2277 
2278 /// Member pointers are constant expressions unless they point to a
2279 /// non-virtual dllimport member function.
2280 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2281                                                  SourceLocation Loc,
2282                                                  QualType Type,
2283                                                  const APValue &Value,
2284                                                  ConstantExprKind Kind) {
2285   const ValueDecl *Member = Value.getMemberPointerDecl();
2286   const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2287   if (!FD)
2288     return true;
2289   if (FD->isConsteval()) {
2290     Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2291     Info.Note(FD->getLocation(), diag::note_declared_at);
2292     return false;
2293   }
2294   return isForManglingOnly(Kind) || FD->isVirtual() ||
2295          !FD->hasAttr<DLLImportAttr>();
2296 }
2297 
2298 /// Check that this core constant expression is of literal type, and if not,
2299 /// produce an appropriate diagnostic.
2300 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2301                              const LValue *This = nullptr) {
2302   if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2303     return true;
2304 
2305   // C++1y: A constant initializer for an object o [...] may also invoke
2306   // constexpr constructors for o and its subobjects even if those objects
2307   // are of non-literal class types.
2308   //
2309   // C++11 missed this detail for aggregates, so classes like this:
2310   //   struct foo_t { union { int i; volatile int j; } u; };
2311   // are not (obviously) initializable like so:
2312   //   __attribute__((__require_constant_initialization__))
2313   //   static const foo_t x = {{0}};
2314   // because "i" is a subobject with non-literal initialization (due to the
2315   // volatile member of the union). See:
2316   //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2317   // Therefore, we use the C++1y behavior.
2318   if (This && Info.EvaluatingDecl == This->getLValueBase())
2319     return true;
2320 
2321   // Prvalue constant expressions must be of literal types.
2322   if (Info.getLangOpts().CPlusPlus11)
2323     Info.FFDiag(E, diag::note_constexpr_nonliteral)
2324       << E->getType();
2325   else
2326     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2327   return false;
2328 }
2329 
2330 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2331                                   EvalInfo &Info, SourceLocation DiagLoc,
2332                                   QualType Type, const APValue &Value,
2333                                   ConstantExprKind Kind,
2334                                   SourceLocation SubobjectLoc,
2335                                   CheckedTemporaries &CheckedTemps) {
2336   if (!Value.hasValue()) {
2337     Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2338       << true << Type;
2339     if (SubobjectLoc.isValid())
2340       Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2341     return false;
2342   }
2343 
2344   // We allow _Atomic(T) to be initialized from anything that T can be
2345   // initialized from.
2346   if (const AtomicType *AT = Type->getAs<AtomicType>())
2347     Type = AT->getValueType();
2348 
2349   // Core issue 1454: For a literal constant expression of array or class type,
2350   // each subobject of its value shall have been initialized by a constant
2351   // expression.
2352   if (Value.isArray()) {
2353     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2354     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2355       if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2356                                  Value.getArrayInitializedElt(I), Kind,
2357                                  SubobjectLoc, CheckedTemps))
2358         return false;
2359     }
2360     if (!Value.hasArrayFiller())
2361       return true;
2362     return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2363                                  Value.getArrayFiller(), Kind, SubobjectLoc,
2364                                  CheckedTemps);
2365   }
2366   if (Value.isUnion() && Value.getUnionField()) {
2367     return CheckEvaluationResult(
2368         CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2369         Value.getUnionValue(), Kind, Value.getUnionField()->getLocation(),
2370         CheckedTemps);
2371   }
2372   if (Value.isStruct()) {
2373     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2374     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2375       unsigned BaseIndex = 0;
2376       for (const CXXBaseSpecifier &BS : CD->bases()) {
2377         if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2378                                    Value.getStructBase(BaseIndex), Kind,
2379                                    BS.getBeginLoc(), CheckedTemps))
2380           return false;
2381         ++BaseIndex;
2382       }
2383     }
2384     for (const auto *I : RD->fields()) {
2385       if (I->isUnnamedBitfield())
2386         continue;
2387 
2388       if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2389                                  Value.getStructField(I->getFieldIndex()),
2390                                  Kind, I->getLocation(), CheckedTemps))
2391         return false;
2392     }
2393   }
2394 
2395   if (Value.isLValue() &&
2396       CERK == CheckEvaluationResultKind::ConstantExpression) {
2397     LValue LVal;
2398     LVal.setFrom(Info.Ctx, Value);
2399     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2400                                          CheckedTemps);
2401   }
2402 
2403   if (Value.isMemberPointer() &&
2404       CERK == CheckEvaluationResultKind::ConstantExpression)
2405     return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2406 
2407   // Everything else is fine.
2408   return true;
2409 }
2410 
2411 /// Check that this core constant expression value is a valid value for a
2412 /// constant expression. If not, report an appropriate diagnostic. Does not
2413 /// check that the expression is of literal type.
2414 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2415                                     QualType Type, const APValue &Value,
2416                                     ConstantExprKind Kind) {
2417   // Nothing to check for a constant expression of type 'cv void'.
2418   if (Type->isVoidType())
2419     return true;
2420 
2421   CheckedTemporaries CheckedTemps;
2422   return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2423                                Info, DiagLoc, Type, Value, Kind,
2424                                SourceLocation(), CheckedTemps);
2425 }
2426 
2427 /// Check that this evaluated value is fully-initialized and can be loaded by
2428 /// an lvalue-to-rvalue conversion.
2429 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2430                                   QualType Type, const APValue &Value) {
2431   CheckedTemporaries CheckedTemps;
2432   return CheckEvaluationResult(
2433       CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2434       ConstantExprKind::Normal, SourceLocation(), CheckedTemps);
2435 }
2436 
2437 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2438 /// "the allocated storage is deallocated within the evaluation".
2439 static bool CheckMemoryLeaks(EvalInfo &Info) {
2440   if (!Info.HeapAllocs.empty()) {
2441     // We can still fold to a constant despite a compile-time memory leak,
2442     // so long as the heap allocation isn't referenced in the result (we check
2443     // that in CheckConstantExpression).
2444     Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2445                  diag::note_constexpr_memory_leak)
2446         << unsigned(Info.HeapAllocs.size() - 1);
2447   }
2448   return true;
2449 }
2450 
2451 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2452   // A null base expression indicates a null pointer.  These are always
2453   // evaluatable, and they are false unless the offset is zero.
2454   if (!Value.getLValueBase()) {
2455     Result = !Value.getLValueOffset().isZero();
2456     return true;
2457   }
2458 
2459   // We have a non-null base.  These are generally known to be true, but if it's
2460   // a weak declaration it can be null at runtime.
2461   Result = true;
2462   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2463   return !Decl || !Decl->isWeak();
2464 }
2465 
2466 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2467   switch (Val.getKind()) {
2468   case APValue::None:
2469   case APValue::Indeterminate:
2470     return false;
2471   case APValue::Int:
2472     Result = Val.getInt().getBoolValue();
2473     return true;
2474   case APValue::FixedPoint:
2475     Result = Val.getFixedPoint().getBoolValue();
2476     return true;
2477   case APValue::Float:
2478     Result = !Val.getFloat().isZero();
2479     return true;
2480   case APValue::ComplexInt:
2481     Result = Val.getComplexIntReal().getBoolValue() ||
2482              Val.getComplexIntImag().getBoolValue();
2483     return true;
2484   case APValue::ComplexFloat:
2485     Result = !Val.getComplexFloatReal().isZero() ||
2486              !Val.getComplexFloatImag().isZero();
2487     return true;
2488   case APValue::LValue:
2489     return EvalPointerValueAsBool(Val, Result);
2490   case APValue::MemberPointer:
2491     Result = Val.getMemberPointerDecl();
2492     return true;
2493   case APValue::Vector:
2494   case APValue::Array:
2495   case APValue::Struct:
2496   case APValue::Union:
2497   case APValue::AddrLabelDiff:
2498     return false;
2499   }
2500 
2501   llvm_unreachable("unknown APValue kind");
2502 }
2503 
2504 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2505                                        EvalInfo &Info) {
2506   assert(!E->isValueDependent());
2507   assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2508   APValue Val;
2509   if (!Evaluate(Val, Info, E))
2510     return false;
2511   return HandleConversionToBool(Val, Result);
2512 }
2513 
2514 template<typename T>
2515 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2516                            const T &SrcValue, QualType DestType) {
2517   Info.CCEDiag(E, diag::note_constexpr_overflow)
2518     << SrcValue << DestType;
2519   return Info.noteUndefinedBehavior();
2520 }
2521 
2522 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2523                                  QualType SrcType, const APFloat &Value,
2524                                  QualType DestType, APSInt &Result) {
2525   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2526   // Determine whether we are converting to unsigned or signed.
2527   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2528 
2529   Result = APSInt(DestWidth, !DestSigned);
2530   bool ignored;
2531   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2532       & APFloat::opInvalidOp)
2533     return HandleOverflow(Info, E, Value, DestType);
2534   return true;
2535 }
2536 
2537 /// Get rounding mode used for evaluation of the specified expression.
2538 /// \param[out] DynamicRM Is set to true is the requested rounding mode is
2539 ///                       dynamic.
2540 /// If rounding mode is unknown at compile time, still try to evaluate the
2541 /// expression. If the result is exact, it does not depend on rounding mode.
2542 /// So return "tonearest" mode instead of "dynamic".
2543 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E,
2544                                                 bool &DynamicRM) {
2545   llvm::RoundingMode RM =
2546       E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2547   DynamicRM = (RM == llvm::RoundingMode::Dynamic);
2548   if (DynamicRM)
2549     RM = llvm::RoundingMode::NearestTiesToEven;
2550   return RM;
2551 }
2552 
2553 /// Check if the given evaluation result is allowed for constant evaluation.
2554 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2555                                      APFloat::opStatus St) {
2556   // In a constant context, assume that any dynamic rounding mode or FP
2557   // exception state matches the default floating-point environment.
2558   if (Info.InConstantContext)
2559     return true;
2560 
2561   FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2562   if ((St & APFloat::opInexact) &&
2563       FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2564     // Inexact result means that it depends on rounding mode. If the requested
2565     // mode is dynamic, the evaluation cannot be made in compile time.
2566     Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2567     return false;
2568   }
2569 
2570   if ((St != APFloat::opOK) &&
2571       (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2572        FPO.getFPExceptionMode() != LangOptions::FPE_Ignore ||
2573        FPO.getAllowFEnvAccess())) {
2574     Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2575     return false;
2576   }
2577 
2578   if ((St & APFloat::opStatus::opInvalidOp) &&
2579       FPO.getFPExceptionMode() != LangOptions::FPE_Ignore) {
2580     // There is no usefully definable result.
2581     Info.FFDiag(E);
2582     return false;
2583   }
2584 
2585   // FIXME: if:
2586   // - evaluation triggered other FP exception, and
2587   // - exception mode is not "ignore", and
2588   // - the expression being evaluated is not a part of global variable
2589   //   initializer,
2590   // the evaluation probably need to be rejected.
2591   return true;
2592 }
2593 
2594 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2595                                    QualType SrcType, QualType DestType,
2596                                    APFloat &Result) {
2597   assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E));
2598   bool DynamicRM;
2599   llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM);
2600   APFloat::opStatus St;
2601   APFloat Value = Result;
2602   bool ignored;
2603   St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2604   return checkFloatingPointResult(Info, E, St);
2605 }
2606 
2607 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2608                                  QualType DestType, QualType SrcType,
2609                                  const APSInt &Value) {
2610   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2611   // Figure out if this is a truncate, extend or noop cast.
2612   // If the input is signed, do a sign extend, noop, or truncate.
2613   APSInt Result = Value.extOrTrunc(DestWidth);
2614   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2615   if (DestType->isBooleanType())
2616     Result = Value.getBoolValue();
2617   return Result;
2618 }
2619 
2620 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2621                                  const FPOptions FPO,
2622                                  QualType SrcType, const APSInt &Value,
2623                                  QualType DestType, APFloat &Result) {
2624   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2625   APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(),
2626        APFloat::rmNearestTiesToEven);
2627   if (!Info.InConstantContext && St != llvm::APFloatBase::opOK &&
2628       FPO.isFPConstrained()) {
2629     Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2630     return false;
2631   }
2632   return true;
2633 }
2634 
2635 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2636                                   APValue &Value, const FieldDecl *FD) {
2637   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2638 
2639   if (!Value.isInt()) {
2640     // Trying to store a pointer-cast-to-integer into a bitfield.
2641     // FIXME: In this case, we should provide the diagnostic for casting
2642     // a pointer to an integer.
2643     assert(Value.isLValue() && "integral value neither int nor lvalue?");
2644     Info.FFDiag(E);
2645     return false;
2646   }
2647 
2648   APSInt &Int = Value.getInt();
2649   unsigned OldBitWidth = Int.getBitWidth();
2650   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2651   if (NewBitWidth < OldBitWidth)
2652     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2653   return true;
2654 }
2655 
2656 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2657                                   llvm::APInt &Res) {
2658   APValue SVal;
2659   if (!Evaluate(SVal, Info, E))
2660     return false;
2661   if (SVal.isInt()) {
2662     Res = SVal.getInt();
2663     return true;
2664   }
2665   if (SVal.isFloat()) {
2666     Res = SVal.getFloat().bitcastToAPInt();
2667     return true;
2668   }
2669   if (SVal.isVector()) {
2670     QualType VecTy = E->getType();
2671     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2672     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2673     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2674     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2675     Res = llvm::APInt::getZero(VecSize);
2676     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2677       APValue &Elt = SVal.getVectorElt(i);
2678       llvm::APInt EltAsInt;
2679       if (Elt.isInt()) {
2680         EltAsInt = Elt.getInt();
2681       } else if (Elt.isFloat()) {
2682         EltAsInt = Elt.getFloat().bitcastToAPInt();
2683       } else {
2684         // Don't try to handle vectors of anything other than int or float
2685         // (not sure if it's possible to hit this case).
2686         Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2687         return false;
2688       }
2689       unsigned BaseEltSize = EltAsInt.getBitWidth();
2690       if (BigEndian)
2691         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2692       else
2693         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2694     }
2695     return true;
2696   }
2697   // Give up if the input isn't an int, float, or vector.  For example, we
2698   // reject "(v4i16)(intptr_t)&a".
2699   Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2700   return false;
2701 }
2702 
2703 /// Perform the given integer operation, which is known to need at most BitWidth
2704 /// bits, and check for overflow in the original type (if that type was not an
2705 /// unsigned type).
2706 template<typename Operation>
2707 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2708                                  const APSInt &LHS, const APSInt &RHS,
2709                                  unsigned BitWidth, Operation Op,
2710                                  APSInt &Result) {
2711   if (LHS.isUnsigned()) {
2712     Result = Op(LHS, RHS);
2713     return true;
2714   }
2715 
2716   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2717   Result = Value.trunc(LHS.getBitWidth());
2718   if (Result.extend(BitWidth) != Value) {
2719     if (Info.checkingForUndefinedBehavior())
2720       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2721                                        diag::warn_integer_constant_overflow)
2722           << toString(Result, 10) << E->getType();
2723     return HandleOverflow(Info, E, Value, E->getType());
2724   }
2725   return true;
2726 }
2727 
2728 /// Perform the given binary integer operation.
2729 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2730                               BinaryOperatorKind Opcode, APSInt RHS,
2731                               APSInt &Result) {
2732   switch (Opcode) {
2733   default:
2734     Info.FFDiag(E);
2735     return false;
2736   case BO_Mul:
2737     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2738                                 std::multiplies<APSInt>(), Result);
2739   case BO_Add:
2740     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2741                                 std::plus<APSInt>(), Result);
2742   case BO_Sub:
2743     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2744                                 std::minus<APSInt>(), Result);
2745   case BO_And: Result = LHS & RHS; return true;
2746   case BO_Xor: Result = LHS ^ RHS; return true;
2747   case BO_Or:  Result = LHS | RHS; return true;
2748   case BO_Div:
2749   case BO_Rem:
2750     if (RHS == 0) {
2751       Info.FFDiag(E, diag::note_expr_divide_by_zero);
2752       return false;
2753     }
2754     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2755     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2756     // this operation and gives the two's complement result.
2757     if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2758         LHS.isMinSignedValue())
2759       return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2760                             E->getType());
2761     return true;
2762   case BO_Shl: {
2763     if (Info.getLangOpts().OpenCL)
2764       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2765       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2766                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2767                     RHS.isUnsigned());
2768     else if (RHS.isSigned() && RHS.isNegative()) {
2769       // During constant-folding, a negative shift is an opposite shift. Such
2770       // a shift is not a constant expression.
2771       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2772       RHS = -RHS;
2773       goto shift_right;
2774     }
2775   shift_left:
2776     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2777     // the shifted type.
2778     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2779     if (SA != RHS) {
2780       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2781         << RHS << E->getType() << LHS.getBitWidth();
2782     } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2783       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2784       // operand, and must not overflow the corresponding unsigned type.
2785       // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2786       // E1 x 2^E2 module 2^N.
2787       if (LHS.isNegative())
2788         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2789       else if (LHS.countLeadingZeros() < SA)
2790         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2791     }
2792     Result = LHS << SA;
2793     return true;
2794   }
2795   case BO_Shr: {
2796     if (Info.getLangOpts().OpenCL)
2797       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2798       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2799                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2800                     RHS.isUnsigned());
2801     else if (RHS.isSigned() && RHS.isNegative()) {
2802       // During constant-folding, a negative shift is an opposite shift. Such a
2803       // shift is not a constant expression.
2804       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2805       RHS = -RHS;
2806       goto shift_left;
2807     }
2808   shift_right:
2809     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2810     // shifted type.
2811     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2812     if (SA != RHS)
2813       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2814         << RHS << E->getType() << LHS.getBitWidth();
2815     Result = LHS >> SA;
2816     return true;
2817   }
2818 
2819   case BO_LT: Result = LHS < RHS; return true;
2820   case BO_GT: Result = LHS > RHS; return true;
2821   case BO_LE: Result = LHS <= RHS; return true;
2822   case BO_GE: Result = LHS >= RHS; return true;
2823   case BO_EQ: Result = LHS == RHS; return true;
2824   case BO_NE: Result = LHS != RHS; return true;
2825   case BO_Cmp:
2826     llvm_unreachable("BO_Cmp should be handled elsewhere");
2827   }
2828 }
2829 
2830 /// Perform the given binary floating-point operation, in-place, on LHS.
2831 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2832                                   APFloat &LHS, BinaryOperatorKind Opcode,
2833                                   const APFloat &RHS) {
2834   bool DynamicRM;
2835   llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM);
2836   APFloat::opStatus St;
2837   switch (Opcode) {
2838   default:
2839     Info.FFDiag(E);
2840     return false;
2841   case BO_Mul:
2842     St = LHS.multiply(RHS, RM);
2843     break;
2844   case BO_Add:
2845     St = LHS.add(RHS, RM);
2846     break;
2847   case BO_Sub:
2848     St = LHS.subtract(RHS, RM);
2849     break;
2850   case BO_Div:
2851     // [expr.mul]p4:
2852     //   If the second operand of / or % is zero the behavior is undefined.
2853     if (RHS.isZero())
2854       Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2855     St = LHS.divide(RHS, RM);
2856     break;
2857   }
2858 
2859   // [expr.pre]p4:
2860   //   If during the evaluation of an expression, the result is not
2861   //   mathematically defined [...], the behavior is undefined.
2862   // FIXME: C++ rules require us to not conform to IEEE 754 here.
2863   if (LHS.isNaN()) {
2864     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2865     return Info.noteUndefinedBehavior();
2866   }
2867 
2868   return checkFloatingPointResult(Info, E, St);
2869 }
2870 
2871 static bool handleLogicalOpForVector(const APInt &LHSValue,
2872                                      BinaryOperatorKind Opcode,
2873                                      const APInt &RHSValue, APInt &Result) {
2874   bool LHS = (LHSValue != 0);
2875   bool RHS = (RHSValue != 0);
2876 
2877   if (Opcode == BO_LAnd)
2878     Result = LHS && RHS;
2879   else
2880     Result = LHS || RHS;
2881   return true;
2882 }
2883 static bool handleLogicalOpForVector(const APFloat &LHSValue,
2884                                      BinaryOperatorKind Opcode,
2885                                      const APFloat &RHSValue, APInt &Result) {
2886   bool LHS = !LHSValue.isZero();
2887   bool RHS = !RHSValue.isZero();
2888 
2889   if (Opcode == BO_LAnd)
2890     Result = LHS && RHS;
2891   else
2892     Result = LHS || RHS;
2893   return true;
2894 }
2895 
2896 static bool handleLogicalOpForVector(const APValue &LHSValue,
2897                                      BinaryOperatorKind Opcode,
2898                                      const APValue &RHSValue, APInt &Result) {
2899   // The result is always an int type, however operands match the first.
2900   if (LHSValue.getKind() == APValue::Int)
2901     return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2902                                     RHSValue.getInt(), Result);
2903   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2904   return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2905                                   RHSValue.getFloat(), Result);
2906 }
2907 
2908 template <typename APTy>
2909 static bool
2910 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
2911                                const APTy &RHSValue, APInt &Result) {
2912   switch (Opcode) {
2913   default:
2914     llvm_unreachable("unsupported binary operator");
2915   case BO_EQ:
2916     Result = (LHSValue == RHSValue);
2917     break;
2918   case BO_NE:
2919     Result = (LHSValue != RHSValue);
2920     break;
2921   case BO_LT:
2922     Result = (LHSValue < RHSValue);
2923     break;
2924   case BO_GT:
2925     Result = (LHSValue > RHSValue);
2926     break;
2927   case BO_LE:
2928     Result = (LHSValue <= RHSValue);
2929     break;
2930   case BO_GE:
2931     Result = (LHSValue >= RHSValue);
2932     break;
2933   }
2934 
2935   // The boolean operations on these vector types use an instruction that
2936   // results in a mask of '-1' for the 'truth' value.  Ensure that we negate 1
2937   // to -1 to make sure that we produce the correct value.
2938   Result.negate();
2939 
2940   return true;
2941 }
2942 
2943 static bool handleCompareOpForVector(const APValue &LHSValue,
2944                                      BinaryOperatorKind Opcode,
2945                                      const APValue &RHSValue, APInt &Result) {
2946   // The result is always an int type, however operands match the first.
2947   if (LHSValue.getKind() == APValue::Int)
2948     return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
2949                                           RHSValue.getInt(), Result);
2950   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2951   return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
2952                                         RHSValue.getFloat(), Result);
2953 }
2954 
2955 // Perform binary operations for vector types, in place on the LHS.
2956 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
2957                                     BinaryOperatorKind Opcode,
2958                                     APValue &LHSValue,
2959                                     const APValue &RHSValue) {
2960   assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
2961          "Operation not supported on vector types");
2962 
2963   const auto *VT = E->getType()->castAs<VectorType>();
2964   unsigned NumElements = VT->getNumElements();
2965   QualType EltTy = VT->getElementType();
2966 
2967   // In the cases (typically C as I've observed) where we aren't evaluating
2968   // constexpr but are checking for cases where the LHS isn't yet evaluatable,
2969   // just give up.
2970   if (!LHSValue.isVector()) {
2971     assert(LHSValue.isLValue() &&
2972            "A vector result that isn't a vector OR uncalculated LValue");
2973     Info.FFDiag(E);
2974     return false;
2975   }
2976 
2977   assert(LHSValue.getVectorLength() == NumElements &&
2978          RHSValue.getVectorLength() == NumElements && "Different vector sizes");
2979 
2980   SmallVector<APValue, 4> ResultElements;
2981 
2982   for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
2983     APValue LHSElt = LHSValue.getVectorElt(EltNum);
2984     APValue RHSElt = RHSValue.getVectorElt(EltNum);
2985 
2986     if (EltTy->isIntegerType()) {
2987       APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
2988                        EltTy->isUnsignedIntegerType()};
2989       bool Success = true;
2990 
2991       if (BinaryOperator::isLogicalOp(Opcode))
2992         Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
2993       else if (BinaryOperator::isComparisonOp(Opcode))
2994         Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
2995       else
2996         Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
2997                                     RHSElt.getInt(), EltResult);
2998 
2999       if (!Success) {
3000         Info.FFDiag(E);
3001         return false;
3002       }
3003       ResultElements.emplace_back(EltResult);
3004 
3005     } else if (EltTy->isFloatingType()) {
3006       assert(LHSElt.getKind() == APValue::Float &&
3007              RHSElt.getKind() == APValue::Float &&
3008              "Mismatched LHS/RHS/Result Type");
3009       APFloat LHSFloat = LHSElt.getFloat();
3010 
3011       if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3012                                  RHSElt.getFloat())) {
3013         Info.FFDiag(E);
3014         return false;
3015       }
3016 
3017       ResultElements.emplace_back(LHSFloat);
3018     }
3019   }
3020 
3021   LHSValue = APValue(ResultElements.data(), ResultElements.size());
3022   return true;
3023 }
3024 
3025 /// Cast an lvalue referring to a base subobject to a derived class, by
3026 /// truncating the lvalue's path to the given length.
3027 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3028                                const RecordDecl *TruncatedType,
3029                                unsigned TruncatedElements) {
3030   SubobjectDesignator &D = Result.Designator;
3031 
3032   // Check we actually point to a derived class object.
3033   if (TruncatedElements == D.Entries.size())
3034     return true;
3035   assert(TruncatedElements >= D.MostDerivedPathLength &&
3036          "not casting to a derived class");
3037   if (!Result.checkSubobject(Info, E, CSK_Derived))
3038     return false;
3039 
3040   // Truncate the path to the subobject, and remove any derived-to-base offsets.
3041   const RecordDecl *RD = TruncatedType;
3042   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3043     if (RD->isInvalidDecl()) return false;
3044     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3045     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3046     if (isVirtualBaseClass(D.Entries[I]))
3047       Result.Offset -= Layout.getVBaseClassOffset(Base);
3048     else
3049       Result.Offset -= Layout.getBaseClassOffset(Base);
3050     RD = Base;
3051   }
3052   D.Entries.resize(TruncatedElements);
3053   return true;
3054 }
3055 
3056 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3057                                    const CXXRecordDecl *Derived,
3058                                    const CXXRecordDecl *Base,
3059                                    const ASTRecordLayout *RL = nullptr) {
3060   if (!RL) {
3061     if (Derived->isInvalidDecl()) return false;
3062     RL = &Info.Ctx.getASTRecordLayout(Derived);
3063   }
3064 
3065   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3066   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3067   return true;
3068 }
3069 
3070 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3071                              const CXXRecordDecl *DerivedDecl,
3072                              const CXXBaseSpecifier *Base) {
3073   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3074 
3075   if (!Base->isVirtual())
3076     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3077 
3078   SubobjectDesignator &D = Obj.Designator;
3079   if (D.Invalid)
3080     return false;
3081 
3082   // Extract most-derived object and corresponding type.
3083   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3084   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3085     return false;
3086 
3087   // Find the virtual base class.
3088   if (DerivedDecl->isInvalidDecl()) return false;
3089   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3090   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3091   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3092   return true;
3093 }
3094 
3095 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3096                                  QualType Type, LValue &Result) {
3097   for (CastExpr::path_const_iterator PathI = E->path_begin(),
3098                                      PathE = E->path_end();
3099        PathI != PathE; ++PathI) {
3100     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3101                           *PathI))
3102       return false;
3103     Type = (*PathI)->getType();
3104   }
3105   return true;
3106 }
3107 
3108 /// Cast an lvalue referring to a derived class to a known base subobject.
3109 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3110                             const CXXRecordDecl *DerivedRD,
3111                             const CXXRecordDecl *BaseRD) {
3112   CXXBasePaths Paths(/*FindAmbiguities=*/false,
3113                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
3114   if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3115     llvm_unreachable("Class must be derived from the passed in base class!");
3116 
3117   for (CXXBasePathElement &Elem : Paths.front())
3118     if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3119       return false;
3120   return true;
3121 }
3122 
3123 /// Update LVal to refer to the given field, which must be a member of the type
3124 /// currently described by LVal.
3125 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3126                                const FieldDecl *FD,
3127                                const ASTRecordLayout *RL = nullptr) {
3128   if (!RL) {
3129     if (FD->getParent()->isInvalidDecl()) return false;
3130     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3131   }
3132 
3133   unsigned I = FD->getFieldIndex();
3134   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3135   LVal.addDecl(Info, E, FD);
3136   return true;
3137 }
3138 
3139 /// Update LVal to refer to the given indirect field.
3140 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3141                                        LValue &LVal,
3142                                        const IndirectFieldDecl *IFD) {
3143   for (const auto *C : IFD->chain())
3144     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3145       return false;
3146   return true;
3147 }
3148 
3149 /// Get the size of the given type in char units.
3150 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
3151                          QualType Type, CharUnits &Size) {
3152   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3153   // extension.
3154   if (Type->isVoidType() || Type->isFunctionType()) {
3155     Size = CharUnits::One();
3156     return true;
3157   }
3158 
3159   if (Type->isDependentType()) {
3160     Info.FFDiag(Loc);
3161     return false;
3162   }
3163 
3164   if (!Type->isConstantSizeType()) {
3165     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3166     // FIXME: Better diagnostic.
3167     Info.FFDiag(Loc);
3168     return false;
3169   }
3170 
3171   Size = Info.Ctx.getTypeSizeInChars(Type);
3172   return true;
3173 }
3174 
3175 /// Update a pointer value to model pointer arithmetic.
3176 /// \param Info - Information about the ongoing evaluation.
3177 /// \param E - The expression being evaluated, for diagnostic purposes.
3178 /// \param LVal - The pointer value to be updated.
3179 /// \param EltTy - The pointee type represented by LVal.
3180 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3181 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3182                                         LValue &LVal, QualType EltTy,
3183                                         APSInt Adjustment) {
3184   CharUnits SizeOfPointee;
3185   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3186     return false;
3187 
3188   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3189   return true;
3190 }
3191 
3192 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3193                                         LValue &LVal, QualType EltTy,
3194                                         int64_t Adjustment) {
3195   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3196                                      APSInt::get(Adjustment));
3197 }
3198 
3199 /// Update an lvalue to refer to a component of a complex number.
3200 /// \param Info - Information about the ongoing evaluation.
3201 /// \param LVal - The lvalue to be updated.
3202 /// \param EltTy - The complex number's component type.
3203 /// \param Imag - False for the real component, true for the imaginary.
3204 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3205                                        LValue &LVal, QualType EltTy,
3206                                        bool Imag) {
3207   if (Imag) {
3208     CharUnits SizeOfComponent;
3209     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3210       return false;
3211     LVal.Offset += SizeOfComponent;
3212   }
3213   LVal.addComplex(Info, E, EltTy, Imag);
3214   return true;
3215 }
3216 
3217 /// Try to evaluate the initializer for a variable declaration.
3218 ///
3219 /// \param Info   Information about the ongoing evaluation.
3220 /// \param E      An expression to be used when printing diagnostics.
3221 /// \param VD     The variable whose initializer should be obtained.
3222 /// \param Version The version of the variable within the frame.
3223 /// \param Frame  The frame in which the variable was created. Must be null
3224 ///               if this variable is not local to the evaluation.
3225 /// \param Result Filled in with a pointer to the value of the variable.
3226 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3227                                 const VarDecl *VD, CallStackFrame *Frame,
3228                                 unsigned Version, APValue *&Result) {
3229   APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3230 
3231   // If this is a local variable, dig out its value.
3232   if (Frame) {
3233     Result = Frame->getTemporary(VD, Version);
3234     if (Result)
3235       return true;
3236 
3237     if (!isa<ParmVarDecl>(VD)) {
3238       // Assume variables referenced within a lambda's call operator that were
3239       // not declared within the call operator are captures and during checking
3240       // of a potential constant expression, assume they are unknown constant
3241       // expressions.
3242       assert(isLambdaCallOperator(Frame->Callee) &&
3243              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3244              "missing value for local variable");
3245       if (Info.checkingPotentialConstantExpression())
3246         return false;
3247       // FIXME: This diagnostic is bogus; we do support captures. Is this code
3248       // still reachable at all?
3249       Info.FFDiag(E->getBeginLoc(),
3250                   diag::note_unimplemented_constexpr_lambda_feature_ast)
3251           << "captures not currently allowed";
3252       return false;
3253     }
3254   }
3255 
3256   // If we're currently evaluating the initializer of this declaration, use that
3257   // in-flight value.
3258   if (Info.EvaluatingDecl == Base) {
3259     Result = Info.EvaluatingDeclValue;
3260     return true;
3261   }
3262 
3263   if (isa<ParmVarDecl>(VD)) {
3264     // Assume parameters of a potential constant expression are usable in
3265     // constant expressions.
3266     if (!Info.checkingPotentialConstantExpression() ||
3267         !Info.CurrentCall->Callee ||
3268         !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3269       if (Info.getLangOpts().CPlusPlus11) {
3270         Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3271             << VD;
3272         NoteLValueLocation(Info, Base);
3273       } else {
3274         Info.FFDiag(E);
3275       }
3276     }
3277     return false;
3278   }
3279 
3280   // Dig out the initializer, and use the declaration which it's attached to.
3281   // FIXME: We should eventually check whether the variable has a reachable
3282   // initializing declaration.
3283   const Expr *Init = VD->getAnyInitializer(VD);
3284   if (!Init) {
3285     // Don't diagnose during potential constant expression checking; an
3286     // initializer might be added later.
3287     if (!Info.checkingPotentialConstantExpression()) {
3288       Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3289         << VD;
3290       NoteLValueLocation(Info, Base);
3291     }
3292     return false;
3293   }
3294 
3295   if (Init->isValueDependent()) {
3296     // The DeclRefExpr is not value-dependent, but the variable it refers to
3297     // has a value-dependent initializer. This should only happen in
3298     // constant-folding cases, where the variable is not actually of a suitable
3299     // type for use in a constant expression (otherwise the DeclRefExpr would
3300     // have been value-dependent too), so diagnose that.
3301     assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3302     if (!Info.checkingPotentialConstantExpression()) {
3303       Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3304                          ? diag::note_constexpr_ltor_non_constexpr
3305                          : diag::note_constexpr_ltor_non_integral, 1)
3306           << VD << VD->getType();
3307       NoteLValueLocation(Info, Base);
3308     }
3309     return false;
3310   }
3311 
3312   // Check that we can fold the initializer. In C++, we will have already done
3313   // this in the cases where it matters for conformance.
3314   if (!VD->evaluateValue()) {
3315     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3316     NoteLValueLocation(Info, Base);
3317     return false;
3318   }
3319 
3320   // Check that the variable is actually usable in constant expressions. For a
3321   // const integral variable or a reference, we might have a non-constant
3322   // initializer that we can nonetheless evaluate the initializer for. Such
3323   // variables are not usable in constant expressions. In C++98, the
3324   // initializer also syntactically needs to be an ICE.
3325   //
3326   // FIXME: We don't diagnose cases that aren't potentially usable in constant
3327   // expressions here; doing so would regress diagnostics for things like
3328   // reading from a volatile constexpr variable.
3329   if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3330        VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||
3331       ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3332        !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3333     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3334     NoteLValueLocation(Info, Base);
3335   }
3336 
3337   // Never use the initializer of a weak variable, not even for constant
3338   // folding. We can't be sure that this is the definition that will be used.
3339   if (VD->isWeak()) {
3340     Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3341     NoteLValueLocation(Info, Base);
3342     return false;
3343   }
3344 
3345   Result = VD->getEvaluatedValue();
3346   return true;
3347 }
3348 
3349 /// Get the base index of the given base class within an APValue representing
3350 /// the given derived class.
3351 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3352                              const CXXRecordDecl *Base) {
3353   Base = Base->getCanonicalDecl();
3354   unsigned Index = 0;
3355   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3356          E = Derived->bases_end(); I != E; ++I, ++Index) {
3357     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3358       return Index;
3359   }
3360 
3361   llvm_unreachable("base class missing from derived class's bases list");
3362 }
3363 
3364 /// Extract the value of a character from a string literal.
3365 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3366                                             uint64_t Index) {
3367   assert(!isa<SourceLocExpr>(Lit) &&
3368          "SourceLocExpr should have already been converted to a StringLiteral");
3369 
3370   // FIXME: Support MakeStringConstant
3371   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3372     std::string Str;
3373     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3374     assert(Index <= Str.size() && "Index too large");
3375     return APSInt::getUnsigned(Str.c_str()[Index]);
3376   }
3377 
3378   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3379     Lit = PE->getFunctionName();
3380   const StringLiteral *S = cast<StringLiteral>(Lit);
3381   const ConstantArrayType *CAT =
3382       Info.Ctx.getAsConstantArrayType(S->getType());
3383   assert(CAT && "string literal isn't an array");
3384   QualType CharType = CAT->getElementType();
3385   assert(CharType->isIntegerType() && "unexpected character type");
3386 
3387   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3388                CharType->isUnsignedIntegerType());
3389   if (Index < S->getLength())
3390     Value = S->getCodeUnit(Index);
3391   return Value;
3392 }
3393 
3394 // Expand a string literal into an array of characters.
3395 //
3396 // FIXME: This is inefficient; we should probably introduce something similar
3397 // to the LLVM ConstantDataArray to make this cheaper.
3398 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3399                                 APValue &Result,
3400                                 QualType AllocType = QualType()) {
3401   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3402       AllocType.isNull() ? S->getType() : AllocType);
3403   assert(CAT && "string literal isn't an array");
3404   QualType CharType = CAT->getElementType();
3405   assert(CharType->isIntegerType() && "unexpected character type");
3406 
3407   unsigned Elts = CAT->getSize().getZExtValue();
3408   Result = APValue(APValue::UninitArray(),
3409                    std::min(S->getLength(), Elts), Elts);
3410   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3411                CharType->isUnsignedIntegerType());
3412   if (Result.hasArrayFiller())
3413     Result.getArrayFiller() = APValue(Value);
3414   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3415     Value = S->getCodeUnit(I);
3416     Result.getArrayInitializedElt(I) = APValue(Value);
3417   }
3418 }
3419 
3420 // Expand an array so that it has more than Index filled elements.
3421 static void expandArray(APValue &Array, unsigned Index) {
3422   unsigned Size = Array.getArraySize();
3423   assert(Index < Size);
3424 
3425   // Always at least double the number of elements for which we store a value.
3426   unsigned OldElts = Array.getArrayInitializedElts();
3427   unsigned NewElts = std::max(Index+1, OldElts * 2);
3428   NewElts = std::min(Size, std::max(NewElts, 8u));
3429 
3430   // Copy the data across.
3431   APValue NewValue(APValue::UninitArray(), NewElts, Size);
3432   for (unsigned I = 0; I != OldElts; ++I)
3433     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3434   for (unsigned I = OldElts; I != NewElts; ++I)
3435     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3436   if (NewValue.hasArrayFiller())
3437     NewValue.getArrayFiller() = Array.getArrayFiller();
3438   Array.swap(NewValue);
3439 }
3440 
3441 /// Determine whether a type would actually be read by an lvalue-to-rvalue
3442 /// conversion. If it's of class type, we may assume that the copy operation
3443 /// is trivial. Note that this is never true for a union type with fields
3444 /// (because the copy always "reads" the active member) and always true for
3445 /// a non-class type.
3446 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3447 static bool isReadByLvalueToRvalueConversion(QualType T) {
3448   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3449   return !RD || isReadByLvalueToRvalueConversion(RD);
3450 }
3451 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3452   // FIXME: A trivial copy of a union copies the object representation, even if
3453   // the union is empty.
3454   if (RD->isUnion())
3455     return !RD->field_empty();
3456   if (RD->isEmpty())
3457     return false;
3458 
3459   for (auto *Field : RD->fields())
3460     if (!Field->isUnnamedBitfield() &&
3461         isReadByLvalueToRvalueConversion(Field->getType()))
3462       return true;
3463 
3464   for (auto &BaseSpec : RD->bases())
3465     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3466       return true;
3467 
3468   return false;
3469 }
3470 
3471 /// Diagnose an attempt to read from any unreadable field within the specified
3472 /// type, which might be a class type.
3473 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3474                                   QualType T) {
3475   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3476   if (!RD)
3477     return false;
3478 
3479   if (!RD->hasMutableFields())
3480     return false;
3481 
3482   for (auto *Field : RD->fields()) {
3483     // If we're actually going to read this field in some way, then it can't
3484     // be mutable. If we're in a union, then assigning to a mutable field
3485     // (even an empty one) can change the active member, so that's not OK.
3486     // FIXME: Add core issue number for the union case.
3487     if (Field->isMutable() &&
3488         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3489       Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3490       Info.Note(Field->getLocation(), diag::note_declared_at);
3491       return true;
3492     }
3493 
3494     if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3495       return true;
3496   }
3497 
3498   for (auto &BaseSpec : RD->bases())
3499     if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3500       return true;
3501 
3502   // All mutable fields were empty, and thus not actually read.
3503   return false;
3504 }
3505 
3506 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3507                                         APValue::LValueBase Base,
3508                                         bool MutableSubobject = false) {
3509   // A temporary or transient heap allocation we created.
3510   if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3511     return true;
3512 
3513   switch (Info.IsEvaluatingDecl) {
3514   case EvalInfo::EvaluatingDeclKind::None:
3515     return false;
3516 
3517   case EvalInfo::EvaluatingDeclKind::Ctor:
3518     // The variable whose initializer we're evaluating.
3519     if (Info.EvaluatingDecl == Base)
3520       return true;
3521 
3522     // A temporary lifetime-extended by the variable whose initializer we're
3523     // evaluating.
3524     if (auto *BaseE = Base.dyn_cast<const Expr *>())
3525       if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3526         return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3527     return false;
3528 
3529   case EvalInfo::EvaluatingDeclKind::Dtor:
3530     // C++2a [expr.const]p6:
3531     //   [during constant destruction] the lifetime of a and its non-mutable
3532     //   subobjects (but not its mutable subobjects) [are] considered to start
3533     //   within e.
3534     if (MutableSubobject || Base != Info.EvaluatingDecl)
3535       return false;
3536     // FIXME: We can meaningfully extend this to cover non-const objects, but
3537     // we will need special handling: we should be able to access only
3538     // subobjects of such objects that are themselves declared const.
3539     QualType T = getType(Base);
3540     return T.isConstQualified() || T->isReferenceType();
3541   }
3542 
3543   llvm_unreachable("unknown evaluating decl kind");
3544 }
3545 
3546 namespace {
3547 /// A handle to a complete object (an object that is not a subobject of
3548 /// another object).
3549 struct CompleteObject {
3550   /// The identity of the object.
3551   APValue::LValueBase Base;
3552   /// The value of the complete object.
3553   APValue *Value;
3554   /// The type of the complete object.
3555   QualType Type;
3556 
3557   CompleteObject() : Value(nullptr) {}
3558   CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3559       : Base(Base), Value(Value), Type(Type) {}
3560 
3561   bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3562     // If this isn't a "real" access (eg, if it's just accessing the type
3563     // info), allow it. We assume the type doesn't change dynamically for
3564     // subobjects of constexpr objects (even though we'd hit UB here if it
3565     // did). FIXME: Is this right?
3566     if (!isAnyAccess(AK))
3567       return true;
3568 
3569     // In C++14 onwards, it is permitted to read a mutable member whose
3570     // lifetime began within the evaluation.
3571     // FIXME: Should we also allow this in C++11?
3572     if (!Info.getLangOpts().CPlusPlus14)
3573       return false;
3574     return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3575   }
3576 
3577   explicit operator bool() const { return !Type.isNull(); }
3578 };
3579 } // end anonymous namespace
3580 
3581 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3582                                  bool IsMutable = false) {
3583   // C++ [basic.type.qualifier]p1:
3584   // - A const object is an object of type const T or a non-mutable subobject
3585   //   of a const object.
3586   if (ObjType.isConstQualified() && !IsMutable)
3587     SubobjType.addConst();
3588   // - A volatile object is an object of type const T or a subobject of a
3589   //   volatile object.
3590   if (ObjType.isVolatileQualified())
3591     SubobjType.addVolatile();
3592   return SubobjType;
3593 }
3594 
3595 /// Find the designated sub-object of an rvalue.
3596 template<typename SubobjectHandler>
3597 typename SubobjectHandler::result_type
3598 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3599               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3600   if (Sub.Invalid)
3601     // A diagnostic will have already been produced.
3602     return handler.failed();
3603   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3604     if (Info.getLangOpts().CPlusPlus11)
3605       Info.FFDiag(E, Sub.isOnePastTheEnd()
3606                          ? diag::note_constexpr_access_past_end
3607                          : diag::note_constexpr_access_unsized_array)
3608           << handler.AccessKind;
3609     else
3610       Info.FFDiag(E);
3611     return handler.failed();
3612   }
3613 
3614   APValue *O = Obj.Value;
3615   QualType ObjType = Obj.Type;
3616   const FieldDecl *LastField = nullptr;
3617   const FieldDecl *VolatileField = nullptr;
3618 
3619   // Walk the designator's path to find the subobject.
3620   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3621     // Reading an indeterminate value is undefined, but assigning over one is OK.
3622     if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3623         (O->isIndeterminate() &&
3624          !isValidIndeterminateAccess(handler.AccessKind))) {
3625       if (!Info.checkingPotentialConstantExpression())
3626         Info.FFDiag(E, diag::note_constexpr_access_uninit)
3627             << handler.AccessKind << O->isIndeterminate();
3628       return handler.failed();
3629     }
3630 
3631     // C++ [class.ctor]p5, C++ [class.dtor]p5:
3632     //    const and volatile semantics are not applied on an object under
3633     //    {con,de}struction.
3634     if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3635         ObjType->isRecordType() &&
3636         Info.isEvaluatingCtorDtor(
3637             Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3638                                          Sub.Entries.begin() + I)) !=
3639                           ConstructionPhase::None) {
3640       ObjType = Info.Ctx.getCanonicalType(ObjType);
3641       ObjType.removeLocalConst();
3642       ObjType.removeLocalVolatile();
3643     }
3644 
3645     // If this is our last pass, check that the final object type is OK.
3646     if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3647       // Accesses to volatile objects are prohibited.
3648       if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3649         if (Info.getLangOpts().CPlusPlus) {
3650           int DiagKind;
3651           SourceLocation Loc;
3652           const NamedDecl *Decl = nullptr;
3653           if (VolatileField) {
3654             DiagKind = 2;
3655             Loc = VolatileField->getLocation();
3656             Decl = VolatileField;
3657           } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3658             DiagKind = 1;
3659             Loc = VD->getLocation();
3660             Decl = VD;
3661           } else {
3662             DiagKind = 0;
3663             if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3664               Loc = E->getExprLoc();
3665           }
3666           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3667               << handler.AccessKind << DiagKind << Decl;
3668           Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3669         } else {
3670           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3671         }
3672         return handler.failed();
3673       }
3674 
3675       // If we are reading an object of class type, there may still be more
3676       // things we need to check: if there are any mutable subobjects, we
3677       // cannot perform this read. (This only happens when performing a trivial
3678       // copy or assignment.)
3679       if (ObjType->isRecordType() &&
3680           !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3681           diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3682         return handler.failed();
3683     }
3684 
3685     if (I == N) {
3686       if (!handler.found(*O, ObjType))
3687         return false;
3688 
3689       // If we modified a bit-field, truncate it to the right width.
3690       if (isModification(handler.AccessKind) &&
3691           LastField && LastField->isBitField() &&
3692           !truncateBitfieldValue(Info, E, *O, LastField))
3693         return false;
3694 
3695       return true;
3696     }
3697 
3698     LastField = nullptr;
3699     if (ObjType->isArrayType()) {
3700       // Next subobject is an array element.
3701       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3702       assert(CAT && "vla in literal type?");
3703       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3704       if (CAT->getSize().ule(Index)) {
3705         // Note, it should not be possible to form a pointer with a valid
3706         // designator which points more than one past the end of the array.
3707         if (Info.getLangOpts().CPlusPlus11)
3708           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3709             << handler.AccessKind;
3710         else
3711           Info.FFDiag(E);
3712         return handler.failed();
3713       }
3714 
3715       ObjType = CAT->getElementType();
3716 
3717       if (O->getArrayInitializedElts() > Index)
3718         O = &O->getArrayInitializedElt(Index);
3719       else if (!isRead(handler.AccessKind)) {
3720         expandArray(*O, Index);
3721         O = &O->getArrayInitializedElt(Index);
3722       } else
3723         O = &O->getArrayFiller();
3724     } else if (ObjType->isAnyComplexType()) {
3725       // Next subobject is a complex number.
3726       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3727       if (Index > 1) {
3728         if (Info.getLangOpts().CPlusPlus11)
3729           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3730             << handler.AccessKind;
3731         else
3732           Info.FFDiag(E);
3733         return handler.failed();
3734       }
3735 
3736       ObjType = getSubobjectType(
3737           ObjType, ObjType->castAs<ComplexType>()->getElementType());
3738 
3739       assert(I == N - 1 && "extracting subobject of scalar?");
3740       if (O->isComplexInt()) {
3741         return handler.found(Index ? O->getComplexIntImag()
3742                                    : O->getComplexIntReal(), ObjType);
3743       } else {
3744         assert(O->isComplexFloat());
3745         return handler.found(Index ? O->getComplexFloatImag()
3746                                    : O->getComplexFloatReal(), ObjType);
3747       }
3748     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3749       if (Field->isMutable() &&
3750           !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3751         Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3752           << handler.AccessKind << Field;
3753         Info.Note(Field->getLocation(), diag::note_declared_at);
3754         return handler.failed();
3755       }
3756 
3757       // Next subobject is a class, struct or union field.
3758       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3759       if (RD->isUnion()) {
3760         const FieldDecl *UnionField = O->getUnionField();
3761         if (!UnionField ||
3762             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3763           if (I == N - 1 && handler.AccessKind == AK_Construct) {
3764             // Placement new onto an inactive union member makes it active.
3765             O->setUnion(Field, APValue());
3766           } else {
3767             // FIXME: If O->getUnionValue() is absent, report that there's no
3768             // active union member rather than reporting the prior active union
3769             // member. We'll need to fix nullptr_t to not use APValue() as its
3770             // representation first.
3771             Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3772                 << handler.AccessKind << Field << !UnionField << UnionField;
3773             return handler.failed();
3774           }
3775         }
3776         O = &O->getUnionValue();
3777       } else
3778         O = &O->getStructField(Field->getFieldIndex());
3779 
3780       ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3781       LastField = Field;
3782       if (Field->getType().isVolatileQualified())
3783         VolatileField = Field;
3784     } else {
3785       // Next subobject is a base class.
3786       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3787       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3788       O = &O->getStructBase(getBaseIndex(Derived, Base));
3789 
3790       ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3791     }
3792   }
3793 }
3794 
3795 namespace {
3796 struct ExtractSubobjectHandler {
3797   EvalInfo &Info;
3798   const Expr *E;
3799   APValue &Result;
3800   const AccessKinds AccessKind;
3801 
3802   typedef bool result_type;
3803   bool failed() { return false; }
3804   bool found(APValue &Subobj, QualType SubobjType) {
3805     Result = Subobj;
3806     if (AccessKind == AK_ReadObjectRepresentation)
3807       return true;
3808     return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3809   }
3810   bool found(APSInt &Value, QualType SubobjType) {
3811     Result = APValue(Value);
3812     return true;
3813   }
3814   bool found(APFloat &Value, QualType SubobjType) {
3815     Result = APValue(Value);
3816     return true;
3817   }
3818 };
3819 } // end anonymous namespace
3820 
3821 /// Extract the designated sub-object of an rvalue.
3822 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3823                              const CompleteObject &Obj,
3824                              const SubobjectDesignator &Sub, APValue &Result,
3825                              AccessKinds AK = AK_Read) {
3826   assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3827   ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3828   return findSubobject(Info, E, Obj, Sub, Handler);
3829 }
3830 
3831 namespace {
3832 struct ModifySubobjectHandler {
3833   EvalInfo &Info;
3834   APValue &NewVal;
3835   const Expr *E;
3836 
3837   typedef bool result_type;
3838   static const AccessKinds AccessKind = AK_Assign;
3839 
3840   bool checkConst(QualType QT) {
3841     // Assigning to a const object has undefined behavior.
3842     if (QT.isConstQualified()) {
3843       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3844       return false;
3845     }
3846     return true;
3847   }
3848 
3849   bool failed() { return false; }
3850   bool found(APValue &Subobj, QualType SubobjType) {
3851     if (!checkConst(SubobjType))
3852       return false;
3853     // We've been given ownership of NewVal, so just swap it in.
3854     Subobj.swap(NewVal);
3855     return true;
3856   }
3857   bool found(APSInt &Value, QualType SubobjType) {
3858     if (!checkConst(SubobjType))
3859       return false;
3860     if (!NewVal.isInt()) {
3861       // Maybe trying to write a cast pointer value into a complex?
3862       Info.FFDiag(E);
3863       return false;
3864     }
3865     Value = NewVal.getInt();
3866     return true;
3867   }
3868   bool found(APFloat &Value, QualType SubobjType) {
3869     if (!checkConst(SubobjType))
3870       return false;
3871     Value = NewVal.getFloat();
3872     return true;
3873   }
3874 };
3875 } // end anonymous namespace
3876 
3877 const AccessKinds ModifySubobjectHandler::AccessKind;
3878 
3879 /// Update the designated sub-object of an rvalue to the given value.
3880 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3881                             const CompleteObject &Obj,
3882                             const SubobjectDesignator &Sub,
3883                             APValue &NewVal) {
3884   ModifySubobjectHandler Handler = { Info, NewVal, E };
3885   return findSubobject(Info, E, Obj, Sub, Handler);
3886 }
3887 
3888 /// Find the position where two subobject designators diverge, or equivalently
3889 /// the length of the common initial subsequence.
3890 static unsigned FindDesignatorMismatch(QualType ObjType,
3891                                        const SubobjectDesignator &A,
3892                                        const SubobjectDesignator &B,
3893                                        bool &WasArrayIndex) {
3894   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3895   for (/**/; I != N; ++I) {
3896     if (!ObjType.isNull() &&
3897         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3898       // Next subobject is an array element.
3899       if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3900         WasArrayIndex = true;
3901         return I;
3902       }
3903       if (ObjType->isAnyComplexType())
3904         ObjType = ObjType->castAs<ComplexType>()->getElementType();
3905       else
3906         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3907     } else {
3908       if (A.Entries[I].getAsBaseOrMember() !=
3909           B.Entries[I].getAsBaseOrMember()) {
3910         WasArrayIndex = false;
3911         return I;
3912       }
3913       if (const FieldDecl *FD = getAsField(A.Entries[I]))
3914         // Next subobject is a field.
3915         ObjType = FD->getType();
3916       else
3917         // Next subobject is a base class.
3918         ObjType = QualType();
3919     }
3920   }
3921   WasArrayIndex = false;
3922   return I;
3923 }
3924 
3925 /// Determine whether the given subobject designators refer to elements of the
3926 /// same array object.
3927 static bool AreElementsOfSameArray(QualType ObjType,
3928                                    const SubobjectDesignator &A,
3929                                    const SubobjectDesignator &B) {
3930   if (A.Entries.size() != B.Entries.size())
3931     return false;
3932 
3933   bool IsArray = A.MostDerivedIsArrayElement;
3934   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3935     // A is a subobject of the array element.
3936     return false;
3937 
3938   // If A (and B) designates an array element, the last entry will be the array
3939   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3940   // of length 1' case, and the entire path must match.
3941   bool WasArrayIndex;
3942   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3943   return CommonLength >= A.Entries.size() - IsArray;
3944 }
3945 
3946 /// Find the complete object to which an LValue refers.
3947 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3948                                          AccessKinds AK, const LValue &LVal,
3949                                          QualType LValType) {
3950   if (LVal.InvalidBase) {
3951     Info.FFDiag(E);
3952     return CompleteObject();
3953   }
3954 
3955   if (!LVal.Base) {
3956     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3957     return CompleteObject();
3958   }
3959 
3960   CallStackFrame *Frame = nullptr;
3961   unsigned Depth = 0;
3962   if (LVal.getLValueCallIndex()) {
3963     std::tie(Frame, Depth) =
3964         Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3965     if (!Frame) {
3966       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3967         << AK << LVal.Base.is<const ValueDecl*>();
3968       NoteLValueLocation(Info, LVal.Base);
3969       return CompleteObject();
3970     }
3971   }
3972 
3973   bool IsAccess = isAnyAccess(AK);
3974 
3975   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3976   // is not a constant expression (even if the object is non-volatile). We also
3977   // apply this rule to C++98, in order to conform to the expected 'volatile'
3978   // semantics.
3979   if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
3980     if (Info.getLangOpts().CPlusPlus)
3981       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3982         << AK << LValType;
3983     else
3984       Info.FFDiag(E);
3985     return CompleteObject();
3986   }
3987 
3988   // Compute value storage location and type of base object.
3989   APValue *BaseVal = nullptr;
3990   QualType BaseType = getType(LVal.Base);
3991 
3992   if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
3993       lifetimeStartedInEvaluation(Info, LVal.Base)) {
3994     // This is the object whose initializer we're evaluating, so its lifetime
3995     // started in the current evaluation.
3996     BaseVal = Info.EvaluatingDeclValue;
3997   } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
3998     // Allow reading from a GUID declaration.
3999     if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4000       if (isModification(AK)) {
4001         // All the remaining cases do not permit modification of the object.
4002         Info.FFDiag(E, diag::note_constexpr_modify_global);
4003         return CompleteObject();
4004       }
4005       APValue &V = GD->getAsAPValue();
4006       if (V.isAbsent()) {
4007         Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4008             << GD->getType();
4009         return CompleteObject();
4010       }
4011       return CompleteObject(LVal.Base, &V, GD->getType());
4012     }
4013 
4014     // Allow reading from template parameter objects.
4015     if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4016       if (isModification(AK)) {
4017         Info.FFDiag(E, diag::note_constexpr_modify_global);
4018         return CompleteObject();
4019       }
4020       return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4021                             TPO->getType());
4022     }
4023 
4024     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4025     // In C++11, constexpr, non-volatile variables initialized with constant
4026     // expressions are constant expressions too. Inside constexpr functions,
4027     // parameters are constant expressions even if they're non-const.
4028     // In C++1y, objects local to a constant expression (those with a Frame) are
4029     // both readable and writable inside constant expressions.
4030     // In C, such things can also be folded, although they are not ICEs.
4031     const VarDecl *VD = dyn_cast<VarDecl>(D);
4032     if (VD) {
4033       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4034         VD = VDef;
4035     }
4036     if (!VD || VD->isInvalidDecl()) {
4037       Info.FFDiag(E);
4038       return CompleteObject();
4039     }
4040 
4041     bool IsConstant = BaseType.isConstant(Info.Ctx);
4042 
4043     // Unless we're looking at a local variable or argument in a constexpr call,
4044     // the variable we're reading must be const.
4045     if (!Frame) {
4046       if (IsAccess && isa<ParmVarDecl>(VD)) {
4047         // Access of a parameter that's not associated with a frame isn't going
4048         // to work out, but we can leave it to evaluateVarDeclInit to provide a
4049         // suitable diagnostic.
4050       } else if (Info.getLangOpts().CPlusPlus14 &&
4051                  lifetimeStartedInEvaluation(Info, LVal.Base)) {
4052         // OK, we can read and modify an object if we're in the process of
4053         // evaluating its initializer, because its lifetime began in this
4054         // evaluation.
4055       } else if (isModification(AK)) {
4056         // All the remaining cases do not permit modification of the object.
4057         Info.FFDiag(E, diag::note_constexpr_modify_global);
4058         return CompleteObject();
4059       } else if (VD->isConstexpr()) {
4060         // OK, we can read this variable.
4061       } else if (BaseType->isIntegralOrEnumerationType()) {
4062         if (!IsConstant) {
4063           if (!IsAccess)
4064             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4065           if (Info.getLangOpts().CPlusPlus) {
4066             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4067             Info.Note(VD->getLocation(), diag::note_declared_at);
4068           } else {
4069             Info.FFDiag(E);
4070           }
4071           return CompleteObject();
4072         }
4073       } else if (!IsAccess) {
4074         return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4075       } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
4076                  BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4077         // This variable might end up being constexpr. Don't diagnose it yet.
4078       } else if (IsConstant) {
4079         // Keep evaluating to see what we can do. In particular, we support
4080         // folding of const floating-point types, in order to make static const
4081         // data members of such types (supported as an extension) more useful.
4082         if (Info.getLangOpts().CPlusPlus) {
4083           Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4084                               ? diag::note_constexpr_ltor_non_constexpr
4085                               : diag::note_constexpr_ltor_non_integral, 1)
4086               << VD << BaseType;
4087           Info.Note(VD->getLocation(), diag::note_declared_at);
4088         } else {
4089           Info.CCEDiag(E);
4090         }
4091       } else {
4092         // Never allow reading a non-const value.
4093         if (Info.getLangOpts().CPlusPlus) {
4094           Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4095                              ? diag::note_constexpr_ltor_non_constexpr
4096                              : diag::note_constexpr_ltor_non_integral, 1)
4097               << VD << BaseType;
4098           Info.Note(VD->getLocation(), diag::note_declared_at);
4099         } else {
4100           Info.FFDiag(E);
4101         }
4102         return CompleteObject();
4103       }
4104     }
4105 
4106     if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
4107       return CompleteObject();
4108   } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4109     Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
4110     if (!Alloc) {
4111       Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4112       return CompleteObject();
4113     }
4114     return CompleteObject(LVal.Base, &(*Alloc)->Value,
4115                           LVal.Base.getDynamicAllocType());
4116   } else {
4117     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4118 
4119     if (!Frame) {
4120       if (const MaterializeTemporaryExpr *MTE =
4121               dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4122         assert(MTE->getStorageDuration() == SD_Static &&
4123                "should have a frame for a non-global materialized temporary");
4124 
4125         // C++20 [expr.const]p4: [DR2126]
4126         //   An object or reference is usable in constant expressions if it is
4127         //   - a temporary object of non-volatile const-qualified literal type
4128         //     whose lifetime is extended to that of a variable that is usable
4129         //     in constant expressions
4130         //
4131         // C++20 [expr.const]p5:
4132         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4133         //   - a non-volatile glvalue that refers to an object that is usable
4134         //     in constant expressions, or
4135         //   - a non-volatile glvalue of literal type that refers to a
4136         //     non-volatile object whose lifetime began within the evaluation
4137         //     of E;
4138         //
4139         // C++11 misses the 'began within the evaluation of e' check and
4140         // instead allows all temporaries, including things like:
4141         //   int &&r = 1;
4142         //   int x = ++r;
4143         //   constexpr int k = r;
4144         // Therefore we use the C++14-onwards rules in C++11 too.
4145         //
4146         // Note that temporaries whose lifetimes began while evaluating a
4147         // variable's constructor are not usable while evaluating the
4148         // corresponding destructor, not even if they're of const-qualified
4149         // types.
4150         if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4151             !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4152           if (!IsAccess)
4153             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4154           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4155           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4156           return CompleteObject();
4157         }
4158 
4159         BaseVal = MTE->getOrCreateValue(false);
4160         assert(BaseVal && "got reference to unevaluated temporary");
4161       } else {
4162         if (!IsAccess)
4163           return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4164         APValue Val;
4165         LVal.moveInto(Val);
4166         Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4167             << AK
4168             << Val.getAsString(Info.Ctx,
4169                                Info.Ctx.getLValueReferenceType(LValType));
4170         NoteLValueLocation(Info, LVal.Base);
4171         return CompleteObject();
4172       }
4173     } else {
4174       BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4175       assert(BaseVal && "missing value for temporary");
4176     }
4177   }
4178 
4179   // In C++14, we can't safely access any mutable state when we might be
4180   // evaluating after an unmodeled side effect. Parameters are modeled as state
4181   // in the caller, but aren't visible once the call returns, so they can be
4182   // modified in a speculatively-evaluated call.
4183   //
4184   // FIXME: Not all local state is mutable. Allow local constant subobjects
4185   // to be read here (but take care with 'mutable' fields).
4186   unsigned VisibleDepth = Depth;
4187   if (llvm::isa_and_nonnull<ParmVarDecl>(
4188           LVal.Base.dyn_cast<const ValueDecl *>()))
4189     ++VisibleDepth;
4190   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4191        Info.EvalStatus.HasSideEffects) ||
4192       (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4193     return CompleteObject();
4194 
4195   return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4196 }
4197 
4198 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4199 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4200 /// glvalue referred to by an entity of reference type.
4201 ///
4202 /// \param Info - Information about the ongoing evaluation.
4203 /// \param Conv - The expression for which we are performing the conversion.
4204 ///               Used for diagnostics.
4205 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4206 ///               case of a non-class type).
4207 /// \param LVal - The glvalue on which we are attempting to perform this action.
4208 /// \param RVal - The produced value will be placed here.
4209 /// \param WantObjectRepresentation - If true, we're looking for the object
4210 ///               representation rather than the value, and in particular,
4211 ///               there is no requirement that the result be fully initialized.
4212 static bool
4213 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
4214                                const LValue &LVal, APValue &RVal,
4215                                bool WantObjectRepresentation = false) {
4216   if (LVal.Designator.Invalid)
4217     return false;
4218 
4219   // Check for special cases where there is no existing APValue to look at.
4220   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4221 
4222   AccessKinds AK =
4223       WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4224 
4225   if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4226     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4227       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4228       // initializer until now for such expressions. Such an expression can't be
4229       // an ICE in C, so this only matters for fold.
4230       if (Type.isVolatileQualified()) {
4231         Info.FFDiag(Conv);
4232         return false;
4233       }
4234       APValue Lit;
4235       if (!Evaluate(Lit, Info, CLE->getInitializer()))
4236         return false;
4237       CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4238       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4239     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4240       // Special-case character extraction so we don't have to construct an
4241       // APValue for the whole string.
4242       assert(LVal.Designator.Entries.size() <= 1 &&
4243              "Can only read characters from string literals");
4244       if (LVal.Designator.Entries.empty()) {
4245         // Fail for now for LValue to RValue conversion of an array.
4246         // (This shouldn't show up in C/C++, but it could be triggered by a
4247         // weird EvaluateAsRValue call from a tool.)
4248         Info.FFDiag(Conv);
4249         return false;
4250       }
4251       if (LVal.Designator.isOnePastTheEnd()) {
4252         if (Info.getLangOpts().CPlusPlus11)
4253           Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4254         else
4255           Info.FFDiag(Conv);
4256         return false;
4257       }
4258       uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4259       RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4260       return true;
4261     }
4262   }
4263 
4264   CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4265   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4266 }
4267 
4268 /// Perform an assignment of Val to LVal. Takes ownership of Val.
4269 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4270                              QualType LValType, APValue &Val) {
4271   if (LVal.Designator.Invalid)
4272     return false;
4273 
4274   if (!Info.getLangOpts().CPlusPlus14) {
4275     Info.FFDiag(E);
4276     return false;
4277   }
4278 
4279   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4280   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4281 }
4282 
4283 namespace {
4284 struct CompoundAssignSubobjectHandler {
4285   EvalInfo &Info;
4286   const CompoundAssignOperator *E;
4287   QualType PromotedLHSType;
4288   BinaryOperatorKind Opcode;
4289   const APValue &RHS;
4290 
4291   static const AccessKinds AccessKind = AK_Assign;
4292 
4293   typedef bool result_type;
4294 
4295   bool checkConst(QualType QT) {
4296     // Assigning to a const object has undefined behavior.
4297     if (QT.isConstQualified()) {
4298       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4299       return false;
4300     }
4301     return true;
4302   }
4303 
4304   bool failed() { return false; }
4305   bool found(APValue &Subobj, QualType SubobjType) {
4306     switch (Subobj.getKind()) {
4307     case APValue::Int:
4308       return found(Subobj.getInt(), SubobjType);
4309     case APValue::Float:
4310       return found(Subobj.getFloat(), SubobjType);
4311     case APValue::ComplexInt:
4312     case APValue::ComplexFloat:
4313       // FIXME: Implement complex compound assignment.
4314       Info.FFDiag(E);
4315       return false;
4316     case APValue::LValue:
4317       return foundPointer(Subobj, SubobjType);
4318     case APValue::Vector:
4319       return foundVector(Subobj, SubobjType);
4320     default:
4321       // FIXME: can this happen?
4322       Info.FFDiag(E);
4323       return false;
4324     }
4325   }
4326 
4327   bool foundVector(APValue &Value, QualType SubobjType) {
4328     if (!checkConst(SubobjType))
4329       return false;
4330 
4331     if (!SubobjType->isVectorType()) {
4332       Info.FFDiag(E);
4333       return false;
4334     }
4335     return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4336   }
4337 
4338   bool found(APSInt &Value, QualType SubobjType) {
4339     if (!checkConst(SubobjType))
4340       return false;
4341 
4342     if (!SubobjType->isIntegerType()) {
4343       // We don't support compound assignment on integer-cast-to-pointer
4344       // values.
4345       Info.FFDiag(E);
4346       return false;
4347     }
4348 
4349     if (RHS.isInt()) {
4350       APSInt LHS =
4351           HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4352       if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4353         return false;
4354       Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4355       return true;
4356     } else if (RHS.isFloat()) {
4357       const FPOptions FPO = E->getFPFeaturesInEffect(
4358                                     Info.Ctx.getLangOpts());
4359       APFloat FValue(0.0);
4360       return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4361                                   PromotedLHSType, FValue) &&
4362              handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4363              HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4364                                   Value);
4365     }
4366 
4367     Info.FFDiag(E);
4368     return false;
4369   }
4370   bool found(APFloat &Value, QualType SubobjType) {
4371     return checkConst(SubobjType) &&
4372            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4373                                   Value) &&
4374            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4375            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4376   }
4377   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4378     if (!checkConst(SubobjType))
4379       return false;
4380 
4381     QualType PointeeType;
4382     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4383       PointeeType = PT->getPointeeType();
4384 
4385     if (PointeeType.isNull() || !RHS.isInt() ||
4386         (Opcode != BO_Add && Opcode != BO_Sub)) {
4387       Info.FFDiag(E);
4388       return false;
4389     }
4390 
4391     APSInt Offset = RHS.getInt();
4392     if (Opcode == BO_Sub)
4393       negateAsSigned(Offset);
4394 
4395     LValue LVal;
4396     LVal.setFrom(Info.Ctx, Subobj);
4397     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4398       return false;
4399     LVal.moveInto(Subobj);
4400     return true;
4401   }
4402 };
4403 } // end anonymous namespace
4404 
4405 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4406 
4407 /// Perform a compound assignment of LVal <op>= RVal.
4408 static bool handleCompoundAssignment(EvalInfo &Info,
4409                                      const CompoundAssignOperator *E,
4410                                      const LValue &LVal, QualType LValType,
4411                                      QualType PromotedLValType,
4412                                      BinaryOperatorKind Opcode,
4413                                      const APValue &RVal) {
4414   if (LVal.Designator.Invalid)
4415     return false;
4416 
4417   if (!Info.getLangOpts().CPlusPlus14) {
4418     Info.FFDiag(E);
4419     return false;
4420   }
4421 
4422   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4423   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4424                                              RVal };
4425   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4426 }
4427 
4428 namespace {
4429 struct IncDecSubobjectHandler {
4430   EvalInfo &Info;
4431   const UnaryOperator *E;
4432   AccessKinds AccessKind;
4433   APValue *Old;
4434 
4435   typedef bool result_type;
4436 
4437   bool checkConst(QualType QT) {
4438     // Assigning to a const object has undefined behavior.
4439     if (QT.isConstQualified()) {
4440       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4441       return false;
4442     }
4443     return true;
4444   }
4445 
4446   bool failed() { return false; }
4447   bool found(APValue &Subobj, QualType SubobjType) {
4448     // Stash the old value. Also clear Old, so we don't clobber it later
4449     // if we're post-incrementing a complex.
4450     if (Old) {
4451       *Old = Subobj;
4452       Old = nullptr;
4453     }
4454 
4455     switch (Subobj.getKind()) {
4456     case APValue::Int:
4457       return found(Subobj.getInt(), SubobjType);
4458     case APValue::Float:
4459       return found(Subobj.getFloat(), SubobjType);
4460     case APValue::ComplexInt:
4461       return found(Subobj.getComplexIntReal(),
4462                    SubobjType->castAs<ComplexType>()->getElementType()
4463                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4464     case APValue::ComplexFloat:
4465       return found(Subobj.getComplexFloatReal(),
4466                    SubobjType->castAs<ComplexType>()->getElementType()
4467                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4468     case APValue::LValue:
4469       return foundPointer(Subobj, SubobjType);
4470     default:
4471       // FIXME: can this happen?
4472       Info.FFDiag(E);
4473       return false;
4474     }
4475   }
4476   bool found(APSInt &Value, QualType SubobjType) {
4477     if (!checkConst(SubobjType))
4478       return false;
4479 
4480     if (!SubobjType->isIntegerType()) {
4481       // We don't support increment / decrement on integer-cast-to-pointer
4482       // values.
4483       Info.FFDiag(E);
4484       return false;
4485     }
4486 
4487     if (Old) *Old = APValue(Value);
4488 
4489     // bool arithmetic promotes to int, and the conversion back to bool
4490     // doesn't reduce mod 2^n, so special-case it.
4491     if (SubobjType->isBooleanType()) {
4492       if (AccessKind == AK_Increment)
4493         Value = 1;
4494       else
4495         Value = !Value;
4496       return true;
4497     }
4498 
4499     bool WasNegative = Value.isNegative();
4500     if (AccessKind == AK_Increment) {
4501       ++Value;
4502 
4503       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4504         APSInt ActualValue(Value, /*IsUnsigned*/true);
4505         return HandleOverflow(Info, E, ActualValue, SubobjType);
4506       }
4507     } else {
4508       --Value;
4509 
4510       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4511         unsigned BitWidth = Value.getBitWidth();
4512         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4513         ActualValue.setBit(BitWidth);
4514         return HandleOverflow(Info, E, ActualValue, SubobjType);
4515       }
4516     }
4517     return true;
4518   }
4519   bool found(APFloat &Value, QualType SubobjType) {
4520     if (!checkConst(SubobjType))
4521       return false;
4522 
4523     if (Old) *Old = APValue(Value);
4524 
4525     APFloat One(Value.getSemantics(), 1);
4526     if (AccessKind == AK_Increment)
4527       Value.add(One, APFloat::rmNearestTiesToEven);
4528     else
4529       Value.subtract(One, APFloat::rmNearestTiesToEven);
4530     return true;
4531   }
4532   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4533     if (!checkConst(SubobjType))
4534       return false;
4535 
4536     QualType PointeeType;
4537     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4538       PointeeType = PT->getPointeeType();
4539     else {
4540       Info.FFDiag(E);
4541       return false;
4542     }
4543 
4544     LValue LVal;
4545     LVal.setFrom(Info.Ctx, Subobj);
4546     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4547                                      AccessKind == AK_Increment ? 1 : -1))
4548       return false;
4549     LVal.moveInto(Subobj);
4550     return true;
4551   }
4552 };
4553 } // end anonymous namespace
4554 
4555 /// Perform an increment or decrement on LVal.
4556 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4557                          QualType LValType, bool IsIncrement, APValue *Old) {
4558   if (LVal.Designator.Invalid)
4559     return false;
4560 
4561   if (!Info.getLangOpts().CPlusPlus14) {
4562     Info.FFDiag(E);
4563     return false;
4564   }
4565 
4566   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4567   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4568   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4569   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4570 }
4571 
4572 /// Build an lvalue for the object argument of a member function call.
4573 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4574                                    LValue &This) {
4575   if (Object->getType()->isPointerType() && Object->isPRValue())
4576     return EvaluatePointer(Object, This, Info);
4577 
4578   if (Object->isGLValue())
4579     return EvaluateLValue(Object, This, Info);
4580 
4581   if (Object->getType()->isLiteralType(Info.Ctx))
4582     return EvaluateTemporary(Object, This, Info);
4583 
4584   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4585   return false;
4586 }
4587 
4588 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
4589 /// lvalue referring to the result.
4590 ///
4591 /// \param Info - Information about the ongoing evaluation.
4592 /// \param LV - An lvalue referring to the base of the member pointer.
4593 /// \param RHS - The member pointer expression.
4594 /// \param IncludeMember - Specifies whether the member itself is included in
4595 ///        the resulting LValue subobject designator. This is not possible when
4596 ///        creating a bound member function.
4597 /// \return The field or method declaration to which the member pointer refers,
4598 ///         or 0 if evaluation fails.
4599 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4600                                                   QualType LVType,
4601                                                   LValue &LV,
4602                                                   const Expr *RHS,
4603                                                   bool IncludeMember = true) {
4604   MemberPtr MemPtr;
4605   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4606     return nullptr;
4607 
4608   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4609   // member value, the behavior is undefined.
4610   if (!MemPtr.getDecl()) {
4611     // FIXME: Specific diagnostic.
4612     Info.FFDiag(RHS);
4613     return nullptr;
4614   }
4615 
4616   if (MemPtr.isDerivedMember()) {
4617     // This is a member of some derived class. Truncate LV appropriately.
4618     // The end of the derived-to-base path for the base object must match the
4619     // derived-to-base path for the member pointer.
4620     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4621         LV.Designator.Entries.size()) {
4622       Info.FFDiag(RHS);
4623       return nullptr;
4624     }
4625     unsigned PathLengthToMember =
4626         LV.Designator.Entries.size() - MemPtr.Path.size();
4627     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4628       const CXXRecordDecl *LVDecl = getAsBaseClass(
4629           LV.Designator.Entries[PathLengthToMember + I]);
4630       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4631       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4632         Info.FFDiag(RHS);
4633         return nullptr;
4634       }
4635     }
4636 
4637     // Truncate the lvalue to the appropriate derived class.
4638     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4639                             PathLengthToMember))
4640       return nullptr;
4641   } else if (!MemPtr.Path.empty()) {
4642     // Extend the LValue path with the member pointer's path.
4643     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4644                                   MemPtr.Path.size() + IncludeMember);
4645 
4646     // Walk down to the appropriate base class.
4647     if (const PointerType *PT = LVType->getAs<PointerType>())
4648       LVType = PT->getPointeeType();
4649     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4650     assert(RD && "member pointer access on non-class-type expression");
4651     // The first class in the path is that of the lvalue.
4652     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4653       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4654       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4655         return nullptr;
4656       RD = Base;
4657     }
4658     // Finally cast to the class containing the member.
4659     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4660                                 MemPtr.getContainingRecord()))
4661       return nullptr;
4662   }
4663 
4664   // Add the member. Note that we cannot build bound member functions here.
4665   if (IncludeMember) {
4666     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4667       if (!HandleLValueMember(Info, RHS, LV, FD))
4668         return nullptr;
4669     } else if (const IndirectFieldDecl *IFD =
4670                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4671       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4672         return nullptr;
4673     } else {
4674       llvm_unreachable("can't construct reference to bound member function");
4675     }
4676   }
4677 
4678   return MemPtr.getDecl();
4679 }
4680 
4681 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4682                                                   const BinaryOperator *BO,
4683                                                   LValue &LV,
4684                                                   bool IncludeMember = true) {
4685   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4686 
4687   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4688     if (Info.noteFailure()) {
4689       MemberPtr MemPtr;
4690       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4691     }
4692     return nullptr;
4693   }
4694 
4695   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4696                                    BO->getRHS(), IncludeMember);
4697 }
4698 
4699 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4700 /// the provided lvalue, which currently refers to the base object.
4701 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4702                                     LValue &Result) {
4703   SubobjectDesignator &D = Result.Designator;
4704   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4705     return false;
4706 
4707   QualType TargetQT = E->getType();
4708   if (const PointerType *PT = TargetQT->getAs<PointerType>())
4709     TargetQT = PT->getPointeeType();
4710 
4711   // Check this cast lands within the final derived-to-base subobject path.
4712   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4713     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4714       << D.MostDerivedType << TargetQT;
4715     return false;
4716   }
4717 
4718   // Check the type of the final cast. We don't need to check the path,
4719   // since a cast can only be formed if the path is unique.
4720   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4721   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4722   const CXXRecordDecl *FinalType;
4723   if (NewEntriesSize == D.MostDerivedPathLength)
4724     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4725   else
4726     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4727   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4728     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4729       << D.MostDerivedType << TargetQT;
4730     return false;
4731   }
4732 
4733   // Truncate the lvalue to the appropriate derived class.
4734   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4735 }
4736 
4737 /// Get the value to use for a default-initialized object of type T.
4738 /// Return false if it encounters something invalid.
4739 static bool getDefaultInitValue(QualType T, APValue &Result) {
4740   bool Success = true;
4741   if (auto *RD = T->getAsCXXRecordDecl()) {
4742     if (RD->isInvalidDecl()) {
4743       Result = APValue();
4744       return false;
4745     }
4746     if (RD->isUnion()) {
4747       Result = APValue((const FieldDecl *)nullptr);
4748       return true;
4749     }
4750     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4751                      std::distance(RD->field_begin(), RD->field_end()));
4752 
4753     unsigned Index = 0;
4754     for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4755                                                   End = RD->bases_end();
4756          I != End; ++I, ++Index)
4757       Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index));
4758 
4759     for (const auto *I : RD->fields()) {
4760       if (I->isUnnamedBitfield())
4761         continue;
4762       Success &= getDefaultInitValue(I->getType(),
4763                                      Result.getStructField(I->getFieldIndex()));
4764     }
4765     return Success;
4766   }
4767 
4768   if (auto *AT =
4769           dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4770     Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4771     if (Result.hasArrayFiller())
4772       Success &=
4773           getDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
4774 
4775     return Success;
4776   }
4777 
4778   Result = APValue::IndeterminateValue();
4779   return true;
4780 }
4781 
4782 namespace {
4783 enum EvalStmtResult {
4784   /// Evaluation failed.
4785   ESR_Failed,
4786   /// Hit a 'return' statement.
4787   ESR_Returned,
4788   /// Evaluation succeeded.
4789   ESR_Succeeded,
4790   /// Hit a 'continue' statement.
4791   ESR_Continue,
4792   /// Hit a 'break' statement.
4793   ESR_Break,
4794   /// Still scanning for 'case' or 'default' statement.
4795   ESR_CaseNotFound
4796 };
4797 }
4798 
4799 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4800   // We don't need to evaluate the initializer for a static local.
4801   if (!VD->hasLocalStorage())
4802     return true;
4803 
4804   LValue Result;
4805   APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
4806                                                    ScopeKind::Block, Result);
4807 
4808   const Expr *InitE = VD->getInit();
4809   if (!InitE) {
4810     if (VD->getType()->isDependentType())
4811       return Info.noteSideEffect();
4812     return getDefaultInitValue(VD->getType(), Val);
4813   }
4814   if (InitE->isValueDependent())
4815     return false;
4816 
4817   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4818     // Wipe out any partially-computed value, to allow tracking that this
4819     // evaluation failed.
4820     Val = APValue();
4821     return false;
4822   }
4823 
4824   return true;
4825 }
4826 
4827 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4828   bool OK = true;
4829 
4830   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4831     OK &= EvaluateVarDecl(Info, VD);
4832 
4833   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4834     for (auto *BD : DD->bindings())
4835       if (auto *VD = BD->getHoldingVar())
4836         OK &= EvaluateDecl(Info, VD);
4837 
4838   return OK;
4839 }
4840 
4841 static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
4842   assert(E->isValueDependent());
4843   if (Info.noteSideEffect())
4844     return true;
4845   assert(E->containsErrors() && "valid value-dependent expression should never "
4846                                 "reach invalid code path.");
4847   return false;
4848 }
4849 
4850 /// Evaluate a condition (either a variable declaration or an expression).
4851 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4852                          const Expr *Cond, bool &Result) {
4853   if (Cond->isValueDependent())
4854     return false;
4855   FullExpressionRAII Scope(Info);
4856   if (CondDecl && !EvaluateDecl(Info, CondDecl))
4857     return false;
4858   if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4859     return false;
4860   return Scope.destroy();
4861 }
4862 
4863 namespace {
4864 /// A location where the result (returned value) of evaluating a
4865 /// statement should be stored.
4866 struct StmtResult {
4867   /// The APValue that should be filled in with the returned value.
4868   APValue &Value;
4869   /// The location containing the result, if any (used to support RVO).
4870   const LValue *Slot;
4871 };
4872 
4873 struct TempVersionRAII {
4874   CallStackFrame &Frame;
4875 
4876   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4877     Frame.pushTempVersion();
4878   }
4879 
4880   ~TempVersionRAII() {
4881     Frame.popTempVersion();
4882   }
4883 };
4884 
4885 }
4886 
4887 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4888                                    const Stmt *S,
4889                                    const SwitchCase *SC = nullptr);
4890 
4891 /// Evaluate the body of a loop, and translate the result as appropriate.
4892 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4893                                        const Stmt *Body,
4894                                        const SwitchCase *Case = nullptr) {
4895   BlockScopeRAII Scope(Info);
4896 
4897   EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4898   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4899     ESR = ESR_Failed;
4900 
4901   switch (ESR) {
4902   case ESR_Break:
4903     return ESR_Succeeded;
4904   case ESR_Succeeded:
4905   case ESR_Continue:
4906     return ESR_Continue;
4907   case ESR_Failed:
4908   case ESR_Returned:
4909   case ESR_CaseNotFound:
4910     return ESR;
4911   }
4912   llvm_unreachable("Invalid EvalStmtResult!");
4913 }
4914 
4915 /// Evaluate a switch statement.
4916 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4917                                      const SwitchStmt *SS) {
4918   BlockScopeRAII Scope(Info);
4919 
4920   // Evaluate the switch condition.
4921   APSInt Value;
4922   {
4923     if (const Stmt *Init = SS->getInit()) {
4924       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4925       if (ESR != ESR_Succeeded) {
4926         if (ESR != ESR_Failed && !Scope.destroy())
4927           ESR = ESR_Failed;
4928         return ESR;
4929       }
4930     }
4931 
4932     FullExpressionRAII CondScope(Info);
4933     if (SS->getConditionVariable() &&
4934         !EvaluateDecl(Info, SS->getConditionVariable()))
4935       return ESR_Failed;
4936     if (SS->getCond()->isValueDependent()) {
4937       if (!EvaluateDependentExpr(SS->getCond(), Info))
4938         return ESR_Failed;
4939     } else {
4940       if (!EvaluateInteger(SS->getCond(), Value, Info))
4941         return ESR_Failed;
4942     }
4943     if (!CondScope.destroy())
4944       return ESR_Failed;
4945   }
4946 
4947   // Find the switch case corresponding to the value of the condition.
4948   // FIXME: Cache this lookup.
4949   const SwitchCase *Found = nullptr;
4950   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4951        SC = SC->getNextSwitchCase()) {
4952     if (isa<DefaultStmt>(SC)) {
4953       Found = SC;
4954       continue;
4955     }
4956 
4957     const CaseStmt *CS = cast<CaseStmt>(SC);
4958     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4959     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4960                               : LHS;
4961     if (LHS <= Value && Value <= RHS) {
4962       Found = SC;
4963       break;
4964     }
4965   }
4966 
4967   if (!Found)
4968     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4969 
4970   // Search the switch body for the switch case and evaluate it from there.
4971   EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
4972   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4973     return ESR_Failed;
4974 
4975   switch (ESR) {
4976   case ESR_Break:
4977     return ESR_Succeeded;
4978   case ESR_Succeeded:
4979   case ESR_Continue:
4980   case ESR_Failed:
4981   case ESR_Returned:
4982     return ESR;
4983   case ESR_CaseNotFound:
4984     // This can only happen if the switch case is nested within a statement
4985     // expression. We have no intention of supporting that.
4986     Info.FFDiag(Found->getBeginLoc(),
4987                 diag::note_constexpr_stmt_expr_unsupported);
4988     return ESR_Failed;
4989   }
4990   llvm_unreachable("Invalid EvalStmtResult!");
4991 }
4992 
4993 // Evaluate a statement.
4994 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4995                                    const Stmt *S, const SwitchCase *Case) {
4996   if (!Info.nextStep(S))
4997     return ESR_Failed;
4998 
4999   // If we're hunting down a 'case' or 'default' label, recurse through
5000   // substatements until we hit the label.
5001   if (Case) {
5002     switch (S->getStmtClass()) {
5003     case Stmt::CompoundStmtClass:
5004       // FIXME: Precompute which substatement of a compound statement we
5005       // would jump to, and go straight there rather than performing a
5006       // linear scan each time.
5007     case Stmt::LabelStmtClass:
5008     case Stmt::AttributedStmtClass:
5009     case Stmt::DoStmtClass:
5010       break;
5011 
5012     case Stmt::CaseStmtClass:
5013     case Stmt::DefaultStmtClass:
5014       if (Case == S)
5015         Case = nullptr;
5016       break;
5017 
5018     case Stmt::IfStmtClass: {
5019       // FIXME: Precompute which side of an 'if' we would jump to, and go
5020       // straight there rather than scanning both sides.
5021       const IfStmt *IS = cast<IfStmt>(S);
5022 
5023       // Wrap the evaluation in a block scope, in case it's a DeclStmt
5024       // preceded by our switch label.
5025       BlockScopeRAII Scope(Info);
5026 
5027       // Step into the init statement in case it brings an (uninitialized)
5028       // variable into scope.
5029       if (const Stmt *Init = IS->getInit()) {
5030         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5031         if (ESR != ESR_CaseNotFound) {
5032           assert(ESR != ESR_Succeeded);
5033           return ESR;
5034         }
5035       }
5036 
5037       // Condition variable must be initialized if it exists.
5038       // FIXME: We can skip evaluating the body if there's a condition
5039       // variable, as there can't be any case labels within it.
5040       // (The same is true for 'for' statements.)
5041 
5042       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5043       if (ESR == ESR_Failed)
5044         return ESR;
5045       if (ESR != ESR_CaseNotFound)
5046         return Scope.destroy() ? ESR : ESR_Failed;
5047       if (!IS->getElse())
5048         return ESR_CaseNotFound;
5049 
5050       ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5051       if (ESR == ESR_Failed)
5052         return ESR;
5053       if (ESR != ESR_CaseNotFound)
5054         return Scope.destroy() ? ESR : ESR_Failed;
5055       return ESR_CaseNotFound;
5056     }
5057 
5058     case Stmt::WhileStmtClass: {
5059       EvalStmtResult ESR =
5060           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5061       if (ESR != ESR_Continue)
5062         return ESR;
5063       break;
5064     }
5065 
5066     case Stmt::ForStmtClass: {
5067       const ForStmt *FS = cast<ForStmt>(S);
5068       BlockScopeRAII Scope(Info);
5069 
5070       // Step into the init statement in case it brings an (uninitialized)
5071       // variable into scope.
5072       if (const Stmt *Init = FS->getInit()) {
5073         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5074         if (ESR != ESR_CaseNotFound) {
5075           assert(ESR != ESR_Succeeded);
5076           return ESR;
5077         }
5078       }
5079 
5080       EvalStmtResult ESR =
5081           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5082       if (ESR != ESR_Continue)
5083         return ESR;
5084       if (const auto *Inc = FS->getInc()) {
5085         if (Inc->isValueDependent()) {
5086           if (!EvaluateDependentExpr(Inc, Info))
5087             return ESR_Failed;
5088         } else {
5089           FullExpressionRAII IncScope(Info);
5090           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5091             return ESR_Failed;
5092         }
5093       }
5094       break;
5095     }
5096 
5097     case Stmt::DeclStmtClass: {
5098       // Start the lifetime of any uninitialized variables we encounter. They
5099       // might be used by the selected branch of the switch.
5100       const DeclStmt *DS = cast<DeclStmt>(S);
5101       for (const auto *D : DS->decls()) {
5102         if (const auto *VD = dyn_cast<VarDecl>(D)) {
5103           if (VD->hasLocalStorage() && !VD->getInit())
5104             if (!EvaluateVarDecl(Info, VD))
5105               return ESR_Failed;
5106           // FIXME: If the variable has initialization that can't be jumped
5107           // over, bail out of any immediately-surrounding compound-statement
5108           // too. There can't be any case labels here.
5109         }
5110       }
5111       return ESR_CaseNotFound;
5112     }
5113 
5114     default:
5115       return ESR_CaseNotFound;
5116     }
5117   }
5118 
5119   switch (S->getStmtClass()) {
5120   default:
5121     if (const Expr *E = dyn_cast<Expr>(S)) {
5122       if (E->isValueDependent()) {
5123         if (!EvaluateDependentExpr(E, Info))
5124           return ESR_Failed;
5125       } else {
5126         // Don't bother evaluating beyond an expression-statement which couldn't
5127         // be evaluated.
5128         // FIXME: Do we need the FullExpressionRAII object here?
5129         // VisitExprWithCleanups should create one when necessary.
5130         FullExpressionRAII Scope(Info);
5131         if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5132           return ESR_Failed;
5133       }
5134       return ESR_Succeeded;
5135     }
5136 
5137     Info.FFDiag(S->getBeginLoc());
5138     return ESR_Failed;
5139 
5140   case Stmt::NullStmtClass:
5141     return ESR_Succeeded;
5142 
5143   case Stmt::DeclStmtClass: {
5144     const DeclStmt *DS = cast<DeclStmt>(S);
5145     for (const auto *D : DS->decls()) {
5146       // Each declaration initialization is its own full-expression.
5147       FullExpressionRAII Scope(Info);
5148       if (!EvaluateDecl(Info, D) && !Info.noteFailure())
5149         return ESR_Failed;
5150       if (!Scope.destroy())
5151         return ESR_Failed;
5152     }
5153     return ESR_Succeeded;
5154   }
5155 
5156   case Stmt::ReturnStmtClass: {
5157     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5158     FullExpressionRAII Scope(Info);
5159     if (RetExpr && RetExpr->isValueDependent()) {
5160       EvaluateDependentExpr(RetExpr, Info);
5161       // We know we returned, but we don't know what the value is.
5162       return ESR_Failed;
5163     }
5164     if (RetExpr &&
5165         !(Result.Slot
5166               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5167               : Evaluate(Result.Value, Info, RetExpr)))
5168       return ESR_Failed;
5169     return Scope.destroy() ? ESR_Returned : ESR_Failed;
5170   }
5171 
5172   case Stmt::CompoundStmtClass: {
5173     BlockScopeRAII Scope(Info);
5174 
5175     const CompoundStmt *CS = cast<CompoundStmt>(S);
5176     for (const auto *BI : CS->body()) {
5177       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5178       if (ESR == ESR_Succeeded)
5179         Case = nullptr;
5180       else if (ESR != ESR_CaseNotFound) {
5181         if (ESR != ESR_Failed && !Scope.destroy())
5182           return ESR_Failed;
5183         return ESR;
5184       }
5185     }
5186     if (Case)
5187       return ESR_CaseNotFound;
5188     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5189   }
5190 
5191   case Stmt::IfStmtClass: {
5192     const IfStmt *IS = cast<IfStmt>(S);
5193 
5194     // Evaluate the condition, as either a var decl or as an expression.
5195     BlockScopeRAII Scope(Info);
5196     if (const Stmt *Init = IS->getInit()) {
5197       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5198       if (ESR != ESR_Succeeded) {
5199         if (ESR != ESR_Failed && !Scope.destroy())
5200           return ESR_Failed;
5201         return ESR;
5202       }
5203     }
5204     bool Cond;
5205     if (IS->isConsteval())
5206       Cond = IS->isNonNegatedConsteval();
5207     else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
5208                            Cond))
5209       return ESR_Failed;
5210 
5211     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5212       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5213       if (ESR != ESR_Succeeded) {
5214         if (ESR != ESR_Failed && !Scope.destroy())
5215           return ESR_Failed;
5216         return ESR;
5217       }
5218     }
5219     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5220   }
5221 
5222   case Stmt::WhileStmtClass: {
5223     const WhileStmt *WS = cast<WhileStmt>(S);
5224     while (true) {
5225       BlockScopeRAII Scope(Info);
5226       bool Continue;
5227       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5228                         Continue))
5229         return ESR_Failed;
5230       if (!Continue)
5231         break;
5232 
5233       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5234       if (ESR != ESR_Continue) {
5235         if (ESR != ESR_Failed && !Scope.destroy())
5236           return ESR_Failed;
5237         return ESR;
5238       }
5239       if (!Scope.destroy())
5240         return ESR_Failed;
5241     }
5242     return ESR_Succeeded;
5243   }
5244 
5245   case Stmt::DoStmtClass: {
5246     const DoStmt *DS = cast<DoStmt>(S);
5247     bool Continue;
5248     do {
5249       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5250       if (ESR != ESR_Continue)
5251         return ESR;
5252       Case = nullptr;
5253 
5254       if (DS->getCond()->isValueDependent()) {
5255         EvaluateDependentExpr(DS->getCond(), Info);
5256         // Bailout as we don't know whether to keep going or terminate the loop.
5257         return ESR_Failed;
5258       }
5259       FullExpressionRAII CondScope(Info);
5260       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5261           !CondScope.destroy())
5262         return ESR_Failed;
5263     } while (Continue);
5264     return ESR_Succeeded;
5265   }
5266 
5267   case Stmt::ForStmtClass: {
5268     const ForStmt *FS = cast<ForStmt>(S);
5269     BlockScopeRAII ForScope(Info);
5270     if (FS->getInit()) {
5271       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5272       if (ESR != ESR_Succeeded) {
5273         if (ESR != ESR_Failed && !ForScope.destroy())
5274           return ESR_Failed;
5275         return ESR;
5276       }
5277     }
5278     while (true) {
5279       BlockScopeRAII IterScope(Info);
5280       bool Continue = true;
5281       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5282                                          FS->getCond(), Continue))
5283         return ESR_Failed;
5284       if (!Continue)
5285         break;
5286 
5287       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5288       if (ESR != ESR_Continue) {
5289         if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5290           return ESR_Failed;
5291         return ESR;
5292       }
5293 
5294       if (const auto *Inc = FS->getInc()) {
5295         if (Inc->isValueDependent()) {
5296           if (!EvaluateDependentExpr(Inc, Info))
5297             return ESR_Failed;
5298         } else {
5299           FullExpressionRAII IncScope(Info);
5300           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5301             return ESR_Failed;
5302         }
5303       }
5304 
5305       if (!IterScope.destroy())
5306         return ESR_Failed;
5307     }
5308     return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5309   }
5310 
5311   case Stmt::CXXForRangeStmtClass: {
5312     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5313     BlockScopeRAII Scope(Info);
5314 
5315     // Evaluate the init-statement if present.
5316     if (FS->getInit()) {
5317       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5318       if (ESR != ESR_Succeeded) {
5319         if (ESR != ESR_Failed && !Scope.destroy())
5320           return ESR_Failed;
5321         return ESR;
5322       }
5323     }
5324 
5325     // Initialize the __range variable.
5326     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5327     if (ESR != ESR_Succeeded) {
5328       if (ESR != ESR_Failed && !Scope.destroy())
5329         return ESR_Failed;
5330       return ESR;
5331     }
5332 
5333     // In error-recovery cases it's possible to get here even if we failed to
5334     // synthesize the __begin and __end variables.
5335     if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
5336       return ESR_Failed;
5337 
5338     // Create the __begin and __end iterators.
5339     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5340     if (ESR != ESR_Succeeded) {
5341       if (ESR != ESR_Failed && !Scope.destroy())
5342         return ESR_Failed;
5343       return ESR;
5344     }
5345     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5346     if (ESR != ESR_Succeeded) {
5347       if (ESR != ESR_Failed && !Scope.destroy())
5348         return ESR_Failed;
5349       return ESR;
5350     }
5351 
5352     while (true) {
5353       // Condition: __begin != __end.
5354       {
5355         if (FS->getCond()->isValueDependent()) {
5356           EvaluateDependentExpr(FS->getCond(), Info);
5357           // We don't know whether to keep going or terminate the loop.
5358           return ESR_Failed;
5359         }
5360         bool Continue = true;
5361         FullExpressionRAII CondExpr(Info);
5362         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5363           return ESR_Failed;
5364         if (!Continue)
5365           break;
5366       }
5367 
5368       // User's variable declaration, initialized by *__begin.
5369       BlockScopeRAII InnerScope(Info);
5370       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5371       if (ESR != ESR_Succeeded) {
5372         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5373           return ESR_Failed;
5374         return ESR;
5375       }
5376 
5377       // Loop body.
5378       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5379       if (ESR != ESR_Continue) {
5380         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5381           return ESR_Failed;
5382         return ESR;
5383       }
5384       if (FS->getInc()->isValueDependent()) {
5385         if (!EvaluateDependentExpr(FS->getInc(), Info))
5386           return ESR_Failed;
5387       } else {
5388         // Increment: ++__begin
5389         if (!EvaluateIgnoredValue(Info, FS->getInc()))
5390           return ESR_Failed;
5391       }
5392 
5393       if (!InnerScope.destroy())
5394         return ESR_Failed;
5395     }
5396 
5397     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5398   }
5399 
5400   case Stmt::SwitchStmtClass:
5401     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5402 
5403   case Stmt::ContinueStmtClass:
5404     return ESR_Continue;
5405 
5406   case Stmt::BreakStmtClass:
5407     return ESR_Break;
5408 
5409   case Stmt::LabelStmtClass:
5410     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5411 
5412   case Stmt::AttributedStmtClass:
5413     // As a general principle, C++11 attributes can be ignored without
5414     // any semantic impact.
5415     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
5416                         Case);
5417 
5418   case Stmt::CaseStmtClass:
5419   case Stmt::DefaultStmtClass:
5420     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5421   case Stmt::CXXTryStmtClass:
5422     // Evaluate try blocks by evaluating all sub statements.
5423     return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5424   }
5425 }
5426 
5427 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5428 /// default constructor. If so, we'll fold it whether or not it's marked as
5429 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
5430 /// so we need special handling.
5431 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5432                                            const CXXConstructorDecl *CD,
5433                                            bool IsValueInitialization) {
5434   if (!CD->isTrivial() || !CD->isDefaultConstructor())
5435     return false;
5436 
5437   // Value-initialization does not call a trivial default constructor, so such a
5438   // call is a core constant expression whether or not the constructor is
5439   // constexpr.
5440   if (!CD->isConstexpr() && !IsValueInitialization) {
5441     if (Info.getLangOpts().CPlusPlus11) {
5442       // FIXME: If DiagDecl is an implicitly-declared special member function,
5443       // we should be much more explicit about why it's not constexpr.
5444       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5445         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5446       Info.Note(CD->getLocation(), diag::note_declared_at);
5447     } else {
5448       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5449     }
5450   }
5451   return true;
5452 }
5453 
5454 /// CheckConstexprFunction - Check that a function can be called in a constant
5455 /// expression.
5456 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5457                                    const FunctionDecl *Declaration,
5458                                    const FunctionDecl *Definition,
5459                                    const Stmt *Body) {
5460   // Potential constant expressions can contain calls to declared, but not yet
5461   // defined, constexpr functions.
5462   if (Info.checkingPotentialConstantExpression() && !Definition &&
5463       Declaration->isConstexpr())
5464     return false;
5465 
5466   // Bail out if the function declaration itself is invalid.  We will
5467   // have produced a relevant diagnostic while parsing it, so just
5468   // note the problematic sub-expression.
5469   if (Declaration->isInvalidDecl()) {
5470     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5471     return false;
5472   }
5473 
5474   // DR1872: An instantiated virtual constexpr function can't be called in a
5475   // constant expression (prior to C++20). We can still constant-fold such a
5476   // call.
5477   if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5478       cast<CXXMethodDecl>(Declaration)->isVirtual())
5479     Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5480 
5481   if (Definition && Definition->isInvalidDecl()) {
5482     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5483     return false;
5484   }
5485 
5486   // Can we evaluate this function call?
5487   if (Definition && Definition->isConstexpr() && Body)
5488     return true;
5489 
5490   if (Info.getLangOpts().CPlusPlus11) {
5491     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5492 
5493     // If this function is not constexpr because it is an inherited
5494     // non-constexpr constructor, diagnose that directly.
5495     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5496     if (CD && CD->isInheritingConstructor()) {
5497       auto *Inherited = CD->getInheritedConstructor().getConstructor();
5498       if (!Inherited->isConstexpr())
5499         DiagDecl = CD = Inherited;
5500     }
5501 
5502     // FIXME: If DiagDecl is an implicitly-declared special member function
5503     // or an inheriting constructor, we should be much more explicit about why
5504     // it's not constexpr.
5505     if (CD && CD->isInheritingConstructor())
5506       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5507         << CD->getInheritedConstructor().getConstructor()->getParent();
5508     else
5509       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5510         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5511     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5512   } else {
5513     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5514   }
5515   return false;
5516 }
5517 
5518 namespace {
5519 struct CheckDynamicTypeHandler {
5520   AccessKinds AccessKind;
5521   typedef bool result_type;
5522   bool failed() { return false; }
5523   bool found(APValue &Subobj, QualType SubobjType) { return true; }
5524   bool found(APSInt &Value, QualType SubobjType) { return true; }
5525   bool found(APFloat &Value, QualType SubobjType) { return true; }
5526 };
5527 } // end anonymous namespace
5528 
5529 /// Check that we can access the notional vptr of an object / determine its
5530 /// dynamic type.
5531 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5532                              AccessKinds AK, bool Polymorphic) {
5533   if (This.Designator.Invalid)
5534     return false;
5535 
5536   CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5537 
5538   if (!Obj)
5539     return false;
5540 
5541   if (!Obj.Value) {
5542     // The object is not usable in constant expressions, so we can't inspect
5543     // its value to see if it's in-lifetime or what the active union members
5544     // are. We can still check for a one-past-the-end lvalue.
5545     if (This.Designator.isOnePastTheEnd() ||
5546         This.Designator.isMostDerivedAnUnsizedArray()) {
5547       Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5548                          ? diag::note_constexpr_access_past_end
5549                          : diag::note_constexpr_access_unsized_array)
5550           << AK;
5551       return false;
5552     } else if (Polymorphic) {
5553       // Conservatively refuse to perform a polymorphic operation if we would
5554       // not be able to read a notional 'vptr' value.
5555       APValue Val;
5556       This.moveInto(Val);
5557       QualType StarThisType =
5558           Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5559       Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5560           << AK << Val.getAsString(Info.Ctx, StarThisType);
5561       return false;
5562     }
5563     return true;
5564   }
5565 
5566   CheckDynamicTypeHandler Handler{AK};
5567   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5568 }
5569 
5570 /// Check that the pointee of the 'this' pointer in a member function call is
5571 /// either within its lifetime or in its period of construction or destruction.
5572 static bool
5573 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5574                                      const LValue &This,
5575                                      const CXXMethodDecl *NamedMember) {
5576   return checkDynamicType(
5577       Info, E, This,
5578       isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5579 }
5580 
5581 struct DynamicType {
5582   /// The dynamic class type of the object.
5583   const CXXRecordDecl *Type;
5584   /// The corresponding path length in the lvalue.
5585   unsigned PathLength;
5586 };
5587 
5588 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5589                                              unsigned PathLength) {
5590   assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5591       Designator.Entries.size() && "invalid path length");
5592   return (PathLength == Designator.MostDerivedPathLength)
5593              ? Designator.MostDerivedType->getAsCXXRecordDecl()
5594              : getAsBaseClass(Designator.Entries[PathLength - 1]);
5595 }
5596 
5597 /// Determine the dynamic type of an object.
5598 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
5599                                                 LValue &This, AccessKinds AK) {
5600   // If we don't have an lvalue denoting an object of class type, there is no
5601   // meaningful dynamic type. (We consider objects of non-class type to have no
5602   // dynamic type.)
5603   if (!checkDynamicType(Info, E, This, AK, true))
5604     return None;
5605 
5606   // Refuse to compute a dynamic type in the presence of virtual bases. This
5607   // shouldn't happen other than in constant-folding situations, since literal
5608   // types can't have virtual bases.
5609   //
5610   // Note that consumers of DynamicType assume that the type has no virtual
5611   // bases, and will need modifications if this restriction is relaxed.
5612   const CXXRecordDecl *Class =
5613       This.Designator.MostDerivedType->getAsCXXRecordDecl();
5614   if (!Class || Class->getNumVBases()) {
5615     Info.FFDiag(E);
5616     return None;
5617   }
5618 
5619   // FIXME: For very deep class hierarchies, it might be beneficial to use a
5620   // binary search here instead. But the overwhelmingly common case is that
5621   // we're not in the middle of a constructor, so it probably doesn't matter
5622   // in practice.
5623   ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5624   for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5625        PathLength <= Path.size(); ++PathLength) {
5626     switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5627                                       Path.slice(0, PathLength))) {
5628     case ConstructionPhase::Bases:
5629     case ConstructionPhase::DestroyingBases:
5630       // We're constructing or destroying a base class. This is not the dynamic
5631       // type.
5632       break;
5633 
5634     case ConstructionPhase::None:
5635     case ConstructionPhase::AfterBases:
5636     case ConstructionPhase::AfterFields:
5637     case ConstructionPhase::Destroying:
5638       // We've finished constructing the base classes and not yet started
5639       // destroying them again, so this is the dynamic type.
5640       return DynamicType{getBaseClassType(This.Designator, PathLength),
5641                          PathLength};
5642     }
5643   }
5644 
5645   // CWG issue 1517: we're constructing a base class of the object described by
5646   // 'This', so that object has not yet begun its period of construction and
5647   // any polymorphic operation on it results in undefined behavior.
5648   Info.FFDiag(E);
5649   return None;
5650 }
5651 
5652 /// Perform virtual dispatch.
5653 static const CXXMethodDecl *HandleVirtualDispatch(
5654     EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5655     llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5656   Optional<DynamicType> DynType = ComputeDynamicType(
5657       Info, E, This,
5658       isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5659   if (!DynType)
5660     return nullptr;
5661 
5662   // Find the final overrider. It must be declared in one of the classes on the
5663   // path from the dynamic type to the static type.
5664   // FIXME: If we ever allow literal types to have virtual base classes, that
5665   // won't be true.
5666   const CXXMethodDecl *Callee = Found;
5667   unsigned PathLength = DynType->PathLength;
5668   for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5669     const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5670     const CXXMethodDecl *Overrider =
5671         Found->getCorrespondingMethodDeclaredInClass(Class, false);
5672     if (Overrider) {
5673       Callee = Overrider;
5674       break;
5675     }
5676   }
5677 
5678   // C++2a [class.abstract]p6:
5679   //   the effect of making a virtual call to a pure virtual function [...] is
5680   //   undefined
5681   if (Callee->isPure()) {
5682     Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5683     Info.Note(Callee->getLocation(), diag::note_declared_at);
5684     return nullptr;
5685   }
5686 
5687   // If necessary, walk the rest of the path to determine the sequence of
5688   // covariant adjustment steps to apply.
5689   if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5690                                        Found->getReturnType())) {
5691     CovariantAdjustmentPath.push_back(Callee->getReturnType());
5692     for (unsigned CovariantPathLength = PathLength + 1;
5693          CovariantPathLength != This.Designator.Entries.size();
5694          ++CovariantPathLength) {
5695       const CXXRecordDecl *NextClass =
5696           getBaseClassType(This.Designator, CovariantPathLength);
5697       const CXXMethodDecl *Next =
5698           Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5699       if (Next && !Info.Ctx.hasSameUnqualifiedType(
5700                       Next->getReturnType(), CovariantAdjustmentPath.back()))
5701         CovariantAdjustmentPath.push_back(Next->getReturnType());
5702     }
5703     if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5704                                          CovariantAdjustmentPath.back()))
5705       CovariantAdjustmentPath.push_back(Found->getReturnType());
5706   }
5707 
5708   // Perform 'this' adjustment.
5709   if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5710     return nullptr;
5711 
5712   return Callee;
5713 }
5714 
5715 /// Perform the adjustment from a value returned by a virtual function to
5716 /// a value of the statically expected type, which may be a pointer or
5717 /// reference to a base class of the returned type.
5718 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5719                                             APValue &Result,
5720                                             ArrayRef<QualType> Path) {
5721   assert(Result.isLValue() &&
5722          "unexpected kind of APValue for covariant return");
5723   if (Result.isNullPointer())
5724     return true;
5725 
5726   LValue LVal;
5727   LVal.setFrom(Info.Ctx, Result);
5728 
5729   const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5730   for (unsigned I = 1; I != Path.size(); ++I) {
5731     const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5732     assert(OldClass && NewClass && "unexpected kind of covariant return");
5733     if (OldClass != NewClass &&
5734         !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5735       return false;
5736     OldClass = NewClass;
5737   }
5738 
5739   LVal.moveInto(Result);
5740   return true;
5741 }
5742 
5743 /// Determine whether \p Base, which is known to be a direct base class of
5744 /// \p Derived, is a public base class.
5745 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5746                               const CXXRecordDecl *Base) {
5747   for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5748     auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5749     if (BaseClass && declaresSameEntity(BaseClass, Base))
5750       return BaseSpec.getAccessSpecifier() == AS_public;
5751   }
5752   llvm_unreachable("Base is not a direct base of Derived");
5753 }
5754 
5755 /// Apply the given dynamic cast operation on the provided lvalue.
5756 ///
5757 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
5758 /// to find a suitable target subobject.
5759 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5760                               LValue &Ptr) {
5761   // We can't do anything with a non-symbolic pointer value.
5762   SubobjectDesignator &D = Ptr.Designator;
5763   if (D.Invalid)
5764     return false;
5765 
5766   // C++ [expr.dynamic.cast]p6:
5767   //   If v is a null pointer value, the result is a null pointer value.
5768   if (Ptr.isNullPointer() && !E->isGLValue())
5769     return true;
5770 
5771   // For all the other cases, we need the pointer to point to an object within
5772   // its lifetime / period of construction / destruction, and we need to know
5773   // its dynamic type.
5774   Optional<DynamicType> DynType =
5775       ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5776   if (!DynType)
5777     return false;
5778 
5779   // C++ [expr.dynamic.cast]p7:
5780   //   If T is "pointer to cv void", then the result is a pointer to the most
5781   //   derived object
5782   if (E->getType()->isVoidPointerType())
5783     return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5784 
5785   const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5786   assert(C && "dynamic_cast target is not void pointer nor class");
5787   CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5788 
5789   auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5790     // C++ [expr.dynamic.cast]p9:
5791     if (!E->isGLValue()) {
5792       //   The value of a failed cast to pointer type is the null pointer value
5793       //   of the required result type.
5794       Ptr.setNull(Info.Ctx, E->getType());
5795       return true;
5796     }
5797 
5798     //   A failed cast to reference type throws [...] std::bad_cast.
5799     unsigned DiagKind;
5800     if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5801                    DynType->Type->isDerivedFrom(C)))
5802       DiagKind = 0;
5803     else if (!Paths || Paths->begin() == Paths->end())
5804       DiagKind = 1;
5805     else if (Paths->isAmbiguous(CQT))
5806       DiagKind = 2;
5807     else {
5808       assert(Paths->front().Access != AS_public && "why did the cast fail?");
5809       DiagKind = 3;
5810     }
5811     Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5812         << DiagKind << Ptr.Designator.getType(Info.Ctx)
5813         << Info.Ctx.getRecordType(DynType->Type)
5814         << E->getType().getUnqualifiedType();
5815     return false;
5816   };
5817 
5818   // Runtime check, phase 1:
5819   //   Walk from the base subobject towards the derived object looking for the
5820   //   target type.
5821   for (int PathLength = Ptr.Designator.Entries.size();
5822        PathLength >= (int)DynType->PathLength; --PathLength) {
5823     const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5824     if (declaresSameEntity(Class, C))
5825       return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5826     // We can only walk across public inheritance edges.
5827     if (PathLength > (int)DynType->PathLength &&
5828         !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5829                            Class))
5830       return RuntimeCheckFailed(nullptr);
5831   }
5832 
5833   // Runtime check, phase 2:
5834   //   Search the dynamic type for an unambiguous public base of type C.
5835   CXXBasePaths Paths(/*FindAmbiguities=*/true,
5836                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
5837   if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5838       Paths.front().Access == AS_public) {
5839     // Downcast to the dynamic type...
5840     if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5841       return false;
5842     // ... then upcast to the chosen base class subobject.
5843     for (CXXBasePathElement &Elem : Paths.front())
5844       if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5845         return false;
5846     return true;
5847   }
5848 
5849   // Otherwise, the runtime check fails.
5850   return RuntimeCheckFailed(&Paths);
5851 }
5852 
5853 namespace {
5854 struct StartLifetimeOfUnionMemberHandler {
5855   EvalInfo &Info;
5856   const Expr *LHSExpr;
5857   const FieldDecl *Field;
5858   bool DuringInit;
5859   bool Failed = false;
5860   static const AccessKinds AccessKind = AK_Assign;
5861 
5862   typedef bool result_type;
5863   bool failed() { return Failed; }
5864   bool found(APValue &Subobj, QualType SubobjType) {
5865     // We are supposed to perform no initialization but begin the lifetime of
5866     // the object. We interpret that as meaning to do what default
5867     // initialization of the object would do if all constructors involved were
5868     // trivial:
5869     //  * All base, non-variant member, and array element subobjects' lifetimes
5870     //    begin
5871     //  * No variant members' lifetimes begin
5872     //  * All scalar subobjects whose lifetimes begin have indeterminate values
5873     assert(SubobjType->isUnionType());
5874     if (declaresSameEntity(Subobj.getUnionField(), Field)) {
5875       // This union member is already active. If it's also in-lifetime, there's
5876       // nothing to do.
5877       if (Subobj.getUnionValue().hasValue())
5878         return true;
5879     } else if (DuringInit) {
5880       // We're currently in the process of initializing a different union
5881       // member.  If we carried on, that initialization would attempt to
5882       // store to an inactive union member, resulting in undefined behavior.
5883       Info.FFDiag(LHSExpr,
5884                   diag::note_constexpr_union_member_change_during_init);
5885       return false;
5886     }
5887     APValue Result;
5888     Failed = !getDefaultInitValue(Field->getType(), Result);
5889     Subobj.setUnion(Field, Result);
5890     return true;
5891   }
5892   bool found(APSInt &Value, QualType SubobjType) {
5893     llvm_unreachable("wrong value kind for union object");
5894   }
5895   bool found(APFloat &Value, QualType SubobjType) {
5896     llvm_unreachable("wrong value kind for union object");
5897   }
5898 };
5899 } // end anonymous namespace
5900 
5901 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5902 
5903 /// Handle a builtin simple-assignment or a call to a trivial assignment
5904 /// operator whose left-hand side might involve a union member access. If it
5905 /// does, implicitly start the lifetime of any accessed union elements per
5906 /// C++20 [class.union]5.
5907 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5908                                           const LValue &LHS) {
5909   if (LHS.InvalidBase || LHS.Designator.Invalid)
5910     return false;
5911 
5912   llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5913   // C++ [class.union]p5:
5914   //   define the set S(E) of subexpressions of E as follows:
5915   unsigned PathLength = LHS.Designator.Entries.size();
5916   for (const Expr *E = LHSExpr; E != nullptr;) {
5917     //   -- If E is of the form A.B, S(E) contains the elements of S(A)...
5918     if (auto *ME = dyn_cast<MemberExpr>(E)) {
5919       auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5920       // Note that we can't implicitly start the lifetime of a reference,
5921       // so we don't need to proceed any further if we reach one.
5922       if (!FD || FD->getType()->isReferenceType())
5923         break;
5924 
5925       //    ... and also contains A.B if B names a union member ...
5926       if (FD->getParent()->isUnion()) {
5927         //    ... of a non-class, non-array type, or of a class type with a
5928         //    trivial default constructor that is not deleted, or an array of
5929         //    such types.
5930         auto *RD =
5931             FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5932         if (!RD || RD->hasTrivialDefaultConstructor())
5933           UnionPathLengths.push_back({PathLength - 1, FD});
5934       }
5935 
5936       E = ME->getBase();
5937       --PathLength;
5938       assert(declaresSameEntity(FD,
5939                                 LHS.Designator.Entries[PathLength]
5940                                     .getAsBaseOrMember().getPointer()));
5941 
5942       //   -- If E is of the form A[B] and is interpreted as a built-in array
5943       //      subscripting operator, S(E) is [S(the array operand, if any)].
5944     } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5945       // Step over an ArrayToPointerDecay implicit cast.
5946       auto *Base = ASE->getBase()->IgnoreImplicit();
5947       if (!Base->getType()->isArrayType())
5948         break;
5949 
5950       E = Base;
5951       --PathLength;
5952 
5953     } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5954       // Step over a derived-to-base conversion.
5955       E = ICE->getSubExpr();
5956       if (ICE->getCastKind() == CK_NoOp)
5957         continue;
5958       if (ICE->getCastKind() != CK_DerivedToBase &&
5959           ICE->getCastKind() != CK_UncheckedDerivedToBase)
5960         break;
5961       // Walk path backwards as we walk up from the base to the derived class.
5962       for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
5963         --PathLength;
5964         (void)Elt;
5965         assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
5966                                   LHS.Designator.Entries[PathLength]
5967                                       .getAsBaseOrMember().getPointer()));
5968       }
5969 
5970     //   -- Otherwise, S(E) is empty.
5971     } else {
5972       break;
5973     }
5974   }
5975 
5976   // Common case: no unions' lifetimes are started.
5977   if (UnionPathLengths.empty())
5978     return true;
5979 
5980   //   if modification of X [would access an inactive union member], an object
5981   //   of the type of X is implicitly created
5982   CompleteObject Obj =
5983       findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
5984   if (!Obj)
5985     return false;
5986   for (std::pair<unsigned, const FieldDecl *> LengthAndField :
5987            llvm::reverse(UnionPathLengths)) {
5988     // Form a designator for the union object.
5989     SubobjectDesignator D = LHS.Designator;
5990     D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
5991 
5992     bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
5993                       ConstructionPhase::AfterBases;
5994     StartLifetimeOfUnionMemberHandler StartLifetime{
5995         Info, LHSExpr, LengthAndField.second, DuringInit};
5996     if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
5997       return false;
5998   }
5999 
6000   return true;
6001 }
6002 
6003 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
6004                             CallRef Call, EvalInfo &Info,
6005                             bool NonNull = false) {
6006   LValue LV;
6007   // Create the parameter slot and register its destruction. For a vararg
6008   // argument, create a temporary.
6009   // FIXME: For calling conventions that destroy parameters in the callee,
6010   // should we consider performing destruction when the function returns
6011   // instead?
6012   APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6013                    : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6014                                                        ScopeKind::Call, LV);
6015   if (!EvaluateInPlace(V, Info, LV, Arg))
6016     return false;
6017 
6018   // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6019   // undefined behavior, so is non-constant.
6020   if (NonNull && V.isLValue() && V.isNullPointer()) {
6021     Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6022     return false;
6023   }
6024 
6025   return true;
6026 }
6027 
6028 /// Evaluate the arguments to a function call.
6029 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6030                          EvalInfo &Info, const FunctionDecl *Callee,
6031                          bool RightToLeft = false) {
6032   bool Success = true;
6033   llvm::SmallBitVector ForbiddenNullArgs;
6034   if (Callee->hasAttr<NonNullAttr>()) {
6035     ForbiddenNullArgs.resize(Args.size());
6036     for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6037       if (!Attr->args_size()) {
6038         ForbiddenNullArgs.set();
6039         break;
6040       } else
6041         for (auto Idx : Attr->args()) {
6042           unsigned ASTIdx = Idx.getASTIndex();
6043           if (ASTIdx >= Args.size())
6044             continue;
6045           ForbiddenNullArgs[ASTIdx] = true;
6046         }
6047     }
6048   }
6049   for (unsigned I = 0; I < Args.size(); I++) {
6050     unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6051     const ParmVarDecl *PVD =
6052         Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6053     bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6054     if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) {
6055       // If we're checking for a potential constant expression, evaluate all
6056       // initializers even if some of them fail.
6057       if (!Info.noteFailure())
6058         return false;
6059       Success = false;
6060     }
6061   }
6062   return Success;
6063 }
6064 
6065 /// Perform a trivial copy from Param, which is the parameter of a copy or move
6066 /// constructor or assignment operator.
6067 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6068                               const Expr *E, APValue &Result,
6069                               bool CopyObjectRepresentation) {
6070   // Find the reference argument.
6071   CallStackFrame *Frame = Info.CurrentCall;
6072   APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6073   if (!RefValue) {
6074     Info.FFDiag(E);
6075     return false;
6076   }
6077 
6078   // Copy out the contents of the RHS object.
6079   LValue RefLValue;
6080   RefLValue.setFrom(Info.Ctx, *RefValue);
6081   return handleLValueToRValueConversion(
6082       Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6083       CopyObjectRepresentation);
6084 }
6085 
6086 /// Evaluate a function call.
6087 static bool HandleFunctionCall(SourceLocation CallLoc,
6088                                const FunctionDecl *Callee, const LValue *This,
6089                                ArrayRef<const Expr *> Args, CallRef Call,
6090                                const Stmt *Body, EvalInfo &Info,
6091                                APValue &Result, const LValue *ResultSlot) {
6092   if (!Info.CheckCallLimit(CallLoc))
6093     return false;
6094 
6095   CallStackFrame Frame(Info, CallLoc, Callee, This, Call);
6096 
6097   // For a trivial copy or move assignment, perform an APValue copy. This is
6098   // essential for unions, where the operations performed by the assignment
6099   // operator cannot be represented as statements.
6100   //
6101   // Skip this for non-union classes with no fields; in that case, the defaulted
6102   // copy/move does not actually read the object.
6103   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6104   if (MD && MD->isDefaulted() &&
6105       (MD->getParent()->isUnion() ||
6106        (MD->isTrivial() &&
6107         isReadByLvalueToRvalueConversion(MD->getParent())))) {
6108     assert(This &&
6109            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
6110     APValue RHSValue;
6111     if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6112                            MD->getParent()->isUnion()))
6113       return false;
6114     if (Info.getLangOpts().CPlusPlus20 && MD->isTrivial() &&
6115         !HandleUnionActiveMemberChange(Info, Args[0], *This))
6116       return false;
6117     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
6118                           RHSValue))
6119       return false;
6120     This->moveInto(Result);
6121     return true;
6122   } else if (MD && isLambdaCallOperator(MD)) {
6123     // We're in a lambda; determine the lambda capture field maps unless we're
6124     // just constexpr checking a lambda's call operator. constexpr checking is
6125     // done before the captures have been added to the closure object (unless
6126     // we're inferring constexpr-ness), so we don't have access to them in this
6127     // case. But since we don't need the captures to constexpr check, we can
6128     // just ignore them.
6129     if (!Info.checkingPotentialConstantExpression())
6130       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6131                                         Frame.LambdaThisCaptureField);
6132   }
6133 
6134   StmtResult Ret = {Result, ResultSlot};
6135   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6136   if (ESR == ESR_Succeeded) {
6137     if (Callee->getReturnType()->isVoidType())
6138       return true;
6139     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6140   }
6141   return ESR == ESR_Returned;
6142 }
6143 
6144 /// Evaluate a constructor call.
6145 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6146                                   CallRef Call,
6147                                   const CXXConstructorDecl *Definition,
6148                                   EvalInfo &Info, APValue &Result) {
6149   SourceLocation CallLoc = E->getExprLoc();
6150   if (!Info.CheckCallLimit(CallLoc))
6151     return false;
6152 
6153   const CXXRecordDecl *RD = Definition->getParent();
6154   if (RD->getNumVBases()) {
6155     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6156     return false;
6157   }
6158 
6159   EvalInfo::EvaluatingConstructorRAII EvalObj(
6160       Info,
6161       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6162       RD->getNumBases());
6163   CallStackFrame Frame(Info, CallLoc, Definition, &This, Call);
6164 
6165   // FIXME: Creating an APValue just to hold a nonexistent return value is
6166   // wasteful.
6167   APValue RetVal;
6168   StmtResult Ret = {RetVal, nullptr};
6169 
6170   // If it's a delegating constructor, delegate.
6171   if (Definition->isDelegatingConstructor()) {
6172     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
6173     if ((*I)->getInit()->isValueDependent()) {
6174       if (!EvaluateDependentExpr((*I)->getInit(), Info))
6175         return false;
6176     } else {
6177       FullExpressionRAII InitScope(Info);
6178       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6179           !InitScope.destroy())
6180         return false;
6181     }
6182     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6183   }
6184 
6185   // For a trivial copy or move constructor, perform an APValue copy. This is
6186   // essential for unions (or classes with anonymous union members), where the
6187   // operations performed by the constructor cannot be represented by
6188   // ctor-initializers.
6189   //
6190   // Skip this for empty non-union classes; we should not perform an
6191   // lvalue-to-rvalue conversion on them because their copy constructor does not
6192   // actually read them.
6193   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6194       (Definition->getParent()->isUnion() ||
6195        (Definition->isTrivial() &&
6196         isReadByLvalueToRvalueConversion(Definition->getParent())))) {
6197     return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6198                              Definition->getParent()->isUnion());
6199   }
6200 
6201   // Reserve space for the struct members.
6202   if (!Result.hasValue()) {
6203     if (!RD->isUnion())
6204       Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6205                        std::distance(RD->field_begin(), RD->field_end()));
6206     else
6207       // A union starts with no active member.
6208       Result = APValue((const FieldDecl*)nullptr);
6209   }
6210 
6211   if (RD->isInvalidDecl()) return false;
6212   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6213 
6214   // A scope for temporaries lifetime-extended by reference members.
6215   BlockScopeRAII LifetimeExtendedScope(Info);
6216 
6217   bool Success = true;
6218   unsigned BasesSeen = 0;
6219 #ifndef NDEBUG
6220   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
6221 #endif
6222   CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
6223   auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6224     // We might be initializing the same field again if this is an indirect
6225     // field initialization.
6226     if (FieldIt == RD->field_end() ||
6227         FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6228       assert(Indirect && "fields out of order?");
6229       return;
6230     }
6231 
6232     // Default-initialize any fields with no explicit initializer.
6233     for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6234       assert(FieldIt != RD->field_end() && "missing field?");
6235       if (!FieldIt->isUnnamedBitfield())
6236         Success &= getDefaultInitValue(
6237             FieldIt->getType(),
6238             Result.getStructField(FieldIt->getFieldIndex()));
6239     }
6240     ++FieldIt;
6241   };
6242   for (const auto *I : Definition->inits()) {
6243     LValue Subobject = This;
6244     LValue SubobjectParent = This;
6245     APValue *Value = &Result;
6246 
6247     // Determine the subobject to initialize.
6248     FieldDecl *FD = nullptr;
6249     if (I->isBaseInitializer()) {
6250       QualType BaseType(I->getBaseClass(), 0);
6251 #ifndef NDEBUG
6252       // Non-virtual base classes are initialized in the order in the class
6253       // definition. We have already checked for virtual base classes.
6254       assert(!BaseIt->isVirtual() && "virtual base for literal type");
6255       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
6256              "base class initializers not in expected order");
6257       ++BaseIt;
6258 #endif
6259       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6260                                   BaseType->getAsCXXRecordDecl(), &Layout))
6261         return false;
6262       Value = &Result.getStructBase(BasesSeen++);
6263     } else if ((FD = I->getMember())) {
6264       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6265         return false;
6266       if (RD->isUnion()) {
6267         Result = APValue(FD);
6268         Value = &Result.getUnionValue();
6269       } else {
6270         SkipToField(FD, false);
6271         Value = &Result.getStructField(FD->getFieldIndex());
6272       }
6273     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6274       // Walk the indirect field decl's chain to find the object to initialize,
6275       // and make sure we've initialized every step along it.
6276       auto IndirectFieldChain = IFD->chain();
6277       for (auto *C : IndirectFieldChain) {
6278         FD = cast<FieldDecl>(C);
6279         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6280         // Switch the union field if it differs. This happens if we had
6281         // preceding zero-initialization, and we're now initializing a union
6282         // subobject other than the first.
6283         // FIXME: In this case, the values of the other subobjects are
6284         // specified, since zero-initialization sets all padding bits to zero.
6285         if (!Value->hasValue() ||
6286             (Value->isUnion() && Value->getUnionField() != FD)) {
6287           if (CD->isUnion())
6288             *Value = APValue(FD);
6289           else
6290             // FIXME: This immediately starts the lifetime of all members of
6291             // an anonymous struct. It would be preferable to strictly start
6292             // member lifetime in initialization order.
6293             Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
6294         }
6295         // Store Subobject as its parent before updating it for the last element
6296         // in the chain.
6297         if (C == IndirectFieldChain.back())
6298           SubobjectParent = Subobject;
6299         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6300           return false;
6301         if (CD->isUnion())
6302           Value = &Value->getUnionValue();
6303         else {
6304           if (C == IndirectFieldChain.front() && !RD->isUnion())
6305             SkipToField(FD, true);
6306           Value = &Value->getStructField(FD->getFieldIndex());
6307         }
6308       }
6309     } else {
6310       llvm_unreachable("unknown base initializer kind");
6311     }
6312 
6313     // Need to override This for implicit field initializers as in this case
6314     // This refers to innermost anonymous struct/union containing initializer,
6315     // not to currently constructed class.
6316     const Expr *Init = I->getInit();
6317     if (Init->isValueDependent()) {
6318       if (!EvaluateDependentExpr(Init, Info))
6319         return false;
6320     } else {
6321       ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6322                                     isa<CXXDefaultInitExpr>(Init));
6323       FullExpressionRAII InitScope(Info);
6324       if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6325           (FD && FD->isBitField() &&
6326            !truncateBitfieldValue(Info, Init, *Value, FD))) {
6327         // If we're checking for a potential constant expression, evaluate all
6328         // initializers even if some of them fail.
6329         if (!Info.noteFailure())
6330           return false;
6331         Success = false;
6332       }
6333     }
6334 
6335     // This is the point at which the dynamic type of the object becomes this
6336     // class type.
6337     if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6338       EvalObj.finishedConstructingBases();
6339   }
6340 
6341   // Default-initialize any remaining fields.
6342   if (!RD->isUnion()) {
6343     for (; FieldIt != RD->field_end(); ++FieldIt) {
6344       if (!FieldIt->isUnnamedBitfield())
6345         Success &= getDefaultInitValue(
6346             FieldIt->getType(),
6347             Result.getStructField(FieldIt->getFieldIndex()));
6348     }
6349   }
6350 
6351   EvalObj.finishedConstructingFields();
6352 
6353   return Success &&
6354          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6355          LifetimeExtendedScope.destroy();
6356 }
6357 
6358 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6359                                   ArrayRef<const Expr*> Args,
6360                                   const CXXConstructorDecl *Definition,
6361                                   EvalInfo &Info, APValue &Result) {
6362   CallScopeRAII CallScope(Info);
6363   CallRef Call = Info.CurrentCall->createCall(Definition);
6364   if (!EvaluateArgs(Args, Call, Info, Definition))
6365     return false;
6366 
6367   return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6368          CallScope.destroy();
6369 }
6370 
6371 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
6372                                   const LValue &This, APValue &Value,
6373                                   QualType T) {
6374   // Objects can only be destroyed while they're within their lifetimes.
6375   // FIXME: We have no representation for whether an object of type nullptr_t
6376   // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6377   // as indeterminate instead?
6378   if (Value.isAbsent() && !T->isNullPtrType()) {
6379     APValue Printable;
6380     This.moveInto(Printable);
6381     Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
6382       << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6383     return false;
6384   }
6385 
6386   // Invent an expression for location purposes.
6387   // FIXME: We shouldn't need to do this.
6388   OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_PRValue);
6389 
6390   // For arrays, destroy elements right-to-left.
6391   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6392     uint64_t Size = CAT->getSize().getZExtValue();
6393     QualType ElemT = CAT->getElementType();
6394 
6395     LValue ElemLV = This;
6396     ElemLV.addArray(Info, &LocE, CAT);
6397     if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6398       return false;
6399 
6400     // Ensure that we have actual array elements available to destroy; the
6401     // destructors might mutate the value, so we can't run them on the array
6402     // filler.
6403     if (Size && Size > Value.getArrayInitializedElts())
6404       expandArray(Value, Value.getArraySize() - 1);
6405 
6406     for (; Size != 0; --Size) {
6407       APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6408       if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6409           !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
6410         return false;
6411     }
6412 
6413     // End the lifetime of this array now.
6414     Value = APValue();
6415     return true;
6416   }
6417 
6418   const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6419   if (!RD) {
6420     if (T.isDestructedType()) {
6421       Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
6422       return false;
6423     }
6424 
6425     Value = APValue();
6426     return true;
6427   }
6428 
6429   if (RD->getNumVBases()) {
6430     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6431     return false;
6432   }
6433 
6434   const CXXDestructorDecl *DD = RD->getDestructor();
6435   if (!DD && !RD->hasTrivialDestructor()) {
6436     Info.FFDiag(CallLoc);
6437     return false;
6438   }
6439 
6440   if (!DD || DD->isTrivial() ||
6441       (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6442     // A trivial destructor just ends the lifetime of the object. Check for
6443     // this case before checking for a body, because we might not bother
6444     // building a body for a trivial destructor. Note that it doesn't matter
6445     // whether the destructor is constexpr in this case; all trivial
6446     // destructors are constexpr.
6447     //
6448     // If an anonymous union would be destroyed, some enclosing destructor must
6449     // have been explicitly defined, and the anonymous union destruction should
6450     // have no effect.
6451     Value = APValue();
6452     return true;
6453   }
6454 
6455   if (!Info.CheckCallLimit(CallLoc))
6456     return false;
6457 
6458   const FunctionDecl *Definition = nullptr;
6459   const Stmt *Body = DD->getBody(Definition);
6460 
6461   if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
6462     return false;
6463 
6464   CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef());
6465 
6466   // We're now in the period of destruction of this object.
6467   unsigned BasesLeft = RD->getNumBases();
6468   EvalInfo::EvaluatingDestructorRAII EvalObj(
6469       Info,
6470       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6471   if (!EvalObj.DidInsert) {
6472     // C++2a [class.dtor]p19:
6473     //   the behavior is undefined if the destructor is invoked for an object
6474     //   whose lifetime has ended
6475     // (Note that formally the lifetime ends when the period of destruction
6476     // begins, even though certain uses of the object remain valid until the
6477     // period of destruction ends.)
6478     Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
6479     return false;
6480   }
6481 
6482   // FIXME: Creating an APValue just to hold a nonexistent return value is
6483   // wasteful.
6484   APValue RetVal;
6485   StmtResult Ret = {RetVal, nullptr};
6486   if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6487     return false;
6488 
6489   // A union destructor does not implicitly destroy its members.
6490   if (RD->isUnion())
6491     return true;
6492 
6493   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6494 
6495   // We don't have a good way to iterate fields in reverse, so collect all the
6496   // fields first and then walk them backwards.
6497   SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
6498   for (const FieldDecl *FD : llvm::reverse(Fields)) {
6499     if (FD->isUnnamedBitfield())
6500       continue;
6501 
6502     LValue Subobject = This;
6503     if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6504       return false;
6505 
6506     APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6507     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6508                                FD->getType()))
6509       return false;
6510   }
6511 
6512   if (BasesLeft != 0)
6513     EvalObj.startedDestroyingBases();
6514 
6515   // Destroy base classes in reverse order.
6516   for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6517     --BasesLeft;
6518 
6519     QualType BaseType = Base.getType();
6520     LValue Subobject = This;
6521     if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
6522                                 BaseType->getAsCXXRecordDecl(), &Layout))
6523       return false;
6524 
6525     APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
6526     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6527                                BaseType))
6528       return false;
6529   }
6530   assert(BasesLeft == 0 && "NumBases was wrong?");
6531 
6532   // The period of destruction ends now. The object is gone.
6533   Value = APValue();
6534   return true;
6535 }
6536 
6537 namespace {
6538 struct DestroyObjectHandler {
6539   EvalInfo &Info;
6540   const Expr *E;
6541   const LValue &This;
6542   const AccessKinds AccessKind;
6543 
6544   typedef bool result_type;
6545   bool failed() { return false; }
6546   bool found(APValue &Subobj, QualType SubobjType) {
6547     return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
6548                                  SubobjType);
6549   }
6550   bool found(APSInt &Value, QualType SubobjType) {
6551     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6552     return false;
6553   }
6554   bool found(APFloat &Value, QualType SubobjType) {
6555     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6556     return false;
6557   }
6558 };
6559 }
6560 
6561 /// Perform a destructor or pseudo-destructor call on the given object, which
6562 /// might in general not be a complete object.
6563 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6564                               const LValue &This, QualType ThisType) {
6565   CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6566   DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6567   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6568 }
6569 
6570 /// Destroy and end the lifetime of the given complete object.
6571 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6572                               APValue::LValueBase LVBase, APValue &Value,
6573                               QualType T) {
6574   // If we've had an unmodeled side-effect, we can't rely on mutable state
6575   // (such as the object we're about to destroy) being correct.
6576   if (Info.EvalStatus.HasSideEffects)
6577     return false;
6578 
6579   LValue LV;
6580   LV.set({LVBase});
6581   return HandleDestructionImpl(Info, Loc, LV, Value, T);
6582 }
6583 
6584 /// Perform a call to 'perator new' or to `__builtin_operator_new'.
6585 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6586                                   LValue &Result) {
6587   if (Info.checkingPotentialConstantExpression() ||
6588       Info.SpeculativeEvaluationDepth)
6589     return false;
6590 
6591   // This is permitted only within a call to std::allocator<T>::allocate.
6592   auto Caller = Info.getStdAllocatorCaller("allocate");
6593   if (!Caller) {
6594     Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
6595                                      ? diag::note_constexpr_new_untyped
6596                                      : diag::note_constexpr_new);
6597     return false;
6598   }
6599 
6600   QualType ElemType = Caller.ElemType;
6601   if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6602     Info.FFDiag(E->getExprLoc(),
6603                 diag::note_constexpr_new_not_complete_object_type)
6604         << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6605     return false;
6606   }
6607 
6608   APSInt ByteSize;
6609   if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6610     return false;
6611   bool IsNothrow = false;
6612   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6613     EvaluateIgnoredValue(Info, E->getArg(I));
6614     IsNothrow |= E->getType()->isNothrowT();
6615   }
6616 
6617   CharUnits ElemSize;
6618   if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6619     return false;
6620   APInt Size, Remainder;
6621   APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6622   APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6623   if (Remainder != 0) {
6624     // This likely indicates a bug in the implementation of 'std::allocator'.
6625     Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6626         << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6627     return false;
6628   }
6629 
6630   if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
6631     if (IsNothrow) {
6632       Result.setNull(Info.Ctx, E->getType());
6633       return true;
6634     }
6635 
6636     Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
6637     return false;
6638   }
6639 
6640   QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
6641                                                      ArrayType::Normal, 0);
6642   APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6643   *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6644   Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6645   return true;
6646 }
6647 
6648 static bool hasVirtualDestructor(QualType T) {
6649   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6650     if (CXXDestructorDecl *DD = RD->getDestructor())
6651       return DD->isVirtual();
6652   return false;
6653 }
6654 
6655 static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6656   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6657     if (CXXDestructorDecl *DD = RD->getDestructor())
6658       return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6659   return nullptr;
6660 }
6661 
6662 /// Check that the given object is a suitable pointer to a heap allocation that
6663 /// still exists and is of the right kind for the purpose of a deletion.
6664 ///
6665 /// On success, returns the heap allocation to deallocate. On failure, produces
6666 /// a diagnostic and returns None.
6667 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6668                                             const LValue &Pointer,
6669                                             DynAlloc::Kind DeallocKind) {
6670   auto PointerAsString = [&] {
6671     return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6672   };
6673 
6674   DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6675   if (!DA) {
6676     Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6677         << PointerAsString();
6678     if (Pointer.Base)
6679       NoteLValueLocation(Info, Pointer.Base);
6680     return None;
6681   }
6682 
6683   Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6684   if (!Alloc) {
6685     Info.FFDiag(E, diag::note_constexpr_double_delete);
6686     return None;
6687   }
6688 
6689   QualType AllocType = Pointer.Base.getDynamicAllocType();
6690   if (DeallocKind != (*Alloc)->getKind()) {
6691     Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6692         << DeallocKind << (*Alloc)->getKind() << AllocType;
6693     NoteLValueLocation(Info, Pointer.Base);
6694     return None;
6695   }
6696 
6697   bool Subobject = false;
6698   if (DeallocKind == DynAlloc::New) {
6699     Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6700                 Pointer.Designator.isOnePastTheEnd();
6701   } else {
6702     Subobject = Pointer.Designator.Entries.size() != 1 ||
6703                 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6704   }
6705   if (Subobject) {
6706     Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6707         << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6708     return None;
6709   }
6710 
6711   return Alloc;
6712 }
6713 
6714 // Perform a call to 'operator delete' or '__builtin_operator_delete'.
6715 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6716   if (Info.checkingPotentialConstantExpression() ||
6717       Info.SpeculativeEvaluationDepth)
6718     return false;
6719 
6720   // This is permitted only within a call to std::allocator<T>::deallocate.
6721   if (!Info.getStdAllocatorCaller("deallocate")) {
6722     Info.FFDiag(E->getExprLoc());
6723     return true;
6724   }
6725 
6726   LValue Pointer;
6727   if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6728     return false;
6729   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6730     EvaluateIgnoredValue(Info, E->getArg(I));
6731 
6732   if (Pointer.Designator.Invalid)
6733     return false;
6734 
6735   // Deleting a null pointer would have no effect, but it's not permitted by
6736   // std::allocator<T>::deallocate's contract.
6737   if (Pointer.isNullPointer()) {
6738     Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
6739     return true;
6740   }
6741 
6742   if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6743     return false;
6744 
6745   Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6746   return true;
6747 }
6748 
6749 //===----------------------------------------------------------------------===//
6750 // Generic Evaluation
6751 //===----------------------------------------------------------------------===//
6752 namespace {
6753 
6754 class BitCastBuffer {
6755   // FIXME: We're going to need bit-level granularity when we support
6756   // bit-fields.
6757   // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6758   // we don't support a host or target where that is the case. Still, we should
6759   // use a more generic type in case we ever do.
6760   SmallVector<Optional<unsigned char>, 32> Bytes;
6761 
6762   static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6763                 "Need at least 8 bit unsigned char");
6764 
6765   bool TargetIsLittleEndian;
6766 
6767 public:
6768   BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6769       : Bytes(Width.getQuantity()),
6770         TargetIsLittleEndian(TargetIsLittleEndian) {}
6771 
6772   LLVM_NODISCARD
6773   bool readObject(CharUnits Offset, CharUnits Width,
6774                   SmallVectorImpl<unsigned char> &Output) const {
6775     for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6776       // If a byte of an integer is uninitialized, then the whole integer is
6777       // uninitialized.
6778       if (!Bytes[I.getQuantity()])
6779         return false;
6780       Output.push_back(*Bytes[I.getQuantity()]);
6781     }
6782     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6783       std::reverse(Output.begin(), Output.end());
6784     return true;
6785   }
6786 
6787   void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6788     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6789       std::reverse(Input.begin(), Input.end());
6790 
6791     size_t Index = 0;
6792     for (unsigned char Byte : Input) {
6793       assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
6794       Bytes[Offset.getQuantity() + Index] = Byte;
6795       ++Index;
6796     }
6797   }
6798 
6799   size_t size() { return Bytes.size(); }
6800 };
6801 
6802 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6803 /// target would represent the value at runtime.
6804 class APValueToBufferConverter {
6805   EvalInfo &Info;
6806   BitCastBuffer Buffer;
6807   const CastExpr *BCE;
6808 
6809   APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6810                            const CastExpr *BCE)
6811       : Info(Info),
6812         Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6813         BCE(BCE) {}
6814 
6815   bool visit(const APValue &Val, QualType Ty) {
6816     return visit(Val, Ty, CharUnits::fromQuantity(0));
6817   }
6818 
6819   // Write out Val with type Ty into Buffer starting at Offset.
6820   bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6821     assert((size_t)Offset.getQuantity() <= Buffer.size());
6822 
6823     // As a special case, nullptr_t has an indeterminate value.
6824     if (Ty->isNullPtrType())
6825       return true;
6826 
6827     // Dig through Src to find the byte at SrcOffset.
6828     switch (Val.getKind()) {
6829     case APValue::Indeterminate:
6830     case APValue::None:
6831       return true;
6832 
6833     case APValue::Int:
6834       return visitInt(Val.getInt(), Ty, Offset);
6835     case APValue::Float:
6836       return visitFloat(Val.getFloat(), Ty, Offset);
6837     case APValue::Array:
6838       return visitArray(Val, Ty, Offset);
6839     case APValue::Struct:
6840       return visitRecord(Val, Ty, Offset);
6841 
6842     case APValue::ComplexInt:
6843     case APValue::ComplexFloat:
6844     case APValue::Vector:
6845     case APValue::FixedPoint:
6846       // FIXME: We should support these.
6847 
6848     case APValue::Union:
6849     case APValue::MemberPointer:
6850     case APValue::AddrLabelDiff: {
6851       Info.FFDiag(BCE->getBeginLoc(),
6852                   diag::note_constexpr_bit_cast_unsupported_type)
6853           << Ty;
6854       return false;
6855     }
6856 
6857     case APValue::LValue:
6858       llvm_unreachable("LValue subobject in bit_cast?");
6859     }
6860     llvm_unreachable("Unhandled APValue::ValueKind");
6861   }
6862 
6863   bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
6864     const RecordDecl *RD = Ty->getAsRecordDecl();
6865     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6866 
6867     // Visit the base classes.
6868     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6869       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6870         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6871         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6872 
6873         if (!visitRecord(Val.getStructBase(I), BS.getType(),
6874                          Layout.getBaseClassOffset(BaseDecl) + Offset))
6875           return false;
6876       }
6877     }
6878 
6879     // Visit the fields.
6880     unsigned FieldIdx = 0;
6881     for (FieldDecl *FD : RD->fields()) {
6882       if (FD->isBitField()) {
6883         Info.FFDiag(BCE->getBeginLoc(),
6884                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6885         return false;
6886       }
6887 
6888       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6889 
6890       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
6891              "only bit-fields can have sub-char alignment");
6892       CharUnits FieldOffset =
6893           Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
6894       QualType FieldTy = FD->getType();
6895       if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
6896         return false;
6897       ++FieldIdx;
6898     }
6899 
6900     return true;
6901   }
6902 
6903   bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
6904     const auto *CAT =
6905         dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
6906     if (!CAT)
6907       return false;
6908 
6909     CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
6910     unsigned NumInitializedElts = Val.getArrayInitializedElts();
6911     unsigned ArraySize = Val.getArraySize();
6912     // First, initialize the initialized elements.
6913     for (unsigned I = 0; I != NumInitializedElts; ++I) {
6914       const APValue &SubObj = Val.getArrayInitializedElt(I);
6915       if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
6916         return false;
6917     }
6918 
6919     // Next, initialize the rest of the array using the filler.
6920     if (Val.hasArrayFiller()) {
6921       const APValue &Filler = Val.getArrayFiller();
6922       for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
6923         if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
6924           return false;
6925       }
6926     }
6927 
6928     return true;
6929   }
6930 
6931   bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
6932     APSInt AdjustedVal = Val;
6933     unsigned Width = AdjustedVal.getBitWidth();
6934     if (Ty->isBooleanType()) {
6935       Width = Info.Ctx.getTypeSize(Ty);
6936       AdjustedVal = AdjustedVal.extend(Width);
6937     }
6938 
6939     SmallVector<unsigned char, 8> Bytes(Width / 8);
6940     llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
6941     Buffer.writeObject(Offset, Bytes);
6942     return true;
6943   }
6944 
6945   bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
6946     APSInt AsInt(Val.bitcastToAPInt());
6947     return visitInt(AsInt, Ty, Offset);
6948   }
6949 
6950 public:
6951   static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
6952                                          const CastExpr *BCE) {
6953     CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
6954     APValueToBufferConverter Converter(Info, DstSize, BCE);
6955     if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
6956       return None;
6957     return Converter.Buffer;
6958   }
6959 };
6960 
6961 /// Write an BitCastBuffer into an APValue.
6962 class BufferToAPValueConverter {
6963   EvalInfo &Info;
6964   const BitCastBuffer &Buffer;
6965   const CastExpr *BCE;
6966 
6967   BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
6968                            const CastExpr *BCE)
6969       : Info(Info), Buffer(Buffer), BCE(BCE) {}
6970 
6971   // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
6972   // with an invalid type, so anything left is a deficiency on our part (FIXME).
6973   // Ideally this will be unreachable.
6974   llvm::NoneType unsupportedType(QualType Ty) {
6975     Info.FFDiag(BCE->getBeginLoc(),
6976                 diag::note_constexpr_bit_cast_unsupported_type)
6977         << Ty;
6978     return None;
6979   }
6980 
6981   llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) {
6982     Info.FFDiag(BCE->getBeginLoc(),
6983                 diag::note_constexpr_bit_cast_unrepresentable_value)
6984         << Ty << toString(Val, /*Radix=*/10);
6985     return None;
6986   }
6987 
6988   Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
6989                           const EnumType *EnumSugar = nullptr) {
6990     if (T->isNullPtrType()) {
6991       uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
6992       return APValue((Expr *)nullptr,
6993                      /*Offset=*/CharUnits::fromQuantity(NullValue),
6994                      APValue::NoLValuePath{}, /*IsNullPtr=*/true);
6995     }
6996 
6997     CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
6998 
6999     // Work around floating point types that contain unused padding bytes. This
7000     // is really just `long double` on x86, which is the only fundamental type
7001     // with padding bytes.
7002     if (T->isRealFloatingType()) {
7003       const llvm::fltSemantics &Semantics =
7004           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7005       unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
7006       assert(NumBits % 8 == 0);
7007       CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
7008       if (NumBytes != SizeOf)
7009         SizeOf = NumBytes;
7010     }
7011 
7012     SmallVector<uint8_t, 8> Bytes;
7013     if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
7014       // If this is std::byte or unsigned char, then its okay to store an
7015       // indeterminate value.
7016       bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
7017       bool IsUChar =
7018           !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
7019                          T->isSpecificBuiltinType(BuiltinType::Char_U));
7020       if (!IsStdByte && !IsUChar) {
7021         QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
7022         Info.FFDiag(BCE->getExprLoc(),
7023                     diag::note_constexpr_bit_cast_indet_dest)
7024             << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
7025         return None;
7026       }
7027 
7028       return APValue::IndeterminateValue();
7029     }
7030 
7031     APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
7032     llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
7033 
7034     if (T->isIntegralOrEnumerationType()) {
7035       Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7036 
7037       unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
7038       if (IntWidth != Val.getBitWidth()) {
7039         APSInt Truncated = Val.trunc(IntWidth);
7040         if (Truncated.extend(Val.getBitWidth()) != Val)
7041           return unrepresentableValue(QualType(T, 0), Val);
7042         Val = Truncated;
7043       }
7044 
7045       return APValue(Val);
7046     }
7047 
7048     if (T->isRealFloatingType()) {
7049       const llvm::fltSemantics &Semantics =
7050           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7051       return APValue(APFloat(Semantics, Val));
7052     }
7053 
7054     return unsupportedType(QualType(T, 0));
7055   }
7056 
7057   Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7058     const RecordDecl *RD = RTy->getAsRecordDecl();
7059     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7060 
7061     unsigned NumBases = 0;
7062     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7063       NumBases = CXXRD->getNumBases();
7064 
7065     APValue ResultVal(APValue::UninitStruct(), NumBases,
7066                       std::distance(RD->field_begin(), RD->field_end()));
7067 
7068     // Visit the base classes.
7069     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7070       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7071         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7072         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7073         if (BaseDecl->isEmpty() ||
7074             Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
7075           continue;
7076 
7077         Optional<APValue> SubObj = visitType(
7078             BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7079         if (!SubObj)
7080           return None;
7081         ResultVal.getStructBase(I) = *SubObj;
7082       }
7083     }
7084 
7085     // Visit the fields.
7086     unsigned FieldIdx = 0;
7087     for (FieldDecl *FD : RD->fields()) {
7088       // FIXME: We don't currently support bit-fields. A lot of the logic for
7089       // this is in CodeGen, so we need to factor it around.
7090       if (FD->isBitField()) {
7091         Info.FFDiag(BCE->getBeginLoc(),
7092                     diag::note_constexpr_bit_cast_unsupported_bitfield);
7093         return None;
7094       }
7095 
7096       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7097       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
7098 
7099       CharUnits FieldOffset =
7100           CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7101           Offset;
7102       QualType FieldTy = FD->getType();
7103       Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7104       if (!SubObj)
7105         return None;
7106       ResultVal.getStructField(FieldIdx) = *SubObj;
7107       ++FieldIdx;
7108     }
7109 
7110     return ResultVal;
7111   }
7112 
7113   Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7114     QualType RepresentationType = Ty->getDecl()->getIntegerType();
7115     assert(!RepresentationType.isNull() &&
7116            "enum forward decl should be caught by Sema");
7117     const auto *AsBuiltin =
7118         RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7119     // Recurse into the underlying type. Treat std::byte transparently as
7120     // unsigned char.
7121     return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7122   }
7123 
7124   Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7125     size_t Size = Ty->getSize().getLimitedValue();
7126     CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7127 
7128     APValue ArrayValue(APValue::UninitArray(), Size, Size);
7129     for (size_t I = 0; I != Size; ++I) {
7130       Optional<APValue> ElementValue =
7131           visitType(Ty->getElementType(), Offset + I * ElementWidth);
7132       if (!ElementValue)
7133         return None;
7134       ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7135     }
7136 
7137     return ArrayValue;
7138   }
7139 
7140   Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7141     return unsupportedType(QualType(Ty, 0));
7142   }
7143 
7144   Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7145     QualType Can = Ty.getCanonicalType();
7146 
7147     switch (Can->getTypeClass()) {
7148 #define TYPE(Class, Base)                                                      \
7149   case Type::Class:                                                            \
7150     return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7151 #define ABSTRACT_TYPE(Class, Base)
7152 #define NON_CANONICAL_TYPE(Class, Base)                                        \
7153   case Type::Class:                                                            \
7154     llvm_unreachable("non-canonical type should be impossible!");
7155 #define DEPENDENT_TYPE(Class, Base)                                            \
7156   case Type::Class:                                                            \
7157     llvm_unreachable(                                                          \
7158         "dependent types aren't supported in the constant evaluator!");
7159 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)                            \
7160   case Type::Class:                                                            \
7161     llvm_unreachable("either dependent or not canonical!");
7162 #include "clang/AST/TypeNodes.inc"
7163     }
7164     llvm_unreachable("Unhandled Type::TypeClass");
7165   }
7166 
7167 public:
7168   // Pull out a full value of type DstType.
7169   static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7170                                    const CastExpr *BCE) {
7171     BufferToAPValueConverter Converter(Info, Buffer, BCE);
7172     return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7173   }
7174 };
7175 
7176 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7177                                                  QualType Ty, EvalInfo *Info,
7178                                                  const ASTContext &Ctx,
7179                                                  bool CheckingDest) {
7180   Ty = Ty.getCanonicalType();
7181 
7182   auto diag = [&](int Reason) {
7183     if (Info)
7184       Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7185           << CheckingDest << (Reason == 4) << Reason;
7186     return false;
7187   };
7188   auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7189     if (Info)
7190       Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7191           << NoteTy << Construct << Ty;
7192     return false;
7193   };
7194 
7195   if (Ty->isUnionType())
7196     return diag(0);
7197   if (Ty->isPointerType())
7198     return diag(1);
7199   if (Ty->isMemberPointerType())
7200     return diag(2);
7201   if (Ty.isVolatileQualified())
7202     return diag(3);
7203 
7204   if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7205     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7206       for (CXXBaseSpecifier &BS : CXXRD->bases())
7207         if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7208                                                   CheckingDest))
7209           return note(1, BS.getType(), BS.getBeginLoc());
7210     }
7211     for (FieldDecl *FD : Record->fields()) {
7212       if (FD->getType()->isReferenceType())
7213         return diag(4);
7214       if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7215                                                 CheckingDest))
7216         return note(0, FD->getType(), FD->getBeginLoc());
7217     }
7218   }
7219 
7220   if (Ty->isArrayType() &&
7221       !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7222                                             Info, Ctx, CheckingDest))
7223     return false;
7224 
7225   return true;
7226 }
7227 
7228 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
7229                                              const ASTContext &Ctx,
7230                                              const CastExpr *BCE) {
7231   bool DestOK = checkBitCastConstexprEligibilityType(
7232       BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
7233   bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
7234                                 BCE->getBeginLoc(),
7235                                 BCE->getSubExpr()->getType(), Info, Ctx, false);
7236   return SourceOK;
7237 }
7238 
7239 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7240                                         APValue &SourceValue,
7241                                         const CastExpr *BCE) {
7242   assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7243          "no host or target supports non 8-bit chars");
7244   assert(SourceValue.isLValue() &&
7245          "LValueToRValueBitcast requires an lvalue operand!");
7246 
7247   if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
7248     return false;
7249 
7250   LValue SourceLValue;
7251   APValue SourceRValue;
7252   SourceLValue.setFrom(Info.Ctx, SourceValue);
7253   if (!handleLValueToRValueConversion(
7254           Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
7255           SourceRValue, /*WantObjectRepresentation=*/true))
7256     return false;
7257 
7258   // Read out SourceValue into a char buffer.
7259   Optional<BitCastBuffer> Buffer =
7260       APValueToBufferConverter::convert(Info, SourceRValue, BCE);
7261   if (!Buffer)
7262     return false;
7263 
7264   // Write out the buffer into a new APValue.
7265   Optional<APValue> MaybeDestValue =
7266       BufferToAPValueConverter::convert(Info, *Buffer, BCE);
7267   if (!MaybeDestValue)
7268     return false;
7269 
7270   DestValue = std::move(*MaybeDestValue);
7271   return true;
7272 }
7273 
7274 template <class Derived>
7275 class ExprEvaluatorBase
7276   : public ConstStmtVisitor<Derived, bool> {
7277 private:
7278   Derived &getDerived() { return static_cast<Derived&>(*this); }
7279   bool DerivedSuccess(const APValue &V, const Expr *E) {
7280     return getDerived().Success(V, E);
7281   }
7282   bool DerivedZeroInitialization(const Expr *E) {
7283     return getDerived().ZeroInitialization(E);
7284   }
7285 
7286   // Check whether a conditional operator with a non-constant condition is a
7287   // potential constant expression. If neither arm is a potential constant
7288   // expression, then the conditional operator is not either.
7289   template<typename ConditionalOperator>
7290   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7291     assert(Info.checkingPotentialConstantExpression());
7292 
7293     // Speculatively evaluate both arms.
7294     SmallVector<PartialDiagnosticAt, 8> Diag;
7295     {
7296       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7297       StmtVisitorTy::Visit(E->getFalseExpr());
7298       if (Diag.empty())
7299         return;
7300     }
7301 
7302     {
7303       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7304       Diag.clear();
7305       StmtVisitorTy::Visit(E->getTrueExpr());
7306       if (Diag.empty())
7307         return;
7308     }
7309 
7310     Error(E, diag::note_constexpr_conditional_never_const);
7311   }
7312 
7313 
7314   template<typename ConditionalOperator>
7315   bool HandleConditionalOperator(const ConditionalOperator *E) {
7316     bool BoolResult;
7317     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7318       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7319         CheckPotentialConstantConditional(E);
7320         return false;
7321       }
7322       if (Info.noteFailure()) {
7323         StmtVisitorTy::Visit(E->getTrueExpr());
7324         StmtVisitorTy::Visit(E->getFalseExpr());
7325       }
7326       return false;
7327     }
7328 
7329     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
7330     return StmtVisitorTy::Visit(EvalExpr);
7331   }
7332 
7333 protected:
7334   EvalInfo &Info;
7335   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
7336   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
7337 
7338   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7339     return Info.CCEDiag(E, D);
7340   }
7341 
7342   bool ZeroInitialization(const Expr *E) { return Error(E); }
7343 
7344 public:
7345   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
7346 
7347   EvalInfo &getEvalInfo() { return Info; }
7348 
7349   /// Report an evaluation error. This should only be called when an error is
7350   /// first discovered. When propagating an error, just return false.
7351   bool Error(const Expr *E, diag::kind D) {
7352     Info.FFDiag(E, D);
7353     return false;
7354   }
7355   bool Error(const Expr *E) {
7356     return Error(E, diag::note_invalid_subexpr_in_const_expr);
7357   }
7358 
7359   bool VisitStmt(const Stmt *) {
7360     llvm_unreachable("Expression evaluator should not be called on stmts");
7361   }
7362   bool VisitExpr(const Expr *E) {
7363     return Error(E);
7364   }
7365 
7366   bool VisitConstantExpr(const ConstantExpr *E) {
7367     if (E->hasAPValueResult())
7368       return DerivedSuccess(E->getAPValueResult(), E);
7369 
7370     return StmtVisitorTy::Visit(E->getSubExpr());
7371   }
7372 
7373   bool VisitParenExpr(const ParenExpr *E)
7374     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7375   bool VisitUnaryExtension(const UnaryOperator *E)
7376     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7377   bool VisitUnaryPlus(const UnaryOperator *E)
7378     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7379   bool VisitChooseExpr(const ChooseExpr *E)
7380     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
7381   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
7382     { return StmtVisitorTy::Visit(E->getResultExpr()); }
7383   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
7384     { return StmtVisitorTy::Visit(E->getReplacement()); }
7385   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7386     TempVersionRAII RAII(*Info.CurrentCall);
7387     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7388     return StmtVisitorTy::Visit(E->getExpr());
7389   }
7390   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7391     TempVersionRAII RAII(*Info.CurrentCall);
7392     // The initializer may not have been parsed yet, or might be erroneous.
7393     if (!E->getExpr())
7394       return Error(E);
7395     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7396     return StmtVisitorTy::Visit(E->getExpr());
7397   }
7398 
7399   bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7400     FullExpressionRAII Scope(Info);
7401     return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
7402   }
7403 
7404   // Temporaries are registered when created, so we don't care about
7405   // CXXBindTemporaryExpr.
7406   bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7407     return StmtVisitorTy::Visit(E->getSubExpr());
7408   }
7409 
7410   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7411     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7412     return static_cast<Derived*>(this)->VisitCastExpr(E);
7413   }
7414   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7415     if (!Info.Ctx.getLangOpts().CPlusPlus20)
7416       CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
7417     return static_cast<Derived*>(this)->VisitCastExpr(E);
7418   }
7419   bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7420     return static_cast<Derived*>(this)->VisitCastExpr(E);
7421   }
7422 
7423   bool VisitBinaryOperator(const BinaryOperator *E) {
7424     switch (E->getOpcode()) {
7425     default:
7426       return Error(E);
7427 
7428     case BO_Comma:
7429       VisitIgnoredValue(E->getLHS());
7430       return StmtVisitorTy::Visit(E->getRHS());
7431 
7432     case BO_PtrMemD:
7433     case BO_PtrMemI: {
7434       LValue Obj;
7435       if (!HandleMemberPointerAccess(Info, E, Obj))
7436         return false;
7437       APValue Result;
7438       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7439         return false;
7440       return DerivedSuccess(Result, E);
7441     }
7442     }
7443   }
7444 
7445   bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
7446     return StmtVisitorTy::Visit(E->getSemanticForm());
7447   }
7448 
7449   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7450     // Evaluate and cache the common expression. We treat it as a temporary,
7451     // even though it's not quite the same thing.
7452     LValue CommonLV;
7453     if (!Evaluate(Info.CurrentCall->createTemporary(
7454                       E->getOpaqueValue(),
7455                       getStorageType(Info.Ctx, E->getOpaqueValue()),
7456                       ScopeKind::FullExpression, CommonLV),
7457                   Info, E->getCommon()))
7458       return false;
7459 
7460     return HandleConditionalOperator(E);
7461   }
7462 
7463   bool VisitConditionalOperator(const ConditionalOperator *E) {
7464     bool IsBcpCall = false;
7465     // If the condition (ignoring parens) is a __builtin_constant_p call,
7466     // the result is a constant expression if it can be folded without
7467     // side-effects. This is an important GNU extension. See GCC PR38377
7468     // for discussion.
7469     if (const CallExpr *CallCE =
7470           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7471       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7472         IsBcpCall = true;
7473 
7474     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7475     // constant expression; we can't check whether it's potentially foldable.
7476     // FIXME: We should instead treat __builtin_constant_p as non-constant if
7477     // it would return 'false' in this mode.
7478     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
7479       return false;
7480 
7481     FoldConstant Fold(Info, IsBcpCall);
7482     if (!HandleConditionalOperator(E)) {
7483       Fold.keepDiagnostics();
7484       return false;
7485     }
7486 
7487     return true;
7488   }
7489 
7490   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7491     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
7492       return DerivedSuccess(*Value, E);
7493 
7494     const Expr *Source = E->getSourceExpr();
7495     if (!Source)
7496       return Error(E);
7497     if (Source == E) {
7498       assert(0 && "OpaqueValueExpr recursively refers to itself");
7499       return Error(E);
7500     }
7501     return StmtVisitorTy::Visit(Source);
7502   }
7503 
7504   bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7505     for (const Expr *SemE : E->semantics()) {
7506       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7507         // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7508         // result expression: there could be two different LValues that would
7509         // refer to the same object in that case, and we can't model that.
7510         if (SemE == E->getResultExpr())
7511           return Error(E);
7512 
7513         // Unique OVEs get evaluated if and when we encounter them when
7514         // emitting the rest of the semantic form, rather than eagerly.
7515         if (OVE->isUnique())
7516           continue;
7517 
7518         LValue LV;
7519         if (!Evaluate(Info.CurrentCall->createTemporary(
7520                           OVE, getStorageType(Info.Ctx, OVE),
7521                           ScopeKind::FullExpression, LV),
7522                       Info, OVE->getSourceExpr()))
7523           return false;
7524       } else if (SemE == E->getResultExpr()) {
7525         if (!StmtVisitorTy::Visit(SemE))
7526           return false;
7527       } else {
7528         if (!EvaluateIgnoredValue(Info, SemE))
7529           return false;
7530       }
7531     }
7532     return true;
7533   }
7534 
7535   bool VisitCallExpr(const CallExpr *E) {
7536     APValue Result;
7537     if (!handleCallExpr(E, Result, nullptr))
7538       return false;
7539     return DerivedSuccess(Result, E);
7540   }
7541 
7542   bool handleCallExpr(const CallExpr *E, APValue &Result,
7543                      const LValue *ResultSlot) {
7544     CallScopeRAII CallScope(Info);
7545 
7546     const Expr *Callee = E->getCallee()->IgnoreParens();
7547     QualType CalleeType = Callee->getType();
7548 
7549     const FunctionDecl *FD = nullptr;
7550     LValue *This = nullptr, ThisVal;
7551     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
7552     bool HasQualifier = false;
7553 
7554     CallRef Call;
7555 
7556     // Extract function decl and 'this' pointer from the callee.
7557     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7558       const CXXMethodDecl *Member = nullptr;
7559       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7560         // Explicit bound member calls, such as x.f() or p->g();
7561         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7562           return false;
7563         Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7564         if (!Member)
7565           return Error(Callee);
7566         This = &ThisVal;
7567         HasQualifier = ME->hasQualifier();
7568       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
7569         // Indirect bound member calls ('.*' or '->*').
7570         const ValueDecl *D =
7571             HandleMemberPointerAccess(Info, BE, ThisVal, false);
7572         if (!D)
7573           return false;
7574         Member = dyn_cast<CXXMethodDecl>(D);
7575         if (!Member)
7576           return Error(Callee);
7577         This = &ThisVal;
7578       } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7579         if (!Info.getLangOpts().CPlusPlus20)
7580           Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7581         return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7582                HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7583       } else
7584         return Error(Callee);
7585       FD = Member;
7586     } else if (CalleeType->isFunctionPointerType()) {
7587       LValue CalleeLV;
7588       if (!EvaluatePointer(Callee, CalleeLV, Info))
7589         return false;
7590 
7591       if (!CalleeLV.getLValueOffset().isZero())
7592         return Error(Callee);
7593       FD = dyn_cast_or_null<FunctionDecl>(
7594           CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
7595       if (!FD)
7596         return Error(Callee);
7597       // Don't call function pointers which have been cast to some other type.
7598       // Per DR (no number yet), the caller and callee can differ in noexcept.
7599       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7600         CalleeType->getPointeeType(), FD->getType())) {
7601         return Error(E);
7602       }
7603 
7604       // For an (overloaded) assignment expression, evaluate the RHS before the
7605       // LHS.
7606       auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
7607       if (OCE && OCE->isAssignmentOp()) {
7608         assert(Args.size() == 2 && "wrong number of arguments in assignment");
7609         Call = Info.CurrentCall->createCall(FD);
7610         if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call,
7611                           Info, FD, /*RightToLeft=*/true))
7612           return false;
7613       }
7614 
7615       // Overloaded operator calls to member functions are represented as normal
7616       // calls with '*this' as the first argument.
7617       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7618       if (MD && !MD->isStatic()) {
7619         // FIXME: When selecting an implicit conversion for an overloaded
7620         // operator delete, we sometimes try to evaluate calls to conversion
7621         // operators without a 'this' parameter!
7622         if (Args.empty())
7623           return Error(E);
7624 
7625         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7626           return false;
7627         This = &ThisVal;
7628         Args = Args.slice(1);
7629       } else if (MD && MD->isLambdaStaticInvoker()) {
7630         // Map the static invoker for the lambda back to the call operator.
7631         // Conveniently, we don't have to slice out the 'this' argument (as is
7632         // being done for the non-static case), since a static member function
7633         // doesn't have an implicit argument passed in.
7634         const CXXRecordDecl *ClosureClass = MD->getParent();
7635         assert(
7636             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7637             "Number of captures must be zero for conversion to function-ptr");
7638 
7639         const CXXMethodDecl *LambdaCallOp =
7640             ClosureClass->getLambdaCallOperator();
7641 
7642         // Set 'FD', the function that will be called below, to the call
7643         // operator.  If the closure object represents a generic lambda, find
7644         // the corresponding specialization of the call operator.
7645 
7646         if (ClosureClass->isGenericLambda()) {
7647           assert(MD->isFunctionTemplateSpecialization() &&
7648                  "A generic lambda's static-invoker function must be a "
7649                  "template specialization");
7650           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7651           FunctionTemplateDecl *CallOpTemplate =
7652               LambdaCallOp->getDescribedFunctionTemplate();
7653           void *InsertPos = nullptr;
7654           FunctionDecl *CorrespondingCallOpSpecialization =
7655               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7656           assert(CorrespondingCallOpSpecialization &&
7657                  "We must always have a function call operator specialization "
7658                  "that corresponds to our static invoker specialization");
7659           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7660         } else
7661           FD = LambdaCallOp;
7662       } else if (FD->isReplaceableGlobalAllocationFunction()) {
7663         if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7664             FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7665           LValue Ptr;
7666           if (!HandleOperatorNewCall(Info, E, Ptr))
7667             return false;
7668           Ptr.moveInto(Result);
7669           return CallScope.destroy();
7670         } else {
7671           return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
7672         }
7673       }
7674     } else
7675       return Error(E);
7676 
7677     // Evaluate the arguments now if we've not already done so.
7678     if (!Call) {
7679       Call = Info.CurrentCall->createCall(FD);
7680       if (!EvaluateArgs(Args, Call, Info, FD))
7681         return false;
7682     }
7683 
7684     SmallVector<QualType, 4> CovariantAdjustmentPath;
7685     if (This) {
7686       auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7687       if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
7688         // Perform virtual dispatch, if necessary.
7689         FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
7690                                    CovariantAdjustmentPath);
7691         if (!FD)
7692           return false;
7693       } else {
7694         // Check that the 'this' pointer points to an object of the right type.
7695         // FIXME: If this is an assignment operator call, we may need to change
7696         // the active union member before we check this.
7697         if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
7698           return false;
7699       }
7700     }
7701 
7702     // Destructor calls are different enough that they have their own codepath.
7703     if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
7704       assert(This && "no 'this' pointer for destructor call");
7705       return HandleDestruction(Info, E, *This,
7706                                Info.Ctx.getRecordType(DD->getParent())) &&
7707              CallScope.destroy();
7708     }
7709 
7710     const FunctionDecl *Definition = nullptr;
7711     Stmt *Body = FD->getBody(Definition);
7712 
7713     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
7714         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call,
7715                             Body, Info, Result, ResultSlot))
7716       return false;
7717 
7718     if (!CovariantAdjustmentPath.empty() &&
7719         !HandleCovariantReturnAdjustment(Info, E, Result,
7720                                          CovariantAdjustmentPath))
7721       return false;
7722 
7723     return CallScope.destroy();
7724   }
7725 
7726   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7727     return StmtVisitorTy::Visit(E->getInitializer());
7728   }
7729   bool VisitInitListExpr(const InitListExpr *E) {
7730     if (E->getNumInits() == 0)
7731       return DerivedZeroInitialization(E);
7732     if (E->getNumInits() == 1)
7733       return StmtVisitorTy::Visit(E->getInit(0));
7734     return Error(E);
7735   }
7736   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
7737     return DerivedZeroInitialization(E);
7738   }
7739   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
7740     return DerivedZeroInitialization(E);
7741   }
7742   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
7743     return DerivedZeroInitialization(E);
7744   }
7745 
7746   /// A member expression where the object is a prvalue is itself a prvalue.
7747   bool VisitMemberExpr(const MemberExpr *E) {
7748     assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
7749            "missing temporary materialization conversion");
7750     assert(!E->isArrow() && "missing call to bound member function?");
7751 
7752     APValue Val;
7753     if (!Evaluate(Val, Info, E->getBase()))
7754       return false;
7755 
7756     QualType BaseTy = E->getBase()->getType();
7757 
7758     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
7759     if (!FD) return Error(E);
7760     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
7761     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7762            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7763 
7764     // Note: there is no lvalue base here. But this case should only ever
7765     // happen in C or in C++98, where we cannot be evaluating a constexpr
7766     // constructor, which is the only case the base matters.
7767     CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
7768     SubobjectDesignator Designator(BaseTy);
7769     Designator.addDeclUnchecked(FD);
7770 
7771     APValue Result;
7772     return extractSubobject(Info, E, Obj, Designator, Result) &&
7773            DerivedSuccess(Result, E);
7774   }
7775 
7776   bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
7777     APValue Val;
7778     if (!Evaluate(Val, Info, E->getBase()))
7779       return false;
7780 
7781     if (Val.isVector()) {
7782       SmallVector<uint32_t, 4> Indices;
7783       E->getEncodedElementAccess(Indices);
7784       if (Indices.size() == 1) {
7785         // Return scalar.
7786         return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
7787       } else {
7788         // Construct new APValue vector.
7789         SmallVector<APValue, 4> Elts;
7790         for (unsigned I = 0; I < Indices.size(); ++I) {
7791           Elts.push_back(Val.getVectorElt(Indices[I]));
7792         }
7793         APValue VecResult(Elts.data(), Indices.size());
7794         return DerivedSuccess(VecResult, E);
7795       }
7796     }
7797 
7798     return false;
7799   }
7800 
7801   bool VisitCastExpr(const CastExpr *E) {
7802     switch (E->getCastKind()) {
7803     default:
7804       break;
7805 
7806     case CK_AtomicToNonAtomic: {
7807       APValue AtomicVal;
7808       // This does not need to be done in place even for class/array types:
7809       // atomic-to-non-atomic conversion implies copying the object
7810       // representation.
7811       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
7812         return false;
7813       return DerivedSuccess(AtomicVal, E);
7814     }
7815 
7816     case CK_NoOp:
7817     case CK_UserDefinedConversion:
7818       return StmtVisitorTy::Visit(E->getSubExpr());
7819 
7820     case CK_LValueToRValue: {
7821       LValue LVal;
7822       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
7823         return false;
7824       APValue RVal;
7825       // Note, we use the subexpression's type in order to retain cv-qualifiers.
7826       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7827                                           LVal, RVal))
7828         return false;
7829       return DerivedSuccess(RVal, E);
7830     }
7831     case CK_LValueToRValueBitCast: {
7832       APValue DestValue, SourceValue;
7833       if (!Evaluate(SourceValue, Info, E->getSubExpr()))
7834         return false;
7835       if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
7836         return false;
7837       return DerivedSuccess(DestValue, E);
7838     }
7839 
7840     case CK_AddressSpaceConversion: {
7841       APValue Value;
7842       if (!Evaluate(Value, Info, E->getSubExpr()))
7843         return false;
7844       return DerivedSuccess(Value, E);
7845     }
7846     }
7847 
7848     return Error(E);
7849   }
7850 
7851   bool VisitUnaryPostInc(const UnaryOperator *UO) {
7852     return VisitUnaryPostIncDec(UO);
7853   }
7854   bool VisitUnaryPostDec(const UnaryOperator *UO) {
7855     return VisitUnaryPostIncDec(UO);
7856   }
7857   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
7858     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7859       return Error(UO);
7860 
7861     LValue LVal;
7862     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
7863       return false;
7864     APValue RVal;
7865     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
7866                       UO->isIncrementOp(), &RVal))
7867       return false;
7868     return DerivedSuccess(RVal, UO);
7869   }
7870 
7871   bool VisitStmtExpr(const StmtExpr *E) {
7872     // We will have checked the full-expressions inside the statement expression
7873     // when they were completed, and don't need to check them again now.
7874     llvm::SaveAndRestore<bool> NotCheckingForUB(
7875         Info.CheckingForUndefinedBehavior, false);
7876 
7877     const CompoundStmt *CS = E->getSubStmt();
7878     if (CS->body_empty())
7879       return true;
7880 
7881     BlockScopeRAII Scope(Info);
7882     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
7883                                            BE = CS->body_end();
7884          /**/; ++BI) {
7885       if (BI + 1 == BE) {
7886         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
7887         if (!FinalExpr) {
7888           Info.FFDiag((*BI)->getBeginLoc(),
7889                       diag::note_constexpr_stmt_expr_unsupported);
7890           return false;
7891         }
7892         return this->Visit(FinalExpr) && Scope.destroy();
7893       }
7894 
7895       APValue ReturnValue;
7896       StmtResult Result = { ReturnValue, nullptr };
7897       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
7898       if (ESR != ESR_Succeeded) {
7899         // FIXME: If the statement-expression terminated due to 'return',
7900         // 'break', or 'continue', it would be nice to propagate that to
7901         // the outer statement evaluation rather than bailing out.
7902         if (ESR != ESR_Failed)
7903           Info.FFDiag((*BI)->getBeginLoc(),
7904                       diag::note_constexpr_stmt_expr_unsupported);
7905         return false;
7906       }
7907     }
7908 
7909     llvm_unreachable("Return from function from the loop above.");
7910   }
7911 
7912   /// Visit a value which is evaluated, but whose value is ignored.
7913   void VisitIgnoredValue(const Expr *E) {
7914     EvaluateIgnoredValue(Info, E);
7915   }
7916 
7917   /// Potentially visit a MemberExpr's base expression.
7918   void VisitIgnoredBaseExpression(const Expr *E) {
7919     // While MSVC doesn't evaluate the base expression, it does diagnose the
7920     // presence of side-effecting behavior.
7921     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
7922       return;
7923     VisitIgnoredValue(E);
7924   }
7925 };
7926 
7927 } // namespace
7928 
7929 //===----------------------------------------------------------------------===//
7930 // Common base class for lvalue and temporary evaluation.
7931 //===----------------------------------------------------------------------===//
7932 namespace {
7933 template<class Derived>
7934 class LValueExprEvaluatorBase
7935   : public ExprEvaluatorBase<Derived> {
7936 protected:
7937   LValue &Result;
7938   bool InvalidBaseOK;
7939   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
7940   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
7941 
7942   bool Success(APValue::LValueBase B) {
7943     Result.set(B);
7944     return true;
7945   }
7946 
7947   bool evaluatePointer(const Expr *E, LValue &Result) {
7948     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
7949   }
7950 
7951 public:
7952   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
7953       : ExprEvaluatorBaseTy(Info), Result(Result),
7954         InvalidBaseOK(InvalidBaseOK) {}
7955 
7956   bool Success(const APValue &V, const Expr *E) {
7957     Result.setFrom(this->Info.Ctx, V);
7958     return true;
7959   }
7960 
7961   bool VisitMemberExpr(const MemberExpr *E) {
7962     // Handle non-static data members.
7963     QualType BaseTy;
7964     bool EvalOK;
7965     if (E->isArrow()) {
7966       EvalOK = evaluatePointer(E->getBase(), Result);
7967       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
7968     } else if (E->getBase()->isPRValue()) {
7969       assert(E->getBase()->getType()->isRecordType());
7970       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
7971       BaseTy = E->getBase()->getType();
7972     } else {
7973       EvalOK = this->Visit(E->getBase());
7974       BaseTy = E->getBase()->getType();
7975     }
7976     if (!EvalOK) {
7977       if (!InvalidBaseOK)
7978         return false;
7979       Result.setInvalid(E);
7980       return true;
7981     }
7982 
7983     const ValueDecl *MD = E->getMemberDecl();
7984     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
7985       assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7986              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7987       (void)BaseTy;
7988       if (!HandleLValueMember(this->Info, E, Result, FD))
7989         return false;
7990     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
7991       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
7992         return false;
7993     } else
7994       return this->Error(E);
7995 
7996     if (MD->getType()->isReferenceType()) {
7997       APValue RefValue;
7998       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
7999                                           RefValue))
8000         return false;
8001       return Success(RefValue, E);
8002     }
8003     return true;
8004   }
8005 
8006   bool VisitBinaryOperator(const BinaryOperator *E) {
8007     switch (E->getOpcode()) {
8008     default:
8009       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8010 
8011     case BO_PtrMemD:
8012     case BO_PtrMemI:
8013       return HandleMemberPointerAccess(this->Info, E, Result);
8014     }
8015   }
8016 
8017   bool VisitCastExpr(const CastExpr *E) {
8018     switch (E->getCastKind()) {
8019     default:
8020       return ExprEvaluatorBaseTy::VisitCastExpr(E);
8021 
8022     case CK_DerivedToBase:
8023     case CK_UncheckedDerivedToBase:
8024       if (!this->Visit(E->getSubExpr()))
8025         return false;
8026 
8027       // Now figure out the necessary offset to add to the base LV to get from
8028       // the derived class to the base class.
8029       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8030                                   Result);
8031     }
8032   }
8033 };
8034 }
8035 
8036 //===----------------------------------------------------------------------===//
8037 // LValue Evaluation
8038 //
8039 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8040 // function designators (in C), decl references to void objects (in C), and
8041 // temporaries (if building with -Wno-address-of-temporary).
8042 //
8043 // LValue evaluation produces values comprising a base expression of one of the
8044 // following types:
8045 // - Declarations
8046 //  * VarDecl
8047 //  * FunctionDecl
8048 // - Literals
8049 //  * CompoundLiteralExpr in C (and in global scope in C++)
8050 //  * StringLiteral
8051 //  * PredefinedExpr
8052 //  * ObjCStringLiteralExpr
8053 //  * ObjCEncodeExpr
8054 //  * AddrLabelExpr
8055 //  * BlockExpr
8056 //  * CallExpr for a MakeStringConstant builtin
8057 // - typeid(T) expressions, as TypeInfoLValues
8058 // - Locals and temporaries
8059 //  * MaterializeTemporaryExpr
8060 //  * Any Expr, with a CallIndex indicating the function in which the temporary
8061 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
8062 //    from the AST (FIXME).
8063 //  * A MaterializeTemporaryExpr that has static storage duration, with no
8064 //    CallIndex, for a lifetime-extended temporary.
8065 //  * The ConstantExpr that is currently being evaluated during evaluation of an
8066 //    immediate invocation.
8067 // plus an offset in bytes.
8068 //===----------------------------------------------------------------------===//
8069 namespace {
8070 class LValueExprEvaluator
8071   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8072 public:
8073   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8074     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8075 
8076   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8077   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8078 
8079   bool VisitDeclRefExpr(const DeclRefExpr *E);
8080   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8081   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8082   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8083   bool VisitMemberExpr(const MemberExpr *E);
8084   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
8085   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8086   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8087   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8088   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8089   bool VisitUnaryDeref(const UnaryOperator *E);
8090   bool VisitUnaryReal(const UnaryOperator *E);
8091   bool VisitUnaryImag(const UnaryOperator *E);
8092   bool VisitUnaryPreInc(const UnaryOperator *UO) {
8093     return VisitUnaryPreIncDec(UO);
8094   }
8095   bool VisitUnaryPreDec(const UnaryOperator *UO) {
8096     return VisitUnaryPreIncDec(UO);
8097   }
8098   bool VisitBinAssign(const BinaryOperator *BO);
8099   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8100 
8101   bool VisitCastExpr(const CastExpr *E) {
8102     switch (E->getCastKind()) {
8103     default:
8104       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8105 
8106     case CK_LValueBitCast:
8107       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8108       if (!Visit(E->getSubExpr()))
8109         return false;
8110       Result.Designator.setInvalid();
8111       return true;
8112 
8113     case CK_BaseToDerived:
8114       if (!Visit(E->getSubExpr()))
8115         return false;
8116       return HandleBaseToDerivedCast(Info, E, Result);
8117 
8118     case CK_Dynamic:
8119       if (!Visit(E->getSubExpr()))
8120         return false;
8121       return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8122     }
8123   }
8124 };
8125 } // end anonymous namespace
8126 
8127 /// Evaluate an expression as an lvalue. This can be legitimately called on
8128 /// expressions which are not glvalues, in three cases:
8129 ///  * function designators in C, and
8130 ///  * "extern void" objects
8131 ///  * @selector() expressions in Objective-C
8132 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
8133                            bool InvalidBaseOK) {
8134   assert(!E->isValueDependent());
8135   assert(E->isGLValue() || E->getType()->isFunctionType() ||
8136          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
8137   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8138 }
8139 
8140 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
8141   const NamedDecl *D = E->getDecl();
8142   if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl>(D))
8143     return Success(cast<ValueDecl>(D));
8144   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
8145     return VisitVarDecl(E, VD);
8146   if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
8147     return Visit(BD->getBinding());
8148   return Error(E);
8149 }
8150 
8151 
8152 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
8153 
8154   // If we are within a lambda's call operator, check whether the 'VD' referred
8155   // to within 'E' actually represents a lambda-capture that maps to a
8156   // data-member/field within the closure object, and if so, evaluate to the
8157   // field or what the field refers to.
8158   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
8159       isa<DeclRefExpr>(E) &&
8160       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
8161     // We don't always have a complete capture-map when checking or inferring if
8162     // the function call operator meets the requirements of a constexpr function
8163     // - but we don't need to evaluate the captures to determine constexprness
8164     // (dcl.constexpr C++17).
8165     if (Info.checkingPotentialConstantExpression())
8166       return false;
8167 
8168     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
8169       // Start with 'Result' referring to the complete closure object...
8170       Result = *Info.CurrentCall->This;
8171       // ... then update it to refer to the field of the closure object
8172       // that represents the capture.
8173       if (!HandleLValueMember(Info, E, Result, FD))
8174         return false;
8175       // And if the field is of reference type, update 'Result' to refer to what
8176       // the field refers to.
8177       if (FD->getType()->isReferenceType()) {
8178         APValue RVal;
8179         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
8180                                             RVal))
8181           return false;
8182         Result.setFrom(Info.Ctx, RVal);
8183       }
8184       return true;
8185     }
8186   }
8187 
8188   CallStackFrame *Frame = nullptr;
8189   unsigned Version = 0;
8190   if (VD->hasLocalStorage()) {
8191     // Only if a local variable was declared in the function currently being
8192     // evaluated, do we expect to be able to find its value in the current
8193     // frame. (Otherwise it was likely declared in an enclosing context and
8194     // could either have a valid evaluatable value (for e.g. a constexpr
8195     // variable) or be ill-formed (and trigger an appropriate evaluation
8196     // diagnostic)).
8197     CallStackFrame *CurrFrame = Info.CurrentCall;
8198     if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
8199       // Function parameters are stored in some caller's frame. (Usually the
8200       // immediate caller, but for an inherited constructor they may be more
8201       // distant.)
8202       if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
8203         if (CurrFrame->Arguments) {
8204           VD = CurrFrame->Arguments.getOrigParam(PVD);
8205           Frame =
8206               Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
8207           Version = CurrFrame->Arguments.Version;
8208         }
8209       } else {
8210         Frame = CurrFrame;
8211         Version = CurrFrame->getCurrentTemporaryVersion(VD);
8212       }
8213     }
8214   }
8215 
8216   if (!VD->getType()->isReferenceType()) {
8217     if (Frame) {
8218       Result.set({VD, Frame->Index, Version});
8219       return true;
8220     }
8221     return Success(VD);
8222   }
8223 
8224   if (!Info.getLangOpts().CPlusPlus11) {
8225     Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
8226         << VD << VD->getType();
8227     Info.Note(VD->getLocation(), diag::note_declared_at);
8228   }
8229 
8230   APValue *V;
8231   if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
8232     return false;
8233   if (!V->hasValue()) {
8234     // FIXME: Is it possible for V to be indeterminate here? If so, we should
8235     // adjust the diagnostic to say that.
8236     if (!Info.checkingPotentialConstantExpression())
8237       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
8238     return false;
8239   }
8240   return Success(*V, E);
8241 }
8242 
8243 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
8244     const MaterializeTemporaryExpr *E) {
8245   // Walk through the expression to find the materialized temporary itself.
8246   SmallVector<const Expr *, 2> CommaLHSs;
8247   SmallVector<SubobjectAdjustment, 2> Adjustments;
8248   const Expr *Inner =
8249       E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
8250 
8251   // If we passed any comma operators, evaluate their LHSs.
8252   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
8253     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
8254       return false;
8255 
8256   // A materialized temporary with static storage duration can appear within the
8257   // result of a constant expression evaluation, so we need to preserve its
8258   // value for use outside this evaluation.
8259   APValue *Value;
8260   if (E->getStorageDuration() == SD_Static) {
8261     // FIXME: What about SD_Thread?
8262     Value = E->getOrCreateValue(true);
8263     *Value = APValue();
8264     Result.set(E);
8265   } else {
8266     Value = &Info.CurrentCall->createTemporary(
8267         E, E->getType(),
8268         E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
8269                                                      : ScopeKind::Block,
8270         Result);
8271   }
8272 
8273   QualType Type = Inner->getType();
8274 
8275   // Materialize the temporary itself.
8276   if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
8277     *Value = APValue();
8278     return false;
8279   }
8280 
8281   // Adjust our lvalue to refer to the desired subobject.
8282   for (unsigned I = Adjustments.size(); I != 0; /**/) {
8283     --I;
8284     switch (Adjustments[I].Kind) {
8285     case SubobjectAdjustment::DerivedToBaseAdjustment:
8286       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
8287                                 Type, Result))
8288         return false;
8289       Type = Adjustments[I].DerivedToBase.BasePath->getType();
8290       break;
8291 
8292     case SubobjectAdjustment::FieldAdjustment:
8293       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
8294         return false;
8295       Type = Adjustments[I].Field->getType();
8296       break;
8297 
8298     case SubobjectAdjustment::MemberPointerAdjustment:
8299       if (!HandleMemberPointerAccess(this->Info, Type, Result,
8300                                      Adjustments[I].Ptr.RHS))
8301         return false;
8302       Type = Adjustments[I].Ptr.MPT->getPointeeType();
8303       break;
8304     }
8305   }
8306 
8307   return true;
8308 }
8309 
8310 bool
8311 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8312   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
8313          "lvalue compound literal in c++?");
8314   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
8315   // only see this when folding in C, so there's no standard to follow here.
8316   return Success(E);
8317 }
8318 
8319 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
8320   TypeInfoLValue TypeInfo;
8321 
8322   if (!E->isPotentiallyEvaluated()) {
8323     if (E->isTypeOperand())
8324       TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
8325     else
8326       TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
8327   } else {
8328     if (!Info.Ctx.getLangOpts().CPlusPlus20) {
8329       Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
8330         << E->getExprOperand()->getType()
8331         << E->getExprOperand()->getSourceRange();
8332     }
8333 
8334     if (!Visit(E->getExprOperand()))
8335       return false;
8336 
8337     Optional<DynamicType> DynType =
8338         ComputeDynamicType(Info, E, Result, AK_TypeId);
8339     if (!DynType)
8340       return false;
8341 
8342     TypeInfo =
8343         TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
8344   }
8345 
8346   return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
8347 }
8348 
8349 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
8350   return Success(E->getGuidDecl());
8351 }
8352 
8353 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
8354   // Handle static data members.
8355   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
8356     VisitIgnoredBaseExpression(E->getBase());
8357     return VisitVarDecl(E, VD);
8358   }
8359 
8360   // Handle static member functions.
8361   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
8362     if (MD->isStatic()) {
8363       VisitIgnoredBaseExpression(E->getBase());
8364       return Success(MD);
8365     }
8366   }
8367 
8368   // Handle non-static data members.
8369   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
8370 }
8371 
8372 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
8373   // FIXME: Deal with vectors as array subscript bases.
8374   if (E->getBase()->getType()->isVectorType())
8375     return Error(E);
8376 
8377   APSInt Index;
8378   bool Success = true;
8379 
8380   // C++17's rules require us to evaluate the LHS first, regardless of which
8381   // side is the base.
8382   for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
8383     if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
8384                                 : !EvaluateInteger(SubExpr, Index, Info)) {
8385       if (!Info.noteFailure())
8386         return false;
8387       Success = false;
8388     }
8389   }
8390 
8391   return Success &&
8392          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
8393 }
8394 
8395 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
8396   return evaluatePointer(E->getSubExpr(), Result);
8397 }
8398 
8399 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8400   if (!Visit(E->getSubExpr()))
8401     return false;
8402   // __real is a no-op on scalar lvalues.
8403   if (E->getSubExpr()->getType()->isAnyComplexType())
8404     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
8405   return true;
8406 }
8407 
8408 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8409   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
8410          "lvalue __imag__ on scalar?");
8411   if (!Visit(E->getSubExpr()))
8412     return false;
8413   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
8414   return true;
8415 }
8416 
8417 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
8418   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8419     return Error(UO);
8420 
8421   if (!this->Visit(UO->getSubExpr()))
8422     return false;
8423 
8424   return handleIncDec(
8425       this->Info, UO, Result, UO->getSubExpr()->getType(),
8426       UO->isIncrementOp(), nullptr);
8427 }
8428 
8429 bool LValueExprEvaluator::VisitCompoundAssignOperator(
8430     const CompoundAssignOperator *CAO) {
8431   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8432     return Error(CAO);
8433 
8434   bool Success = true;
8435 
8436   // C++17 onwards require that we evaluate the RHS first.
8437   APValue RHS;
8438   if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
8439     if (!Info.noteFailure())
8440       return false;
8441     Success = false;
8442   }
8443 
8444   // The overall lvalue result is the result of evaluating the LHS.
8445   if (!this->Visit(CAO->getLHS()) || !Success)
8446     return false;
8447 
8448   return handleCompoundAssignment(
8449       this->Info, CAO,
8450       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
8451       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
8452 }
8453 
8454 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
8455   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8456     return Error(E);
8457 
8458   bool Success = true;
8459 
8460   // C++17 onwards require that we evaluate the RHS first.
8461   APValue NewVal;
8462   if (!Evaluate(NewVal, this->Info, E->getRHS())) {
8463     if (!Info.noteFailure())
8464       return false;
8465     Success = false;
8466   }
8467 
8468   if (!this->Visit(E->getLHS()) || !Success)
8469     return false;
8470 
8471   if (Info.getLangOpts().CPlusPlus20 &&
8472       !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
8473     return false;
8474 
8475   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
8476                           NewVal);
8477 }
8478 
8479 //===----------------------------------------------------------------------===//
8480 // Pointer Evaluation
8481 //===----------------------------------------------------------------------===//
8482 
8483 /// Attempts to compute the number of bytes available at the pointer
8484 /// returned by a function with the alloc_size attribute. Returns true if we
8485 /// were successful. Places an unsigned number into `Result`.
8486 ///
8487 /// This expects the given CallExpr to be a call to a function with an
8488 /// alloc_size attribute.
8489 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8490                                             const CallExpr *Call,
8491                                             llvm::APInt &Result) {
8492   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
8493 
8494   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
8495   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
8496   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
8497   if (Call->getNumArgs() <= SizeArgNo)
8498     return false;
8499 
8500   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
8501     Expr::EvalResult ExprResult;
8502     if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
8503       return false;
8504     Into = ExprResult.Val.getInt();
8505     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
8506       return false;
8507     Into = Into.zextOrSelf(BitsInSizeT);
8508     return true;
8509   };
8510 
8511   APSInt SizeOfElem;
8512   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
8513     return false;
8514 
8515   if (!AllocSize->getNumElemsParam().isValid()) {
8516     Result = std::move(SizeOfElem);
8517     return true;
8518   }
8519 
8520   APSInt NumberOfElems;
8521   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
8522   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
8523     return false;
8524 
8525   bool Overflow;
8526   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
8527   if (Overflow)
8528     return false;
8529 
8530   Result = std::move(BytesAvailable);
8531   return true;
8532 }
8533 
8534 /// Convenience function. LVal's base must be a call to an alloc_size
8535 /// function.
8536 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8537                                             const LValue &LVal,
8538                                             llvm::APInt &Result) {
8539   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8540          "Can't get the size of a non alloc_size function");
8541   const auto *Base = LVal.getLValueBase().get<const Expr *>();
8542   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
8543   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
8544 }
8545 
8546 /// Attempts to evaluate the given LValueBase as the result of a call to
8547 /// a function with the alloc_size attribute. If it was possible to do so, this
8548 /// function will return true, make Result's Base point to said function call,
8549 /// and mark Result's Base as invalid.
8550 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
8551                                       LValue &Result) {
8552   if (Base.isNull())
8553     return false;
8554 
8555   // Because we do no form of static analysis, we only support const variables.
8556   //
8557   // Additionally, we can't support parameters, nor can we support static
8558   // variables (in the latter case, use-before-assign isn't UB; in the former,
8559   // we have no clue what they'll be assigned to).
8560   const auto *VD =
8561       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
8562   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
8563     return false;
8564 
8565   const Expr *Init = VD->getAnyInitializer();
8566   if (!Init)
8567     return false;
8568 
8569   const Expr *E = Init->IgnoreParens();
8570   if (!tryUnwrapAllocSizeCall(E))
8571     return false;
8572 
8573   // Store E instead of E unwrapped so that the type of the LValue's base is
8574   // what the user wanted.
8575   Result.setInvalid(E);
8576 
8577   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
8578   Result.addUnsizedArray(Info, E, Pointee);
8579   return true;
8580 }
8581 
8582 namespace {
8583 class PointerExprEvaluator
8584   : public ExprEvaluatorBase<PointerExprEvaluator> {
8585   LValue &Result;
8586   bool InvalidBaseOK;
8587 
8588   bool Success(const Expr *E) {
8589     Result.set(E);
8590     return true;
8591   }
8592 
8593   bool evaluateLValue(const Expr *E, LValue &Result) {
8594     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
8595   }
8596 
8597   bool evaluatePointer(const Expr *E, LValue &Result) {
8598     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
8599   }
8600 
8601   bool visitNonBuiltinCallExpr(const CallExpr *E);
8602 public:
8603 
8604   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
8605       : ExprEvaluatorBaseTy(info), Result(Result),
8606         InvalidBaseOK(InvalidBaseOK) {}
8607 
8608   bool Success(const APValue &V, const Expr *E) {
8609     Result.setFrom(Info.Ctx, V);
8610     return true;
8611   }
8612   bool ZeroInitialization(const Expr *E) {
8613     Result.setNull(Info.Ctx, E->getType());
8614     return true;
8615   }
8616 
8617   bool VisitBinaryOperator(const BinaryOperator *E);
8618   bool VisitCastExpr(const CastExpr* E);
8619   bool VisitUnaryAddrOf(const UnaryOperator *E);
8620   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
8621       { return Success(E); }
8622   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
8623     if (E->isExpressibleAsConstantInitializer())
8624       return Success(E);
8625     if (Info.noteFailure())
8626       EvaluateIgnoredValue(Info, E->getSubExpr());
8627     return Error(E);
8628   }
8629   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
8630       { return Success(E); }
8631   bool VisitCallExpr(const CallExpr *E);
8632   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
8633   bool VisitBlockExpr(const BlockExpr *E) {
8634     if (!E->getBlockDecl()->hasCaptures())
8635       return Success(E);
8636     return Error(E);
8637   }
8638   bool VisitCXXThisExpr(const CXXThisExpr *E) {
8639     // Can't look at 'this' when checking a potential constant expression.
8640     if (Info.checkingPotentialConstantExpression())
8641       return false;
8642     if (!Info.CurrentCall->This) {
8643       if (Info.getLangOpts().CPlusPlus11)
8644         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
8645       else
8646         Info.FFDiag(E);
8647       return false;
8648     }
8649     Result = *Info.CurrentCall->This;
8650     // If we are inside a lambda's call operator, the 'this' expression refers
8651     // to the enclosing '*this' object (either by value or reference) which is
8652     // either copied into the closure object's field that represents the '*this'
8653     // or refers to '*this'.
8654     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
8655       // Ensure we actually have captured 'this'. (an error will have
8656       // been previously reported if not).
8657       if (!Info.CurrentCall->LambdaThisCaptureField)
8658         return false;
8659 
8660       // Update 'Result' to refer to the data member/field of the closure object
8661       // that represents the '*this' capture.
8662       if (!HandleLValueMember(Info, E, Result,
8663                              Info.CurrentCall->LambdaThisCaptureField))
8664         return false;
8665       // If we captured '*this' by reference, replace the field with its referent.
8666       if (Info.CurrentCall->LambdaThisCaptureField->getType()
8667               ->isPointerType()) {
8668         APValue RVal;
8669         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
8670                                             RVal))
8671           return false;
8672 
8673         Result.setFrom(Info.Ctx, RVal);
8674       }
8675     }
8676     return true;
8677   }
8678 
8679   bool VisitCXXNewExpr(const CXXNewExpr *E);
8680 
8681   bool VisitSourceLocExpr(const SourceLocExpr *E) {
8682     assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
8683     APValue LValResult = E->EvaluateInContext(
8684         Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8685     Result.setFrom(Info.Ctx, LValResult);
8686     return true;
8687   }
8688 
8689   bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
8690     std::string ResultStr = E->ComputeName(Info.Ctx);
8691 
8692     QualType CharTy = Info.Ctx.CharTy.withConst();
8693     APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
8694                ResultStr.size() + 1);
8695     QualType ArrayTy = Info.Ctx.getConstantArrayType(CharTy, Size, nullptr,
8696                                                      ArrayType::Normal, 0);
8697 
8698     StringLiteral *SL =
8699         StringLiteral::Create(Info.Ctx, ResultStr, StringLiteral::Ascii,
8700                               /*Pascal*/ false, ArrayTy, E->getLocation());
8701 
8702     evaluateLValue(SL, Result);
8703     Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
8704     return true;
8705   }
8706 
8707   // FIXME: Missing: @protocol, @selector
8708 };
8709 } // end anonymous namespace
8710 
8711 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
8712                             bool InvalidBaseOK) {
8713   assert(!E->isValueDependent());
8714   assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
8715   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8716 }
8717 
8718 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8719   if (E->getOpcode() != BO_Add &&
8720       E->getOpcode() != BO_Sub)
8721     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8722 
8723   const Expr *PExp = E->getLHS();
8724   const Expr *IExp = E->getRHS();
8725   if (IExp->getType()->isPointerType())
8726     std::swap(PExp, IExp);
8727 
8728   bool EvalPtrOK = evaluatePointer(PExp, Result);
8729   if (!EvalPtrOK && !Info.noteFailure())
8730     return false;
8731 
8732   llvm::APSInt Offset;
8733   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
8734     return false;
8735 
8736   if (E->getOpcode() == BO_Sub)
8737     negateAsSigned(Offset);
8738 
8739   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
8740   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
8741 }
8742 
8743 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8744   return evaluateLValue(E->getSubExpr(), Result);
8745 }
8746 
8747 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8748   const Expr *SubExpr = E->getSubExpr();
8749 
8750   switch (E->getCastKind()) {
8751   default:
8752     break;
8753   case CK_BitCast:
8754   case CK_CPointerToObjCPointerCast:
8755   case CK_BlockPointerToObjCPointerCast:
8756   case CK_AnyPointerToBlockPointerCast:
8757   case CK_AddressSpaceConversion:
8758     if (!Visit(SubExpr))
8759       return false;
8760     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
8761     // permitted in constant expressions in C++11. Bitcasts from cv void* are
8762     // also static_casts, but we disallow them as a resolution to DR1312.
8763     if (!E->getType()->isVoidPointerType()) {
8764       if (!Result.InvalidBase && !Result.Designator.Invalid &&
8765           !Result.IsNullPtr &&
8766           Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
8767                                           E->getType()->getPointeeType()) &&
8768           Info.getStdAllocatorCaller("allocate")) {
8769         // Inside a call to std::allocator::allocate and friends, we permit
8770         // casting from void* back to cv1 T* for a pointer that points to a
8771         // cv2 T.
8772       } else {
8773         Result.Designator.setInvalid();
8774         if (SubExpr->getType()->isVoidPointerType())
8775           CCEDiag(E, diag::note_constexpr_invalid_cast)
8776             << 3 << SubExpr->getType();
8777         else
8778           CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8779       }
8780     }
8781     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
8782       ZeroInitialization(E);
8783     return true;
8784 
8785   case CK_DerivedToBase:
8786   case CK_UncheckedDerivedToBase:
8787     if (!evaluatePointer(E->getSubExpr(), Result))
8788       return false;
8789     if (!Result.Base && Result.Offset.isZero())
8790       return true;
8791 
8792     // Now figure out the necessary offset to add to the base LV to get from
8793     // the derived class to the base class.
8794     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
8795                                   castAs<PointerType>()->getPointeeType(),
8796                                 Result);
8797 
8798   case CK_BaseToDerived:
8799     if (!Visit(E->getSubExpr()))
8800       return false;
8801     if (!Result.Base && Result.Offset.isZero())
8802       return true;
8803     return HandleBaseToDerivedCast(Info, E, Result);
8804 
8805   case CK_Dynamic:
8806     if (!Visit(E->getSubExpr()))
8807       return false;
8808     return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8809 
8810   case CK_NullToPointer:
8811     VisitIgnoredValue(E->getSubExpr());
8812     return ZeroInitialization(E);
8813 
8814   case CK_IntegralToPointer: {
8815     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8816 
8817     APValue Value;
8818     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
8819       break;
8820 
8821     if (Value.isInt()) {
8822       unsigned Size = Info.Ctx.getTypeSize(E->getType());
8823       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
8824       Result.Base = (Expr*)nullptr;
8825       Result.InvalidBase = false;
8826       Result.Offset = CharUnits::fromQuantity(N);
8827       Result.Designator.setInvalid();
8828       Result.IsNullPtr = false;
8829       return true;
8830     } else {
8831       // Cast is of an lvalue, no need to change value.
8832       Result.setFrom(Info.Ctx, Value);
8833       return true;
8834     }
8835   }
8836 
8837   case CK_ArrayToPointerDecay: {
8838     if (SubExpr->isGLValue()) {
8839       if (!evaluateLValue(SubExpr, Result))
8840         return false;
8841     } else {
8842       APValue &Value = Info.CurrentCall->createTemporary(
8843           SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
8844       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
8845         return false;
8846     }
8847     // The result is a pointer to the first element of the array.
8848     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
8849     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
8850       Result.addArray(Info, E, CAT);
8851     else
8852       Result.addUnsizedArray(Info, E, AT->getElementType());
8853     return true;
8854   }
8855 
8856   case CK_FunctionToPointerDecay:
8857     return evaluateLValue(SubExpr, Result);
8858 
8859   case CK_LValueToRValue: {
8860     LValue LVal;
8861     if (!evaluateLValue(E->getSubExpr(), LVal))
8862       return false;
8863 
8864     APValue RVal;
8865     // Note, we use the subexpression's type in order to retain cv-qualifiers.
8866     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8867                                         LVal, RVal))
8868       return InvalidBaseOK &&
8869              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
8870     return Success(RVal, E);
8871   }
8872   }
8873 
8874   return ExprEvaluatorBaseTy::VisitCastExpr(E);
8875 }
8876 
8877 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
8878                                 UnaryExprOrTypeTrait ExprKind) {
8879   // C++ [expr.alignof]p3:
8880   //     When alignof is applied to a reference type, the result is the
8881   //     alignment of the referenced type.
8882   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
8883     T = Ref->getPointeeType();
8884 
8885   if (T.getQualifiers().hasUnaligned())
8886     return CharUnits::One();
8887 
8888   const bool AlignOfReturnsPreferred =
8889       Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
8890 
8891   // __alignof is defined to return the preferred alignment.
8892   // Before 8, clang returned the preferred alignment for alignof and _Alignof
8893   // as well.
8894   if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
8895     return Info.Ctx.toCharUnitsFromBits(
8896       Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
8897   // alignof and _Alignof are defined to return the ABI alignment.
8898   else if (ExprKind == UETT_AlignOf)
8899     return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
8900   else
8901     llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
8902 }
8903 
8904 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
8905                                 UnaryExprOrTypeTrait ExprKind) {
8906   E = E->IgnoreParens();
8907 
8908   // The kinds of expressions that we have special-case logic here for
8909   // should be kept up to date with the special checks for those
8910   // expressions in Sema.
8911 
8912   // alignof decl is always accepted, even if it doesn't make sense: we default
8913   // to 1 in those cases.
8914   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8915     return Info.Ctx.getDeclAlign(DRE->getDecl(),
8916                                  /*RefAsPointee*/true);
8917 
8918   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
8919     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
8920                                  /*RefAsPointee*/true);
8921 
8922   return GetAlignOfType(Info, E->getType(), ExprKind);
8923 }
8924 
8925 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
8926   if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
8927     return Info.Ctx.getDeclAlign(VD);
8928   if (const auto *E = Value.Base.dyn_cast<const Expr *>())
8929     return GetAlignOfExpr(Info, E, UETT_AlignOf);
8930   return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
8931 }
8932 
8933 /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
8934 /// __builtin_is_aligned and __builtin_assume_aligned.
8935 static bool getAlignmentArgument(const Expr *E, QualType ForType,
8936                                  EvalInfo &Info, APSInt &Alignment) {
8937   if (!EvaluateInteger(E, Alignment, Info))
8938     return false;
8939   if (Alignment < 0 || !Alignment.isPowerOf2()) {
8940     Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
8941     return false;
8942   }
8943   unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
8944   APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
8945   if (APSInt::compareValues(Alignment, MaxValue) > 0) {
8946     Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
8947         << MaxValue << ForType << Alignment;
8948     return false;
8949   }
8950   // Ensure both alignment and source value have the same bit width so that we
8951   // don't assert when computing the resulting value.
8952   APSInt ExtAlignment =
8953       APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
8954   assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
8955          "Alignment should not be changed by ext/trunc");
8956   Alignment = ExtAlignment;
8957   assert(Alignment.getBitWidth() == SrcWidth);
8958   return true;
8959 }
8960 
8961 // To be clear: this happily visits unsupported builtins. Better name welcomed.
8962 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
8963   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
8964     return true;
8965 
8966   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
8967     return false;
8968 
8969   Result.setInvalid(E);
8970   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
8971   Result.addUnsizedArray(Info, E, PointeeTy);
8972   return true;
8973 }
8974 
8975 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
8976   if (IsConstantCall(E))
8977     return Success(E);
8978 
8979   if (unsigned BuiltinOp = E->getBuiltinCallee())
8980     return VisitBuiltinCallExpr(E, BuiltinOp);
8981 
8982   return visitNonBuiltinCallExpr(E);
8983 }
8984 
8985 // Determine if T is a character type for which we guarantee that
8986 // sizeof(T) == 1.
8987 static bool isOneByteCharacterType(QualType T) {
8988   return T->isCharType() || T->isChar8Type();
8989 }
8990 
8991 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8992                                                 unsigned BuiltinOp) {
8993   switch (BuiltinOp) {
8994   case Builtin::BI__builtin_addressof:
8995     return evaluateLValue(E->getArg(0), Result);
8996   case Builtin::BI__builtin_assume_aligned: {
8997     // We need to be very careful here because: if the pointer does not have the
8998     // asserted alignment, then the behavior is undefined, and undefined
8999     // behavior is non-constant.
9000     if (!evaluatePointer(E->getArg(0), Result))
9001       return false;
9002 
9003     LValue OffsetResult(Result);
9004     APSInt Alignment;
9005     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9006                               Alignment))
9007       return false;
9008     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
9009 
9010     if (E->getNumArgs() > 2) {
9011       APSInt Offset;
9012       if (!EvaluateInteger(E->getArg(2), Offset, Info))
9013         return false;
9014 
9015       int64_t AdditionalOffset = -Offset.getZExtValue();
9016       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
9017     }
9018 
9019     // If there is a base object, then it must have the correct alignment.
9020     if (OffsetResult.Base) {
9021       CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
9022 
9023       if (BaseAlignment < Align) {
9024         Result.Designator.setInvalid();
9025         // FIXME: Add support to Diagnostic for long / long long.
9026         CCEDiag(E->getArg(0),
9027                 diag::note_constexpr_baa_insufficient_alignment) << 0
9028           << (unsigned)BaseAlignment.getQuantity()
9029           << (unsigned)Align.getQuantity();
9030         return false;
9031       }
9032     }
9033 
9034     // The offset must also have the correct alignment.
9035     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
9036       Result.Designator.setInvalid();
9037 
9038       (OffsetResult.Base
9039            ? CCEDiag(E->getArg(0),
9040                      diag::note_constexpr_baa_insufficient_alignment) << 1
9041            : CCEDiag(E->getArg(0),
9042                      diag::note_constexpr_baa_value_insufficient_alignment))
9043         << (int)OffsetResult.Offset.getQuantity()
9044         << (unsigned)Align.getQuantity();
9045       return false;
9046     }
9047 
9048     return true;
9049   }
9050   case Builtin::BI__builtin_align_up:
9051   case Builtin::BI__builtin_align_down: {
9052     if (!evaluatePointer(E->getArg(0), Result))
9053       return false;
9054     APSInt Alignment;
9055     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9056                               Alignment))
9057       return false;
9058     CharUnits BaseAlignment = getBaseAlignment(Info, Result);
9059     CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
9060     // For align_up/align_down, we can return the same value if the alignment
9061     // is known to be greater or equal to the requested value.
9062     if (PtrAlign.getQuantity() >= Alignment)
9063       return true;
9064 
9065     // The alignment could be greater than the minimum at run-time, so we cannot
9066     // infer much about the resulting pointer value. One case is possible:
9067     // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
9068     // can infer the correct index if the requested alignment is smaller than
9069     // the base alignment so we can perform the computation on the offset.
9070     if (BaseAlignment.getQuantity() >= Alignment) {
9071       assert(Alignment.getBitWidth() <= 64 &&
9072              "Cannot handle > 64-bit address-space");
9073       uint64_t Alignment64 = Alignment.getZExtValue();
9074       CharUnits NewOffset = CharUnits::fromQuantity(
9075           BuiltinOp == Builtin::BI__builtin_align_down
9076               ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
9077               : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
9078       Result.adjustOffset(NewOffset - Result.Offset);
9079       // TODO: diagnose out-of-bounds values/only allow for arrays?
9080       return true;
9081     }
9082     // Otherwise, we cannot constant-evaluate the result.
9083     Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
9084         << Alignment;
9085     return false;
9086   }
9087   case Builtin::BI__builtin_operator_new:
9088     return HandleOperatorNewCall(Info, E, Result);
9089   case Builtin::BI__builtin_launder:
9090     return evaluatePointer(E->getArg(0), Result);
9091   case Builtin::BIstrchr:
9092   case Builtin::BIwcschr:
9093   case Builtin::BImemchr:
9094   case Builtin::BIwmemchr:
9095     if (Info.getLangOpts().CPlusPlus11)
9096       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9097         << /*isConstexpr*/0 << /*isConstructor*/0
9098         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9099     else
9100       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9101     LLVM_FALLTHROUGH;
9102   case Builtin::BI__builtin_strchr:
9103   case Builtin::BI__builtin_wcschr:
9104   case Builtin::BI__builtin_memchr:
9105   case Builtin::BI__builtin_char_memchr:
9106   case Builtin::BI__builtin_wmemchr: {
9107     if (!Visit(E->getArg(0)))
9108       return false;
9109     APSInt Desired;
9110     if (!EvaluateInteger(E->getArg(1), Desired, Info))
9111       return false;
9112     uint64_t MaxLength = uint64_t(-1);
9113     if (BuiltinOp != Builtin::BIstrchr &&
9114         BuiltinOp != Builtin::BIwcschr &&
9115         BuiltinOp != Builtin::BI__builtin_strchr &&
9116         BuiltinOp != Builtin::BI__builtin_wcschr) {
9117       APSInt N;
9118       if (!EvaluateInteger(E->getArg(2), N, Info))
9119         return false;
9120       MaxLength = N.getExtValue();
9121     }
9122     // We cannot find the value if there are no candidates to match against.
9123     if (MaxLength == 0u)
9124       return ZeroInitialization(E);
9125     if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9126         Result.Designator.Invalid)
9127       return false;
9128     QualType CharTy = Result.Designator.getType(Info.Ctx);
9129     bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
9130                      BuiltinOp == Builtin::BI__builtin_memchr;
9131     assert(IsRawByte ||
9132            Info.Ctx.hasSameUnqualifiedType(
9133                CharTy, E->getArg(0)->getType()->getPointeeType()));
9134     // Pointers to const void may point to objects of incomplete type.
9135     if (IsRawByte && CharTy->isIncompleteType()) {
9136       Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
9137       return false;
9138     }
9139     // Give up on byte-oriented matching against multibyte elements.
9140     // FIXME: We can compare the bytes in the correct order.
9141     if (IsRawByte && !isOneByteCharacterType(CharTy)) {
9142       Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
9143           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
9144           << CharTy;
9145       return false;
9146     }
9147     // Figure out what value we're actually looking for (after converting to
9148     // the corresponding unsigned type if necessary).
9149     uint64_t DesiredVal;
9150     bool StopAtNull = false;
9151     switch (BuiltinOp) {
9152     case Builtin::BIstrchr:
9153     case Builtin::BI__builtin_strchr:
9154       // strchr compares directly to the passed integer, and therefore
9155       // always fails if given an int that is not a char.
9156       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
9157                                                   E->getArg(1)->getType(),
9158                                                   Desired),
9159                                Desired))
9160         return ZeroInitialization(E);
9161       StopAtNull = true;
9162       LLVM_FALLTHROUGH;
9163     case Builtin::BImemchr:
9164     case Builtin::BI__builtin_memchr:
9165     case Builtin::BI__builtin_char_memchr:
9166       // memchr compares by converting both sides to unsigned char. That's also
9167       // correct for strchr if we get this far (to cope with plain char being
9168       // unsigned in the strchr case).
9169       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
9170       break;
9171 
9172     case Builtin::BIwcschr:
9173     case Builtin::BI__builtin_wcschr:
9174       StopAtNull = true;
9175       LLVM_FALLTHROUGH;
9176     case Builtin::BIwmemchr:
9177     case Builtin::BI__builtin_wmemchr:
9178       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
9179       DesiredVal = Desired.getZExtValue();
9180       break;
9181     }
9182 
9183     for (; MaxLength; --MaxLength) {
9184       APValue Char;
9185       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
9186           !Char.isInt())
9187         return false;
9188       if (Char.getInt().getZExtValue() == DesiredVal)
9189         return true;
9190       if (StopAtNull && !Char.getInt())
9191         break;
9192       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
9193         return false;
9194     }
9195     // Not found: return nullptr.
9196     return ZeroInitialization(E);
9197   }
9198 
9199   case Builtin::BImemcpy:
9200   case Builtin::BImemmove:
9201   case Builtin::BIwmemcpy:
9202   case Builtin::BIwmemmove:
9203     if (Info.getLangOpts().CPlusPlus11)
9204       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9205         << /*isConstexpr*/0 << /*isConstructor*/0
9206         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9207     else
9208       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9209     LLVM_FALLTHROUGH;
9210   case Builtin::BI__builtin_memcpy:
9211   case Builtin::BI__builtin_memmove:
9212   case Builtin::BI__builtin_wmemcpy:
9213   case Builtin::BI__builtin_wmemmove: {
9214     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
9215                  BuiltinOp == Builtin::BIwmemmove ||
9216                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
9217                  BuiltinOp == Builtin::BI__builtin_wmemmove;
9218     bool Move = BuiltinOp == Builtin::BImemmove ||
9219                 BuiltinOp == Builtin::BIwmemmove ||
9220                 BuiltinOp == Builtin::BI__builtin_memmove ||
9221                 BuiltinOp == Builtin::BI__builtin_wmemmove;
9222 
9223     // The result of mem* is the first argument.
9224     if (!Visit(E->getArg(0)))
9225       return false;
9226     LValue Dest = Result;
9227 
9228     LValue Src;
9229     if (!EvaluatePointer(E->getArg(1), Src, Info))
9230       return false;
9231 
9232     APSInt N;
9233     if (!EvaluateInteger(E->getArg(2), N, Info))
9234       return false;
9235     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
9236 
9237     // If the size is zero, we treat this as always being a valid no-op.
9238     // (Even if one of the src and dest pointers is null.)
9239     if (!N)
9240       return true;
9241 
9242     // Otherwise, if either of the operands is null, we can't proceed. Don't
9243     // try to determine the type of the copied objects, because there aren't
9244     // any.
9245     if (!Src.Base || !Dest.Base) {
9246       APValue Val;
9247       (!Src.Base ? Src : Dest).moveInto(Val);
9248       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
9249           << Move << WChar << !!Src.Base
9250           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
9251       return false;
9252     }
9253     if (Src.Designator.Invalid || Dest.Designator.Invalid)
9254       return false;
9255 
9256     // We require that Src and Dest are both pointers to arrays of
9257     // trivially-copyable type. (For the wide version, the designator will be
9258     // invalid if the designated object is not a wchar_t.)
9259     QualType T = Dest.Designator.getType(Info.Ctx);
9260     QualType SrcT = Src.Designator.getType(Info.Ctx);
9261     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
9262       // FIXME: Consider using our bit_cast implementation to support this.
9263       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
9264       return false;
9265     }
9266     if (T->isIncompleteType()) {
9267       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
9268       return false;
9269     }
9270     if (!T.isTriviallyCopyableType(Info.Ctx)) {
9271       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
9272       return false;
9273     }
9274 
9275     // Figure out how many T's we're copying.
9276     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
9277     if (!WChar) {
9278       uint64_t Remainder;
9279       llvm::APInt OrigN = N;
9280       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
9281       if (Remainder) {
9282         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9283             << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
9284             << (unsigned)TSize;
9285         return false;
9286       }
9287     }
9288 
9289     // Check that the copying will remain within the arrays, just so that we
9290     // can give a more meaningful diagnostic. This implicitly also checks that
9291     // N fits into 64 bits.
9292     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
9293     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
9294     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
9295       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9296           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
9297           << toString(N, 10, /*Signed*/false);
9298       return false;
9299     }
9300     uint64_t NElems = N.getZExtValue();
9301     uint64_t NBytes = NElems * TSize;
9302 
9303     // Check for overlap.
9304     int Direction = 1;
9305     if (HasSameBase(Src, Dest)) {
9306       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
9307       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
9308       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
9309         // Dest is inside the source region.
9310         if (!Move) {
9311           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9312           return false;
9313         }
9314         // For memmove and friends, copy backwards.
9315         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
9316             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
9317           return false;
9318         Direction = -1;
9319       } else if (!Move && SrcOffset >= DestOffset &&
9320                  SrcOffset - DestOffset < NBytes) {
9321         // Src is inside the destination region for memcpy: invalid.
9322         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9323         return false;
9324       }
9325     }
9326 
9327     while (true) {
9328       APValue Val;
9329       // FIXME: Set WantObjectRepresentation to true if we're copying a
9330       // char-like type?
9331       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
9332           !handleAssignment(Info, E, Dest, T, Val))
9333         return false;
9334       // Do not iterate past the last element; if we're copying backwards, that
9335       // might take us off the start of the array.
9336       if (--NElems == 0)
9337         return true;
9338       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
9339           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
9340         return false;
9341     }
9342   }
9343 
9344   default:
9345     break;
9346   }
9347 
9348   return visitNonBuiltinCallExpr(E);
9349 }
9350 
9351 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9352                                      APValue &Result, const InitListExpr *ILE,
9353                                      QualType AllocType);
9354 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
9355                                           APValue &Result,
9356                                           const CXXConstructExpr *CCE,
9357                                           QualType AllocType);
9358 
9359 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
9360   if (!Info.getLangOpts().CPlusPlus20)
9361     Info.CCEDiag(E, diag::note_constexpr_new);
9362 
9363   // We cannot speculatively evaluate a delete expression.
9364   if (Info.SpeculativeEvaluationDepth)
9365     return false;
9366 
9367   FunctionDecl *OperatorNew = E->getOperatorNew();
9368 
9369   bool IsNothrow = false;
9370   bool IsPlacement = false;
9371   if (OperatorNew->isReservedGlobalPlacementOperator() &&
9372       Info.CurrentCall->isStdFunction() && !E->isArray()) {
9373     // FIXME Support array placement new.
9374     assert(E->getNumPlacementArgs() == 1);
9375     if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
9376       return false;
9377     if (Result.Designator.Invalid)
9378       return false;
9379     IsPlacement = true;
9380   } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
9381     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
9382         << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
9383     return false;
9384   } else if (E->getNumPlacementArgs()) {
9385     // The only new-placement list we support is of the form (std::nothrow).
9386     //
9387     // FIXME: There is no restriction on this, but it's not clear that any
9388     // other form makes any sense. We get here for cases such as:
9389     //
9390     //   new (std::align_val_t{N}) X(int)
9391     //
9392     // (which should presumably be valid only if N is a multiple of
9393     // alignof(int), and in any case can't be deallocated unless N is
9394     // alignof(X) and X has new-extended alignment).
9395     if (E->getNumPlacementArgs() != 1 ||
9396         !E->getPlacementArg(0)->getType()->isNothrowT())
9397       return Error(E, diag::note_constexpr_new_placement);
9398 
9399     LValue Nothrow;
9400     if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
9401       return false;
9402     IsNothrow = true;
9403   }
9404 
9405   const Expr *Init = E->getInitializer();
9406   const InitListExpr *ResizedArrayILE = nullptr;
9407   const CXXConstructExpr *ResizedArrayCCE = nullptr;
9408   bool ValueInit = false;
9409 
9410   QualType AllocType = E->getAllocatedType();
9411   if (Optional<const Expr*> ArraySize = E->getArraySize()) {
9412     const Expr *Stripped = *ArraySize;
9413     for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
9414          Stripped = ICE->getSubExpr())
9415       if (ICE->getCastKind() != CK_NoOp &&
9416           ICE->getCastKind() != CK_IntegralCast)
9417         break;
9418 
9419     llvm::APSInt ArrayBound;
9420     if (!EvaluateInteger(Stripped, ArrayBound, Info))
9421       return false;
9422 
9423     // C++ [expr.new]p9:
9424     //   The expression is erroneous if:
9425     //   -- [...] its value before converting to size_t [or] applying the
9426     //      second standard conversion sequence is less than zero
9427     if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
9428       if (IsNothrow)
9429         return ZeroInitialization(E);
9430 
9431       Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
9432           << ArrayBound << (*ArraySize)->getSourceRange();
9433       return false;
9434     }
9435 
9436     //   -- its value is such that the size of the allocated object would
9437     //      exceed the implementation-defined limit
9438     if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
9439                                                 ArrayBound) >
9440         ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
9441       if (IsNothrow)
9442         return ZeroInitialization(E);
9443 
9444       Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
9445         << ArrayBound << (*ArraySize)->getSourceRange();
9446       return false;
9447     }
9448 
9449     //   -- the new-initializer is a braced-init-list and the number of
9450     //      array elements for which initializers are provided [...]
9451     //      exceeds the number of elements to initialize
9452     if (!Init) {
9453       // No initialization is performed.
9454     } else if (isa<CXXScalarValueInitExpr>(Init) ||
9455                isa<ImplicitValueInitExpr>(Init)) {
9456       ValueInit = true;
9457     } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
9458       ResizedArrayCCE = CCE;
9459     } else {
9460       auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
9461       assert(CAT && "unexpected type for array initializer");
9462 
9463       unsigned Bits =
9464           std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
9465       llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits);
9466       llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits);
9467       if (InitBound.ugt(AllocBound)) {
9468         if (IsNothrow)
9469           return ZeroInitialization(E);
9470 
9471         Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
9472             << toString(AllocBound, 10, /*Signed=*/false)
9473             << toString(InitBound, 10, /*Signed=*/false)
9474             << (*ArraySize)->getSourceRange();
9475         return false;
9476       }
9477 
9478       // If the sizes differ, we must have an initializer list, and we need
9479       // special handling for this case when we initialize.
9480       if (InitBound != AllocBound)
9481         ResizedArrayILE = cast<InitListExpr>(Init);
9482     }
9483 
9484     AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
9485                                               ArrayType::Normal, 0);
9486   } else {
9487     assert(!AllocType->isArrayType() &&
9488            "array allocation with non-array new");
9489   }
9490 
9491   APValue *Val;
9492   if (IsPlacement) {
9493     AccessKinds AK = AK_Construct;
9494     struct FindObjectHandler {
9495       EvalInfo &Info;
9496       const Expr *E;
9497       QualType AllocType;
9498       const AccessKinds AccessKind;
9499       APValue *Value;
9500 
9501       typedef bool result_type;
9502       bool failed() { return false; }
9503       bool found(APValue &Subobj, QualType SubobjType) {
9504         // FIXME: Reject the cases where [basic.life]p8 would not permit the
9505         // old name of the object to be used to name the new object.
9506         if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
9507           Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
9508             SubobjType << AllocType;
9509           return false;
9510         }
9511         Value = &Subobj;
9512         return true;
9513       }
9514       bool found(APSInt &Value, QualType SubobjType) {
9515         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9516         return false;
9517       }
9518       bool found(APFloat &Value, QualType SubobjType) {
9519         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9520         return false;
9521       }
9522     } Handler = {Info, E, AllocType, AK, nullptr};
9523 
9524     CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
9525     if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
9526       return false;
9527 
9528     Val = Handler.Value;
9529 
9530     // [basic.life]p1:
9531     //   The lifetime of an object o of type T ends when [...] the storage
9532     //   which the object occupies is [...] reused by an object that is not
9533     //   nested within o (6.6.2).
9534     *Val = APValue();
9535   } else {
9536     // Perform the allocation and obtain a pointer to the resulting object.
9537     Val = Info.createHeapAlloc(E, AllocType, Result);
9538     if (!Val)
9539       return false;
9540   }
9541 
9542   if (ValueInit) {
9543     ImplicitValueInitExpr VIE(AllocType);
9544     if (!EvaluateInPlace(*Val, Info, Result, &VIE))
9545       return false;
9546   } else if (ResizedArrayILE) {
9547     if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
9548                                   AllocType))
9549       return false;
9550   } else if (ResizedArrayCCE) {
9551     if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
9552                                        AllocType))
9553       return false;
9554   } else if (Init) {
9555     if (!EvaluateInPlace(*Val, Info, Result, Init))
9556       return false;
9557   } else if (!getDefaultInitValue(AllocType, *Val)) {
9558     return false;
9559   }
9560 
9561   // Array new returns a pointer to the first element, not a pointer to the
9562   // array.
9563   if (auto *AT = AllocType->getAsArrayTypeUnsafe())
9564     Result.addArray(Info, E, cast<ConstantArrayType>(AT));
9565 
9566   return true;
9567 }
9568 //===----------------------------------------------------------------------===//
9569 // Member Pointer Evaluation
9570 //===----------------------------------------------------------------------===//
9571 
9572 namespace {
9573 class MemberPointerExprEvaluator
9574   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
9575   MemberPtr &Result;
9576 
9577   bool Success(const ValueDecl *D) {
9578     Result = MemberPtr(D);
9579     return true;
9580   }
9581 public:
9582 
9583   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
9584     : ExprEvaluatorBaseTy(Info), Result(Result) {}
9585 
9586   bool Success(const APValue &V, const Expr *E) {
9587     Result.setFrom(V);
9588     return true;
9589   }
9590   bool ZeroInitialization(const Expr *E) {
9591     return Success((const ValueDecl*)nullptr);
9592   }
9593 
9594   bool VisitCastExpr(const CastExpr *E);
9595   bool VisitUnaryAddrOf(const UnaryOperator *E);
9596 };
9597 } // end anonymous namespace
9598 
9599 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
9600                                   EvalInfo &Info) {
9601   assert(!E->isValueDependent());
9602   assert(E->isPRValue() && E->getType()->isMemberPointerType());
9603   return MemberPointerExprEvaluator(Info, Result).Visit(E);
9604 }
9605 
9606 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9607   switch (E->getCastKind()) {
9608   default:
9609     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9610 
9611   case CK_NullToMemberPointer:
9612     VisitIgnoredValue(E->getSubExpr());
9613     return ZeroInitialization(E);
9614 
9615   case CK_BaseToDerivedMemberPointer: {
9616     if (!Visit(E->getSubExpr()))
9617       return false;
9618     if (E->path_empty())
9619       return true;
9620     // Base-to-derived member pointer casts store the path in derived-to-base
9621     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
9622     // the wrong end of the derived->base arc, so stagger the path by one class.
9623     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
9624     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
9625          PathI != PathE; ++PathI) {
9626       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9627       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
9628       if (!Result.castToDerived(Derived))
9629         return Error(E);
9630     }
9631     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
9632     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
9633       return Error(E);
9634     return true;
9635   }
9636 
9637   case CK_DerivedToBaseMemberPointer:
9638     if (!Visit(E->getSubExpr()))
9639       return false;
9640     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9641          PathE = E->path_end(); PathI != PathE; ++PathI) {
9642       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9643       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9644       if (!Result.castToBase(Base))
9645         return Error(E);
9646     }
9647     return true;
9648   }
9649 }
9650 
9651 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9652   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
9653   // member can be formed.
9654   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
9655 }
9656 
9657 //===----------------------------------------------------------------------===//
9658 // Record Evaluation
9659 //===----------------------------------------------------------------------===//
9660 
9661 namespace {
9662   class RecordExprEvaluator
9663   : public ExprEvaluatorBase<RecordExprEvaluator> {
9664     const LValue &This;
9665     APValue &Result;
9666   public:
9667 
9668     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
9669       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
9670 
9671     bool Success(const APValue &V, const Expr *E) {
9672       Result = V;
9673       return true;
9674     }
9675     bool ZeroInitialization(const Expr *E) {
9676       return ZeroInitialization(E, E->getType());
9677     }
9678     bool ZeroInitialization(const Expr *E, QualType T);
9679 
9680     bool VisitCallExpr(const CallExpr *E) {
9681       return handleCallExpr(E, Result, &This);
9682     }
9683     bool VisitCastExpr(const CastExpr *E);
9684     bool VisitInitListExpr(const InitListExpr *E);
9685     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9686       return VisitCXXConstructExpr(E, E->getType());
9687     }
9688     bool VisitLambdaExpr(const LambdaExpr *E);
9689     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
9690     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
9691     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
9692     bool VisitBinCmp(const BinaryOperator *E);
9693   };
9694 }
9695 
9696 /// Perform zero-initialization on an object of non-union class type.
9697 /// C++11 [dcl.init]p5:
9698 ///  To zero-initialize an object or reference of type T means:
9699 ///    [...]
9700 ///    -- if T is a (possibly cv-qualified) non-union class type,
9701 ///       each non-static data member and each base-class subobject is
9702 ///       zero-initialized
9703 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
9704                                           const RecordDecl *RD,
9705                                           const LValue &This, APValue &Result) {
9706   assert(!RD->isUnion() && "Expected non-union class type");
9707   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
9708   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
9709                    std::distance(RD->field_begin(), RD->field_end()));
9710 
9711   if (RD->isInvalidDecl()) return false;
9712   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9713 
9714   if (CD) {
9715     unsigned Index = 0;
9716     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
9717            End = CD->bases_end(); I != End; ++I, ++Index) {
9718       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
9719       LValue Subobject = This;
9720       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
9721         return false;
9722       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
9723                                          Result.getStructBase(Index)))
9724         return false;
9725     }
9726   }
9727 
9728   for (const auto *I : RD->fields()) {
9729     // -- if T is a reference type, no initialization is performed.
9730     if (I->isUnnamedBitfield() || I->getType()->isReferenceType())
9731       continue;
9732 
9733     LValue Subobject = This;
9734     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
9735       return false;
9736 
9737     ImplicitValueInitExpr VIE(I->getType());
9738     if (!EvaluateInPlace(
9739           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
9740       return false;
9741   }
9742 
9743   return true;
9744 }
9745 
9746 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
9747   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
9748   if (RD->isInvalidDecl()) return false;
9749   if (RD->isUnion()) {
9750     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
9751     // object's first non-static named data member is zero-initialized
9752     RecordDecl::field_iterator I = RD->field_begin();
9753     while (I != RD->field_end() && (*I)->isUnnamedBitfield())
9754       ++I;
9755     if (I == RD->field_end()) {
9756       Result = APValue((const FieldDecl*)nullptr);
9757       return true;
9758     }
9759 
9760     LValue Subobject = This;
9761     if (!HandleLValueMember(Info, E, Subobject, *I))
9762       return false;
9763     Result = APValue(*I);
9764     ImplicitValueInitExpr VIE(I->getType());
9765     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
9766   }
9767 
9768   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
9769     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
9770     return false;
9771   }
9772 
9773   return HandleClassZeroInitialization(Info, E, RD, This, Result);
9774 }
9775 
9776 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
9777   switch (E->getCastKind()) {
9778   default:
9779     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9780 
9781   case CK_ConstructorConversion:
9782     return Visit(E->getSubExpr());
9783 
9784   case CK_DerivedToBase:
9785   case CK_UncheckedDerivedToBase: {
9786     APValue DerivedObject;
9787     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
9788       return false;
9789     if (!DerivedObject.isStruct())
9790       return Error(E->getSubExpr());
9791 
9792     // Derived-to-base rvalue conversion: just slice off the derived part.
9793     APValue *Value = &DerivedObject;
9794     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
9795     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9796          PathE = E->path_end(); PathI != PathE; ++PathI) {
9797       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
9798       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9799       Value = &Value->getStructBase(getBaseIndex(RD, Base));
9800       RD = Base;
9801     }
9802     Result = *Value;
9803     return true;
9804   }
9805   }
9806 }
9807 
9808 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9809   if (E->isTransparent())
9810     return Visit(E->getInit(0));
9811 
9812   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
9813   if (RD->isInvalidDecl()) return false;
9814   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9815   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
9816 
9817   EvalInfo::EvaluatingConstructorRAII EvalObj(
9818       Info,
9819       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
9820       CXXRD && CXXRD->getNumBases());
9821 
9822   if (RD->isUnion()) {
9823     const FieldDecl *Field = E->getInitializedFieldInUnion();
9824     Result = APValue(Field);
9825     if (!Field)
9826       return true;
9827 
9828     // If the initializer list for a union does not contain any elements, the
9829     // first element of the union is value-initialized.
9830     // FIXME: The element should be initialized from an initializer list.
9831     //        Is this difference ever observable for initializer lists which
9832     //        we don't build?
9833     ImplicitValueInitExpr VIE(Field->getType());
9834     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
9835 
9836     LValue Subobject = This;
9837     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
9838       return false;
9839 
9840     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9841     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9842                                   isa<CXXDefaultInitExpr>(InitExpr));
9843 
9844     if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
9845       if (Field->isBitField())
9846         return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
9847                                      Field);
9848       return true;
9849     }
9850 
9851     return false;
9852   }
9853 
9854   if (!Result.hasValue())
9855     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
9856                      std::distance(RD->field_begin(), RD->field_end()));
9857   unsigned ElementNo = 0;
9858   bool Success = true;
9859 
9860   // Initialize base classes.
9861   if (CXXRD && CXXRD->getNumBases()) {
9862     for (const auto &Base : CXXRD->bases()) {
9863       assert(ElementNo < E->getNumInits() && "missing init for base class");
9864       const Expr *Init = E->getInit(ElementNo);
9865 
9866       LValue Subobject = This;
9867       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
9868         return false;
9869 
9870       APValue &FieldVal = Result.getStructBase(ElementNo);
9871       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
9872         if (!Info.noteFailure())
9873           return false;
9874         Success = false;
9875       }
9876       ++ElementNo;
9877     }
9878 
9879     EvalObj.finishedConstructingBases();
9880   }
9881 
9882   // Initialize members.
9883   for (const auto *Field : RD->fields()) {
9884     // Anonymous bit-fields are not considered members of the class for
9885     // purposes of aggregate initialization.
9886     if (Field->isUnnamedBitfield())
9887       continue;
9888 
9889     LValue Subobject = This;
9890 
9891     bool HaveInit = ElementNo < E->getNumInits();
9892 
9893     // FIXME: Diagnostics here should point to the end of the initializer
9894     // list, not the start.
9895     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
9896                             Subobject, Field, &Layout))
9897       return false;
9898 
9899     // Perform an implicit value-initialization for members beyond the end of
9900     // the initializer list.
9901     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
9902     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
9903 
9904     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9905     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9906                                   isa<CXXDefaultInitExpr>(Init));
9907 
9908     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9909     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
9910         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
9911                                                        FieldVal, Field))) {
9912       if (!Info.noteFailure())
9913         return false;
9914       Success = false;
9915     }
9916   }
9917 
9918   EvalObj.finishedConstructingFields();
9919 
9920   return Success;
9921 }
9922 
9923 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
9924                                                 QualType T) {
9925   // Note that E's type is not necessarily the type of our class here; we might
9926   // be initializing an array element instead.
9927   const CXXConstructorDecl *FD = E->getConstructor();
9928   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
9929 
9930   bool ZeroInit = E->requiresZeroInitialization();
9931   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
9932     // If we've already performed zero-initialization, we're already done.
9933     if (Result.hasValue())
9934       return true;
9935 
9936     if (ZeroInit)
9937       return ZeroInitialization(E, T);
9938 
9939     return getDefaultInitValue(T, Result);
9940   }
9941 
9942   const FunctionDecl *Definition = nullptr;
9943   auto Body = FD->getBody(Definition);
9944 
9945   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9946     return false;
9947 
9948   // Avoid materializing a temporary for an elidable copy/move constructor.
9949   if (E->isElidable() && !ZeroInit) {
9950     // FIXME: This only handles the simplest case, where the source object
9951     //        is passed directly as the first argument to the constructor.
9952     //        This should also handle stepping though implicit casts and
9953     //        and conversion sequences which involve two steps, with a
9954     //        conversion operator followed by a converting constructor.
9955     const Expr *SrcObj = E->getArg(0);
9956     assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
9957     assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
9958     if (const MaterializeTemporaryExpr *ME =
9959             dyn_cast<MaterializeTemporaryExpr>(SrcObj))
9960       return Visit(ME->getSubExpr());
9961   }
9962 
9963   if (ZeroInit && !ZeroInitialization(E, T))
9964     return false;
9965 
9966   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
9967   return HandleConstructorCall(E, This, Args,
9968                                cast<CXXConstructorDecl>(Definition), Info,
9969                                Result);
9970 }
9971 
9972 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
9973     const CXXInheritedCtorInitExpr *E) {
9974   if (!Info.CurrentCall) {
9975     assert(Info.checkingPotentialConstantExpression());
9976     return false;
9977   }
9978 
9979   const CXXConstructorDecl *FD = E->getConstructor();
9980   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
9981     return false;
9982 
9983   const FunctionDecl *Definition = nullptr;
9984   auto Body = FD->getBody(Definition);
9985 
9986   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9987     return false;
9988 
9989   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
9990                                cast<CXXConstructorDecl>(Definition), Info,
9991                                Result);
9992 }
9993 
9994 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
9995     const CXXStdInitializerListExpr *E) {
9996   const ConstantArrayType *ArrayType =
9997       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
9998 
9999   LValue Array;
10000   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
10001     return false;
10002 
10003   // Get a pointer to the first element of the array.
10004   Array.addArray(Info, E, ArrayType);
10005 
10006   auto InvalidType = [&] {
10007     Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
10008       << E->getType();
10009     return false;
10010   };
10011 
10012   // FIXME: Perform the checks on the field types in SemaInit.
10013   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
10014   RecordDecl::field_iterator Field = Record->field_begin();
10015   if (Field == Record->field_end())
10016     return InvalidType();
10017 
10018   // Start pointer.
10019   if (!Field->getType()->isPointerType() ||
10020       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10021                             ArrayType->getElementType()))
10022     return InvalidType();
10023 
10024   // FIXME: What if the initializer_list type has base classes, etc?
10025   Result = APValue(APValue::UninitStruct(), 0, 2);
10026   Array.moveInto(Result.getStructField(0));
10027 
10028   if (++Field == Record->field_end())
10029     return InvalidType();
10030 
10031   if (Field->getType()->isPointerType() &&
10032       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10033                            ArrayType->getElementType())) {
10034     // End pointer.
10035     if (!HandleLValueArrayAdjustment(Info, E, Array,
10036                                      ArrayType->getElementType(),
10037                                      ArrayType->getSize().getZExtValue()))
10038       return false;
10039     Array.moveInto(Result.getStructField(1));
10040   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
10041     // Length.
10042     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
10043   else
10044     return InvalidType();
10045 
10046   if (++Field != Record->field_end())
10047     return InvalidType();
10048 
10049   return true;
10050 }
10051 
10052 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
10053   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
10054   if (ClosureClass->isInvalidDecl())
10055     return false;
10056 
10057   const size_t NumFields =
10058       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
10059 
10060   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
10061                                             E->capture_init_end()) &&
10062          "The number of lambda capture initializers should equal the number of "
10063          "fields within the closure type");
10064 
10065   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
10066   // Iterate through all the lambda's closure object's fields and initialize
10067   // them.
10068   auto *CaptureInitIt = E->capture_init_begin();
10069   const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
10070   bool Success = true;
10071   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
10072   for (const auto *Field : ClosureClass->fields()) {
10073     assert(CaptureInitIt != E->capture_init_end());
10074     // Get the initializer for this field
10075     Expr *const CurFieldInit = *CaptureInitIt++;
10076 
10077     // If there is no initializer, either this is a VLA or an error has
10078     // occurred.
10079     if (!CurFieldInit)
10080       return Error(E);
10081 
10082     LValue Subobject = This;
10083 
10084     if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
10085       return false;
10086 
10087     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10088     if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
10089       if (!Info.keepEvaluatingAfterFailure())
10090         return false;
10091       Success = false;
10092     }
10093     ++CaptureIt;
10094   }
10095   return Success;
10096 }
10097 
10098 static bool EvaluateRecord(const Expr *E, const LValue &This,
10099                            APValue &Result, EvalInfo &Info) {
10100   assert(!E->isValueDependent());
10101   assert(E->isPRValue() && E->getType()->isRecordType() &&
10102          "can't evaluate expression as a record rvalue");
10103   return RecordExprEvaluator(Info, This, Result).Visit(E);
10104 }
10105 
10106 //===----------------------------------------------------------------------===//
10107 // Temporary Evaluation
10108 //
10109 // Temporaries are represented in the AST as rvalues, but generally behave like
10110 // lvalues. The full-object of which the temporary is a subobject is implicitly
10111 // materialized so that a reference can bind to it.
10112 //===----------------------------------------------------------------------===//
10113 namespace {
10114 class TemporaryExprEvaluator
10115   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
10116 public:
10117   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
10118     LValueExprEvaluatorBaseTy(Info, Result, false) {}
10119 
10120   /// Visit an expression which constructs the value of this temporary.
10121   bool VisitConstructExpr(const Expr *E) {
10122     APValue &Value = Info.CurrentCall->createTemporary(
10123         E, E->getType(), ScopeKind::FullExpression, Result);
10124     return EvaluateInPlace(Value, Info, Result, E);
10125   }
10126 
10127   bool VisitCastExpr(const CastExpr *E) {
10128     switch (E->getCastKind()) {
10129     default:
10130       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
10131 
10132     case CK_ConstructorConversion:
10133       return VisitConstructExpr(E->getSubExpr());
10134     }
10135   }
10136   bool VisitInitListExpr(const InitListExpr *E) {
10137     return VisitConstructExpr(E);
10138   }
10139   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10140     return VisitConstructExpr(E);
10141   }
10142   bool VisitCallExpr(const CallExpr *E) {
10143     return VisitConstructExpr(E);
10144   }
10145   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
10146     return VisitConstructExpr(E);
10147   }
10148   bool VisitLambdaExpr(const LambdaExpr *E) {
10149     return VisitConstructExpr(E);
10150   }
10151 };
10152 } // end anonymous namespace
10153 
10154 /// Evaluate an expression of record type as a temporary.
10155 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
10156   assert(!E->isValueDependent());
10157   assert(E->isPRValue() && E->getType()->isRecordType());
10158   return TemporaryExprEvaluator(Info, Result).Visit(E);
10159 }
10160 
10161 //===----------------------------------------------------------------------===//
10162 // Vector Evaluation
10163 //===----------------------------------------------------------------------===//
10164 
10165 namespace {
10166   class VectorExprEvaluator
10167   : public ExprEvaluatorBase<VectorExprEvaluator> {
10168     APValue &Result;
10169   public:
10170 
10171     VectorExprEvaluator(EvalInfo &info, APValue &Result)
10172       : ExprEvaluatorBaseTy(info), Result(Result) {}
10173 
10174     bool Success(ArrayRef<APValue> V, const Expr *E) {
10175       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
10176       // FIXME: remove this APValue copy.
10177       Result = APValue(V.data(), V.size());
10178       return true;
10179     }
10180     bool Success(const APValue &V, const Expr *E) {
10181       assert(V.isVector());
10182       Result = V;
10183       return true;
10184     }
10185     bool ZeroInitialization(const Expr *E);
10186 
10187     bool VisitUnaryReal(const UnaryOperator *E)
10188       { return Visit(E->getSubExpr()); }
10189     bool VisitCastExpr(const CastExpr* E);
10190     bool VisitInitListExpr(const InitListExpr *E);
10191     bool VisitUnaryImag(const UnaryOperator *E);
10192     bool VisitBinaryOperator(const BinaryOperator *E);
10193     bool VisitUnaryOperator(const UnaryOperator *E);
10194     // FIXME: Missing: conditional operator (for GNU
10195     //                 conditional select), shufflevector, ExtVectorElementExpr
10196   };
10197 } // end anonymous namespace
10198 
10199 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
10200   assert(E->isPRValue() && E->getType()->isVectorType() &&
10201          "not a vector prvalue");
10202   return VectorExprEvaluator(Info, Result).Visit(E);
10203 }
10204 
10205 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
10206   const VectorType *VTy = E->getType()->castAs<VectorType>();
10207   unsigned NElts = VTy->getNumElements();
10208 
10209   const Expr *SE = E->getSubExpr();
10210   QualType SETy = SE->getType();
10211 
10212   switch (E->getCastKind()) {
10213   case CK_VectorSplat: {
10214     APValue Val = APValue();
10215     if (SETy->isIntegerType()) {
10216       APSInt IntResult;
10217       if (!EvaluateInteger(SE, IntResult, Info))
10218         return false;
10219       Val = APValue(std::move(IntResult));
10220     } else if (SETy->isRealFloatingType()) {
10221       APFloat FloatResult(0.0);
10222       if (!EvaluateFloat(SE, FloatResult, Info))
10223         return false;
10224       Val = APValue(std::move(FloatResult));
10225     } else {
10226       return Error(E);
10227     }
10228 
10229     // Splat and create vector APValue.
10230     SmallVector<APValue, 4> Elts(NElts, Val);
10231     return Success(Elts, E);
10232   }
10233   case CK_BitCast: {
10234     // Evaluate the operand into an APInt we can extract from.
10235     llvm::APInt SValInt;
10236     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
10237       return false;
10238     // Extract the elements
10239     QualType EltTy = VTy->getElementType();
10240     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
10241     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
10242     SmallVector<APValue, 4> Elts;
10243     if (EltTy->isRealFloatingType()) {
10244       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
10245       unsigned FloatEltSize = EltSize;
10246       if (&Sem == &APFloat::x87DoubleExtended())
10247         FloatEltSize = 80;
10248       for (unsigned i = 0; i < NElts; i++) {
10249         llvm::APInt Elt;
10250         if (BigEndian)
10251           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
10252         else
10253           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
10254         Elts.push_back(APValue(APFloat(Sem, Elt)));
10255       }
10256     } else if (EltTy->isIntegerType()) {
10257       for (unsigned i = 0; i < NElts; i++) {
10258         llvm::APInt Elt;
10259         if (BigEndian)
10260           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
10261         else
10262           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
10263         Elts.push_back(APValue(APSInt(Elt, !EltTy->isSignedIntegerType())));
10264       }
10265     } else {
10266       return Error(E);
10267     }
10268     return Success(Elts, E);
10269   }
10270   default:
10271     return ExprEvaluatorBaseTy::VisitCastExpr(E);
10272   }
10273 }
10274 
10275 bool
10276 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10277   const VectorType *VT = E->getType()->castAs<VectorType>();
10278   unsigned NumInits = E->getNumInits();
10279   unsigned NumElements = VT->getNumElements();
10280 
10281   QualType EltTy = VT->getElementType();
10282   SmallVector<APValue, 4> Elements;
10283 
10284   // The number of initializers can be less than the number of
10285   // vector elements. For OpenCL, this can be due to nested vector
10286   // initialization. For GCC compatibility, missing trailing elements
10287   // should be initialized with zeroes.
10288   unsigned CountInits = 0, CountElts = 0;
10289   while (CountElts < NumElements) {
10290     // Handle nested vector initialization.
10291     if (CountInits < NumInits
10292         && E->getInit(CountInits)->getType()->isVectorType()) {
10293       APValue v;
10294       if (!EvaluateVector(E->getInit(CountInits), v, Info))
10295         return Error(E);
10296       unsigned vlen = v.getVectorLength();
10297       for (unsigned j = 0; j < vlen; j++)
10298         Elements.push_back(v.getVectorElt(j));
10299       CountElts += vlen;
10300     } else if (EltTy->isIntegerType()) {
10301       llvm::APSInt sInt(32);
10302       if (CountInits < NumInits) {
10303         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
10304           return false;
10305       } else // trailing integer zero.
10306         sInt = Info.Ctx.MakeIntValue(0, EltTy);
10307       Elements.push_back(APValue(sInt));
10308       CountElts++;
10309     } else {
10310       llvm::APFloat f(0.0);
10311       if (CountInits < NumInits) {
10312         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
10313           return false;
10314       } else // trailing float zero.
10315         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
10316       Elements.push_back(APValue(f));
10317       CountElts++;
10318     }
10319     CountInits++;
10320   }
10321   return Success(Elements, E);
10322 }
10323 
10324 bool
10325 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
10326   const auto *VT = E->getType()->castAs<VectorType>();
10327   QualType EltTy = VT->getElementType();
10328   APValue ZeroElement;
10329   if (EltTy->isIntegerType())
10330     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
10331   else
10332     ZeroElement =
10333         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
10334 
10335   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
10336   return Success(Elements, E);
10337 }
10338 
10339 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
10340   VisitIgnoredValue(E->getSubExpr());
10341   return ZeroInitialization(E);
10342 }
10343 
10344 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10345   BinaryOperatorKind Op = E->getOpcode();
10346   assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
10347          "Operation not supported on vector types");
10348 
10349   if (Op == BO_Comma)
10350     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10351 
10352   Expr *LHS = E->getLHS();
10353   Expr *RHS = E->getRHS();
10354 
10355   assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
10356          "Must both be vector types");
10357   // Checking JUST the types are the same would be fine, except shifts don't
10358   // need to have their types be the same (since you always shift by an int).
10359   assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
10360              E->getType()->castAs<VectorType>()->getNumElements() &&
10361          RHS->getType()->castAs<VectorType>()->getNumElements() ==
10362              E->getType()->castAs<VectorType>()->getNumElements() &&
10363          "All operands must be the same size.");
10364 
10365   APValue LHSValue;
10366   APValue RHSValue;
10367   bool LHSOK = Evaluate(LHSValue, Info, LHS);
10368   if (!LHSOK && !Info.noteFailure())
10369     return false;
10370   if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
10371     return false;
10372 
10373   if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
10374     return false;
10375 
10376   return Success(LHSValue, E);
10377 }
10378 
10379 static llvm::Optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
10380                                                          QualType ResultTy,
10381                                                          UnaryOperatorKind Op,
10382                                                          APValue Elt) {
10383   switch (Op) {
10384   case UO_Plus:
10385     // Nothing to do here.
10386     return Elt;
10387   case UO_Minus:
10388     if (Elt.getKind() == APValue::Int) {
10389       Elt.getInt().negate();
10390     } else {
10391       assert(Elt.getKind() == APValue::Float &&
10392              "Vector can only be int or float type");
10393       Elt.getFloat().changeSign();
10394     }
10395     return Elt;
10396   case UO_Not:
10397     // This is only valid for integral types anyway, so we don't have to handle
10398     // float here.
10399     assert(Elt.getKind() == APValue::Int &&
10400            "Vector operator ~ can only be int");
10401     Elt.getInt().flipAllBits();
10402     return Elt;
10403   case UO_LNot: {
10404     if (Elt.getKind() == APValue::Int) {
10405       Elt.getInt() = !Elt.getInt();
10406       // operator ! on vectors returns -1 for 'truth', so negate it.
10407       Elt.getInt().negate();
10408       return Elt;
10409     }
10410     assert(Elt.getKind() == APValue::Float &&
10411            "Vector can only be int or float type");
10412     // Float types result in an int of the same size, but -1 for true, or 0 for
10413     // false.
10414     APSInt EltResult{Ctx.getIntWidth(ResultTy),
10415                      ResultTy->isUnsignedIntegerType()};
10416     if (Elt.getFloat().isZero())
10417       EltResult.setAllBits();
10418     else
10419       EltResult.clearAllBits();
10420 
10421     return APValue{EltResult};
10422   }
10423   default:
10424     // FIXME: Implement the rest of the unary operators.
10425     return llvm::None;
10426   }
10427 }
10428 
10429 bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10430   Expr *SubExpr = E->getSubExpr();
10431   const auto *VD = SubExpr->getType()->castAs<VectorType>();
10432   // This result element type differs in the case of negating a floating point
10433   // vector, since the result type is the a vector of the equivilant sized
10434   // integer.
10435   const QualType ResultEltTy = VD->getElementType();
10436   UnaryOperatorKind Op = E->getOpcode();
10437 
10438   APValue SubExprValue;
10439   if (!Evaluate(SubExprValue, Info, SubExpr))
10440     return false;
10441 
10442   // FIXME: This vector evaluator someday needs to be changed to be LValue
10443   // aware/keep LValue information around, rather than dealing with just vector
10444   // types directly. Until then, we cannot handle cases where the operand to
10445   // these unary operators is an LValue. The only case I've been able to see
10446   // cause this is operator++ assigning to a member expression (only valid in
10447   // altivec compilations) in C mode, so this shouldn't limit us too much.
10448   if (SubExprValue.isLValue())
10449     return false;
10450 
10451   assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
10452          "Vector length doesn't match type?");
10453 
10454   SmallVector<APValue, 4> ResultElements;
10455   for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
10456     llvm::Optional<APValue> Elt = handleVectorUnaryOperator(
10457         Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
10458     if (!Elt)
10459       return false;
10460     ResultElements.push_back(*Elt);
10461   }
10462   return Success(APValue(ResultElements.data(), ResultElements.size()), E);
10463 }
10464 
10465 //===----------------------------------------------------------------------===//
10466 // Array Evaluation
10467 //===----------------------------------------------------------------------===//
10468 
10469 namespace {
10470   class ArrayExprEvaluator
10471   : public ExprEvaluatorBase<ArrayExprEvaluator> {
10472     const LValue &This;
10473     APValue &Result;
10474   public:
10475 
10476     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
10477       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
10478 
10479     bool Success(const APValue &V, const Expr *E) {
10480       assert(V.isArray() && "expected array");
10481       Result = V;
10482       return true;
10483     }
10484 
10485     bool ZeroInitialization(const Expr *E) {
10486       const ConstantArrayType *CAT =
10487           Info.Ctx.getAsConstantArrayType(E->getType());
10488       if (!CAT) {
10489         if (E->getType()->isIncompleteArrayType()) {
10490           // We can be asked to zero-initialize a flexible array member; this
10491           // is represented as an ImplicitValueInitExpr of incomplete array
10492           // type. In this case, the array has zero elements.
10493           Result = APValue(APValue::UninitArray(), 0, 0);
10494           return true;
10495         }
10496         // FIXME: We could handle VLAs here.
10497         return Error(E);
10498       }
10499 
10500       Result = APValue(APValue::UninitArray(), 0,
10501                        CAT->getSize().getZExtValue());
10502       if (!Result.hasArrayFiller())
10503         return true;
10504 
10505       // Zero-initialize all elements.
10506       LValue Subobject = This;
10507       Subobject.addArray(Info, E, CAT);
10508       ImplicitValueInitExpr VIE(CAT->getElementType());
10509       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
10510     }
10511 
10512     bool VisitCallExpr(const CallExpr *E) {
10513       return handleCallExpr(E, Result, &This);
10514     }
10515     bool VisitInitListExpr(const InitListExpr *E,
10516                            QualType AllocType = QualType());
10517     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
10518     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
10519     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
10520                                const LValue &Subobject,
10521                                APValue *Value, QualType Type);
10522     bool VisitStringLiteral(const StringLiteral *E,
10523                             QualType AllocType = QualType()) {
10524       expandStringLiteral(Info, E, Result, AllocType);
10525       return true;
10526     }
10527   };
10528 } // end anonymous namespace
10529 
10530 static bool EvaluateArray(const Expr *E, const LValue &This,
10531                           APValue &Result, EvalInfo &Info) {
10532   assert(!E->isValueDependent());
10533   assert(E->isPRValue() && E->getType()->isArrayType() &&
10534          "not an array prvalue");
10535   return ArrayExprEvaluator(Info, This, Result).Visit(E);
10536 }
10537 
10538 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10539                                      APValue &Result, const InitListExpr *ILE,
10540                                      QualType AllocType) {
10541   assert(!ILE->isValueDependent());
10542   assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
10543          "not an array prvalue");
10544   return ArrayExprEvaluator(Info, This, Result)
10545       .VisitInitListExpr(ILE, AllocType);
10546 }
10547 
10548 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10549                                           APValue &Result,
10550                                           const CXXConstructExpr *CCE,
10551                                           QualType AllocType) {
10552   assert(!CCE->isValueDependent());
10553   assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
10554          "not an array prvalue");
10555   return ArrayExprEvaluator(Info, This, Result)
10556       .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
10557 }
10558 
10559 // Return true iff the given array filler may depend on the element index.
10560 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
10561   // For now, just allow non-class value-initialization and initialization
10562   // lists comprised of them.
10563   if (isa<ImplicitValueInitExpr>(FillerExpr))
10564     return false;
10565   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
10566     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
10567       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
10568         return true;
10569     }
10570     return false;
10571   }
10572   return true;
10573 }
10574 
10575 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
10576                                            QualType AllocType) {
10577   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
10578       AllocType.isNull() ? E->getType() : AllocType);
10579   if (!CAT)
10580     return Error(E);
10581 
10582   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
10583   // an appropriately-typed string literal enclosed in braces.
10584   if (E->isStringLiteralInit()) {
10585     auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
10586     // FIXME: Support ObjCEncodeExpr here once we support it in
10587     // ArrayExprEvaluator generally.
10588     if (!SL)
10589       return Error(E);
10590     return VisitStringLiteral(SL, AllocType);
10591   }
10592   // Any other transparent list init will need proper handling of the
10593   // AllocType; we can't just recurse to the inner initializer.
10594   assert(!E->isTransparent() &&
10595          "transparent array list initialization is not string literal init?");
10596 
10597   bool Success = true;
10598 
10599   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
10600          "zero-initialized array shouldn't have any initialized elts");
10601   APValue Filler;
10602   if (Result.isArray() && Result.hasArrayFiller())
10603     Filler = Result.getArrayFiller();
10604 
10605   unsigned NumEltsToInit = E->getNumInits();
10606   unsigned NumElts = CAT->getSize().getZExtValue();
10607   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
10608 
10609   // If the initializer might depend on the array index, run it for each
10610   // array element.
10611   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
10612     NumEltsToInit = NumElts;
10613 
10614   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
10615                           << NumEltsToInit << ".\n");
10616 
10617   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
10618 
10619   // If the array was previously zero-initialized, preserve the
10620   // zero-initialized values.
10621   if (Filler.hasValue()) {
10622     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
10623       Result.getArrayInitializedElt(I) = Filler;
10624     if (Result.hasArrayFiller())
10625       Result.getArrayFiller() = Filler;
10626   }
10627 
10628   LValue Subobject = This;
10629   Subobject.addArray(Info, E, CAT);
10630   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
10631     const Expr *Init =
10632         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
10633     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10634                          Info, Subobject, Init) ||
10635         !HandleLValueArrayAdjustment(Info, Init, Subobject,
10636                                      CAT->getElementType(), 1)) {
10637       if (!Info.noteFailure())
10638         return false;
10639       Success = false;
10640     }
10641   }
10642 
10643   if (!Result.hasArrayFiller())
10644     return Success;
10645 
10646   // If we get here, we have a trivial filler, which we can just evaluate
10647   // once and splat over the rest of the array elements.
10648   assert(FillerExpr && "no array filler for incomplete init list");
10649   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
10650                          FillerExpr) && Success;
10651 }
10652 
10653 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
10654   LValue CommonLV;
10655   if (E->getCommonExpr() &&
10656       !Evaluate(Info.CurrentCall->createTemporary(
10657                     E->getCommonExpr(),
10658                     getStorageType(Info.Ctx, E->getCommonExpr()),
10659                     ScopeKind::FullExpression, CommonLV),
10660                 Info, E->getCommonExpr()->getSourceExpr()))
10661     return false;
10662 
10663   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
10664 
10665   uint64_t Elements = CAT->getSize().getZExtValue();
10666   Result = APValue(APValue::UninitArray(), Elements, Elements);
10667 
10668   LValue Subobject = This;
10669   Subobject.addArray(Info, E, CAT);
10670 
10671   bool Success = true;
10672   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
10673     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10674                          Info, Subobject, E->getSubExpr()) ||
10675         !HandleLValueArrayAdjustment(Info, E, Subobject,
10676                                      CAT->getElementType(), 1)) {
10677       if (!Info.noteFailure())
10678         return false;
10679       Success = false;
10680     }
10681   }
10682 
10683   return Success;
10684 }
10685 
10686 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
10687   return VisitCXXConstructExpr(E, This, &Result, E->getType());
10688 }
10689 
10690 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10691                                                const LValue &Subobject,
10692                                                APValue *Value,
10693                                                QualType Type) {
10694   bool HadZeroInit = Value->hasValue();
10695 
10696   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
10697     unsigned FinalSize = CAT->getSize().getZExtValue();
10698 
10699     // Preserve the array filler if we had prior zero-initialization.
10700     APValue Filler =
10701       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
10702                                              : APValue();
10703 
10704     *Value = APValue(APValue::UninitArray(), 0, FinalSize);
10705     if (FinalSize == 0)
10706       return true;
10707 
10708     LValue ArrayElt = Subobject;
10709     ArrayElt.addArray(Info, E, CAT);
10710     // We do the whole initialization in two passes, first for just one element,
10711     // then for the whole array. It's possible we may find out we can't do const
10712     // init in the first pass, in which case we avoid allocating a potentially
10713     // large array. We don't do more passes because expanding array requires
10714     // copying the data, which is wasteful.
10715     for (const unsigned N : {1u, FinalSize}) {
10716       unsigned OldElts = Value->getArrayInitializedElts();
10717       if (OldElts == N)
10718         break;
10719 
10720       // Expand the array to appropriate size.
10721       APValue NewValue(APValue::UninitArray(), N, FinalSize);
10722       for (unsigned I = 0; I < OldElts; ++I)
10723         NewValue.getArrayInitializedElt(I).swap(
10724             Value->getArrayInitializedElt(I));
10725       Value->swap(NewValue);
10726 
10727       if (HadZeroInit)
10728         for (unsigned I = OldElts; I < N; ++I)
10729           Value->getArrayInitializedElt(I) = Filler;
10730 
10731       // Initialize the elements.
10732       for (unsigned I = OldElts; I < N; ++I) {
10733         if (!VisitCXXConstructExpr(E, ArrayElt,
10734                                    &Value->getArrayInitializedElt(I),
10735                                    CAT->getElementType()) ||
10736             !HandleLValueArrayAdjustment(Info, E, ArrayElt,
10737                                          CAT->getElementType(), 1))
10738           return false;
10739         // When checking for const initilization any diagnostic is considered
10740         // an error.
10741         if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
10742             !Info.keepEvaluatingAfterFailure())
10743           return false;
10744       }
10745     }
10746 
10747     return true;
10748   }
10749 
10750   if (!Type->isRecordType())
10751     return Error(E);
10752 
10753   return RecordExprEvaluator(Info, Subobject, *Value)
10754              .VisitCXXConstructExpr(E, Type);
10755 }
10756 
10757 //===----------------------------------------------------------------------===//
10758 // Integer Evaluation
10759 //
10760 // As a GNU extension, we support casting pointers to sufficiently-wide integer
10761 // types and back in constant folding. Integer values are thus represented
10762 // either as an integer-valued APValue, or as an lvalue-valued APValue.
10763 //===----------------------------------------------------------------------===//
10764 
10765 namespace {
10766 class IntExprEvaluator
10767         : public ExprEvaluatorBase<IntExprEvaluator> {
10768   APValue &Result;
10769 public:
10770   IntExprEvaluator(EvalInfo &info, APValue &result)
10771       : ExprEvaluatorBaseTy(info), Result(result) {}
10772 
10773   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
10774     assert(E->getType()->isIntegralOrEnumerationType() &&
10775            "Invalid evaluation result.");
10776     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
10777            "Invalid evaluation result.");
10778     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10779            "Invalid evaluation result.");
10780     Result = APValue(SI);
10781     return true;
10782   }
10783   bool Success(const llvm::APSInt &SI, const Expr *E) {
10784     return Success(SI, E, Result);
10785   }
10786 
10787   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
10788     assert(E->getType()->isIntegralOrEnumerationType() &&
10789            "Invalid evaluation result.");
10790     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10791            "Invalid evaluation result.");
10792     Result = APValue(APSInt(I));
10793     Result.getInt().setIsUnsigned(
10794                             E->getType()->isUnsignedIntegerOrEnumerationType());
10795     return true;
10796   }
10797   bool Success(const llvm::APInt &I, const Expr *E) {
10798     return Success(I, E, Result);
10799   }
10800 
10801   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
10802     assert(E->getType()->isIntegralOrEnumerationType() &&
10803            "Invalid evaluation result.");
10804     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
10805     return true;
10806   }
10807   bool Success(uint64_t Value, const Expr *E) {
10808     return Success(Value, E, Result);
10809   }
10810 
10811   bool Success(CharUnits Size, const Expr *E) {
10812     return Success(Size.getQuantity(), E);
10813   }
10814 
10815   bool Success(const APValue &V, const Expr *E) {
10816     if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
10817       Result = V;
10818       return true;
10819     }
10820     return Success(V.getInt(), E);
10821   }
10822 
10823   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
10824 
10825   //===--------------------------------------------------------------------===//
10826   //                            Visitor Methods
10827   //===--------------------------------------------------------------------===//
10828 
10829   bool VisitIntegerLiteral(const IntegerLiteral *E) {
10830     return Success(E->getValue(), E);
10831   }
10832   bool VisitCharacterLiteral(const CharacterLiteral *E) {
10833     return Success(E->getValue(), E);
10834   }
10835 
10836   bool CheckReferencedDecl(const Expr *E, const Decl *D);
10837   bool VisitDeclRefExpr(const DeclRefExpr *E) {
10838     if (CheckReferencedDecl(E, E->getDecl()))
10839       return true;
10840 
10841     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
10842   }
10843   bool VisitMemberExpr(const MemberExpr *E) {
10844     if (CheckReferencedDecl(E, E->getMemberDecl())) {
10845       VisitIgnoredBaseExpression(E->getBase());
10846       return true;
10847     }
10848 
10849     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
10850   }
10851 
10852   bool VisitCallExpr(const CallExpr *E);
10853   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
10854   bool VisitBinaryOperator(const BinaryOperator *E);
10855   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
10856   bool VisitUnaryOperator(const UnaryOperator *E);
10857 
10858   bool VisitCastExpr(const CastExpr* E);
10859   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
10860 
10861   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
10862     return Success(E->getValue(), E);
10863   }
10864 
10865   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
10866     return Success(E->getValue(), E);
10867   }
10868 
10869   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
10870     if (Info.ArrayInitIndex == uint64_t(-1)) {
10871       // We were asked to evaluate this subexpression independent of the
10872       // enclosing ArrayInitLoopExpr. We can't do that.
10873       Info.FFDiag(E);
10874       return false;
10875     }
10876     return Success(Info.ArrayInitIndex, E);
10877   }
10878 
10879   // Note, GNU defines __null as an integer, not a pointer.
10880   bool VisitGNUNullExpr(const GNUNullExpr *E) {
10881     return ZeroInitialization(E);
10882   }
10883 
10884   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
10885     return Success(E->getValue(), E);
10886   }
10887 
10888   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
10889     return Success(E->getValue(), E);
10890   }
10891 
10892   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
10893     return Success(E->getValue(), E);
10894   }
10895 
10896   bool VisitUnaryReal(const UnaryOperator *E);
10897   bool VisitUnaryImag(const UnaryOperator *E);
10898 
10899   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
10900   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
10901   bool VisitSourceLocExpr(const SourceLocExpr *E);
10902   bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
10903   bool VisitRequiresExpr(const RequiresExpr *E);
10904   // FIXME: Missing: array subscript of vector, member of vector
10905 };
10906 
10907 class FixedPointExprEvaluator
10908     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
10909   APValue &Result;
10910 
10911  public:
10912   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
10913       : ExprEvaluatorBaseTy(info), Result(result) {}
10914 
10915   bool Success(const llvm::APInt &I, const Expr *E) {
10916     return Success(
10917         APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10918   }
10919 
10920   bool Success(uint64_t Value, const Expr *E) {
10921     return Success(
10922         APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10923   }
10924 
10925   bool Success(const APValue &V, const Expr *E) {
10926     return Success(V.getFixedPoint(), E);
10927   }
10928 
10929   bool Success(const APFixedPoint &V, const Expr *E) {
10930     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
10931     assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10932            "Invalid evaluation result.");
10933     Result = APValue(V);
10934     return true;
10935   }
10936 
10937   //===--------------------------------------------------------------------===//
10938   //                            Visitor Methods
10939   //===--------------------------------------------------------------------===//
10940 
10941   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
10942     return Success(E->getValue(), E);
10943   }
10944 
10945   bool VisitCastExpr(const CastExpr *E);
10946   bool VisitUnaryOperator(const UnaryOperator *E);
10947   bool VisitBinaryOperator(const BinaryOperator *E);
10948 };
10949 } // end anonymous namespace
10950 
10951 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
10952 /// produce either the integer value or a pointer.
10953 ///
10954 /// GCC has a heinous extension which folds casts between pointer types and
10955 /// pointer-sized integral types. We support this by allowing the evaluation of
10956 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
10957 /// Some simple arithmetic on such values is supported (they are treated much
10958 /// like char*).
10959 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
10960                                     EvalInfo &Info) {
10961   assert(!E->isValueDependent());
10962   assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
10963   return IntExprEvaluator(Info, Result).Visit(E);
10964 }
10965 
10966 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
10967   assert(!E->isValueDependent());
10968   APValue Val;
10969   if (!EvaluateIntegerOrLValue(E, Val, Info))
10970     return false;
10971   if (!Val.isInt()) {
10972     // FIXME: It would be better to produce the diagnostic for casting
10973     //        a pointer to an integer.
10974     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10975     return false;
10976   }
10977   Result = Val.getInt();
10978   return true;
10979 }
10980 
10981 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
10982   APValue Evaluated = E->EvaluateInContext(
10983       Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
10984   return Success(Evaluated, E);
10985 }
10986 
10987 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
10988                                EvalInfo &Info) {
10989   assert(!E->isValueDependent());
10990   if (E->getType()->isFixedPointType()) {
10991     APValue Val;
10992     if (!FixedPointExprEvaluator(Info, Val).Visit(E))
10993       return false;
10994     if (!Val.isFixedPoint())
10995       return false;
10996 
10997     Result = Val.getFixedPoint();
10998     return true;
10999   }
11000   return false;
11001 }
11002 
11003 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
11004                                         EvalInfo &Info) {
11005   assert(!E->isValueDependent());
11006   if (E->getType()->isIntegerType()) {
11007     auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
11008     APSInt Val;
11009     if (!EvaluateInteger(E, Val, Info))
11010       return false;
11011     Result = APFixedPoint(Val, FXSema);
11012     return true;
11013   } else if (E->getType()->isFixedPointType()) {
11014     return EvaluateFixedPoint(E, Result, Info);
11015   }
11016   return false;
11017 }
11018 
11019 /// Check whether the given declaration can be directly converted to an integral
11020 /// rvalue. If not, no diagnostic is produced; there are other things we can
11021 /// try.
11022 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
11023   // Enums are integer constant exprs.
11024   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
11025     // Check for signedness/width mismatches between E type and ECD value.
11026     bool SameSign = (ECD->getInitVal().isSigned()
11027                      == E->getType()->isSignedIntegerOrEnumerationType());
11028     bool SameWidth = (ECD->getInitVal().getBitWidth()
11029                       == Info.Ctx.getIntWidth(E->getType()));
11030     if (SameSign && SameWidth)
11031       return Success(ECD->getInitVal(), E);
11032     else {
11033       // Get rid of mismatch (otherwise Success assertions will fail)
11034       // by computing a new value matching the type of E.
11035       llvm::APSInt Val = ECD->getInitVal();
11036       if (!SameSign)
11037         Val.setIsSigned(!ECD->getInitVal().isSigned());
11038       if (!SameWidth)
11039         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
11040       return Success(Val, E);
11041     }
11042   }
11043   return false;
11044 }
11045 
11046 /// Values returned by __builtin_classify_type, chosen to match the values
11047 /// produced by GCC's builtin.
11048 enum class GCCTypeClass {
11049   None = -1,
11050   Void = 0,
11051   Integer = 1,
11052   // GCC reserves 2 for character types, but instead classifies them as
11053   // integers.
11054   Enum = 3,
11055   Bool = 4,
11056   Pointer = 5,
11057   // GCC reserves 6 for references, but appears to never use it (because
11058   // expressions never have reference type, presumably).
11059   PointerToDataMember = 7,
11060   RealFloat = 8,
11061   Complex = 9,
11062   // GCC reserves 10 for functions, but does not use it since GCC version 6 due
11063   // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
11064   // GCC claims to reserve 11 for pointers to member functions, but *actually*
11065   // uses 12 for that purpose, same as for a class or struct. Maybe it
11066   // internally implements a pointer to member as a struct?  Who knows.
11067   PointerToMemberFunction = 12, // Not a bug, see above.
11068   ClassOrStruct = 12,
11069   Union = 13,
11070   // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
11071   // decay to pointer. (Prior to version 6 it was only used in C++ mode).
11072   // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
11073   // literals.
11074 };
11075 
11076 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11077 /// as GCC.
11078 static GCCTypeClass
11079 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
11080   assert(!T->isDependentType() && "unexpected dependent type");
11081 
11082   QualType CanTy = T.getCanonicalType();
11083   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
11084 
11085   switch (CanTy->getTypeClass()) {
11086 #define TYPE(ID, BASE)
11087 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
11088 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
11089 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
11090 #include "clang/AST/TypeNodes.inc"
11091   case Type::Auto:
11092   case Type::DeducedTemplateSpecialization:
11093       llvm_unreachable("unexpected non-canonical or dependent type");
11094 
11095   case Type::Builtin:
11096     switch (BT->getKind()) {
11097 #define BUILTIN_TYPE(ID, SINGLETON_ID)
11098 #define SIGNED_TYPE(ID, SINGLETON_ID) \
11099     case BuiltinType::ID: return GCCTypeClass::Integer;
11100 #define FLOATING_TYPE(ID, SINGLETON_ID) \
11101     case BuiltinType::ID: return GCCTypeClass::RealFloat;
11102 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
11103     case BuiltinType::ID: break;
11104 #include "clang/AST/BuiltinTypes.def"
11105     case BuiltinType::Void:
11106       return GCCTypeClass::Void;
11107 
11108     case BuiltinType::Bool:
11109       return GCCTypeClass::Bool;
11110 
11111     case BuiltinType::Char_U:
11112     case BuiltinType::UChar:
11113     case BuiltinType::WChar_U:
11114     case BuiltinType::Char8:
11115     case BuiltinType::Char16:
11116     case BuiltinType::Char32:
11117     case BuiltinType::UShort:
11118     case BuiltinType::UInt:
11119     case BuiltinType::ULong:
11120     case BuiltinType::ULongLong:
11121     case BuiltinType::UInt128:
11122       return GCCTypeClass::Integer;
11123 
11124     case BuiltinType::UShortAccum:
11125     case BuiltinType::UAccum:
11126     case BuiltinType::ULongAccum:
11127     case BuiltinType::UShortFract:
11128     case BuiltinType::UFract:
11129     case BuiltinType::ULongFract:
11130     case BuiltinType::SatUShortAccum:
11131     case BuiltinType::SatUAccum:
11132     case BuiltinType::SatULongAccum:
11133     case BuiltinType::SatUShortFract:
11134     case BuiltinType::SatUFract:
11135     case BuiltinType::SatULongFract:
11136       return GCCTypeClass::None;
11137 
11138     case BuiltinType::NullPtr:
11139 
11140     case BuiltinType::ObjCId:
11141     case BuiltinType::ObjCClass:
11142     case BuiltinType::ObjCSel:
11143 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
11144     case BuiltinType::Id:
11145 #include "clang/Basic/OpenCLImageTypes.def"
11146 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
11147     case BuiltinType::Id:
11148 #include "clang/Basic/OpenCLExtensionTypes.def"
11149     case BuiltinType::OCLSampler:
11150     case BuiltinType::OCLEvent:
11151     case BuiltinType::OCLClkEvent:
11152     case BuiltinType::OCLQueue:
11153     case BuiltinType::OCLReserveID:
11154 #define SVE_TYPE(Name, Id, SingletonId) \
11155     case BuiltinType::Id:
11156 #include "clang/Basic/AArch64SVEACLETypes.def"
11157 #define PPC_VECTOR_TYPE(Name, Id, Size) \
11158     case BuiltinType::Id:
11159 #include "clang/Basic/PPCTypes.def"
11160 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
11161 #include "clang/Basic/RISCVVTypes.def"
11162       return GCCTypeClass::None;
11163 
11164     case BuiltinType::Dependent:
11165       llvm_unreachable("unexpected dependent type");
11166     };
11167     llvm_unreachable("unexpected placeholder type");
11168 
11169   case Type::Enum:
11170     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
11171 
11172   case Type::Pointer:
11173   case Type::ConstantArray:
11174   case Type::VariableArray:
11175   case Type::IncompleteArray:
11176   case Type::FunctionNoProto:
11177   case Type::FunctionProto:
11178     return GCCTypeClass::Pointer;
11179 
11180   case Type::MemberPointer:
11181     return CanTy->isMemberDataPointerType()
11182                ? GCCTypeClass::PointerToDataMember
11183                : GCCTypeClass::PointerToMemberFunction;
11184 
11185   case Type::Complex:
11186     return GCCTypeClass::Complex;
11187 
11188   case Type::Record:
11189     return CanTy->isUnionType() ? GCCTypeClass::Union
11190                                 : GCCTypeClass::ClassOrStruct;
11191 
11192   case Type::Atomic:
11193     // GCC classifies _Atomic T the same as T.
11194     return EvaluateBuiltinClassifyType(
11195         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
11196 
11197   case Type::BlockPointer:
11198   case Type::Vector:
11199   case Type::ExtVector:
11200   case Type::ConstantMatrix:
11201   case Type::ObjCObject:
11202   case Type::ObjCInterface:
11203   case Type::ObjCObjectPointer:
11204   case Type::Pipe:
11205   case Type::BitInt:
11206     // GCC classifies vectors as None. We follow its lead and classify all
11207     // other types that don't fit into the regular classification the same way.
11208     return GCCTypeClass::None;
11209 
11210   case Type::LValueReference:
11211   case Type::RValueReference:
11212     llvm_unreachable("invalid type for expression");
11213   }
11214 
11215   llvm_unreachable("unexpected type class");
11216 }
11217 
11218 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11219 /// as GCC.
11220 static GCCTypeClass
11221 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
11222   // If no argument was supplied, default to None. This isn't
11223   // ideal, however it is what gcc does.
11224   if (E->getNumArgs() == 0)
11225     return GCCTypeClass::None;
11226 
11227   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
11228   // being an ICE, but still folds it to a constant using the type of the first
11229   // argument.
11230   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
11231 }
11232 
11233 /// EvaluateBuiltinConstantPForLValue - Determine the result of
11234 /// __builtin_constant_p when applied to the given pointer.
11235 ///
11236 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
11237 /// or it points to the first character of a string literal.
11238 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
11239   APValue::LValueBase Base = LV.getLValueBase();
11240   if (Base.isNull()) {
11241     // A null base is acceptable.
11242     return true;
11243   } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
11244     if (!isa<StringLiteral>(E))
11245       return false;
11246     return LV.getLValueOffset().isZero();
11247   } else if (Base.is<TypeInfoLValue>()) {
11248     // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
11249     // evaluate to true.
11250     return true;
11251   } else {
11252     // Any other base is not constant enough for GCC.
11253     return false;
11254   }
11255 }
11256 
11257 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
11258 /// GCC as we can manage.
11259 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
11260   // This evaluation is not permitted to have side-effects, so evaluate it in
11261   // a speculative evaluation context.
11262   SpeculativeEvaluationRAII SpeculativeEval(Info);
11263 
11264   // Constant-folding is always enabled for the operand of __builtin_constant_p
11265   // (even when the enclosing evaluation context otherwise requires a strict
11266   // language-specific constant expression).
11267   FoldConstant Fold(Info, true);
11268 
11269   QualType ArgType = Arg->getType();
11270 
11271   // __builtin_constant_p always has one operand. The rules which gcc follows
11272   // are not precisely documented, but are as follows:
11273   //
11274   //  - If the operand is of integral, floating, complex or enumeration type,
11275   //    and can be folded to a known value of that type, it returns 1.
11276   //  - If the operand can be folded to a pointer to the first character
11277   //    of a string literal (or such a pointer cast to an integral type)
11278   //    or to a null pointer or an integer cast to a pointer, it returns 1.
11279   //
11280   // Otherwise, it returns 0.
11281   //
11282   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
11283   // its support for this did not work prior to GCC 9 and is not yet well
11284   // understood.
11285   if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
11286       ArgType->isAnyComplexType() || ArgType->isPointerType() ||
11287       ArgType->isNullPtrType()) {
11288     APValue V;
11289     if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
11290       Fold.keepDiagnostics();
11291       return false;
11292     }
11293 
11294     // For a pointer (possibly cast to integer), there are special rules.
11295     if (V.getKind() == APValue::LValue)
11296       return EvaluateBuiltinConstantPForLValue(V);
11297 
11298     // Otherwise, any constant value is good enough.
11299     return V.hasValue();
11300   }
11301 
11302   // Anything else isn't considered to be sufficiently constant.
11303   return false;
11304 }
11305 
11306 /// Retrieves the "underlying object type" of the given expression,
11307 /// as used by __builtin_object_size.
11308 static QualType getObjectType(APValue::LValueBase B) {
11309   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
11310     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
11311       return VD->getType();
11312   } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
11313     if (isa<CompoundLiteralExpr>(E))
11314       return E->getType();
11315   } else if (B.is<TypeInfoLValue>()) {
11316     return B.getTypeInfoType();
11317   } else if (B.is<DynamicAllocLValue>()) {
11318     return B.getDynamicAllocType();
11319   }
11320 
11321   return QualType();
11322 }
11323 
11324 /// A more selective version of E->IgnoreParenCasts for
11325 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
11326 /// to change the type of E.
11327 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
11328 ///
11329 /// Always returns an RValue with a pointer representation.
11330 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
11331   assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
11332 
11333   auto *NoParens = E->IgnoreParens();
11334   auto *Cast = dyn_cast<CastExpr>(NoParens);
11335   if (Cast == nullptr)
11336     return NoParens;
11337 
11338   // We only conservatively allow a few kinds of casts, because this code is
11339   // inherently a simple solution that seeks to support the common case.
11340   auto CastKind = Cast->getCastKind();
11341   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
11342       CastKind != CK_AddressSpaceConversion)
11343     return NoParens;
11344 
11345   auto *SubExpr = Cast->getSubExpr();
11346   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
11347     return NoParens;
11348   return ignorePointerCastsAndParens(SubExpr);
11349 }
11350 
11351 /// Checks to see if the given LValue's Designator is at the end of the LValue's
11352 /// record layout. e.g.
11353 ///   struct { struct { int a, b; } fst, snd; } obj;
11354 ///   obj.fst   // no
11355 ///   obj.snd   // yes
11356 ///   obj.fst.a // no
11357 ///   obj.fst.b // no
11358 ///   obj.snd.a // no
11359 ///   obj.snd.b // yes
11360 ///
11361 /// Please note: this function is specialized for how __builtin_object_size
11362 /// views "objects".
11363 ///
11364 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
11365 /// correct result, it will always return true.
11366 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
11367   assert(!LVal.Designator.Invalid);
11368 
11369   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
11370     const RecordDecl *Parent = FD->getParent();
11371     Invalid = Parent->isInvalidDecl();
11372     if (Invalid || Parent->isUnion())
11373       return true;
11374     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
11375     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
11376   };
11377 
11378   auto &Base = LVal.getLValueBase();
11379   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
11380     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
11381       bool Invalid;
11382       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11383         return Invalid;
11384     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
11385       for (auto *FD : IFD->chain()) {
11386         bool Invalid;
11387         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
11388           return Invalid;
11389       }
11390     }
11391   }
11392 
11393   unsigned I = 0;
11394   QualType BaseType = getType(Base);
11395   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
11396     // If we don't know the array bound, conservatively assume we're looking at
11397     // the final array element.
11398     ++I;
11399     if (BaseType->isIncompleteArrayType())
11400       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
11401     else
11402       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
11403   }
11404 
11405   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
11406     const auto &Entry = LVal.Designator.Entries[I];
11407     if (BaseType->isArrayType()) {
11408       // Because __builtin_object_size treats arrays as objects, we can ignore
11409       // the index iff this is the last array in the Designator.
11410       if (I + 1 == E)
11411         return true;
11412       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
11413       uint64_t Index = Entry.getAsArrayIndex();
11414       if (Index + 1 != CAT->getSize())
11415         return false;
11416       BaseType = CAT->getElementType();
11417     } else if (BaseType->isAnyComplexType()) {
11418       const auto *CT = BaseType->castAs<ComplexType>();
11419       uint64_t Index = Entry.getAsArrayIndex();
11420       if (Index != 1)
11421         return false;
11422       BaseType = CT->getElementType();
11423     } else if (auto *FD = getAsField(Entry)) {
11424       bool Invalid;
11425       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11426         return Invalid;
11427       BaseType = FD->getType();
11428     } else {
11429       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
11430       return false;
11431     }
11432   }
11433   return true;
11434 }
11435 
11436 /// Tests to see if the LValue has a user-specified designator (that isn't
11437 /// necessarily valid). Note that this always returns 'true' if the LValue has
11438 /// an unsized array as its first designator entry, because there's currently no
11439 /// way to tell if the user typed *foo or foo[0].
11440 static bool refersToCompleteObject(const LValue &LVal) {
11441   if (LVal.Designator.Invalid)
11442     return false;
11443 
11444   if (!LVal.Designator.Entries.empty())
11445     return LVal.Designator.isMostDerivedAnUnsizedArray();
11446 
11447   if (!LVal.InvalidBase)
11448     return true;
11449 
11450   // If `E` is a MemberExpr, then the first part of the designator is hiding in
11451   // the LValueBase.
11452   const auto *E = LVal.Base.dyn_cast<const Expr *>();
11453   return !E || !isa<MemberExpr>(E);
11454 }
11455 
11456 /// Attempts to detect a user writing into a piece of memory that's impossible
11457 /// to figure out the size of by just using types.
11458 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
11459   const SubobjectDesignator &Designator = LVal.Designator;
11460   // Notes:
11461   // - Users can only write off of the end when we have an invalid base. Invalid
11462   //   bases imply we don't know where the memory came from.
11463   // - We used to be a bit more aggressive here; we'd only be conservative if
11464   //   the array at the end was flexible, or if it had 0 or 1 elements. This
11465   //   broke some common standard library extensions (PR30346), but was
11466   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
11467   //   with some sort of list. OTOH, it seems that GCC is always
11468   //   conservative with the last element in structs (if it's an array), so our
11469   //   current behavior is more compatible than an explicit list approach would
11470   //   be.
11471   return LVal.InvalidBase &&
11472          Designator.Entries.size() == Designator.MostDerivedPathLength &&
11473          Designator.MostDerivedIsArrayElement &&
11474          isDesignatorAtObjectEnd(Ctx, LVal);
11475 }
11476 
11477 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
11478 /// Fails if the conversion would cause loss of precision.
11479 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
11480                                             CharUnits &Result) {
11481   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
11482   if (Int.ugt(CharUnitsMax))
11483     return false;
11484   Result = CharUnits::fromQuantity(Int.getZExtValue());
11485   return true;
11486 }
11487 
11488 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
11489 /// determine how many bytes exist from the beginning of the object to either
11490 /// the end of the current subobject, or the end of the object itself, depending
11491 /// on what the LValue looks like + the value of Type.
11492 ///
11493 /// If this returns false, the value of Result is undefined.
11494 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
11495                                unsigned Type, const LValue &LVal,
11496                                CharUnits &EndOffset) {
11497   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
11498 
11499   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
11500     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
11501       return false;
11502     return HandleSizeof(Info, ExprLoc, Ty, Result);
11503   };
11504 
11505   // We want to evaluate the size of the entire object. This is a valid fallback
11506   // for when Type=1 and the designator is invalid, because we're asked for an
11507   // upper-bound.
11508   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
11509     // Type=3 wants a lower bound, so we can't fall back to this.
11510     if (Type == 3 && !DetermineForCompleteObject)
11511       return false;
11512 
11513     llvm::APInt APEndOffset;
11514     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11515         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11516       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11517 
11518     if (LVal.InvalidBase)
11519       return false;
11520 
11521     QualType BaseTy = getObjectType(LVal.getLValueBase());
11522     return CheckedHandleSizeof(BaseTy, EndOffset);
11523   }
11524 
11525   // We want to evaluate the size of a subobject.
11526   const SubobjectDesignator &Designator = LVal.Designator;
11527 
11528   // The following is a moderately common idiom in C:
11529   //
11530   // struct Foo { int a; char c[1]; };
11531   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
11532   // strcpy(&F->c[0], Bar);
11533   //
11534   // In order to not break too much legacy code, we need to support it.
11535   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
11536     // If we can resolve this to an alloc_size call, we can hand that back,
11537     // because we know for certain how many bytes there are to write to.
11538     llvm::APInt APEndOffset;
11539     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11540         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11541       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11542 
11543     // If we cannot determine the size of the initial allocation, then we can't
11544     // given an accurate upper-bound. However, we are still able to give
11545     // conservative lower-bounds for Type=3.
11546     if (Type == 1)
11547       return false;
11548   }
11549 
11550   CharUnits BytesPerElem;
11551   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
11552     return false;
11553 
11554   // According to the GCC documentation, we want the size of the subobject
11555   // denoted by the pointer. But that's not quite right -- what we actually
11556   // want is the size of the immediately-enclosing array, if there is one.
11557   int64_t ElemsRemaining;
11558   if (Designator.MostDerivedIsArrayElement &&
11559       Designator.Entries.size() == Designator.MostDerivedPathLength) {
11560     uint64_t ArraySize = Designator.getMostDerivedArraySize();
11561     uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
11562     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
11563   } else {
11564     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
11565   }
11566 
11567   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
11568   return true;
11569 }
11570 
11571 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
11572 /// returns true and stores the result in @p Size.
11573 ///
11574 /// If @p WasError is non-null, this will report whether the failure to evaluate
11575 /// is to be treated as an Error in IntExprEvaluator.
11576 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
11577                                          EvalInfo &Info, uint64_t &Size) {
11578   // Determine the denoted object.
11579   LValue LVal;
11580   {
11581     // The operand of __builtin_object_size is never evaluated for side-effects.
11582     // If there are any, but we can determine the pointed-to object anyway, then
11583     // ignore the side-effects.
11584     SpeculativeEvaluationRAII SpeculativeEval(Info);
11585     IgnoreSideEffectsRAII Fold(Info);
11586 
11587     if (E->isGLValue()) {
11588       // It's possible for us to be given GLValues if we're called via
11589       // Expr::tryEvaluateObjectSize.
11590       APValue RVal;
11591       if (!EvaluateAsRValue(Info, E, RVal))
11592         return false;
11593       LVal.setFrom(Info.Ctx, RVal);
11594     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
11595                                 /*InvalidBaseOK=*/true))
11596       return false;
11597   }
11598 
11599   // If we point to before the start of the object, there are no accessible
11600   // bytes.
11601   if (LVal.getLValueOffset().isNegative()) {
11602     Size = 0;
11603     return true;
11604   }
11605 
11606   CharUnits EndOffset;
11607   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
11608     return false;
11609 
11610   // If we've fallen outside of the end offset, just pretend there's nothing to
11611   // write to/read from.
11612   if (EndOffset <= LVal.getLValueOffset())
11613     Size = 0;
11614   else
11615     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
11616   return true;
11617 }
11618 
11619 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
11620   if (unsigned BuiltinOp = E->getBuiltinCallee())
11621     return VisitBuiltinCallExpr(E, BuiltinOp);
11622 
11623   return ExprEvaluatorBaseTy::VisitCallExpr(E);
11624 }
11625 
11626 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
11627                                      APValue &Val, APSInt &Alignment) {
11628   QualType SrcTy = E->getArg(0)->getType();
11629   if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
11630     return false;
11631   // Even though we are evaluating integer expressions we could get a pointer
11632   // argument for the __builtin_is_aligned() case.
11633   if (SrcTy->isPointerType()) {
11634     LValue Ptr;
11635     if (!EvaluatePointer(E->getArg(0), Ptr, Info))
11636       return false;
11637     Ptr.moveInto(Val);
11638   } else if (!SrcTy->isIntegralOrEnumerationType()) {
11639     Info.FFDiag(E->getArg(0));
11640     return false;
11641   } else {
11642     APSInt SrcInt;
11643     if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
11644       return false;
11645     assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
11646            "Bit widths must be the same");
11647     Val = APValue(SrcInt);
11648   }
11649   assert(Val.hasValue());
11650   return true;
11651 }
11652 
11653 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
11654                                             unsigned BuiltinOp) {
11655   switch (BuiltinOp) {
11656   default:
11657     return ExprEvaluatorBaseTy::VisitCallExpr(E);
11658 
11659   case Builtin::BI__builtin_dynamic_object_size:
11660   case Builtin::BI__builtin_object_size: {
11661     // The type was checked when we built the expression.
11662     unsigned Type =
11663         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11664     assert(Type <= 3 && "unexpected type");
11665 
11666     uint64_t Size;
11667     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
11668       return Success(Size, E);
11669 
11670     if (E->getArg(0)->HasSideEffects(Info.Ctx))
11671       return Success((Type & 2) ? 0 : -1, E);
11672 
11673     // Expression had no side effects, but we couldn't statically determine the
11674     // size of the referenced object.
11675     switch (Info.EvalMode) {
11676     case EvalInfo::EM_ConstantExpression:
11677     case EvalInfo::EM_ConstantFold:
11678     case EvalInfo::EM_IgnoreSideEffects:
11679       // Leave it to IR generation.
11680       return Error(E);
11681     case EvalInfo::EM_ConstantExpressionUnevaluated:
11682       // Reduce it to a constant now.
11683       return Success((Type & 2) ? 0 : -1, E);
11684     }
11685 
11686     llvm_unreachable("unexpected EvalMode");
11687   }
11688 
11689   case Builtin::BI__builtin_os_log_format_buffer_size: {
11690     analyze_os_log::OSLogBufferLayout Layout;
11691     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
11692     return Success(Layout.size().getQuantity(), E);
11693   }
11694 
11695   case Builtin::BI__builtin_is_aligned: {
11696     APValue Src;
11697     APSInt Alignment;
11698     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11699       return false;
11700     if (Src.isLValue()) {
11701       // If we evaluated a pointer, check the minimum known alignment.
11702       LValue Ptr;
11703       Ptr.setFrom(Info.Ctx, Src);
11704       CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
11705       CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
11706       // We can return true if the known alignment at the computed offset is
11707       // greater than the requested alignment.
11708       assert(PtrAlign.isPowerOfTwo());
11709       assert(Alignment.isPowerOf2());
11710       if (PtrAlign.getQuantity() >= Alignment)
11711         return Success(1, E);
11712       // If the alignment is not known to be sufficient, some cases could still
11713       // be aligned at run time. However, if the requested alignment is less or
11714       // equal to the base alignment and the offset is not aligned, we know that
11715       // the run-time value can never be aligned.
11716       if (BaseAlignment.getQuantity() >= Alignment &&
11717           PtrAlign.getQuantity() < Alignment)
11718         return Success(0, E);
11719       // Otherwise we can't infer whether the value is sufficiently aligned.
11720       // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
11721       //  in cases where we can't fully evaluate the pointer.
11722       Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
11723           << Alignment;
11724       return false;
11725     }
11726     assert(Src.isInt());
11727     return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
11728   }
11729   case Builtin::BI__builtin_align_up: {
11730     APValue Src;
11731     APSInt Alignment;
11732     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11733       return false;
11734     if (!Src.isInt())
11735       return Error(E);
11736     APSInt AlignedVal =
11737         APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
11738                Src.getInt().isUnsigned());
11739     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11740     return Success(AlignedVal, E);
11741   }
11742   case Builtin::BI__builtin_align_down: {
11743     APValue Src;
11744     APSInt Alignment;
11745     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11746       return false;
11747     if (!Src.isInt())
11748       return Error(E);
11749     APSInt AlignedVal =
11750         APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
11751     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11752     return Success(AlignedVal, E);
11753   }
11754 
11755   case Builtin::BI__builtin_bitreverse8:
11756   case Builtin::BI__builtin_bitreverse16:
11757   case Builtin::BI__builtin_bitreverse32:
11758   case Builtin::BI__builtin_bitreverse64: {
11759     APSInt Val;
11760     if (!EvaluateInteger(E->getArg(0), Val, Info))
11761       return false;
11762 
11763     return Success(Val.reverseBits(), E);
11764   }
11765 
11766   case Builtin::BI__builtin_bswap16:
11767   case Builtin::BI__builtin_bswap32:
11768   case Builtin::BI__builtin_bswap64: {
11769     APSInt Val;
11770     if (!EvaluateInteger(E->getArg(0), Val, Info))
11771       return false;
11772 
11773     return Success(Val.byteSwap(), E);
11774   }
11775 
11776   case Builtin::BI__builtin_classify_type:
11777     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
11778 
11779   case Builtin::BI__builtin_clrsb:
11780   case Builtin::BI__builtin_clrsbl:
11781   case Builtin::BI__builtin_clrsbll: {
11782     APSInt Val;
11783     if (!EvaluateInteger(E->getArg(0), Val, Info))
11784       return false;
11785 
11786     return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
11787   }
11788 
11789   case Builtin::BI__builtin_clz:
11790   case Builtin::BI__builtin_clzl:
11791   case Builtin::BI__builtin_clzll:
11792   case Builtin::BI__builtin_clzs: {
11793     APSInt Val;
11794     if (!EvaluateInteger(E->getArg(0), Val, Info))
11795       return false;
11796     if (!Val)
11797       return Error(E);
11798 
11799     return Success(Val.countLeadingZeros(), E);
11800   }
11801 
11802   case Builtin::BI__builtin_constant_p: {
11803     const Expr *Arg = E->getArg(0);
11804     if (EvaluateBuiltinConstantP(Info, Arg))
11805       return Success(true, E);
11806     if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
11807       // Outside a constant context, eagerly evaluate to false in the presence
11808       // of side-effects in order to avoid -Wunsequenced false-positives in
11809       // a branch on __builtin_constant_p(expr).
11810       return Success(false, E);
11811     }
11812     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11813     return false;
11814   }
11815 
11816   case Builtin::BI__builtin_is_constant_evaluated: {
11817     const auto *Callee = Info.CurrentCall->getCallee();
11818     if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
11819         (Info.CallStackDepth == 1 ||
11820          (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
11821           Callee->getIdentifier() &&
11822           Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
11823       // FIXME: Find a better way to avoid duplicated diagnostics.
11824       if (Info.EvalStatus.Diag)
11825         Info.report((Info.CallStackDepth == 1) ? E->getExprLoc()
11826                                                : Info.CurrentCall->CallLoc,
11827                     diag::warn_is_constant_evaluated_always_true_constexpr)
11828             << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
11829                                          : "std::is_constant_evaluated");
11830     }
11831 
11832     return Success(Info.InConstantContext, E);
11833   }
11834 
11835   case Builtin::BI__builtin_ctz:
11836   case Builtin::BI__builtin_ctzl:
11837   case Builtin::BI__builtin_ctzll:
11838   case Builtin::BI__builtin_ctzs: {
11839     APSInt Val;
11840     if (!EvaluateInteger(E->getArg(0), Val, Info))
11841       return false;
11842     if (!Val)
11843       return Error(E);
11844 
11845     return Success(Val.countTrailingZeros(), E);
11846   }
11847 
11848   case Builtin::BI__builtin_eh_return_data_regno: {
11849     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11850     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
11851     return Success(Operand, E);
11852   }
11853 
11854   case Builtin::BI__builtin_expect:
11855   case Builtin::BI__builtin_expect_with_probability:
11856     return Visit(E->getArg(0));
11857 
11858   case Builtin::BI__builtin_ffs:
11859   case Builtin::BI__builtin_ffsl:
11860   case Builtin::BI__builtin_ffsll: {
11861     APSInt Val;
11862     if (!EvaluateInteger(E->getArg(0), Val, Info))
11863       return false;
11864 
11865     unsigned N = Val.countTrailingZeros();
11866     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
11867   }
11868 
11869   case Builtin::BI__builtin_fpclassify: {
11870     APFloat Val(0.0);
11871     if (!EvaluateFloat(E->getArg(5), Val, Info))
11872       return false;
11873     unsigned Arg;
11874     switch (Val.getCategory()) {
11875     case APFloat::fcNaN: Arg = 0; break;
11876     case APFloat::fcInfinity: Arg = 1; break;
11877     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
11878     case APFloat::fcZero: Arg = 4; break;
11879     }
11880     return Visit(E->getArg(Arg));
11881   }
11882 
11883   case Builtin::BI__builtin_isinf_sign: {
11884     APFloat Val(0.0);
11885     return EvaluateFloat(E->getArg(0), Val, Info) &&
11886            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
11887   }
11888 
11889   case Builtin::BI__builtin_isinf: {
11890     APFloat Val(0.0);
11891     return EvaluateFloat(E->getArg(0), Val, Info) &&
11892            Success(Val.isInfinity() ? 1 : 0, E);
11893   }
11894 
11895   case Builtin::BI__builtin_isfinite: {
11896     APFloat Val(0.0);
11897     return EvaluateFloat(E->getArg(0), Val, Info) &&
11898            Success(Val.isFinite() ? 1 : 0, E);
11899   }
11900 
11901   case Builtin::BI__builtin_isnan: {
11902     APFloat Val(0.0);
11903     return EvaluateFloat(E->getArg(0), Val, Info) &&
11904            Success(Val.isNaN() ? 1 : 0, E);
11905   }
11906 
11907   case Builtin::BI__builtin_isnormal: {
11908     APFloat Val(0.0);
11909     return EvaluateFloat(E->getArg(0), Val, Info) &&
11910            Success(Val.isNormal() ? 1 : 0, E);
11911   }
11912 
11913   case Builtin::BI__builtin_parity:
11914   case Builtin::BI__builtin_parityl:
11915   case Builtin::BI__builtin_parityll: {
11916     APSInt Val;
11917     if (!EvaluateInteger(E->getArg(0), Val, Info))
11918       return false;
11919 
11920     return Success(Val.countPopulation() % 2, E);
11921   }
11922 
11923   case Builtin::BI__builtin_popcount:
11924   case Builtin::BI__builtin_popcountl:
11925   case Builtin::BI__builtin_popcountll: {
11926     APSInt Val;
11927     if (!EvaluateInteger(E->getArg(0), Val, Info))
11928       return false;
11929 
11930     return Success(Val.countPopulation(), E);
11931   }
11932 
11933   case Builtin::BI__builtin_rotateleft8:
11934   case Builtin::BI__builtin_rotateleft16:
11935   case Builtin::BI__builtin_rotateleft32:
11936   case Builtin::BI__builtin_rotateleft64:
11937   case Builtin::BI_rotl8: // Microsoft variants of rotate right
11938   case Builtin::BI_rotl16:
11939   case Builtin::BI_rotl:
11940   case Builtin::BI_lrotl:
11941   case Builtin::BI_rotl64: {
11942     APSInt Val, Amt;
11943     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
11944         !EvaluateInteger(E->getArg(1), Amt, Info))
11945       return false;
11946 
11947     return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
11948   }
11949 
11950   case Builtin::BI__builtin_rotateright8:
11951   case Builtin::BI__builtin_rotateright16:
11952   case Builtin::BI__builtin_rotateright32:
11953   case Builtin::BI__builtin_rotateright64:
11954   case Builtin::BI_rotr8: // Microsoft variants of rotate right
11955   case Builtin::BI_rotr16:
11956   case Builtin::BI_rotr:
11957   case Builtin::BI_lrotr:
11958   case Builtin::BI_rotr64: {
11959     APSInt Val, Amt;
11960     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
11961         !EvaluateInteger(E->getArg(1), Amt, Info))
11962       return false;
11963 
11964     return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
11965   }
11966 
11967   case Builtin::BIstrlen:
11968   case Builtin::BIwcslen:
11969     // A call to strlen is not a constant expression.
11970     if (Info.getLangOpts().CPlusPlus11)
11971       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11972         << /*isConstexpr*/0 << /*isConstructor*/0
11973         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11974     else
11975       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11976     LLVM_FALLTHROUGH;
11977   case Builtin::BI__builtin_strlen:
11978   case Builtin::BI__builtin_wcslen: {
11979     // As an extension, we support __builtin_strlen() as a constant expression,
11980     // and support folding strlen() to a constant.
11981     uint64_t StrLen;
11982     if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
11983       return Success(StrLen, E);
11984     return false;
11985   }
11986 
11987   case Builtin::BIstrcmp:
11988   case Builtin::BIwcscmp:
11989   case Builtin::BIstrncmp:
11990   case Builtin::BIwcsncmp:
11991   case Builtin::BImemcmp:
11992   case Builtin::BIbcmp:
11993   case Builtin::BIwmemcmp:
11994     // A call to strlen is not a constant expression.
11995     if (Info.getLangOpts().CPlusPlus11)
11996       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11997         << /*isConstexpr*/0 << /*isConstructor*/0
11998         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11999     else
12000       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12001     LLVM_FALLTHROUGH;
12002   case Builtin::BI__builtin_strcmp:
12003   case Builtin::BI__builtin_wcscmp:
12004   case Builtin::BI__builtin_strncmp:
12005   case Builtin::BI__builtin_wcsncmp:
12006   case Builtin::BI__builtin_memcmp:
12007   case Builtin::BI__builtin_bcmp:
12008   case Builtin::BI__builtin_wmemcmp: {
12009     LValue String1, String2;
12010     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
12011         !EvaluatePointer(E->getArg(1), String2, Info))
12012       return false;
12013 
12014     uint64_t MaxLength = uint64_t(-1);
12015     if (BuiltinOp != Builtin::BIstrcmp &&
12016         BuiltinOp != Builtin::BIwcscmp &&
12017         BuiltinOp != Builtin::BI__builtin_strcmp &&
12018         BuiltinOp != Builtin::BI__builtin_wcscmp) {
12019       APSInt N;
12020       if (!EvaluateInteger(E->getArg(2), N, Info))
12021         return false;
12022       MaxLength = N.getExtValue();
12023     }
12024 
12025     // Empty substrings compare equal by definition.
12026     if (MaxLength == 0u)
12027       return Success(0, E);
12028 
12029     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
12030         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
12031         String1.Designator.Invalid || String2.Designator.Invalid)
12032       return false;
12033 
12034     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
12035     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
12036 
12037     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
12038                      BuiltinOp == Builtin::BIbcmp ||
12039                      BuiltinOp == Builtin::BI__builtin_memcmp ||
12040                      BuiltinOp == Builtin::BI__builtin_bcmp;
12041 
12042     assert(IsRawByte ||
12043            (Info.Ctx.hasSameUnqualifiedType(
12044                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
12045             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
12046 
12047     // For memcmp, allow comparing any arrays of '[[un]signed] char' or
12048     // 'char8_t', but no other types.
12049     if (IsRawByte &&
12050         !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
12051       // FIXME: Consider using our bit_cast implementation to support this.
12052       Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
12053           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
12054           << CharTy1 << CharTy2;
12055       return false;
12056     }
12057 
12058     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
12059       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
12060              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
12061              Char1.isInt() && Char2.isInt();
12062     };
12063     const auto &AdvanceElems = [&] {
12064       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
12065              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
12066     };
12067 
12068     bool StopAtNull =
12069         (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
12070          BuiltinOp != Builtin::BIwmemcmp &&
12071          BuiltinOp != Builtin::BI__builtin_memcmp &&
12072          BuiltinOp != Builtin::BI__builtin_bcmp &&
12073          BuiltinOp != Builtin::BI__builtin_wmemcmp);
12074     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
12075                   BuiltinOp == Builtin::BIwcsncmp ||
12076                   BuiltinOp == Builtin::BIwmemcmp ||
12077                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
12078                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
12079                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
12080 
12081     for (; MaxLength; --MaxLength) {
12082       APValue Char1, Char2;
12083       if (!ReadCurElems(Char1, Char2))
12084         return false;
12085       if (Char1.getInt().ne(Char2.getInt())) {
12086         if (IsWide) // wmemcmp compares with wchar_t signedness.
12087           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
12088         // memcmp always compares unsigned chars.
12089         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
12090       }
12091       if (StopAtNull && !Char1.getInt())
12092         return Success(0, E);
12093       assert(!(StopAtNull && !Char2.getInt()));
12094       if (!AdvanceElems())
12095         return false;
12096     }
12097     // We hit the strncmp / memcmp limit.
12098     return Success(0, E);
12099   }
12100 
12101   case Builtin::BI__atomic_always_lock_free:
12102   case Builtin::BI__atomic_is_lock_free:
12103   case Builtin::BI__c11_atomic_is_lock_free: {
12104     APSInt SizeVal;
12105     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
12106       return false;
12107 
12108     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
12109     // of two less than or equal to the maximum inline atomic width, we know it
12110     // is lock-free.  If the size isn't a power of two, or greater than the
12111     // maximum alignment where we promote atomics, we know it is not lock-free
12112     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
12113     // the answer can only be determined at runtime; for example, 16-byte
12114     // atomics have lock-free implementations on some, but not all,
12115     // x86-64 processors.
12116 
12117     // Check power-of-two.
12118     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
12119     if (Size.isPowerOfTwo()) {
12120       // Check against inlining width.
12121       unsigned InlineWidthBits =
12122           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
12123       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
12124         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
12125             Size == CharUnits::One() ||
12126             E->getArg(1)->isNullPointerConstant(Info.Ctx,
12127                                                 Expr::NPC_NeverValueDependent))
12128           // OK, we will inline appropriately-aligned operations of this size,
12129           // and _Atomic(T) is appropriately-aligned.
12130           return Success(1, E);
12131 
12132         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
12133           castAs<PointerType>()->getPointeeType();
12134         if (!PointeeType->isIncompleteType() &&
12135             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
12136           // OK, we will inline operations on this object.
12137           return Success(1, E);
12138         }
12139       }
12140     }
12141 
12142     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
12143         Success(0, E) : Error(E);
12144   }
12145   case Builtin::BI__builtin_add_overflow:
12146   case Builtin::BI__builtin_sub_overflow:
12147   case Builtin::BI__builtin_mul_overflow:
12148   case Builtin::BI__builtin_sadd_overflow:
12149   case Builtin::BI__builtin_uadd_overflow:
12150   case Builtin::BI__builtin_uaddl_overflow:
12151   case Builtin::BI__builtin_uaddll_overflow:
12152   case Builtin::BI__builtin_usub_overflow:
12153   case Builtin::BI__builtin_usubl_overflow:
12154   case Builtin::BI__builtin_usubll_overflow:
12155   case Builtin::BI__builtin_umul_overflow:
12156   case Builtin::BI__builtin_umull_overflow:
12157   case Builtin::BI__builtin_umulll_overflow:
12158   case Builtin::BI__builtin_saddl_overflow:
12159   case Builtin::BI__builtin_saddll_overflow:
12160   case Builtin::BI__builtin_ssub_overflow:
12161   case Builtin::BI__builtin_ssubl_overflow:
12162   case Builtin::BI__builtin_ssubll_overflow:
12163   case Builtin::BI__builtin_smul_overflow:
12164   case Builtin::BI__builtin_smull_overflow:
12165   case Builtin::BI__builtin_smulll_overflow: {
12166     LValue ResultLValue;
12167     APSInt LHS, RHS;
12168 
12169     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
12170     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
12171         !EvaluateInteger(E->getArg(1), RHS, Info) ||
12172         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
12173       return false;
12174 
12175     APSInt Result;
12176     bool DidOverflow = false;
12177 
12178     // If the types don't have to match, enlarge all 3 to the largest of them.
12179     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12180         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12181         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12182       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
12183                       ResultType->isSignedIntegerOrEnumerationType();
12184       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
12185                       ResultType->isSignedIntegerOrEnumerationType();
12186       uint64_t LHSSize = LHS.getBitWidth();
12187       uint64_t RHSSize = RHS.getBitWidth();
12188       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
12189       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
12190 
12191       // Add an additional bit if the signedness isn't uniformly agreed to. We
12192       // could do this ONLY if there is a signed and an unsigned that both have
12193       // MaxBits, but the code to check that is pretty nasty.  The issue will be
12194       // caught in the shrink-to-result later anyway.
12195       if (IsSigned && !AllSigned)
12196         ++MaxBits;
12197 
12198       LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
12199       RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
12200       Result = APSInt(MaxBits, !IsSigned);
12201     }
12202 
12203     // Find largest int.
12204     switch (BuiltinOp) {
12205     default:
12206       llvm_unreachable("Invalid value for BuiltinOp");
12207     case Builtin::BI__builtin_add_overflow:
12208     case Builtin::BI__builtin_sadd_overflow:
12209     case Builtin::BI__builtin_saddl_overflow:
12210     case Builtin::BI__builtin_saddll_overflow:
12211     case Builtin::BI__builtin_uadd_overflow:
12212     case Builtin::BI__builtin_uaddl_overflow:
12213     case Builtin::BI__builtin_uaddll_overflow:
12214       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
12215                               : LHS.uadd_ov(RHS, DidOverflow);
12216       break;
12217     case Builtin::BI__builtin_sub_overflow:
12218     case Builtin::BI__builtin_ssub_overflow:
12219     case Builtin::BI__builtin_ssubl_overflow:
12220     case Builtin::BI__builtin_ssubll_overflow:
12221     case Builtin::BI__builtin_usub_overflow:
12222     case Builtin::BI__builtin_usubl_overflow:
12223     case Builtin::BI__builtin_usubll_overflow:
12224       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
12225                               : LHS.usub_ov(RHS, DidOverflow);
12226       break;
12227     case Builtin::BI__builtin_mul_overflow:
12228     case Builtin::BI__builtin_smul_overflow:
12229     case Builtin::BI__builtin_smull_overflow:
12230     case Builtin::BI__builtin_smulll_overflow:
12231     case Builtin::BI__builtin_umul_overflow:
12232     case Builtin::BI__builtin_umull_overflow:
12233     case Builtin::BI__builtin_umulll_overflow:
12234       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
12235                               : LHS.umul_ov(RHS, DidOverflow);
12236       break;
12237     }
12238 
12239     // In the case where multiple sizes are allowed, truncate and see if
12240     // the values are the same.
12241     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12242         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12243         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12244       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
12245       // since it will give us the behavior of a TruncOrSelf in the case where
12246       // its parameter <= its size.  We previously set Result to be at least the
12247       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
12248       // will work exactly like TruncOrSelf.
12249       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
12250       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
12251 
12252       if (!APSInt::isSameValue(Temp, Result))
12253         DidOverflow = true;
12254       Result = Temp;
12255     }
12256 
12257     APValue APV{Result};
12258     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
12259       return false;
12260     return Success(DidOverflow, E);
12261   }
12262   }
12263 }
12264 
12265 /// Determine whether this is a pointer past the end of the complete
12266 /// object referred to by the lvalue.
12267 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
12268                                             const LValue &LV) {
12269   // A null pointer can be viewed as being "past the end" but we don't
12270   // choose to look at it that way here.
12271   if (!LV.getLValueBase())
12272     return false;
12273 
12274   // If the designator is valid and refers to a subobject, we're not pointing
12275   // past the end.
12276   if (!LV.getLValueDesignator().Invalid &&
12277       !LV.getLValueDesignator().isOnePastTheEnd())
12278     return false;
12279 
12280   // A pointer to an incomplete type might be past-the-end if the type's size is
12281   // zero.  We cannot tell because the type is incomplete.
12282   QualType Ty = getType(LV.getLValueBase());
12283   if (Ty->isIncompleteType())
12284     return true;
12285 
12286   // We're a past-the-end pointer if we point to the byte after the object,
12287   // no matter what our type or path is.
12288   auto Size = Ctx.getTypeSizeInChars(Ty);
12289   return LV.getLValueOffset() == Size;
12290 }
12291 
12292 namespace {
12293 
12294 /// Data recursive integer evaluator of certain binary operators.
12295 ///
12296 /// We use a data recursive algorithm for binary operators so that we are able
12297 /// to handle extreme cases of chained binary operators without causing stack
12298 /// overflow.
12299 class DataRecursiveIntBinOpEvaluator {
12300   struct EvalResult {
12301     APValue Val;
12302     bool Failed;
12303 
12304     EvalResult() : Failed(false) { }
12305 
12306     void swap(EvalResult &RHS) {
12307       Val.swap(RHS.Val);
12308       Failed = RHS.Failed;
12309       RHS.Failed = false;
12310     }
12311   };
12312 
12313   struct Job {
12314     const Expr *E;
12315     EvalResult LHSResult; // meaningful only for binary operator expression.
12316     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
12317 
12318     Job() = default;
12319     Job(Job &&) = default;
12320 
12321     void startSpeculativeEval(EvalInfo &Info) {
12322       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
12323     }
12324 
12325   private:
12326     SpeculativeEvaluationRAII SpecEvalRAII;
12327   };
12328 
12329   SmallVector<Job, 16> Queue;
12330 
12331   IntExprEvaluator &IntEval;
12332   EvalInfo &Info;
12333   APValue &FinalResult;
12334 
12335 public:
12336   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
12337     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
12338 
12339   /// True if \param E is a binary operator that we are going to handle
12340   /// data recursively.
12341   /// We handle binary operators that are comma, logical, or that have operands
12342   /// with integral or enumeration type.
12343   static bool shouldEnqueue(const BinaryOperator *E) {
12344     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
12345            (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() &&
12346             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12347             E->getRHS()->getType()->isIntegralOrEnumerationType());
12348   }
12349 
12350   bool Traverse(const BinaryOperator *E) {
12351     enqueue(E);
12352     EvalResult PrevResult;
12353     while (!Queue.empty())
12354       process(PrevResult);
12355 
12356     if (PrevResult.Failed) return false;
12357 
12358     FinalResult.swap(PrevResult.Val);
12359     return true;
12360   }
12361 
12362 private:
12363   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
12364     return IntEval.Success(Value, E, Result);
12365   }
12366   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
12367     return IntEval.Success(Value, E, Result);
12368   }
12369   bool Error(const Expr *E) {
12370     return IntEval.Error(E);
12371   }
12372   bool Error(const Expr *E, diag::kind D) {
12373     return IntEval.Error(E, D);
12374   }
12375 
12376   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
12377     return Info.CCEDiag(E, D);
12378   }
12379 
12380   // Returns true if visiting the RHS is necessary, false otherwise.
12381   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12382                          bool &SuppressRHSDiags);
12383 
12384   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12385                   const BinaryOperator *E, APValue &Result);
12386 
12387   void EvaluateExpr(const Expr *E, EvalResult &Result) {
12388     Result.Failed = !Evaluate(Result.Val, Info, E);
12389     if (Result.Failed)
12390       Result.Val = APValue();
12391   }
12392 
12393   void process(EvalResult &Result);
12394 
12395   void enqueue(const Expr *E) {
12396     E = E->IgnoreParens();
12397     Queue.resize(Queue.size()+1);
12398     Queue.back().E = E;
12399     Queue.back().Kind = Job::AnyExprKind;
12400   }
12401 };
12402 
12403 }
12404 
12405 bool DataRecursiveIntBinOpEvaluator::
12406        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12407                          bool &SuppressRHSDiags) {
12408   if (E->getOpcode() == BO_Comma) {
12409     // Ignore LHS but note if we could not evaluate it.
12410     if (LHSResult.Failed)
12411       return Info.noteSideEffect();
12412     return true;
12413   }
12414 
12415   if (E->isLogicalOp()) {
12416     bool LHSAsBool;
12417     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
12418       // We were able to evaluate the LHS, see if we can get away with not
12419       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
12420       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
12421         Success(LHSAsBool, E, LHSResult.Val);
12422         return false; // Ignore RHS
12423       }
12424     } else {
12425       LHSResult.Failed = true;
12426 
12427       // Since we weren't able to evaluate the left hand side, it
12428       // might have had side effects.
12429       if (!Info.noteSideEffect())
12430         return false;
12431 
12432       // We can't evaluate the LHS; however, sometimes the result
12433       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12434       // Don't ignore RHS and suppress diagnostics from this arm.
12435       SuppressRHSDiags = true;
12436     }
12437 
12438     return true;
12439   }
12440 
12441   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12442          E->getRHS()->getType()->isIntegralOrEnumerationType());
12443 
12444   if (LHSResult.Failed && !Info.noteFailure())
12445     return false; // Ignore RHS;
12446 
12447   return true;
12448 }
12449 
12450 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
12451                                     bool IsSub) {
12452   // Compute the new offset in the appropriate width, wrapping at 64 bits.
12453   // FIXME: When compiling for a 32-bit target, we should use 32-bit
12454   // offsets.
12455   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
12456   CharUnits &Offset = LVal.getLValueOffset();
12457   uint64_t Offset64 = Offset.getQuantity();
12458   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
12459   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
12460                                          : Offset64 + Index64);
12461 }
12462 
12463 bool DataRecursiveIntBinOpEvaluator::
12464        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12465                   const BinaryOperator *E, APValue &Result) {
12466   if (E->getOpcode() == BO_Comma) {
12467     if (RHSResult.Failed)
12468       return false;
12469     Result = RHSResult.Val;
12470     return true;
12471   }
12472 
12473   if (E->isLogicalOp()) {
12474     bool lhsResult, rhsResult;
12475     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
12476     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
12477 
12478     if (LHSIsOK) {
12479       if (RHSIsOK) {
12480         if (E->getOpcode() == BO_LOr)
12481           return Success(lhsResult || rhsResult, E, Result);
12482         else
12483           return Success(lhsResult && rhsResult, E, Result);
12484       }
12485     } else {
12486       if (RHSIsOK) {
12487         // We can't evaluate the LHS; however, sometimes the result
12488         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12489         if (rhsResult == (E->getOpcode() == BO_LOr))
12490           return Success(rhsResult, E, Result);
12491       }
12492     }
12493 
12494     return false;
12495   }
12496 
12497   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12498          E->getRHS()->getType()->isIntegralOrEnumerationType());
12499 
12500   if (LHSResult.Failed || RHSResult.Failed)
12501     return false;
12502 
12503   const APValue &LHSVal = LHSResult.Val;
12504   const APValue &RHSVal = RHSResult.Val;
12505 
12506   // Handle cases like (unsigned long)&a + 4.
12507   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
12508     Result = LHSVal;
12509     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
12510     return true;
12511   }
12512 
12513   // Handle cases like 4 + (unsigned long)&a
12514   if (E->getOpcode() == BO_Add &&
12515       RHSVal.isLValue() && LHSVal.isInt()) {
12516     Result = RHSVal;
12517     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
12518     return true;
12519   }
12520 
12521   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
12522     // Handle (intptr_t)&&A - (intptr_t)&&B.
12523     if (!LHSVal.getLValueOffset().isZero() ||
12524         !RHSVal.getLValueOffset().isZero())
12525       return false;
12526     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
12527     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
12528     if (!LHSExpr || !RHSExpr)
12529       return false;
12530     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12531     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12532     if (!LHSAddrExpr || !RHSAddrExpr)
12533       return false;
12534     // Make sure both labels come from the same function.
12535     if (LHSAddrExpr->getLabel()->getDeclContext() !=
12536         RHSAddrExpr->getLabel()->getDeclContext())
12537       return false;
12538     Result = APValue(LHSAddrExpr, RHSAddrExpr);
12539     return true;
12540   }
12541 
12542   // All the remaining cases expect both operands to be an integer
12543   if (!LHSVal.isInt() || !RHSVal.isInt())
12544     return Error(E);
12545 
12546   // Set up the width and signedness manually, in case it can't be deduced
12547   // from the operation we're performing.
12548   // FIXME: Don't do this in the cases where we can deduce it.
12549   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
12550                E->getType()->isUnsignedIntegerOrEnumerationType());
12551   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
12552                          RHSVal.getInt(), Value))
12553     return false;
12554   return Success(Value, E, Result);
12555 }
12556 
12557 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
12558   Job &job = Queue.back();
12559 
12560   switch (job.Kind) {
12561     case Job::AnyExprKind: {
12562       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
12563         if (shouldEnqueue(Bop)) {
12564           job.Kind = Job::BinOpKind;
12565           enqueue(Bop->getLHS());
12566           return;
12567         }
12568       }
12569 
12570       EvaluateExpr(job.E, Result);
12571       Queue.pop_back();
12572       return;
12573     }
12574 
12575     case Job::BinOpKind: {
12576       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12577       bool SuppressRHSDiags = false;
12578       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
12579         Queue.pop_back();
12580         return;
12581       }
12582       if (SuppressRHSDiags)
12583         job.startSpeculativeEval(Info);
12584       job.LHSResult.swap(Result);
12585       job.Kind = Job::BinOpVisitedLHSKind;
12586       enqueue(Bop->getRHS());
12587       return;
12588     }
12589 
12590     case Job::BinOpVisitedLHSKind: {
12591       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12592       EvalResult RHS;
12593       RHS.swap(Result);
12594       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
12595       Queue.pop_back();
12596       return;
12597     }
12598   }
12599 
12600   llvm_unreachable("Invalid Job::Kind!");
12601 }
12602 
12603 namespace {
12604 enum class CmpResult {
12605   Unequal,
12606   Less,
12607   Equal,
12608   Greater,
12609   Unordered,
12610 };
12611 }
12612 
12613 template <class SuccessCB, class AfterCB>
12614 static bool
12615 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
12616                                  SuccessCB &&Success, AfterCB &&DoAfter) {
12617   assert(!E->isValueDependent());
12618   assert(E->isComparisonOp() && "expected comparison operator");
12619   assert((E->getOpcode() == BO_Cmp ||
12620           E->getType()->isIntegralOrEnumerationType()) &&
12621          "unsupported binary expression evaluation");
12622   auto Error = [&](const Expr *E) {
12623     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12624     return false;
12625   };
12626 
12627   bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
12628   bool IsEquality = E->isEqualityOp();
12629 
12630   QualType LHSTy = E->getLHS()->getType();
12631   QualType RHSTy = E->getRHS()->getType();
12632 
12633   if (LHSTy->isIntegralOrEnumerationType() &&
12634       RHSTy->isIntegralOrEnumerationType()) {
12635     APSInt LHS, RHS;
12636     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
12637     if (!LHSOK && !Info.noteFailure())
12638       return false;
12639     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
12640       return false;
12641     if (LHS < RHS)
12642       return Success(CmpResult::Less, E);
12643     if (LHS > RHS)
12644       return Success(CmpResult::Greater, E);
12645     return Success(CmpResult::Equal, E);
12646   }
12647 
12648   if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
12649     APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
12650     APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
12651 
12652     bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
12653     if (!LHSOK && !Info.noteFailure())
12654       return false;
12655     if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
12656       return false;
12657     if (LHSFX < RHSFX)
12658       return Success(CmpResult::Less, E);
12659     if (LHSFX > RHSFX)
12660       return Success(CmpResult::Greater, E);
12661     return Success(CmpResult::Equal, E);
12662   }
12663 
12664   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
12665     ComplexValue LHS, RHS;
12666     bool LHSOK;
12667     if (E->isAssignmentOp()) {
12668       LValue LV;
12669       EvaluateLValue(E->getLHS(), LV, Info);
12670       LHSOK = false;
12671     } else if (LHSTy->isRealFloatingType()) {
12672       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
12673       if (LHSOK) {
12674         LHS.makeComplexFloat();
12675         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
12676       }
12677     } else {
12678       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
12679     }
12680     if (!LHSOK && !Info.noteFailure())
12681       return false;
12682 
12683     if (E->getRHS()->getType()->isRealFloatingType()) {
12684       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
12685         return false;
12686       RHS.makeComplexFloat();
12687       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
12688     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
12689       return false;
12690 
12691     if (LHS.isComplexFloat()) {
12692       APFloat::cmpResult CR_r =
12693         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
12694       APFloat::cmpResult CR_i =
12695         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
12696       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
12697       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12698     } else {
12699       assert(IsEquality && "invalid complex comparison");
12700       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
12701                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
12702       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12703     }
12704   }
12705 
12706   if (LHSTy->isRealFloatingType() &&
12707       RHSTy->isRealFloatingType()) {
12708     APFloat RHS(0.0), LHS(0.0);
12709 
12710     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
12711     if (!LHSOK && !Info.noteFailure())
12712       return false;
12713 
12714     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
12715       return false;
12716 
12717     assert(E->isComparisonOp() && "Invalid binary operator!");
12718     llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
12719     if (!Info.InConstantContext &&
12720         APFloatCmpResult == APFloat::cmpUnordered &&
12721         E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
12722       // Note: Compares may raise invalid in some cases involving NaN or sNaN.
12723       Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
12724       return false;
12725     }
12726     auto GetCmpRes = [&]() {
12727       switch (APFloatCmpResult) {
12728       case APFloat::cmpEqual:
12729         return CmpResult::Equal;
12730       case APFloat::cmpLessThan:
12731         return CmpResult::Less;
12732       case APFloat::cmpGreaterThan:
12733         return CmpResult::Greater;
12734       case APFloat::cmpUnordered:
12735         return CmpResult::Unordered;
12736       }
12737       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
12738     };
12739     return Success(GetCmpRes(), E);
12740   }
12741 
12742   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
12743     LValue LHSValue, RHSValue;
12744 
12745     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12746     if (!LHSOK && !Info.noteFailure())
12747       return false;
12748 
12749     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12750       return false;
12751 
12752     // Reject differing bases from the normal codepath; we special-case
12753     // comparisons to null.
12754     if (!HasSameBase(LHSValue, RHSValue)) {
12755       // Inequalities and subtractions between unrelated pointers have
12756       // unspecified or undefined behavior.
12757       if (!IsEquality) {
12758         Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified);
12759         return false;
12760       }
12761       // A constant address may compare equal to the address of a symbol.
12762       // The one exception is that address of an object cannot compare equal
12763       // to a null pointer constant.
12764       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
12765           (!RHSValue.Base && !RHSValue.Offset.isZero()))
12766         return Error(E);
12767       // It's implementation-defined whether distinct literals will have
12768       // distinct addresses. In clang, the result of such a comparison is
12769       // unspecified, so it is not a constant expression. However, we do know
12770       // that the address of a literal will be non-null.
12771       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
12772           LHSValue.Base && RHSValue.Base)
12773         return Error(E);
12774       // We can't tell whether weak symbols will end up pointing to the same
12775       // object.
12776       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
12777         return Error(E);
12778       // We can't compare the address of the start of one object with the
12779       // past-the-end address of another object, per C++ DR1652.
12780       if ((LHSValue.Base && LHSValue.Offset.isZero() &&
12781            isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
12782           (RHSValue.Base && RHSValue.Offset.isZero() &&
12783            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
12784         return Error(E);
12785       // We can't tell whether an object is at the same address as another
12786       // zero sized object.
12787       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
12788           (LHSValue.Base && isZeroSized(RHSValue)))
12789         return Error(E);
12790       return Success(CmpResult::Unequal, E);
12791     }
12792 
12793     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12794     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12795 
12796     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12797     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12798 
12799     // C++11 [expr.rel]p3:
12800     //   Pointers to void (after pointer conversions) can be compared, with a
12801     //   result defined as follows: If both pointers represent the same
12802     //   address or are both the null pointer value, the result is true if the
12803     //   operator is <= or >= and false otherwise; otherwise the result is
12804     //   unspecified.
12805     // We interpret this as applying to pointers to *cv* void.
12806     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
12807       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
12808 
12809     // C++11 [expr.rel]p2:
12810     // - If two pointers point to non-static data members of the same object,
12811     //   or to subobjects or array elements fo such members, recursively, the
12812     //   pointer to the later declared member compares greater provided the
12813     //   two members have the same access control and provided their class is
12814     //   not a union.
12815     //   [...]
12816     // - Otherwise pointer comparisons are unspecified.
12817     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
12818       bool WasArrayIndex;
12819       unsigned Mismatch = FindDesignatorMismatch(
12820           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
12821       // At the point where the designators diverge, the comparison has a
12822       // specified value if:
12823       //  - we are comparing array indices
12824       //  - we are comparing fields of a union, or fields with the same access
12825       // Otherwise, the result is unspecified and thus the comparison is not a
12826       // constant expression.
12827       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
12828           Mismatch < RHSDesignator.Entries.size()) {
12829         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
12830         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
12831         if (!LF && !RF)
12832           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
12833         else if (!LF)
12834           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12835               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
12836               << RF->getParent() << RF;
12837         else if (!RF)
12838           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12839               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
12840               << LF->getParent() << LF;
12841         else if (!LF->getParent()->isUnion() &&
12842                  LF->getAccess() != RF->getAccess())
12843           Info.CCEDiag(E,
12844                        diag::note_constexpr_pointer_comparison_differing_access)
12845               << LF << LF->getAccess() << RF << RF->getAccess()
12846               << LF->getParent();
12847       }
12848     }
12849 
12850     // The comparison here must be unsigned, and performed with the same
12851     // width as the pointer.
12852     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
12853     uint64_t CompareLHS = LHSOffset.getQuantity();
12854     uint64_t CompareRHS = RHSOffset.getQuantity();
12855     assert(PtrSize <= 64 && "Unexpected pointer width");
12856     uint64_t Mask = ~0ULL >> (64 - PtrSize);
12857     CompareLHS &= Mask;
12858     CompareRHS &= Mask;
12859 
12860     // If there is a base and this is a relational operator, we can only
12861     // compare pointers within the object in question; otherwise, the result
12862     // depends on where the object is located in memory.
12863     if (!LHSValue.Base.isNull() && IsRelational) {
12864       QualType BaseTy = getType(LHSValue.Base);
12865       if (BaseTy->isIncompleteType())
12866         return Error(E);
12867       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
12868       uint64_t OffsetLimit = Size.getQuantity();
12869       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
12870         return Error(E);
12871     }
12872 
12873     if (CompareLHS < CompareRHS)
12874       return Success(CmpResult::Less, E);
12875     if (CompareLHS > CompareRHS)
12876       return Success(CmpResult::Greater, E);
12877     return Success(CmpResult::Equal, E);
12878   }
12879 
12880   if (LHSTy->isMemberPointerType()) {
12881     assert(IsEquality && "unexpected member pointer operation");
12882     assert(RHSTy->isMemberPointerType() && "invalid comparison");
12883 
12884     MemberPtr LHSValue, RHSValue;
12885 
12886     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
12887     if (!LHSOK && !Info.noteFailure())
12888       return false;
12889 
12890     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12891       return false;
12892 
12893     // C++11 [expr.eq]p2:
12894     //   If both operands are null, they compare equal. Otherwise if only one is
12895     //   null, they compare unequal.
12896     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
12897       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
12898       return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12899     }
12900 
12901     //   Otherwise if either is a pointer to a virtual member function, the
12902     //   result is unspecified.
12903     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
12904       if (MD->isVirtual())
12905         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12906     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
12907       if (MD->isVirtual())
12908         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12909 
12910     //   Otherwise they compare equal if and only if they would refer to the
12911     //   same member of the same most derived object or the same subobject if
12912     //   they were dereferenced with a hypothetical object of the associated
12913     //   class type.
12914     bool Equal = LHSValue == RHSValue;
12915     return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12916   }
12917 
12918   if (LHSTy->isNullPtrType()) {
12919     assert(E->isComparisonOp() && "unexpected nullptr operation");
12920     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
12921     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
12922     // are compared, the result is true of the operator is <=, >= or ==, and
12923     // false otherwise.
12924     return Success(CmpResult::Equal, E);
12925   }
12926 
12927   return DoAfter();
12928 }
12929 
12930 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
12931   if (!CheckLiteralType(Info, E))
12932     return false;
12933 
12934   auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12935     ComparisonCategoryResult CCR;
12936     switch (CR) {
12937     case CmpResult::Unequal:
12938       llvm_unreachable("should never produce Unequal for three-way comparison");
12939     case CmpResult::Less:
12940       CCR = ComparisonCategoryResult::Less;
12941       break;
12942     case CmpResult::Equal:
12943       CCR = ComparisonCategoryResult::Equal;
12944       break;
12945     case CmpResult::Greater:
12946       CCR = ComparisonCategoryResult::Greater;
12947       break;
12948     case CmpResult::Unordered:
12949       CCR = ComparisonCategoryResult::Unordered;
12950       break;
12951     }
12952     // Evaluation succeeded. Lookup the information for the comparison category
12953     // type and fetch the VarDecl for the result.
12954     const ComparisonCategoryInfo &CmpInfo =
12955         Info.Ctx.CompCategories.getInfoForType(E->getType());
12956     const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
12957     // Check and evaluate the result as a constant expression.
12958     LValue LV;
12959     LV.set(VD);
12960     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
12961       return false;
12962     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
12963                                    ConstantExprKind::Normal);
12964   };
12965   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12966     return ExprEvaluatorBaseTy::VisitBinCmp(E);
12967   });
12968 }
12969 
12970 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12971   // We don't support assignment in C. C++ assignments don't get here because
12972   // assignment is an lvalue in C++.
12973   if (E->isAssignmentOp()) {
12974     Error(E);
12975     if (!Info.noteFailure())
12976       return false;
12977   }
12978 
12979   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
12980     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
12981 
12982   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
12983           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
12984          "DataRecursiveIntBinOpEvaluator should have handled integral types");
12985 
12986   if (E->isComparisonOp()) {
12987     // Evaluate builtin binary comparisons by evaluating them as three-way
12988     // comparisons and then translating the result.
12989     auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12990       assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
12991              "should only produce Unequal for equality comparisons");
12992       bool IsEqual   = CR == CmpResult::Equal,
12993            IsLess    = CR == CmpResult::Less,
12994            IsGreater = CR == CmpResult::Greater;
12995       auto Op = E->getOpcode();
12996       switch (Op) {
12997       default:
12998         llvm_unreachable("unsupported binary operator");
12999       case BO_EQ:
13000       case BO_NE:
13001         return Success(IsEqual == (Op == BO_EQ), E);
13002       case BO_LT:
13003         return Success(IsLess, E);
13004       case BO_GT:
13005         return Success(IsGreater, E);
13006       case BO_LE:
13007         return Success(IsEqual || IsLess, E);
13008       case BO_GE:
13009         return Success(IsEqual || IsGreater, E);
13010       }
13011     };
13012     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
13013       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13014     });
13015   }
13016 
13017   QualType LHSTy = E->getLHS()->getType();
13018   QualType RHSTy = E->getRHS()->getType();
13019 
13020   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
13021       E->getOpcode() == BO_Sub) {
13022     LValue LHSValue, RHSValue;
13023 
13024     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
13025     if (!LHSOK && !Info.noteFailure())
13026       return false;
13027 
13028     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13029       return false;
13030 
13031     // Reject differing bases from the normal codepath; we special-case
13032     // comparisons to null.
13033     if (!HasSameBase(LHSValue, RHSValue)) {
13034       // Handle &&A - &&B.
13035       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
13036         return Error(E);
13037       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
13038       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
13039       if (!LHSExpr || !RHSExpr)
13040         return Error(E);
13041       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
13042       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
13043       if (!LHSAddrExpr || !RHSAddrExpr)
13044         return Error(E);
13045       // Make sure both labels come from the same function.
13046       if (LHSAddrExpr->getLabel()->getDeclContext() !=
13047           RHSAddrExpr->getLabel()->getDeclContext())
13048         return Error(E);
13049       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
13050     }
13051     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
13052     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
13053 
13054     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
13055     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
13056 
13057     // C++11 [expr.add]p6:
13058     //   Unless both pointers point to elements of the same array object, or
13059     //   one past the last element of the array object, the behavior is
13060     //   undefined.
13061     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
13062         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
13063                                 RHSDesignator))
13064       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
13065 
13066     QualType Type = E->getLHS()->getType();
13067     QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
13068 
13069     CharUnits ElementSize;
13070     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
13071       return false;
13072 
13073     // As an extension, a type may have zero size (empty struct or union in
13074     // C, array of zero length). Pointer subtraction in such cases has
13075     // undefined behavior, so is not constant.
13076     if (ElementSize.isZero()) {
13077       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
13078           << ElementType;
13079       return false;
13080     }
13081 
13082     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
13083     // and produce incorrect results when it overflows. Such behavior
13084     // appears to be non-conforming, but is common, so perhaps we should
13085     // assume the standard intended for such cases to be undefined behavior
13086     // and check for them.
13087 
13088     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
13089     // overflow in the final conversion to ptrdiff_t.
13090     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
13091     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
13092     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
13093                     false);
13094     APSInt TrueResult = (LHS - RHS) / ElemSize;
13095     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
13096 
13097     if (Result.extend(65) != TrueResult &&
13098         !HandleOverflow(Info, E, TrueResult, E->getType()))
13099       return false;
13100     return Success(Result, E);
13101   }
13102 
13103   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13104 }
13105 
13106 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
13107 /// a result as the expression's type.
13108 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
13109                                     const UnaryExprOrTypeTraitExpr *E) {
13110   switch(E->getKind()) {
13111   case UETT_PreferredAlignOf:
13112   case UETT_AlignOf: {
13113     if (E->isArgumentType())
13114       return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
13115                      E);
13116     else
13117       return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
13118                      E);
13119   }
13120 
13121   case UETT_VecStep: {
13122     QualType Ty = E->getTypeOfArgument();
13123 
13124     if (Ty->isVectorType()) {
13125       unsigned n = Ty->castAs<VectorType>()->getNumElements();
13126 
13127       // The vec_step built-in functions that take a 3-component
13128       // vector return 4. (OpenCL 1.1 spec 6.11.12)
13129       if (n == 3)
13130         n = 4;
13131 
13132       return Success(n, E);
13133     } else
13134       return Success(1, E);
13135   }
13136 
13137   case UETT_SizeOf: {
13138     QualType SrcTy = E->getTypeOfArgument();
13139     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
13140     //   the result is the size of the referenced type."
13141     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
13142       SrcTy = Ref->getPointeeType();
13143 
13144     CharUnits Sizeof;
13145     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
13146       return false;
13147     return Success(Sizeof, E);
13148   }
13149   case UETT_OpenMPRequiredSimdAlign:
13150     assert(E->isArgumentType());
13151     return Success(
13152         Info.Ctx.toCharUnitsFromBits(
13153                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
13154             .getQuantity(),
13155         E);
13156   }
13157 
13158   llvm_unreachable("unknown expr/type trait");
13159 }
13160 
13161 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
13162   CharUnits Result;
13163   unsigned n = OOE->getNumComponents();
13164   if (n == 0)
13165     return Error(OOE);
13166   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
13167   for (unsigned i = 0; i != n; ++i) {
13168     OffsetOfNode ON = OOE->getComponent(i);
13169     switch (ON.getKind()) {
13170     case OffsetOfNode::Array: {
13171       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
13172       APSInt IdxResult;
13173       if (!EvaluateInteger(Idx, IdxResult, Info))
13174         return false;
13175       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
13176       if (!AT)
13177         return Error(OOE);
13178       CurrentType = AT->getElementType();
13179       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
13180       Result += IdxResult.getSExtValue() * ElementSize;
13181       break;
13182     }
13183 
13184     case OffsetOfNode::Field: {
13185       FieldDecl *MemberDecl = ON.getField();
13186       const RecordType *RT = CurrentType->getAs<RecordType>();
13187       if (!RT)
13188         return Error(OOE);
13189       RecordDecl *RD = RT->getDecl();
13190       if (RD->isInvalidDecl()) return false;
13191       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13192       unsigned i = MemberDecl->getFieldIndex();
13193       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
13194       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
13195       CurrentType = MemberDecl->getType().getNonReferenceType();
13196       break;
13197     }
13198 
13199     case OffsetOfNode::Identifier:
13200       llvm_unreachable("dependent __builtin_offsetof");
13201 
13202     case OffsetOfNode::Base: {
13203       CXXBaseSpecifier *BaseSpec = ON.getBase();
13204       if (BaseSpec->isVirtual())
13205         return Error(OOE);
13206 
13207       // Find the layout of the class whose base we are looking into.
13208       const RecordType *RT = CurrentType->getAs<RecordType>();
13209       if (!RT)
13210         return Error(OOE);
13211       RecordDecl *RD = RT->getDecl();
13212       if (RD->isInvalidDecl()) return false;
13213       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13214 
13215       // Find the base class itself.
13216       CurrentType = BaseSpec->getType();
13217       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
13218       if (!BaseRT)
13219         return Error(OOE);
13220 
13221       // Add the offset to the base.
13222       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
13223       break;
13224     }
13225     }
13226   }
13227   return Success(Result, OOE);
13228 }
13229 
13230 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13231   switch (E->getOpcode()) {
13232   default:
13233     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
13234     // See C99 6.6p3.
13235     return Error(E);
13236   case UO_Extension:
13237     // FIXME: Should extension allow i-c-e extension expressions in its scope?
13238     // If so, we could clear the diagnostic ID.
13239     return Visit(E->getSubExpr());
13240   case UO_Plus:
13241     // The result is just the value.
13242     return Visit(E->getSubExpr());
13243   case UO_Minus: {
13244     if (!Visit(E->getSubExpr()))
13245       return false;
13246     if (!Result.isInt()) return Error(E);
13247     const APSInt &Value = Result.getInt();
13248     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
13249         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
13250                         E->getType()))
13251       return false;
13252     return Success(-Value, E);
13253   }
13254   case UO_Not: {
13255     if (!Visit(E->getSubExpr()))
13256       return false;
13257     if (!Result.isInt()) return Error(E);
13258     return Success(~Result.getInt(), E);
13259   }
13260   case UO_LNot: {
13261     bool bres;
13262     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13263       return false;
13264     return Success(!bres, E);
13265   }
13266   }
13267 }
13268 
13269 /// HandleCast - This is used to evaluate implicit or explicit casts where the
13270 /// result type is integer.
13271 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
13272   const Expr *SubExpr = E->getSubExpr();
13273   QualType DestType = E->getType();
13274   QualType SrcType = SubExpr->getType();
13275 
13276   switch (E->getCastKind()) {
13277   case CK_BaseToDerived:
13278   case CK_DerivedToBase:
13279   case CK_UncheckedDerivedToBase:
13280   case CK_Dynamic:
13281   case CK_ToUnion:
13282   case CK_ArrayToPointerDecay:
13283   case CK_FunctionToPointerDecay:
13284   case CK_NullToPointer:
13285   case CK_NullToMemberPointer:
13286   case CK_BaseToDerivedMemberPointer:
13287   case CK_DerivedToBaseMemberPointer:
13288   case CK_ReinterpretMemberPointer:
13289   case CK_ConstructorConversion:
13290   case CK_IntegralToPointer:
13291   case CK_ToVoid:
13292   case CK_VectorSplat:
13293   case CK_IntegralToFloating:
13294   case CK_FloatingCast:
13295   case CK_CPointerToObjCPointerCast:
13296   case CK_BlockPointerToObjCPointerCast:
13297   case CK_AnyPointerToBlockPointerCast:
13298   case CK_ObjCObjectLValueCast:
13299   case CK_FloatingRealToComplex:
13300   case CK_FloatingComplexToReal:
13301   case CK_FloatingComplexCast:
13302   case CK_FloatingComplexToIntegralComplex:
13303   case CK_IntegralRealToComplex:
13304   case CK_IntegralComplexCast:
13305   case CK_IntegralComplexToFloatingComplex:
13306   case CK_BuiltinFnToFnPtr:
13307   case CK_ZeroToOCLOpaqueType:
13308   case CK_NonAtomicToAtomic:
13309   case CK_AddressSpaceConversion:
13310   case CK_IntToOCLSampler:
13311   case CK_FloatingToFixedPoint:
13312   case CK_FixedPointToFloating:
13313   case CK_FixedPointCast:
13314   case CK_IntegralToFixedPoint:
13315   case CK_MatrixCast:
13316     llvm_unreachable("invalid cast kind for integral value");
13317 
13318   case CK_BitCast:
13319   case CK_Dependent:
13320   case CK_LValueBitCast:
13321   case CK_ARCProduceObject:
13322   case CK_ARCConsumeObject:
13323   case CK_ARCReclaimReturnedObject:
13324   case CK_ARCExtendBlockObject:
13325   case CK_CopyAndAutoreleaseBlockObject:
13326     return Error(E);
13327 
13328   case CK_UserDefinedConversion:
13329   case CK_LValueToRValue:
13330   case CK_AtomicToNonAtomic:
13331   case CK_NoOp:
13332   case CK_LValueToRValueBitCast:
13333     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13334 
13335   case CK_MemberPointerToBoolean:
13336   case CK_PointerToBoolean:
13337   case CK_IntegralToBoolean:
13338   case CK_FloatingToBoolean:
13339   case CK_BooleanToSignedIntegral:
13340   case CK_FloatingComplexToBoolean:
13341   case CK_IntegralComplexToBoolean: {
13342     bool BoolResult;
13343     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
13344       return false;
13345     uint64_t IntResult = BoolResult;
13346     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
13347       IntResult = (uint64_t)-1;
13348     return Success(IntResult, E);
13349   }
13350 
13351   case CK_FixedPointToIntegral: {
13352     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
13353     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13354       return false;
13355     bool Overflowed;
13356     llvm::APSInt Result = Src.convertToInt(
13357         Info.Ctx.getIntWidth(DestType),
13358         DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
13359     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
13360       return false;
13361     return Success(Result, E);
13362   }
13363 
13364   case CK_FixedPointToBoolean: {
13365     // Unsigned padding does not affect this.
13366     APValue Val;
13367     if (!Evaluate(Val, Info, SubExpr))
13368       return false;
13369     return Success(Val.getFixedPoint().getBoolValue(), E);
13370   }
13371 
13372   case CK_IntegralCast: {
13373     if (!Visit(SubExpr))
13374       return false;
13375 
13376     if (!Result.isInt()) {
13377       // Allow casts of address-of-label differences if they are no-ops
13378       // or narrowing.  (The narrowing case isn't actually guaranteed to
13379       // be constant-evaluatable except in some narrow cases which are hard
13380       // to detect here.  We let it through on the assumption the user knows
13381       // what they are doing.)
13382       if (Result.isAddrLabelDiff())
13383         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
13384       // Only allow casts of lvalues if they are lossless.
13385       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
13386     }
13387 
13388     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
13389                                       Result.getInt()), E);
13390   }
13391 
13392   case CK_PointerToIntegral: {
13393     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
13394 
13395     LValue LV;
13396     if (!EvaluatePointer(SubExpr, LV, Info))
13397       return false;
13398 
13399     if (LV.getLValueBase()) {
13400       // Only allow based lvalue casts if they are lossless.
13401       // FIXME: Allow a larger integer size than the pointer size, and allow
13402       // narrowing back down to pointer width in subsequent integral casts.
13403       // FIXME: Check integer type's active bits, not its type size.
13404       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
13405         return Error(E);
13406 
13407       LV.Designator.setInvalid();
13408       LV.moveInto(Result);
13409       return true;
13410     }
13411 
13412     APSInt AsInt;
13413     APValue V;
13414     LV.moveInto(V);
13415     if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
13416       llvm_unreachable("Can't cast this!");
13417 
13418     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
13419   }
13420 
13421   case CK_IntegralComplexToReal: {
13422     ComplexValue C;
13423     if (!EvaluateComplex(SubExpr, C, Info))
13424       return false;
13425     return Success(C.getComplexIntReal(), E);
13426   }
13427 
13428   case CK_FloatingToIntegral: {
13429     APFloat F(0.0);
13430     if (!EvaluateFloat(SubExpr, F, Info))
13431       return false;
13432 
13433     APSInt Value;
13434     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
13435       return false;
13436     return Success(Value, E);
13437   }
13438   }
13439 
13440   llvm_unreachable("unknown cast resulting in integral value");
13441 }
13442 
13443 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13444   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13445     ComplexValue LV;
13446     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13447       return false;
13448     if (!LV.isComplexInt())
13449       return Error(E);
13450     return Success(LV.getComplexIntReal(), E);
13451   }
13452 
13453   return Visit(E->getSubExpr());
13454 }
13455 
13456 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13457   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
13458     ComplexValue LV;
13459     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13460       return false;
13461     if (!LV.isComplexInt())
13462       return Error(E);
13463     return Success(LV.getComplexIntImag(), E);
13464   }
13465 
13466   VisitIgnoredValue(E->getSubExpr());
13467   return Success(0, E);
13468 }
13469 
13470 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
13471   return Success(E->getPackLength(), E);
13472 }
13473 
13474 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
13475   return Success(E->getValue(), E);
13476 }
13477 
13478 bool IntExprEvaluator::VisitConceptSpecializationExpr(
13479        const ConceptSpecializationExpr *E) {
13480   return Success(E->isSatisfied(), E);
13481 }
13482 
13483 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
13484   return Success(E->isSatisfied(), E);
13485 }
13486 
13487 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13488   switch (E->getOpcode()) {
13489     default:
13490       // Invalid unary operators
13491       return Error(E);
13492     case UO_Plus:
13493       // The result is just the value.
13494       return Visit(E->getSubExpr());
13495     case UO_Minus: {
13496       if (!Visit(E->getSubExpr())) return false;
13497       if (!Result.isFixedPoint())
13498         return Error(E);
13499       bool Overflowed;
13500       APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
13501       if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
13502         return false;
13503       return Success(Negated, E);
13504     }
13505     case UO_LNot: {
13506       bool bres;
13507       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13508         return false;
13509       return Success(!bres, E);
13510     }
13511   }
13512 }
13513 
13514 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
13515   const Expr *SubExpr = E->getSubExpr();
13516   QualType DestType = E->getType();
13517   assert(DestType->isFixedPointType() &&
13518          "Expected destination type to be a fixed point type");
13519   auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
13520 
13521   switch (E->getCastKind()) {
13522   case CK_FixedPointCast: {
13523     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13524     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13525       return false;
13526     bool Overflowed;
13527     APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
13528     if (Overflowed) {
13529       if (Info.checkingForUndefinedBehavior())
13530         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13531                                          diag::warn_fixedpoint_constant_overflow)
13532           << Result.toString() << E->getType();
13533       if (!HandleOverflow(Info, E, Result, E->getType()))
13534         return false;
13535     }
13536     return Success(Result, E);
13537   }
13538   case CK_IntegralToFixedPoint: {
13539     APSInt Src;
13540     if (!EvaluateInteger(SubExpr, Src, Info))
13541       return false;
13542 
13543     bool Overflowed;
13544     APFixedPoint IntResult = APFixedPoint::getFromIntValue(
13545         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13546 
13547     if (Overflowed) {
13548       if (Info.checkingForUndefinedBehavior())
13549         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13550                                          diag::warn_fixedpoint_constant_overflow)
13551           << IntResult.toString() << E->getType();
13552       if (!HandleOverflow(Info, E, IntResult, E->getType()))
13553         return false;
13554     }
13555 
13556     return Success(IntResult, E);
13557   }
13558   case CK_FloatingToFixedPoint: {
13559     APFloat Src(0.0);
13560     if (!EvaluateFloat(SubExpr, Src, Info))
13561       return false;
13562 
13563     bool Overflowed;
13564     APFixedPoint Result = APFixedPoint::getFromFloatValue(
13565         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13566 
13567     if (Overflowed) {
13568       if (Info.checkingForUndefinedBehavior())
13569         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13570                                          diag::warn_fixedpoint_constant_overflow)
13571           << Result.toString() << E->getType();
13572       if (!HandleOverflow(Info, E, Result, E->getType()))
13573         return false;
13574     }
13575 
13576     return Success(Result, E);
13577   }
13578   case CK_NoOp:
13579   case CK_LValueToRValue:
13580     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13581   default:
13582     return Error(E);
13583   }
13584 }
13585 
13586 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13587   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13588     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13589 
13590   const Expr *LHS = E->getLHS();
13591   const Expr *RHS = E->getRHS();
13592   FixedPointSemantics ResultFXSema =
13593       Info.Ctx.getFixedPointSemantics(E->getType());
13594 
13595   APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
13596   if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
13597     return false;
13598   APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
13599   if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
13600     return false;
13601 
13602   bool OpOverflow = false, ConversionOverflow = false;
13603   APFixedPoint Result(LHSFX.getSemantics());
13604   switch (E->getOpcode()) {
13605   case BO_Add: {
13606     Result = LHSFX.add(RHSFX, &OpOverflow)
13607                   .convert(ResultFXSema, &ConversionOverflow);
13608     break;
13609   }
13610   case BO_Sub: {
13611     Result = LHSFX.sub(RHSFX, &OpOverflow)
13612                   .convert(ResultFXSema, &ConversionOverflow);
13613     break;
13614   }
13615   case BO_Mul: {
13616     Result = LHSFX.mul(RHSFX, &OpOverflow)
13617                   .convert(ResultFXSema, &ConversionOverflow);
13618     break;
13619   }
13620   case BO_Div: {
13621     if (RHSFX.getValue() == 0) {
13622       Info.FFDiag(E, diag::note_expr_divide_by_zero);
13623       return false;
13624     }
13625     Result = LHSFX.div(RHSFX, &OpOverflow)
13626                   .convert(ResultFXSema, &ConversionOverflow);
13627     break;
13628   }
13629   case BO_Shl:
13630   case BO_Shr: {
13631     FixedPointSemantics LHSSema = LHSFX.getSemantics();
13632     llvm::APSInt RHSVal = RHSFX.getValue();
13633 
13634     unsigned ShiftBW =
13635         LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
13636     unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
13637     // Embedded-C 4.1.6.2.2:
13638     //   The right operand must be nonnegative and less than the total number
13639     //   of (nonpadding) bits of the fixed-point operand ...
13640     if (RHSVal.isNegative())
13641       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
13642     else if (Amt != RHSVal)
13643       Info.CCEDiag(E, diag::note_constexpr_large_shift)
13644           << RHSVal << E->getType() << ShiftBW;
13645 
13646     if (E->getOpcode() == BO_Shl)
13647       Result = LHSFX.shl(Amt, &OpOverflow);
13648     else
13649       Result = LHSFX.shr(Amt, &OpOverflow);
13650     break;
13651   }
13652   default:
13653     return false;
13654   }
13655   if (OpOverflow || ConversionOverflow) {
13656     if (Info.checkingForUndefinedBehavior())
13657       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13658                                        diag::warn_fixedpoint_constant_overflow)
13659         << Result.toString() << E->getType();
13660     if (!HandleOverflow(Info, E, Result, E->getType()))
13661       return false;
13662   }
13663   return Success(Result, E);
13664 }
13665 
13666 //===----------------------------------------------------------------------===//
13667 // Float Evaluation
13668 //===----------------------------------------------------------------------===//
13669 
13670 namespace {
13671 class FloatExprEvaluator
13672   : public ExprEvaluatorBase<FloatExprEvaluator> {
13673   APFloat &Result;
13674 public:
13675   FloatExprEvaluator(EvalInfo &info, APFloat &result)
13676     : ExprEvaluatorBaseTy(info), Result(result) {}
13677 
13678   bool Success(const APValue &V, const Expr *e) {
13679     Result = V.getFloat();
13680     return true;
13681   }
13682 
13683   bool ZeroInitialization(const Expr *E) {
13684     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
13685     return true;
13686   }
13687 
13688   bool VisitCallExpr(const CallExpr *E);
13689 
13690   bool VisitUnaryOperator(const UnaryOperator *E);
13691   bool VisitBinaryOperator(const BinaryOperator *E);
13692   bool VisitFloatingLiteral(const FloatingLiteral *E);
13693   bool VisitCastExpr(const CastExpr *E);
13694 
13695   bool VisitUnaryReal(const UnaryOperator *E);
13696   bool VisitUnaryImag(const UnaryOperator *E);
13697 
13698   // FIXME: Missing: array subscript of vector, member of vector
13699 };
13700 } // end anonymous namespace
13701 
13702 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
13703   assert(!E->isValueDependent());
13704   assert(E->isPRValue() && E->getType()->isRealFloatingType());
13705   return FloatExprEvaluator(Info, Result).Visit(E);
13706 }
13707 
13708 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
13709                                   QualType ResultTy,
13710                                   const Expr *Arg,
13711                                   bool SNaN,
13712                                   llvm::APFloat &Result) {
13713   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
13714   if (!S) return false;
13715 
13716   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
13717 
13718   llvm::APInt fill;
13719 
13720   // Treat empty strings as if they were zero.
13721   if (S->getString().empty())
13722     fill = llvm::APInt(32, 0);
13723   else if (S->getString().getAsInteger(0, fill))
13724     return false;
13725 
13726   if (Context.getTargetInfo().isNan2008()) {
13727     if (SNaN)
13728       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13729     else
13730       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13731   } else {
13732     // Prior to IEEE 754-2008, architectures were allowed to choose whether
13733     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
13734     // a different encoding to what became a standard in 2008, and for pre-
13735     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
13736     // sNaN. This is now known as "legacy NaN" encoding.
13737     if (SNaN)
13738       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13739     else
13740       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13741   }
13742 
13743   return true;
13744 }
13745 
13746 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
13747   switch (E->getBuiltinCallee()) {
13748   default:
13749     return ExprEvaluatorBaseTy::VisitCallExpr(E);
13750 
13751   case Builtin::BI__builtin_huge_val:
13752   case Builtin::BI__builtin_huge_valf:
13753   case Builtin::BI__builtin_huge_vall:
13754   case Builtin::BI__builtin_huge_valf128:
13755   case Builtin::BI__builtin_inf:
13756   case Builtin::BI__builtin_inff:
13757   case Builtin::BI__builtin_infl:
13758   case Builtin::BI__builtin_inff128: {
13759     const llvm::fltSemantics &Sem =
13760       Info.Ctx.getFloatTypeSemantics(E->getType());
13761     Result = llvm::APFloat::getInf(Sem);
13762     return true;
13763   }
13764 
13765   case Builtin::BI__builtin_nans:
13766   case Builtin::BI__builtin_nansf:
13767   case Builtin::BI__builtin_nansl:
13768   case Builtin::BI__builtin_nansf128:
13769     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13770                                true, Result))
13771       return Error(E);
13772     return true;
13773 
13774   case Builtin::BI__builtin_nan:
13775   case Builtin::BI__builtin_nanf:
13776   case Builtin::BI__builtin_nanl:
13777   case Builtin::BI__builtin_nanf128:
13778     // If this is __builtin_nan() turn this into a nan, otherwise we
13779     // can't constant fold it.
13780     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13781                                false, Result))
13782       return Error(E);
13783     return true;
13784 
13785   case Builtin::BI__builtin_fabs:
13786   case Builtin::BI__builtin_fabsf:
13787   case Builtin::BI__builtin_fabsl:
13788   case Builtin::BI__builtin_fabsf128:
13789     // The C standard says "fabs raises no floating-point exceptions,
13790     // even if x is a signaling NaN. The returned value is independent of
13791     // the current rounding direction mode."  Therefore constant folding can
13792     // proceed without regard to the floating point settings.
13793     // Reference, WG14 N2478 F.10.4.3
13794     if (!EvaluateFloat(E->getArg(0), Result, Info))
13795       return false;
13796 
13797     if (Result.isNegative())
13798       Result.changeSign();
13799     return true;
13800 
13801   case Builtin::BI__arithmetic_fence:
13802     return EvaluateFloat(E->getArg(0), Result, Info);
13803 
13804   // FIXME: Builtin::BI__builtin_powi
13805   // FIXME: Builtin::BI__builtin_powif
13806   // FIXME: Builtin::BI__builtin_powil
13807 
13808   case Builtin::BI__builtin_copysign:
13809   case Builtin::BI__builtin_copysignf:
13810   case Builtin::BI__builtin_copysignl:
13811   case Builtin::BI__builtin_copysignf128: {
13812     APFloat RHS(0.);
13813     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
13814         !EvaluateFloat(E->getArg(1), RHS, Info))
13815       return false;
13816     Result.copySign(RHS);
13817     return true;
13818   }
13819   }
13820 }
13821 
13822 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13823   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13824     ComplexValue CV;
13825     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13826       return false;
13827     Result = CV.FloatReal;
13828     return true;
13829   }
13830 
13831   return Visit(E->getSubExpr());
13832 }
13833 
13834 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13835   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13836     ComplexValue CV;
13837     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13838       return false;
13839     Result = CV.FloatImag;
13840     return true;
13841   }
13842 
13843   VisitIgnoredValue(E->getSubExpr());
13844   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
13845   Result = llvm::APFloat::getZero(Sem);
13846   return true;
13847 }
13848 
13849 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13850   switch (E->getOpcode()) {
13851   default: return Error(E);
13852   case UO_Plus:
13853     return EvaluateFloat(E->getSubExpr(), Result, Info);
13854   case UO_Minus:
13855     // In C standard, WG14 N2478 F.3 p4
13856     // "the unary - raises no floating point exceptions,
13857     // even if the operand is signalling."
13858     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
13859       return false;
13860     Result.changeSign();
13861     return true;
13862   }
13863 }
13864 
13865 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13866   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13867     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13868 
13869   APFloat RHS(0.0);
13870   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
13871   if (!LHSOK && !Info.noteFailure())
13872     return false;
13873   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
13874          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
13875 }
13876 
13877 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
13878   Result = E->getValue();
13879   return true;
13880 }
13881 
13882 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
13883   const Expr* SubExpr = E->getSubExpr();
13884 
13885   switch (E->getCastKind()) {
13886   default:
13887     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13888 
13889   case CK_IntegralToFloating: {
13890     APSInt IntResult;
13891     const FPOptions FPO = E->getFPFeaturesInEffect(
13892                                   Info.Ctx.getLangOpts());
13893     return EvaluateInteger(SubExpr, IntResult, Info) &&
13894            HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
13895                                 IntResult, E->getType(), Result);
13896   }
13897 
13898   case CK_FixedPointToFloating: {
13899     APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13900     if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
13901       return false;
13902     Result =
13903         FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
13904     return true;
13905   }
13906 
13907   case CK_FloatingCast: {
13908     if (!Visit(SubExpr))
13909       return false;
13910     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
13911                                   Result);
13912   }
13913 
13914   case CK_FloatingComplexToReal: {
13915     ComplexValue V;
13916     if (!EvaluateComplex(SubExpr, V, Info))
13917       return false;
13918     Result = V.getComplexFloatReal();
13919     return true;
13920   }
13921   }
13922 }
13923 
13924 //===----------------------------------------------------------------------===//
13925 // Complex Evaluation (for float and integer)
13926 //===----------------------------------------------------------------------===//
13927 
13928 namespace {
13929 class ComplexExprEvaluator
13930   : public ExprEvaluatorBase<ComplexExprEvaluator> {
13931   ComplexValue &Result;
13932 
13933 public:
13934   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
13935     : ExprEvaluatorBaseTy(info), Result(Result) {}
13936 
13937   bool Success(const APValue &V, const Expr *e) {
13938     Result.setFrom(V);
13939     return true;
13940   }
13941 
13942   bool ZeroInitialization(const Expr *E);
13943 
13944   //===--------------------------------------------------------------------===//
13945   //                            Visitor Methods
13946   //===--------------------------------------------------------------------===//
13947 
13948   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
13949   bool VisitCastExpr(const CastExpr *E);
13950   bool VisitBinaryOperator(const BinaryOperator *E);
13951   bool VisitUnaryOperator(const UnaryOperator *E);
13952   bool VisitInitListExpr(const InitListExpr *E);
13953   bool VisitCallExpr(const CallExpr *E);
13954 };
13955 } // end anonymous namespace
13956 
13957 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
13958                             EvalInfo &Info) {
13959   assert(!E->isValueDependent());
13960   assert(E->isPRValue() && E->getType()->isAnyComplexType());
13961   return ComplexExprEvaluator(Info, Result).Visit(E);
13962 }
13963 
13964 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
13965   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
13966   if (ElemTy->isRealFloatingType()) {
13967     Result.makeComplexFloat();
13968     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
13969     Result.FloatReal = Zero;
13970     Result.FloatImag = Zero;
13971   } else {
13972     Result.makeComplexInt();
13973     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
13974     Result.IntReal = Zero;
13975     Result.IntImag = Zero;
13976   }
13977   return true;
13978 }
13979 
13980 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
13981   const Expr* SubExpr = E->getSubExpr();
13982 
13983   if (SubExpr->getType()->isRealFloatingType()) {
13984     Result.makeComplexFloat();
13985     APFloat &Imag = Result.FloatImag;
13986     if (!EvaluateFloat(SubExpr, Imag, Info))
13987       return false;
13988 
13989     Result.FloatReal = APFloat(Imag.getSemantics());
13990     return true;
13991   } else {
13992     assert(SubExpr->getType()->isIntegerType() &&
13993            "Unexpected imaginary literal.");
13994 
13995     Result.makeComplexInt();
13996     APSInt &Imag = Result.IntImag;
13997     if (!EvaluateInteger(SubExpr, Imag, Info))
13998       return false;
13999 
14000     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
14001     return true;
14002   }
14003 }
14004 
14005 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
14006 
14007   switch (E->getCastKind()) {
14008   case CK_BitCast:
14009   case CK_BaseToDerived:
14010   case CK_DerivedToBase:
14011   case CK_UncheckedDerivedToBase:
14012   case CK_Dynamic:
14013   case CK_ToUnion:
14014   case CK_ArrayToPointerDecay:
14015   case CK_FunctionToPointerDecay:
14016   case CK_NullToPointer:
14017   case CK_NullToMemberPointer:
14018   case CK_BaseToDerivedMemberPointer:
14019   case CK_DerivedToBaseMemberPointer:
14020   case CK_MemberPointerToBoolean:
14021   case CK_ReinterpretMemberPointer:
14022   case CK_ConstructorConversion:
14023   case CK_IntegralToPointer:
14024   case CK_PointerToIntegral:
14025   case CK_PointerToBoolean:
14026   case CK_ToVoid:
14027   case CK_VectorSplat:
14028   case CK_IntegralCast:
14029   case CK_BooleanToSignedIntegral:
14030   case CK_IntegralToBoolean:
14031   case CK_IntegralToFloating:
14032   case CK_FloatingToIntegral:
14033   case CK_FloatingToBoolean:
14034   case CK_FloatingCast:
14035   case CK_CPointerToObjCPointerCast:
14036   case CK_BlockPointerToObjCPointerCast:
14037   case CK_AnyPointerToBlockPointerCast:
14038   case CK_ObjCObjectLValueCast:
14039   case CK_FloatingComplexToReal:
14040   case CK_FloatingComplexToBoolean:
14041   case CK_IntegralComplexToReal:
14042   case CK_IntegralComplexToBoolean:
14043   case CK_ARCProduceObject:
14044   case CK_ARCConsumeObject:
14045   case CK_ARCReclaimReturnedObject:
14046   case CK_ARCExtendBlockObject:
14047   case CK_CopyAndAutoreleaseBlockObject:
14048   case CK_BuiltinFnToFnPtr:
14049   case CK_ZeroToOCLOpaqueType:
14050   case CK_NonAtomicToAtomic:
14051   case CK_AddressSpaceConversion:
14052   case CK_IntToOCLSampler:
14053   case CK_FloatingToFixedPoint:
14054   case CK_FixedPointToFloating:
14055   case CK_FixedPointCast:
14056   case CK_FixedPointToBoolean:
14057   case CK_FixedPointToIntegral:
14058   case CK_IntegralToFixedPoint:
14059   case CK_MatrixCast:
14060     llvm_unreachable("invalid cast kind for complex value");
14061 
14062   case CK_LValueToRValue:
14063   case CK_AtomicToNonAtomic:
14064   case CK_NoOp:
14065   case CK_LValueToRValueBitCast:
14066     return ExprEvaluatorBaseTy::VisitCastExpr(E);
14067 
14068   case CK_Dependent:
14069   case CK_LValueBitCast:
14070   case CK_UserDefinedConversion:
14071     return Error(E);
14072 
14073   case CK_FloatingRealToComplex: {
14074     APFloat &Real = Result.FloatReal;
14075     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
14076       return false;
14077 
14078     Result.makeComplexFloat();
14079     Result.FloatImag = APFloat(Real.getSemantics());
14080     return true;
14081   }
14082 
14083   case CK_FloatingComplexCast: {
14084     if (!Visit(E->getSubExpr()))
14085       return false;
14086 
14087     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14088     QualType From
14089       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14090 
14091     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
14092            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
14093   }
14094 
14095   case CK_FloatingComplexToIntegralComplex: {
14096     if (!Visit(E->getSubExpr()))
14097       return false;
14098 
14099     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14100     QualType From
14101       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14102     Result.makeComplexInt();
14103     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
14104                                 To, Result.IntReal) &&
14105            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
14106                                 To, Result.IntImag);
14107   }
14108 
14109   case CK_IntegralRealToComplex: {
14110     APSInt &Real = Result.IntReal;
14111     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
14112       return false;
14113 
14114     Result.makeComplexInt();
14115     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
14116     return true;
14117   }
14118 
14119   case CK_IntegralComplexCast: {
14120     if (!Visit(E->getSubExpr()))
14121       return false;
14122 
14123     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14124     QualType From
14125       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14126 
14127     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
14128     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
14129     return true;
14130   }
14131 
14132   case CK_IntegralComplexToFloatingComplex: {
14133     if (!Visit(E->getSubExpr()))
14134       return false;
14135 
14136     const FPOptions FPO = E->getFPFeaturesInEffect(
14137                                   Info.Ctx.getLangOpts());
14138     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14139     QualType From
14140       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14141     Result.makeComplexFloat();
14142     return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
14143                                 To, Result.FloatReal) &&
14144            HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
14145                                 To, Result.FloatImag);
14146   }
14147   }
14148 
14149   llvm_unreachable("unknown cast resulting in complex value");
14150 }
14151 
14152 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14153   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14154     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14155 
14156   // Track whether the LHS or RHS is real at the type system level. When this is
14157   // the case we can simplify our evaluation strategy.
14158   bool LHSReal = false, RHSReal = false;
14159 
14160   bool LHSOK;
14161   if (E->getLHS()->getType()->isRealFloatingType()) {
14162     LHSReal = true;
14163     APFloat &Real = Result.FloatReal;
14164     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
14165     if (LHSOK) {
14166       Result.makeComplexFloat();
14167       Result.FloatImag = APFloat(Real.getSemantics());
14168     }
14169   } else {
14170     LHSOK = Visit(E->getLHS());
14171   }
14172   if (!LHSOK && !Info.noteFailure())
14173     return false;
14174 
14175   ComplexValue RHS;
14176   if (E->getRHS()->getType()->isRealFloatingType()) {
14177     RHSReal = true;
14178     APFloat &Real = RHS.FloatReal;
14179     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
14180       return false;
14181     RHS.makeComplexFloat();
14182     RHS.FloatImag = APFloat(Real.getSemantics());
14183   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
14184     return false;
14185 
14186   assert(!(LHSReal && RHSReal) &&
14187          "Cannot have both operands of a complex operation be real.");
14188   switch (E->getOpcode()) {
14189   default: return Error(E);
14190   case BO_Add:
14191     if (Result.isComplexFloat()) {
14192       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
14193                                        APFloat::rmNearestTiesToEven);
14194       if (LHSReal)
14195         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14196       else if (!RHSReal)
14197         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
14198                                          APFloat::rmNearestTiesToEven);
14199     } else {
14200       Result.getComplexIntReal() += RHS.getComplexIntReal();
14201       Result.getComplexIntImag() += RHS.getComplexIntImag();
14202     }
14203     break;
14204   case BO_Sub:
14205     if (Result.isComplexFloat()) {
14206       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
14207                                             APFloat::rmNearestTiesToEven);
14208       if (LHSReal) {
14209         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14210         Result.getComplexFloatImag().changeSign();
14211       } else if (!RHSReal) {
14212         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
14213                                               APFloat::rmNearestTiesToEven);
14214       }
14215     } else {
14216       Result.getComplexIntReal() -= RHS.getComplexIntReal();
14217       Result.getComplexIntImag() -= RHS.getComplexIntImag();
14218     }
14219     break;
14220   case BO_Mul:
14221     if (Result.isComplexFloat()) {
14222       // This is an implementation of complex multiplication according to the
14223       // constraints laid out in C11 Annex G. The implementation uses the
14224       // following naming scheme:
14225       //   (a + ib) * (c + id)
14226       ComplexValue LHS = Result;
14227       APFloat &A = LHS.getComplexFloatReal();
14228       APFloat &B = LHS.getComplexFloatImag();
14229       APFloat &C = RHS.getComplexFloatReal();
14230       APFloat &D = RHS.getComplexFloatImag();
14231       APFloat &ResR = Result.getComplexFloatReal();
14232       APFloat &ResI = Result.getComplexFloatImag();
14233       if (LHSReal) {
14234         assert(!RHSReal && "Cannot have two real operands for a complex op!");
14235         ResR = A * C;
14236         ResI = A * D;
14237       } else if (RHSReal) {
14238         ResR = C * A;
14239         ResI = C * B;
14240       } else {
14241         // In the fully general case, we need to handle NaNs and infinities
14242         // robustly.
14243         APFloat AC = A * C;
14244         APFloat BD = B * D;
14245         APFloat AD = A * D;
14246         APFloat BC = B * C;
14247         ResR = AC - BD;
14248         ResI = AD + BC;
14249         if (ResR.isNaN() && ResI.isNaN()) {
14250           bool Recalc = false;
14251           if (A.isInfinity() || B.isInfinity()) {
14252             A = APFloat::copySign(
14253                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14254             B = APFloat::copySign(
14255                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14256             if (C.isNaN())
14257               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14258             if (D.isNaN())
14259               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14260             Recalc = true;
14261           }
14262           if (C.isInfinity() || D.isInfinity()) {
14263             C = APFloat::copySign(
14264                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14265             D = APFloat::copySign(
14266                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14267             if (A.isNaN())
14268               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14269             if (B.isNaN())
14270               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14271             Recalc = true;
14272           }
14273           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
14274                           AD.isInfinity() || BC.isInfinity())) {
14275             if (A.isNaN())
14276               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14277             if (B.isNaN())
14278               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14279             if (C.isNaN())
14280               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14281             if (D.isNaN())
14282               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14283             Recalc = true;
14284           }
14285           if (Recalc) {
14286             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
14287             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
14288           }
14289         }
14290       }
14291     } else {
14292       ComplexValue LHS = Result;
14293       Result.getComplexIntReal() =
14294         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
14295          LHS.getComplexIntImag() * RHS.getComplexIntImag());
14296       Result.getComplexIntImag() =
14297         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
14298          LHS.getComplexIntImag() * RHS.getComplexIntReal());
14299     }
14300     break;
14301   case BO_Div:
14302     if (Result.isComplexFloat()) {
14303       // This is an implementation of complex division according to the
14304       // constraints laid out in C11 Annex G. The implementation uses the
14305       // following naming scheme:
14306       //   (a + ib) / (c + id)
14307       ComplexValue LHS = Result;
14308       APFloat &A = LHS.getComplexFloatReal();
14309       APFloat &B = LHS.getComplexFloatImag();
14310       APFloat &C = RHS.getComplexFloatReal();
14311       APFloat &D = RHS.getComplexFloatImag();
14312       APFloat &ResR = Result.getComplexFloatReal();
14313       APFloat &ResI = Result.getComplexFloatImag();
14314       if (RHSReal) {
14315         ResR = A / C;
14316         ResI = B / C;
14317       } else {
14318         if (LHSReal) {
14319           // No real optimizations we can do here, stub out with zero.
14320           B = APFloat::getZero(A.getSemantics());
14321         }
14322         int DenomLogB = 0;
14323         APFloat MaxCD = maxnum(abs(C), abs(D));
14324         if (MaxCD.isFinite()) {
14325           DenomLogB = ilogb(MaxCD);
14326           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
14327           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
14328         }
14329         APFloat Denom = C * C + D * D;
14330         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
14331                       APFloat::rmNearestTiesToEven);
14332         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
14333                       APFloat::rmNearestTiesToEven);
14334         if (ResR.isNaN() && ResI.isNaN()) {
14335           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
14336             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
14337             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
14338           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
14339                      D.isFinite()) {
14340             A = APFloat::copySign(
14341                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14342             B = APFloat::copySign(
14343                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14344             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
14345             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
14346           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
14347             C = APFloat::copySign(
14348                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14349             D = APFloat::copySign(
14350                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14351             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
14352             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
14353           }
14354         }
14355       }
14356     } else {
14357       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
14358         return Error(E, diag::note_expr_divide_by_zero);
14359 
14360       ComplexValue LHS = Result;
14361       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
14362         RHS.getComplexIntImag() * RHS.getComplexIntImag();
14363       Result.getComplexIntReal() =
14364         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
14365          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
14366       Result.getComplexIntImag() =
14367         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
14368          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
14369     }
14370     break;
14371   }
14372 
14373   return true;
14374 }
14375 
14376 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14377   // Get the operand value into 'Result'.
14378   if (!Visit(E->getSubExpr()))
14379     return false;
14380 
14381   switch (E->getOpcode()) {
14382   default:
14383     return Error(E);
14384   case UO_Extension:
14385     return true;
14386   case UO_Plus:
14387     // The result is always just the subexpr.
14388     return true;
14389   case UO_Minus:
14390     if (Result.isComplexFloat()) {
14391       Result.getComplexFloatReal().changeSign();
14392       Result.getComplexFloatImag().changeSign();
14393     }
14394     else {
14395       Result.getComplexIntReal() = -Result.getComplexIntReal();
14396       Result.getComplexIntImag() = -Result.getComplexIntImag();
14397     }
14398     return true;
14399   case UO_Not:
14400     if (Result.isComplexFloat())
14401       Result.getComplexFloatImag().changeSign();
14402     else
14403       Result.getComplexIntImag() = -Result.getComplexIntImag();
14404     return true;
14405   }
14406 }
14407 
14408 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
14409   if (E->getNumInits() == 2) {
14410     if (E->getType()->isComplexType()) {
14411       Result.makeComplexFloat();
14412       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
14413         return false;
14414       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
14415         return false;
14416     } else {
14417       Result.makeComplexInt();
14418       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
14419         return false;
14420       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
14421         return false;
14422     }
14423     return true;
14424   }
14425   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
14426 }
14427 
14428 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
14429   switch (E->getBuiltinCallee()) {
14430   case Builtin::BI__builtin_complex:
14431     Result.makeComplexFloat();
14432     if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
14433       return false;
14434     if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
14435       return false;
14436     return true;
14437 
14438   default:
14439     break;
14440   }
14441 
14442   return ExprEvaluatorBaseTy::VisitCallExpr(E);
14443 }
14444 
14445 //===----------------------------------------------------------------------===//
14446 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
14447 // implicit conversion.
14448 //===----------------------------------------------------------------------===//
14449 
14450 namespace {
14451 class AtomicExprEvaluator :
14452     public ExprEvaluatorBase<AtomicExprEvaluator> {
14453   const LValue *This;
14454   APValue &Result;
14455 public:
14456   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
14457       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
14458 
14459   bool Success(const APValue &V, const Expr *E) {
14460     Result = V;
14461     return true;
14462   }
14463 
14464   bool ZeroInitialization(const Expr *E) {
14465     ImplicitValueInitExpr VIE(
14466         E->getType()->castAs<AtomicType>()->getValueType());
14467     // For atomic-qualified class (and array) types in C++, initialize the
14468     // _Atomic-wrapped subobject directly, in-place.
14469     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
14470                 : Evaluate(Result, Info, &VIE);
14471   }
14472 
14473   bool VisitCastExpr(const CastExpr *E) {
14474     switch (E->getCastKind()) {
14475     default:
14476       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14477     case CK_NonAtomicToAtomic:
14478       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
14479                   : Evaluate(Result, Info, E->getSubExpr());
14480     }
14481   }
14482 };
14483 } // end anonymous namespace
14484 
14485 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
14486                            EvalInfo &Info) {
14487   assert(!E->isValueDependent());
14488   assert(E->isPRValue() && E->getType()->isAtomicType());
14489   return AtomicExprEvaluator(Info, This, Result).Visit(E);
14490 }
14491 
14492 //===----------------------------------------------------------------------===//
14493 // Void expression evaluation, primarily for a cast to void on the LHS of a
14494 // comma operator
14495 //===----------------------------------------------------------------------===//
14496 
14497 namespace {
14498 class VoidExprEvaluator
14499   : public ExprEvaluatorBase<VoidExprEvaluator> {
14500 public:
14501   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
14502 
14503   bool Success(const APValue &V, const Expr *e) { return true; }
14504 
14505   bool ZeroInitialization(const Expr *E) { return true; }
14506 
14507   bool VisitCastExpr(const CastExpr *E) {
14508     switch (E->getCastKind()) {
14509     default:
14510       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14511     case CK_ToVoid:
14512       VisitIgnoredValue(E->getSubExpr());
14513       return true;
14514     }
14515   }
14516 
14517   bool VisitCallExpr(const CallExpr *E) {
14518     switch (E->getBuiltinCallee()) {
14519     case Builtin::BI__assume:
14520     case Builtin::BI__builtin_assume:
14521       // The argument is not evaluated!
14522       return true;
14523 
14524     case Builtin::BI__builtin_operator_delete:
14525       return HandleOperatorDeleteCall(Info, E);
14526 
14527     default:
14528       break;
14529     }
14530 
14531     return ExprEvaluatorBaseTy::VisitCallExpr(E);
14532   }
14533 
14534   bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
14535 };
14536 } // end anonymous namespace
14537 
14538 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
14539   // We cannot speculatively evaluate a delete expression.
14540   if (Info.SpeculativeEvaluationDepth)
14541     return false;
14542 
14543   FunctionDecl *OperatorDelete = E->getOperatorDelete();
14544   if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
14545     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14546         << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
14547     return false;
14548   }
14549 
14550   const Expr *Arg = E->getArgument();
14551 
14552   LValue Pointer;
14553   if (!EvaluatePointer(Arg, Pointer, Info))
14554     return false;
14555   if (Pointer.Designator.Invalid)
14556     return false;
14557 
14558   // Deleting a null pointer has no effect.
14559   if (Pointer.isNullPointer()) {
14560     // This is the only case where we need to produce an extension warning:
14561     // the only other way we can succeed is if we find a dynamic allocation,
14562     // and we will have warned when we allocated it in that case.
14563     if (!Info.getLangOpts().CPlusPlus20)
14564       Info.CCEDiag(E, diag::note_constexpr_new);
14565     return true;
14566   }
14567 
14568   Optional<DynAlloc *> Alloc = CheckDeleteKind(
14569       Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
14570   if (!Alloc)
14571     return false;
14572   QualType AllocType = Pointer.Base.getDynamicAllocType();
14573 
14574   // For the non-array case, the designator must be empty if the static type
14575   // does not have a virtual destructor.
14576   if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
14577       !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
14578     Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
14579         << Arg->getType()->getPointeeType() << AllocType;
14580     return false;
14581   }
14582 
14583   // For a class type with a virtual destructor, the selected operator delete
14584   // is the one looked up when building the destructor.
14585   if (!E->isArrayForm() && !E->isGlobalDelete()) {
14586     const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
14587     if (VirtualDelete &&
14588         !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
14589       Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14590           << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
14591       return false;
14592     }
14593   }
14594 
14595   if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
14596                          (*Alloc)->Value, AllocType))
14597     return false;
14598 
14599   if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
14600     // The element was already erased. This means the destructor call also
14601     // deleted the object.
14602     // FIXME: This probably results in undefined behavior before we get this
14603     // far, and should be diagnosed elsewhere first.
14604     Info.FFDiag(E, diag::note_constexpr_double_delete);
14605     return false;
14606   }
14607 
14608   return true;
14609 }
14610 
14611 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
14612   assert(!E->isValueDependent());
14613   assert(E->isPRValue() && E->getType()->isVoidType());
14614   return VoidExprEvaluator(Info).Visit(E);
14615 }
14616 
14617 //===----------------------------------------------------------------------===//
14618 // Top level Expr::EvaluateAsRValue method.
14619 //===----------------------------------------------------------------------===//
14620 
14621 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
14622   assert(!E->isValueDependent());
14623   // In C, function designators are not lvalues, but we evaluate them as if they
14624   // are.
14625   QualType T = E->getType();
14626   if (E->isGLValue() || T->isFunctionType()) {
14627     LValue LV;
14628     if (!EvaluateLValue(E, LV, Info))
14629       return false;
14630     LV.moveInto(Result);
14631   } else if (T->isVectorType()) {
14632     if (!EvaluateVector(E, Result, Info))
14633       return false;
14634   } else if (T->isIntegralOrEnumerationType()) {
14635     if (!IntExprEvaluator(Info, Result).Visit(E))
14636       return false;
14637   } else if (T->hasPointerRepresentation()) {
14638     LValue LV;
14639     if (!EvaluatePointer(E, LV, Info))
14640       return false;
14641     LV.moveInto(Result);
14642   } else if (T->isRealFloatingType()) {
14643     llvm::APFloat F(0.0);
14644     if (!EvaluateFloat(E, F, Info))
14645       return false;
14646     Result = APValue(F);
14647   } else if (T->isAnyComplexType()) {
14648     ComplexValue C;
14649     if (!EvaluateComplex(E, C, Info))
14650       return false;
14651     C.moveInto(Result);
14652   } else if (T->isFixedPointType()) {
14653     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
14654   } else if (T->isMemberPointerType()) {
14655     MemberPtr P;
14656     if (!EvaluateMemberPointer(E, P, Info))
14657       return false;
14658     P.moveInto(Result);
14659     return true;
14660   } else if (T->isArrayType()) {
14661     LValue LV;
14662     APValue &Value =
14663         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14664     if (!EvaluateArray(E, LV, Value, Info))
14665       return false;
14666     Result = Value;
14667   } else if (T->isRecordType()) {
14668     LValue LV;
14669     APValue &Value =
14670         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14671     if (!EvaluateRecord(E, LV, Value, Info))
14672       return false;
14673     Result = Value;
14674   } else if (T->isVoidType()) {
14675     if (!Info.getLangOpts().CPlusPlus11)
14676       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
14677         << E->getType();
14678     if (!EvaluateVoid(E, Info))
14679       return false;
14680   } else if (T->isAtomicType()) {
14681     QualType Unqual = T.getAtomicUnqualifiedType();
14682     if (Unqual->isArrayType() || Unqual->isRecordType()) {
14683       LValue LV;
14684       APValue &Value = Info.CurrentCall->createTemporary(
14685           E, Unqual, ScopeKind::FullExpression, LV);
14686       if (!EvaluateAtomic(E, &LV, Value, Info))
14687         return false;
14688     } else {
14689       if (!EvaluateAtomic(E, nullptr, Result, Info))
14690         return false;
14691     }
14692   } else if (Info.getLangOpts().CPlusPlus11) {
14693     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
14694     return false;
14695   } else {
14696     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
14697     return false;
14698   }
14699 
14700   return true;
14701 }
14702 
14703 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
14704 /// cases, the in-place evaluation is essential, since later initializers for
14705 /// an object can indirectly refer to subobjects which were initialized earlier.
14706 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
14707                             const Expr *E, bool AllowNonLiteralTypes) {
14708   assert(!E->isValueDependent());
14709 
14710   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
14711     return false;
14712 
14713   if (E->isPRValue()) {
14714     // Evaluate arrays and record types in-place, so that later initializers can
14715     // refer to earlier-initialized members of the object.
14716     QualType T = E->getType();
14717     if (T->isArrayType())
14718       return EvaluateArray(E, This, Result, Info);
14719     else if (T->isRecordType())
14720       return EvaluateRecord(E, This, Result, Info);
14721     else if (T->isAtomicType()) {
14722       QualType Unqual = T.getAtomicUnqualifiedType();
14723       if (Unqual->isArrayType() || Unqual->isRecordType())
14724         return EvaluateAtomic(E, &This, Result, Info);
14725     }
14726   }
14727 
14728   // For any other type, in-place evaluation is unimportant.
14729   return Evaluate(Result, Info, E);
14730 }
14731 
14732 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
14733 /// lvalue-to-rvalue cast if it is an lvalue.
14734 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
14735   assert(!E->isValueDependent());
14736   if (Info.EnableNewConstInterp) {
14737     if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
14738       return false;
14739   } else {
14740     if (E->getType().isNull())
14741       return false;
14742 
14743     if (!CheckLiteralType(Info, E))
14744       return false;
14745 
14746     if (!::Evaluate(Result, Info, E))
14747       return false;
14748 
14749     if (E->isGLValue()) {
14750       LValue LV;
14751       LV.setFrom(Info.Ctx, Result);
14752       if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
14753         return false;
14754     }
14755   }
14756 
14757   // Check this core constant expression is a constant expression.
14758   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
14759                                  ConstantExprKind::Normal) &&
14760          CheckMemoryLeaks(Info);
14761 }
14762 
14763 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
14764                                  const ASTContext &Ctx, bool &IsConst) {
14765   // Fast-path evaluations of integer literals, since we sometimes see files
14766   // containing vast quantities of these.
14767   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
14768     Result.Val = APValue(APSInt(L->getValue(),
14769                                 L->getType()->isUnsignedIntegerType()));
14770     IsConst = true;
14771     return true;
14772   }
14773 
14774   // This case should be rare, but we need to check it before we check on
14775   // the type below.
14776   if (Exp->getType().isNull()) {
14777     IsConst = false;
14778     return true;
14779   }
14780 
14781   // FIXME: Evaluating values of large array and record types can cause
14782   // performance problems. Only do so in C++11 for now.
14783   if (Exp->isPRValue() &&
14784       (Exp->getType()->isArrayType() || Exp->getType()->isRecordType()) &&
14785       !Ctx.getLangOpts().CPlusPlus11) {
14786     IsConst = false;
14787     return true;
14788   }
14789   return false;
14790 }
14791 
14792 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
14793                                       Expr::SideEffectsKind SEK) {
14794   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
14795          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
14796 }
14797 
14798 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
14799                              const ASTContext &Ctx, EvalInfo &Info) {
14800   assert(!E->isValueDependent());
14801   bool IsConst;
14802   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
14803     return IsConst;
14804 
14805   return EvaluateAsRValue(Info, E, Result.Val);
14806 }
14807 
14808 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
14809                           const ASTContext &Ctx,
14810                           Expr::SideEffectsKind AllowSideEffects,
14811                           EvalInfo &Info) {
14812   assert(!E->isValueDependent());
14813   if (!E->getType()->isIntegralOrEnumerationType())
14814     return false;
14815 
14816   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
14817       !ExprResult.Val.isInt() ||
14818       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14819     return false;
14820 
14821   return true;
14822 }
14823 
14824 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
14825                                  const ASTContext &Ctx,
14826                                  Expr::SideEffectsKind AllowSideEffects,
14827                                  EvalInfo &Info) {
14828   assert(!E->isValueDependent());
14829   if (!E->getType()->isFixedPointType())
14830     return false;
14831 
14832   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
14833     return false;
14834 
14835   if (!ExprResult.Val.isFixedPoint() ||
14836       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14837     return false;
14838 
14839   return true;
14840 }
14841 
14842 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
14843 /// any crazy technique (that has nothing to do with language standards) that
14844 /// we want to.  If this function returns true, it returns the folded constant
14845 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
14846 /// will be applied to the result.
14847 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
14848                             bool InConstantContext) const {
14849   assert(!isValueDependent() &&
14850          "Expression evaluator can't be called on a dependent expression.");
14851   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14852   Info.InConstantContext = InConstantContext;
14853   return ::EvaluateAsRValue(this, Result, Ctx, Info);
14854 }
14855 
14856 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
14857                                       bool InConstantContext) const {
14858   assert(!isValueDependent() &&
14859          "Expression evaluator can't be called on a dependent expression.");
14860   EvalResult Scratch;
14861   return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
14862          HandleConversionToBool(Scratch.Val, Result);
14863 }
14864 
14865 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
14866                          SideEffectsKind AllowSideEffects,
14867                          bool InConstantContext) const {
14868   assert(!isValueDependent() &&
14869          "Expression evaluator can't be called on a dependent expression.");
14870   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14871   Info.InConstantContext = InConstantContext;
14872   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
14873 }
14874 
14875 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
14876                                 SideEffectsKind AllowSideEffects,
14877                                 bool InConstantContext) const {
14878   assert(!isValueDependent() &&
14879          "Expression evaluator can't be called on a dependent expression.");
14880   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14881   Info.InConstantContext = InConstantContext;
14882   return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
14883 }
14884 
14885 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
14886                            SideEffectsKind AllowSideEffects,
14887                            bool InConstantContext) const {
14888   assert(!isValueDependent() &&
14889          "Expression evaluator can't be called on a dependent expression.");
14890 
14891   if (!getType()->isRealFloatingType())
14892     return false;
14893 
14894   EvalResult ExprResult;
14895   if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
14896       !ExprResult.Val.isFloat() ||
14897       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14898     return false;
14899 
14900   Result = ExprResult.Val.getFloat();
14901   return true;
14902 }
14903 
14904 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
14905                             bool InConstantContext) const {
14906   assert(!isValueDependent() &&
14907          "Expression evaluator can't be called on a dependent expression.");
14908 
14909   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
14910   Info.InConstantContext = InConstantContext;
14911   LValue LV;
14912   CheckedTemporaries CheckedTemps;
14913   if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
14914       Result.HasSideEffects ||
14915       !CheckLValueConstantExpression(Info, getExprLoc(),
14916                                      Ctx.getLValueReferenceType(getType()), LV,
14917                                      ConstantExprKind::Normal, CheckedTemps))
14918     return false;
14919 
14920   LV.moveInto(Result.Val);
14921   return true;
14922 }
14923 
14924 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base,
14925                                 APValue DestroyedValue, QualType Type,
14926                                 SourceLocation Loc, Expr::EvalStatus &EStatus,
14927                                 bool IsConstantDestruction) {
14928   EvalInfo Info(Ctx, EStatus,
14929                 IsConstantDestruction ? EvalInfo::EM_ConstantExpression
14930                                       : EvalInfo::EM_ConstantFold);
14931   Info.setEvaluatingDecl(Base, DestroyedValue,
14932                          EvalInfo::EvaluatingDeclKind::Dtor);
14933   Info.InConstantContext = IsConstantDestruction;
14934 
14935   LValue LVal;
14936   LVal.set(Base);
14937 
14938   if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
14939       EStatus.HasSideEffects)
14940     return false;
14941 
14942   if (!Info.discardCleanups())
14943     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14944 
14945   return true;
14946 }
14947 
14948 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx,
14949                                   ConstantExprKind Kind) const {
14950   assert(!isValueDependent() &&
14951          "Expression evaluator can't be called on a dependent expression.");
14952 
14953   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
14954   EvalInfo Info(Ctx, Result, EM);
14955   Info.InConstantContext = true;
14956 
14957   // The type of the object we're initializing is 'const T' for a class NTTP.
14958   QualType T = getType();
14959   if (Kind == ConstantExprKind::ClassTemplateArgument)
14960     T.addConst();
14961 
14962   // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
14963   // represent the result of the evaluation. CheckConstantExpression ensures
14964   // this doesn't escape.
14965   MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
14966   APValue::LValueBase Base(&BaseMTE);
14967 
14968   Info.setEvaluatingDecl(Base, Result.Val);
14969   LValue LVal;
14970   LVal.set(Base);
14971 
14972   if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || Result.HasSideEffects)
14973     return false;
14974 
14975   if (!Info.discardCleanups())
14976     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14977 
14978   if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
14979                                Result.Val, Kind))
14980     return false;
14981   if (!CheckMemoryLeaks(Info))
14982     return false;
14983 
14984   // If this is a class template argument, it's required to have constant
14985   // destruction too.
14986   if (Kind == ConstantExprKind::ClassTemplateArgument &&
14987       (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result,
14988                             true) ||
14989        Result.HasSideEffects)) {
14990     // FIXME: Prefix a note to indicate that the problem is lack of constant
14991     // destruction.
14992     return false;
14993   }
14994 
14995   return true;
14996 }
14997 
14998 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
14999                                  const VarDecl *VD,
15000                                  SmallVectorImpl<PartialDiagnosticAt> &Notes,
15001                                  bool IsConstantInitialization) const {
15002   assert(!isValueDependent() &&
15003          "Expression evaluator can't be called on a dependent expression.");
15004 
15005   // FIXME: Evaluating initializers for large array and record types can cause
15006   // performance problems. Only do so in C++11 for now.
15007   if (isPRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
15008       !Ctx.getLangOpts().CPlusPlus11)
15009     return false;
15010 
15011   Expr::EvalStatus EStatus;
15012   EStatus.Diag = &Notes;
15013 
15014   EvalInfo Info(Ctx, EStatus,
15015                 (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11)
15016                     ? EvalInfo::EM_ConstantExpression
15017                     : EvalInfo::EM_ConstantFold);
15018   Info.setEvaluatingDecl(VD, Value);
15019   Info.InConstantContext = IsConstantInitialization;
15020 
15021   SourceLocation DeclLoc = VD->getLocation();
15022   QualType DeclTy = VD->getType();
15023 
15024   if (Info.EnableNewConstInterp) {
15025     auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
15026     if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
15027       return false;
15028   } else {
15029     LValue LVal;
15030     LVal.set(VD);
15031 
15032     if (!EvaluateInPlace(Value, Info, LVal, this,
15033                          /*AllowNonLiteralTypes=*/true) ||
15034         EStatus.HasSideEffects)
15035       return false;
15036 
15037     // At this point, any lifetime-extended temporaries are completely
15038     // initialized.
15039     Info.performLifetimeExtension();
15040 
15041     if (!Info.discardCleanups())
15042       llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15043   }
15044   return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
15045                                  ConstantExprKind::Normal) &&
15046          CheckMemoryLeaks(Info);
15047 }
15048 
15049 bool VarDecl::evaluateDestruction(
15050     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
15051   Expr::EvalStatus EStatus;
15052   EStatus.Diag = &Notes;
15053 
15054   // Only treat the destruction as constant destruction if we formally have
15055   // constant initialization (or are usable in a constant expression).
15056   bool IsConstantDestruction = hasConstantInitialization();
15057 
15058   // Make a copy of the value for the destructor to mutate, if we know it.
15059   // Otherwise, treat the value as default-initialized; if the destructor works
15060   // anyway, then the destruction is constant (and must be essentially empty).
15061   APValue DestroyedValue;
15062   if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
15063     DestroyedValue = *getEvaluatedValue();
15064   else if (!getDefaultInitValue(getType(), DestroyedValue))
15065     return false;
15066 
15067   if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
15068                            getType(), getLocation(), EStatus,
15069                            IsConstantDestruction) ||
15070       EStatus.HasSideEffects)
15071     return false;
15072 
15073   ensureEvaluatedStmt()->HasConstantDestruction = true;
15074   return true;
15075 }
15076 
15077 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
15078 /// constant folded, but discard the result.
15079 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
15080   assert(!isValueDependent() &&
15081          "Expression evaluator can't be called on a dependent expression.");
15082 
15083   EvalResult Result;
15084   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
15085          !hasUnacceptableSideEffect(Result, SEK);
15086 }
15087 
15088 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
15089                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
15090   assert(!isValueDependent() &&
15091          "Expression evaluator can't be called on a dependent expression.");
15092 
15093   EvalResult EVResult;
15094   EVResult.Diag = Diag;
15095   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15096   Info.InConstantContext = true;
15097 
15098   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
15099   (void)Result;
15100   assert(Result && "Could not evaluate expression");
15101   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
15102 
15103   return EVResult.Val.getInt();
15104 }
15105 
15106 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
15107     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
15108   assert(!isValueDependent() &&
15109          "Expression evaluator can't be called on a dependent expression.");
15110 
15111   EvalResult EVResult;
15112   EVResult.Diag = Diag;
15113   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15114   Info.InConstantContext = true;
15115   Info.CheckingForUndefinedBehavior = true;
15116 
15117   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
15118   (void)Result;
15119   assert(Result && "Could not evaluate expression");
15120   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
15121 
15122   return EVResult.Val.getInt();
15123 }
15124 
15125 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
15126   assert(!isValueDependent() &&
15127          "Expression evaluator can't be called on a dependent expression.");
15128 
15129   bool IsConst;
15130   EvalResult EVResult;
15131   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
15132     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15133     Info.CheckingForUndefinedBehavior = true;
15134     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
15135   }
15136 }
15137 
15138 bool Expr::EvalResult::isGlobalLValue() const {
15139   assert(Val.isLValue());
15140   return IsGlobalLValue(Val.getLValueBase());
15141 }
15142 
15143 /// isIntegerConstantExpr - this recursive routine will test if an expression is
15144 /// an integer constant expression.
15145 
15146 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
15147 /// comma, etc
15148 
15149 // CheckICE - This function does the fundamental ICE checking: the returned
15150 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
15151 // and a (possibly null) SourceLocation indicating the location of the problem.
15152 //
15153 // Note that to reduce code duplication, this helper does no evaluation
15154 // itself; the caller checks whether the expression is evaluatable, and
15155 // in the rare cases where CheckICE actually cares about the evaluated
15156 // value, it calls into Evaluate.
15157 
15158 namespace {
15159 
15160 enum ICEKind {
15161   /// This expression is an ICE.
15162   IK_ICE,
15163   /// This expression is not an ICE, but if it isn't evaluated, it's
15164   /// a legal subexpression for an ICE. This return value is used to handle
15165   /// the comma operator in C99 mode, and non-constant subexpressions.
15166   IK_ICEIfUnevaluated,
15167   /// This expression is not an ICE, and is not a legal subexpression for one.
15168   IK_NotICE
15169 };
15170 
15171 struct ICEDiag {
15172   ICEKind Kind;
15173   SourceLocation Loc;
15174 
15175   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
15176 };
15177 
15178 }
15179 
15180 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
15181 
15182 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
15183 
15184 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
15185   Expr::EvalResult EVResult;
15186   Expr::EvalStatus Status;
15187   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15188 
15189   Info.InConstantContext = true;
15190   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
15191       !EVResult.Val.isInt())
15192     return ICEDiag(IK_NotICE, E->getBeginLoc());
15193 
15194   return NoDiag();
15195 }
15196 
15197 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
15198   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
15199   if (!E->getType()->isIntegralOrEnumerationType())
15200     return ICEDiag(IK_NotICE, E->getBeginLoc());
15201 
15202   switch (E->getStmtClass()) {
15203 #define ABSTRACT_STMT(Node)
15204 #define STMT(Node, Base) case Expr::Node##Class:
15205 #define EXPR(Node, Base)
15206 #include "clang/AST/StmtNodes.inc"
15207   case Expr::PredefinedExprClass:
15208   case Expr::FloatingLiteralClass:
15209   case Expr::ImaginaryLiteralClass:
15210   case Expr::StringLiteralClass:
15211   case Expr::ArraySubscriptExprClass:
15212   case Expr::MatrixSubscriptExprClass:
15213   case Expr::OMPArraySectionExprClass:
15214   case Expr::OMPArrayShapingExprClass:
15215   case Expr::OMPIteratorExprClass:
15216   case Expr::MemberExprClass:
15217   case Expr::CompoundAssignOperatorClass:
15218   case Expr::CompoundLiteralExprClass:
15219   case Expr::ExtVectorElementExprClass:
15220   case Expr::DesignatedInitExprClass:
15221   case Expr::ArrayInitLoopExprClass:
15222   case Expr::ArrayInitIndexExprClass:
15223   case Expr::NoInitExprClass:
15224   case Expr::DesignatedInitUpdateExprClass:
15225   case Expr::ImplicitValueInitExprClass:
15226   case Expr::ParenListExprClass:
15227   case Expr::VAArgExprClass:
15228   case Expr::AddrLabelExprClass:
15229   case Expr::StmtExprClass:
15230   case Expr::CXXMemberCallExprClass:
15231   case Expr::CUDAKernelCallExprClass:
15232   case Expr::CXXAddrspaceCastExprClass:
15233   case Expr::CXXDynamicCastExprClass:
15234   case Expr::CXXTypeidExprClass:
15235   case Expr::CXXUuidofExprClass:
15236   case Expr::MSPropertyRefExprClass:
15237   case Expr::MSPropertySubscriptExprClass:
15238   case Expr::CXXNullPtrLiteralExprClass:
15239   case Expr::UserDefinedLiteralClass:
15240   case Expr::CXXThisExprClass:
15241   case Expr::CXXThrowExprClass:
15242   case Expr::CXXNewExprClass:
15243   case Expr::CXXDeleteExprClass:
15244   case Expr::CXXPseudoDestructorExprClass:
15245   case Expr::UnresolvedLookupExprClass:
15246   case Expr::TypoExprClass:
15247   case Expr::RecoveryExprClass:
15248   case Expr::DependentScopeDeclRefExprClass:
15249   case Expr::CXXConstructExprClass:
15250   case Expr::CXXInheritedCtorInitExprClass:
15251   case Expr::CXXStdInitializerListExprClass:
15252   case Expr::CXXBindTemporaryExprClass:
15253   case Expr::ExprWithCleanupsClass:
15254   case Expr::CXXTemporaryObjectExprClass:
15255   case Expr::CXXUnresolvedConstructExprClass:
15256   case Expr::CXXDependentScopeMemberExprClass:
15257   case Expr::UnresolvedMemberExprClass:
15258   case Expr::ObjCStringLiteralClass:
15259   case Expr::ObjCBoxedExprClass:
15260   case Expr::ObjCArrayLiteralClass:
15261   case Expr::ObjCDictionaryLiteralClass:
15262   case Expr::ObjCEncodeExprClass:
15263   case Expr::ObjCMessageExprClass:
15264   case Expr::ObjCSelectorExprClass:
15265   case Expr::ObjCProtocolExprClass:
15266   case Expr::ObjCIvarRefExprClass:
15267   case Expr::ObjCPropertyRefExprClass:
15268   case Expr::ObjCSubscriptRefExprClass:
15269   case Expr::ObjCIsaExprClass:
15270   case Expr::ObjCAvailabilityCheckExprClass:
15271   case Expr::ShuffleVectorExprClass:
15272   case Expr::ConvertVectorExprClass:
15273   case Expr::BlockExprClass:
15274   case Expr::NoStmtClass:
15275   case Expr::OpaqueValueExprClass:
15276   case Expr::PackExpansionExprClass:
15277   case Expr::SubstNonTypeTemplateParmPackExprClass:
15278   case Expr::FunctionParmPackExprClass:
15279   case Expr::AsTypeExprClass:
15280   case Expr::ObjCIndirectCopyRestoreExprClass:
15281   case Expr::MaterializeTemporaryExprClass:
15282   case Expr::PseudoObjectExprClass:
15283   case Expr::AtomicExprClass:
15284   case Expr::LambdaExprClass:
15285   case Expr::CXXFoldExprClass:
15286   case Expr::CoawaitExprClass:
15287   case Expr::DependentCoawaitExprClass:
15288   case Expr::CoyieldExprClass:
15289   case Expr::SYCLUniqueStableNameExprClass:
15290     return ICEDiag(IK_NotICE, E->getBeginLoc());
15291 
15292   case Expr::InitListExprClass: {
15293     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
15294     // form "T x = { a };" is equivalent to "T x = a;".
15295     // Unless we're initializing a reference, T is a scalar as it is known to be
15296     // of integral or enumeration type.
15297     if (E->isPRValue())
15298       if (cast<InitListExpr>(E)->getNumInits() == 1)
15299         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
15300     return ICEDiag(IK_NotICE, E->getBeginLoc());
15301   }
15302 
15303   case Expr::SizeOfPackExprClass:
15304   case Expr::GNUNullExprClass:
15305   case Expr::SourceLocExprClass:
15306     return NoDiag();
15307 
15308   case Expr::SubstNonTypeTemplateParmExprClass:
15309     return
15310       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
15311 
15312   case Expr::ConstantExprClass:
15313     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
15314 
15315   case Expr::ParenExprClass:
15316     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
15317   case Expr::GenericSelectionExprClass:
15318     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
15319   case Expr::IntegerLiteralClass:
15320   case Expr::FixedPointLiteralClass:
15321   case Expr::CharacterLiteralClass:
15322   case Expr::ObjCBoolLiteralExprClass:
15323   case Expr::CXXBoolLiteralExprClass:
15324   case Expr::CXXScalarValueInitExprClass:
15325   case Expr::TypeTraitExprClass:
15326   case Expr::ConceptSpecializationExprClass:
15327   case Expr::RequiresExprClass:
15328   case Expr::ArrayTypeTraitExprClass:
15329   case Expr::ExpressionTraitExprClass:
15330   case Expr::CXXNoexceptExprClass:
15331     return NoDiag();
15332   case Expr::CallExprClass:
15333   case Expr::CXXOperatorCallExprClass: {
15334     // C99 6.6/3 allows function calls within unevaluated subexpressions of
15335     // constant expressions, but they can never be ICEs because an ICE cannot
15336     // contain an operand of (pointer to) function type.
15337     const CallExpr *CE = cast<CallExpr>(E);
15338     if (CE->getBuiltinCallee())
15339       return CheckEvalInICE(E, Ctx);
15340     return ICEDiag(IK_NotICE, E->getBeginLoc());
15341   }
15342   case Expr::CXXRewrittenBinaryOperatorClass:
15343     return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
15344                     Ctx);
15345   case Expr::DeclRefExprClass: {
15346     const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
15347     if (isa<EnumConstantDecl>(D))
15348       return NoDiag();
15349 
15350     // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
15351     // integer variables in constant expressions:
15352     //
15353     // C++ 7.1.5.1p2
15354     //   A variable of non-volatile const-qualified integral or enumeration
15355     //   type initialized by an ICE can be used in ICEs.
15356     //
15357     // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
15358     // that mode, use of reference variables should not be allowed.
15359     const VarDecl *VD = dyn_cast<VarDecl>(D);
15360     if (VD && VD->isUsableInConstantExpressions(Ctx) &&
15361         !VD->getType()->isReferenceType())
15362       return NoDiag();
15363 
15364     return ICEDiag(IK_NotICE, E->getBeginLoc());
15365   }
15366   case Expr::UnaryOperatorClass: {
15367     const UnaryOperator *Exp = cast<UnaryOperator>(E);
15368     switch (Exp->getOpcode()) {
15369     case UO_PostInc:
15370     case UO_PostDec:
15371     case UO_PreInc:
15372     case UO_PreDec:
15373     case UO_AddrOf:
15374     case UO_Deref:
15375     case UO_Coawait:
15376       // C99 6.6/3 allows increment and decrement within unevaluated
15377       // subexpressions of constant expressions, but they can never be ICEs
15378       // because an ICE cannot contain an lvalue operand.
15379       return ICEDiag(IK_NotICE, E->getBeginLoc());
15380     case UO_Extension:
15381     case UO_LNot:
15382     case UO_Plus:
15383     case UO_Minus:
15384     case UO_Not:
15385     case UO_Real:
15386     case UO_Imag:
15387       return CheckICE(Exp->getSubExpr(), Ctx);
15388     }
15389     llvm_unreachable("invalid unary operator class");
15390   }
15391   case Expr::OffsetOfExprClass: {
15392     // Note that per C99, offsetof must be an ICE. And AFAIK, using
15393     // EvaluateAsRValue matches the proposed gcc behavior for cases like
15394     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
15395     // compliance: we should warn earlier for offsetof expressions with
15396     // array subscripts that aren't ICEs, and if the array subscripts
15397     // are ICEs, the value of the offsetof must be an integer constant.
15398     return CheckEvalInICE(E, Ctx);
15399   }
15400   case Expr::UnaryExprOrTypeTraitExprClass: {
15401     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
15402     if ((Exp->getKind() ==  UETT_SizeOf) &&
15403         Exp->getTypeOfArgument()->isVariableArrayType())
15404       return ICEDiag(IK_NotICE, E->getBeginLoc());
15405     return NoDiag();
15406   }
15407   case Expr::BinaryOperatorClass: {
15408     const BinaryOperator *Exp = cast<BinaryOperator>(E);
15409     switch (Exp->getOpcode()) {
15410     case BO_PtrMemD:
15411     case BO_PtrMemI:
15412     case BO_Assign:
15413     case BO_MulAssign:
15414     case BO_DivAssign:
15415     case BO_RemAssign:
15416     case BO_AddAssign:
15417     case BO_SubAssign:
15418     case BO_ShlAssign:
15419     case BO_ShrAssign:
15420     case BO_AndAssign:
15421     case BO_XorAssign:
15422     case BO_OrAssign:
15423       // C99 6.6/3 allows assignments within unevaluated subexpressions of
15424       // constant expressions, but they can never be ICEs because an ICE cannot
15425       // contain an lvalue operand.
15426       return ICEDiag(IK_NotICE, E->getBeginLoc());
15427 
15428     case BO_Mul:
15429     case BO_Div:
15430     case BO_Rem:
15431     case BO_Add:
15432     case BO_Sub:
15433     case BO_Shl:
15434     case BO_Shr:
15435     case BO_LT:
15436     case BO_GT:
15437     case BO_LE:
15438     case BO_GE:
15439     case BO_EQ:
15440     case BO_NE:
15441     case BO_And:
15442     case BO_Xor:
15443     case BO_Or:
15444     case BO_Comma:
15445     case BO_Cmp: {
15446       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15447       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15448       if (Exp->getOpcode() == BO_Div ||
15449           Exp->getOpcode() == BO_Rem) {
15450         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
15451         // we don't evaluate one.
15452         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
15453           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
15454           if (REval == 0)
15455             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15456           if (REval.isSigned() && REval.isAllOnes()) {
15457             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
15458             if (LEval.isMinSignedValue())
15459               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15460           }
15461         }
15462       }
15463       if (Exp->getOpcode() == BO_Comma) {
15464         if (Ctx.getLangOpts().C99) {
15465           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
15466           // if it isn't evaluated.
15467           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
15468             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15469         } else {
15470           // In both C89 and C++, commas in ICEs are illegal.
15471           return ICEDiag(IK_NotICE, E->getBeginLoc());
15472         }
15473       }
15474       return Worst(LHSResult, RHSResult);
15475     }
15476     case BO_LAnd:
15477     case BO_LOr: {
15478       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15479       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15480       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
15481         // Rare case where the RHS has a comma "side-effect"; we need
15482         // to actually check the condition to see whether the side
15483         // with the comma is evaluated.
15484         if ((Exp->getOpcode() == BO_LAnd) !=
15485             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
15486           return RHSResult;
15487         return NoDiag();
15488       }
15489 
15490       return Worst(LHSResult, RHSResult);
15491     }
15492     }
15493     llvm_unreachable("invalid binary operator kind");
15494   }
15495   case Expr::ImplicitCastExprClass:
15496   case Expr::CStyleCastExprClass:
15497   case Expr::CXXFunctionalCastExprClass:
15498   case Expr::CXXStaticCastExprClass:
15499   case Expr::CXXReinterpretCastExprClass:
15500   case Expr::CXXConstCastExprClass:
15501   case Expr::ObjCBridgedCastExprClass: {
15502     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
15503     if (isa<ExplicitCastExpr>(E)) {
15504       if (const FloatingLiteral *FL
15505             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
15506         unsigned DestWidth = Ctx.getIntWidth(E->getType());
15507         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
15508         APSInt IgnoredVal(DestWidth, !DestSigned);
15509         bool Ignored;
15510         // If the value does not fit in the destination type, the behavior is
15511         // undefined, so we are not required to treat it as a constant
15512         // expression.
15513         if (FL->getValue().convertToInteger(IgnoredVal,
15514                                             llvm::APFloat::rmTowardZero,
15515                                             &Ignored) & APFloat::opInvalidOp)
15516           return ICEDiag(IK_NotICE, E->getBeginLoc());
15517         return NoDiag();
15518       }
15519     }
15520     switch (cast<CastExpr>(E)->getCastKind()) {
15521     case CK_LValueToRValue:
15522     case CK_AtomicToNonAtomic:
15523     case CK_NonAtomicToAtomic:
15524     case CK_NoOp:
15525     case CK_IntegralToBoolean:
15526     case CK_IntegralCast:
15527       return CheckICE(SubExpr, Ctx);
15528     default:
15529       return ICEDiag(IK_NotICE, E->getBeginLoc());
15530     }
15531   }
15532   case Expr::BinaryConditionalOperatorClass: {
15533     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
15534     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
15535     if (CommonResult.Kind == IK_NotICE) return CommonResult;
15536     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15537     if (FalseResult.Kind == IK_NotICE) return FalseResult;
15538     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
15539     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
15540         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
15541     return FalseResult;
15542   }
15543   case Expr::ConditionalOperatorClass: {
15544     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
15545     // If the condition (ignoring parens) is a __builtin_constant_p call,
15546     // then only the true side is actually considered in an integer constant
15547     // expression, and it is fully evaluated.  This is an important GNU
15548     // extension.  See GCC PR38377 for discussion.
15549     if (const CallExpr *CallCE
15550         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
15551       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
15552         return CheckEvalInICE(E, Ctx);
15553     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
15554     if (CondResult.Kind == IK_NotICE)
15555       return CondResult;
15556 
15557     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
15558     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15559 
15560     if (TrueResult.Kind == IK_NotICE)
15561       return TrueResult;
15562     if (FalseResult.Kind == IK_NotICE)
15563       return FalseResult;
15564     if (CondResult.Kind == IK_ICEIfUnevaluated)
15565       return CondResult;
15566     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
15567       return NoDiag();
15568     // Rare case where the diagnostics depend on which side is evaluated
15569     // Note that if we get here, CondResult is 0, and at least one of
15570     // TrueResult and FalseResult is non-zero.
15571     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
15572       return FalseResult;
15573     return TrueResult;
15574   }
15575   case Expr::CXXDefaultArgExprClass:
15576     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
15577   case Expr::CXXDefaultInitExprClass:
15578     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
15579   case Expr::ChooseExprClass: {
15580     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
15581   }
15582   case Expr::BuiltinBitCastExprClass: {
15583     if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
15584       return ICEDiag(IK_NotICE, E->getBeginLoc());
15585     return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
15586   }
15587   }
15588 
15589   llvm_unreachable("Invalid StmtClass!");
15590 }
15591 
15592 /// Evaluate an expression as a C++11 integral constant expression.
15593 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
15594                                                     const Expr *E,
15595                                                     llvm::APSInt *Value,
15596                                                     SourceLocation *Loc) {
15597   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15598     if (Loc) *Loc = E->getExprLoc();
15599     return false;
15600   }
15601 
15602   APValue Result;
15603   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
15604     return false;
15605 
15606   if (!Result.isInt()) {
15607     if (Loc) *Loc = E->getExprLoc();
15608     return false;
15609   }
15610 
15611   if (Value) *Value = Result.getInt();
15612   return true;
15613 }
15614 
15615 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
15616                                  SourceLocation *Loc) const {
15617   assert(!isValueDependent() &&
15618          "Expression evaluator can't be called on a dependent expression.");
15619 
15620   if (Ctx.getLangOpts().CPlusPlus11)
15621     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
15622 
15623   ICEDiag D = CheckICE(this, Ctx);
15624   if (D.Kind != IK_ICE) {
15625     if (Loc) *Loc = D.Loc;
15626     return false;
15627   }
15628   return true;
15629 }
15630 
15631 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx,
15632                                                     SourceLocation *Loc,
15633                                                     bool isEvaluated) const {
15634   if (isValueDependent()) {
15635     // Expression evaluator can't succeed on a dependent expression.
15636     return None;
15637   }
15638 
15639   APSInt Value;
15640 
15641   if (Ctx.getLangOpts().CPlusPlus11) {
15642     if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc))
15643       return Value;
15644     return None;
15645   }
15646 
15647   if (!isIntegerConstantExpr(Ctx, Loc))
15648     return None;
15649 
15650   // The only possible side-effects here are due to UB discovered in the
15651   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
15652   // required to treat the expression as an ICE, so we produce the folded
15653   // value.
15654   EvalResult ExprResult;
15655   Expr::EvalStatus Status;
15656   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
15657   Info.InConstantContext = true;
15658 
15659   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
15660     llvm_unreachable("ICE cannot be evaluated!");
15661 
15662   return ExprResult.Val.getInt();
15663 }
15664 
15665 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
15666   assert(!isValueDependent() &&
15667          "Expression evaluator can't be called on a dependent expression.");
15668 
15669   return CheckICE(this, Ctx).Kind == IK_ICE;
15670 }
15671 
15672 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
15673                                SourceLocation *Loc) const {
15674   assert(!isValueDependent() &&
15675          "Expression evaluator can't be called on a dependent expression.");
15676 
15677   // We support this checking in C++98 mode in order to diagnose compatibility
15678   // issues.
15679   assert(Ctx.getLangOpts().CPlusPlus);
15680 
15681   // Build evaluation settings.
15682   Expr::EvalStatus Status;
15683   SmallVector<PartialDiagnosticAt, 8> Diags;
15684   Status.Diag = &Diags;
15685   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15686 
15687   APValue Scratch;
15688   bool IsConstExpr =
15689       ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
15690       // FIXME: We don't produce a diagnostic for this, but the callers that
15691       // call us on arbitrary full-expressions should generally not care.
15692       Info.discardCleanups() && !Status.HasSideEffects;
15693 
15694   if (!Diags.empty()) {
15695     IsConstExpr = false;
15696     if (Loc) *Loc = Diags[0].first;
15697   } else if (!IsConstExpr) {
15698     // FIXME: This shouldn't happen.
15699     if (Loc) *Loc = getExprLoc();
15700   }
15701 
15702   return IsConstExpr;
15703 }
15704 
15705 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
15706                                     const FunctionDecl *Callee,
15707                                     ArrayRef<const Expr*> Args,
15708                                     const Expr *This) const {
15709   assert(!isValueDependent() &&
15710          "Expression evaluator can't be called on a dependent expression.");
15711 
15712   Expr::EvalStatus Status;
15713   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
15714   Info.InConstantContext = true;
15715 
15716   LValue ThisVal;
15717   const LValue *ThisPtr = nullptr;
15718   if (This) {
15719 #ifndef NDEBUG
15720     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
15721     assert(MD && "Don't provide `this` for non-methods.");
15722     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
15723 #endif
15724     if (!This->isValueDependent() &&
15725         EvaluateObjectArgument(Info, This, ThisVal) &&
15726         !Info.EvalStatus.HasSideEffects)
15727       ThisPtr = &ThisVal;
15728 
15729     // Ignore any side-effects from a failed evaluation. This is safe because
15730     // they can't interfere with any other argument evaluation.
15731     Info.EvalStatus.HasSideEffects = false;
15732   }
15733 
15734   CallRef Call = Info.CurrentCall->createCall(Callee);
15735   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
15736        I != E; ++I) {
15737     unsigned Idx = I - Args.begin();
15738     if (Idx >= Callee->getNumParams())
15739       break;
15740     const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
15741     if ((*I)->isValueDependent() ||
15742         !EvaluateCallArg(PVD, *I, Call, Info) ||
15743         Info.EvalStatus.HasSideEffects) {
15744       // If evaluation fails, throw away the argument entirely.
15745       if (APValue *Slot = Info.getParamSlot(Call, PVD))
15746         *Slot = APValue();
15747     }
15748 
15749     // Ignore any side-effects from a failed evaluation. This is safe because
15750     // they can't interfere with any other argument evaluation.
15751     Info.EvalStatus.HasSideEffects = false;
15752   }
15753 
15754   // Parameter cleanups happen in the caller and are not part of this
15755   // evaluation.
15756   Info.discardCleanups();
15757   Info.EvalStatus.HasSideEffects = false;
15758 
15759   // Build fake call to Callee.
15760   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call);
15761   // FIXME: Missing ExprWithCleanups in enable_if conditions?
15762   FullExpressionRAII Scope(Info);
15763   return Evaluate(Value, Info, this) && Scope.destroy() &&
15764          !Info.EvalStatus.HasSideEffects;
15765 }
15766 
15767 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
15768                                    SmallVectorImpl<
15769                                      PartialDiagnosticAt> &Diags) {
15770   // FIXME: It would be useful to check constexpr function templates, but at the
15771   // moment the constant expression evaluator cannot cope with the non-rigorous
15772   // ASTs which we build for dependent expressions.
15773   if (FD->isDependentContext())
15774     return true;
15775 
15776   Expr::EvalStatus Status;
15777   Status.Diag = &Diags;
15778 
15779   EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
15780   Info.InConstantContext = true;
15781   Info.CheckingPotentialConstantExpression = true;
15782 
15783   // The constexpr VM attempts to compile all methods to bytecode here.
15784   if (Info.EnableNewConstInterp) {
15785     Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
15786     return Diags.empty();
15787   }
15788 
15789   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
15790   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
15791 
15792   // Fabricate an arbitrary expression on the stack and pretend that it
15793   // is a temporary being used as the 'this' pointer.
15794   LValue This;
15795   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
15796   This.set({&VIE, Info.CurrentCall->Index});
15797 
15798   ArrayRef<const Expr*> Args;
15799 
15800   APValue Scratch;
15801   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
15802     // Evaluate the call as a constant initializer, to allow the construction
15803     // of objects of non-literal types.
15804     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
15805     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
15806   } else {
15807     SourceLocation Loc = FD->getLocation();
15808     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
15809                        Args, CallRef(), FD->getBody(), Info, Scratch, nullptr);
15810   }
15811 
15812   return Diags.empty();
15813 }
15814 
15815 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
15816                                               const FunctionDecl *FD,
15817                                               SmallVectorImpl<
15818                                                 PartialDiagnosticAt> &Diags) {
15819   assert(!E->isValueDependent() &&
15820          "Expression evaluator can't be called on a dependent expression.");
15821 
15822   Expr::EvalStatus Status;
15823   Status.Diag = &Diags;
15824 
15825   EvalInfo Info(FD->getASTContext(), Status,
15826                 EvalInfo::EM_ConstantExpressionUnevaluated);
15827   Info.InConstantContext = true;
15828   Info.CheckingPotentialConstantExpression = true;
15829 
15830   // Fabricate a call stack frame to give the arguments a plausible cover story.
15831   CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef());
15832 
15833   APValue ResultScratch;
15834   Evaluate(ResultScratch, Info, E);
15835   return Diags.empty();
15836 }
15837 
15838 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
15839                                  unsigned Type) const {
15840   if (!getType()->isPointerType())
15841     return false;
15842 
15843   Expr::EvalStatus Status;
15844   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
15845   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
15846 }
15847 
15848 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
15849                                   EvalInfo &Info) {
15850   if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
15851     return false;
15852 
15853   LValue String;
15854 
15855   if (!EvaluatePointer(E, String, Info))
15856     return false;
15857 
15858   QualType CharTy = E->getType()->getPointeeType();
15859 
15860   // Fast path: if it's a string literal, search the string value.
15861   if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
15862           String.getLValueBase().dyn_cast<const Expr *>())) {
15863     StringRef Str = S->getBytes();
15864     int64_t Off = String.Offset.getQuantity();
15865     if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
15866         S->getCharByteWidth() == 1 &&
15867         // FIXME: Add fast-path for wchar_t too.
15868         Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
15869       Str = Str.substr(Off);
15870 
15871       StringRef::size_type Pos = Str.find(0);
15872       if (Pos != StringRef::npos)
15873         Str = Str.substr(0, Pos);
15874 
15875       Result = Str.size();
15876       return true;
15877     }
15878 
15879     // Fall through to slow path.
15880   }
15881 
15882   // Slow path: scan the bytes of the string looking for the terminating 0.
15883   for (uint64_t Strlen = 0; /**/; ++Strlen) {
15884     APValue Char;
15885     if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
15886         !Char.isInt())
15887       return false;
15888     if (!Char.getInt()) {
15889       Result = Strlen;
15890       return true;
15891     }
15892     if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
15893       return false;
15894   }
15895 }
15896 
15897 bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
15898   Expr::EvalStatus Status;
15899   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
15900   return EvaluateBuiltinStrLen(this, Result, Info);
15901 }
15902