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     ASTContext &getCtx() const override { return Ctx; }
987 
988     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
989                            EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
990       EvaluatingDecl = Base;
991       IsEvaluatingDecl = EDK;
992       EvaluatingDeclValue = &Value;
993     }
994 
995     bool CheckCallLimit(SourceLocation Loc) {
996       // Don't perform any constexpr calls (other than the call we're checking)
997       // when checking a potential constant expression.
998       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
999         return false;
1000       if (NextCallIndex == 0) {
1001         // NextCallIndex has wrapped around.
1002         FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
1003         return false;
1004       }
1005       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
1006         return true;
1007       FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
1008         << getLangOpts().ConstexprCallDepth;
1009       return false;
1010     }
1011 
1012     std::pair<CallStackFrame *, unsigned>
1013     getCallFrameAndDepth(unsigned CallIndex) {
1014       assert(CallIndex && "no call index in getCallFrameAndDepth");
1015       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1016       // be null in this loop.
1017       unsigned Depth = CallStackDepth;
1018       CallStackFrame *Frame = CurrentCall;
1019       while (Frame->Index > CallIndex) {
1020         Frame = Frame->Caller;
1021         --Depth;
1022       }
1023       if (Frame->Index == CallIndex)
1024         return {Frame, Depth};
1025       return {nullptr, 0};
1026     }
1027 
1028     bool nextStep(const Stmt *S) {
1029       if (!StepsLeft) {
1030         FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1031         return false;
1032       }
1033       --StepsLeft;
1034       return true;
1035     }
1036 
1037     APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1038 
1039     Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) {
1040       Optional<DynAlloc*> Result;
1041       auto It = HeapAllocs.find(DA);
1042       if (It != HeapAllocs.end())
1043         Result = &It->second;
1044       return Result;
1045     }
1046 
1047     /// Get the allocated storage for the given parameter of the given call.
1048     APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1049       CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1050       return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1051                    : nullptr;
1052     }
1053 
1054     /// Information about a stack frame for std::allocator<T>::[de]allocate.
1055     struct StdAllocatorCaller {
1056       unsigned FrameIndex;
1057       QualType ElemType;
1058       explicit operator bool() const { return FrameIndex != 0; };
1059     };
1060 
1061     StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1062       for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1063            Call = Call->Caller) {
1064         const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1065         if (!MD)
1066           continue;
1067         const IdentifierInfo *FnII = MD->getIdentifier();
1068         if (!FnII || !FnII->isStr(FnName))
1069           continue;
1070 
1071         const auto *CTSD =
1072             dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1073         if (!CTSD)
1074           continue;
1075 
1076         const IdentifierInfo *ClassII = CTSD->getIdentifier();
1077         const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1078         if (CTSD->isInStdNamespace() && ClassII &&
1079             ClassII->isStr("allocator") && TAL.size() >= 1 &&
1080             TAL[0].getKind() == TemplateArgument::Type)
1081           return {Call->Index, TAL[0].getAsType()};
1082       }
1083 
1084       return {};
1085     }
1086 
1087     void performLifetimeExtension() {
1088       // Disable the cleanups for lifetime-extended temporaries.
1089       llvm::erase_if(CleanupStack, [](Cleanup &C) {
1090         return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1091       });
1092     }
1093 
1094     /// Throw away any remaining cleanups at the end of evaluation. If any
1095     /// cleanups would have had a side-effect, note that as an unmodeled
1096     /// side-effect and return false. Otherwise, return true.
1097     bool discardCleanups() {
1098       for (Cleanup &C : CleanupStack) {
1099         if (C.hasSideEffect() && !noteSideEffect()) {
1100           CleanupStack.clear();
1101           return false;
1102         }
1103       }
1104       CleanupStack.clear();
1105       return true;
1106     }
1107 
1108   private:
1109     interp::Frame *getCurrentFrame() override { return CurrentCall; }
1110     const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1111 
1112     bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1113     void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1114 
1115     void setFoldFailureDiagnostic(bool Flag) override {
1116       HasFoldFailureDiagnostic = Flag;
1117     }
1118 
1119     Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
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     // ... the address of an unnamed global constant
1982     return isa<FunctionDecl, MSGuidDecl, UnnamedGlobalConstantDecl>(D);
1983   }
1984 
1985   if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
1986     return true;
1987 
1988   const Expr *E = B.get<const Expr*>();
1989   switch (E->getStmtClass()) {
1990   default:
1991     return false;
1992   case Expr::CompoundLiteralExprClass: {
1993     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1994     return CLE->isFileScope() && CLE->isLValue();
1995   }
1996   case Expr::MaterializeTemporaryExprClass:
1997     // A materialized temporary might have been lifetime-extended to static
1998     // storage duration.
1999     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
2000   // A string literal has static storage duration.
2001   case Expr::StringLiteralClass:
2002   case Expr::PredefinedExprClass:
2003   case Expr::ObjCStringLiteralClass:
2004   case Expr::ObjCEncodeExprClass:
2005     return true;
2006   case Expr::ObjCBoxedExprClass:
2007     return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2008   case Expr::CallExprClass:
2009     return IsConstantCall(cast<CallExpr>(E));
2010   // For GCC compatibility, &&label has static storage duration.
2011   case Expr::AddrLabelExprClass:
2012     return true;
2013   // A Block literal expression may be used as the initialization value for
2014   // Block variables at global or local static scope.
2015   case Expr::BlockExprClass:
2016     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2017   // The APValue generated from a __builtin_source_location will be emitted as a
2018   // literal.
2019   case Expr::SourceLocExprClass:
2020     return true;
2021   case Expr::ImplicitValueInitExprClass:
2022     // FIXME:
2023     // We can never form an lvalue with an implicit value initialization as its
2024     // base through expression evaluation, so these only appear in one case: the
2025     // implicit variable declaration we invent when checking whether a constexpr
2026     // constructor can produce a constant expression. We must assume that such
2027     // an expression might be a global lvalue.
2028     return true;
2029   }
2030 }
2031 
2032 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2033   return LVal.Base.dyn_cast<const ValueDecl*>();
2034 }
2035 
2036 static bool IsLiteralLValue(const LValue &Value) {
2037   if (Value.getLValueCallIndex())
2038     return false;
2039   const Expr *E = Value.Base.dyn_cast<const Expr*>();
2040   return E && !isa<MaterializeTemporaryExpr>(E);
2041 }
2042 
2043 static bool IsWeakLValue(const LValue &Value) {
2044   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2045   return Decl && Decl->isWeak();
2046 }
2047 
2048 static bool isZeroSized(const LValue &Value) {
2049   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2050   if (Decl && isa<VarDecl>(Decl)) {
2051     QualType Ty = Decl->getType();
2052     if (Ty->isArrayType())
2053       return Ty->isIncompleteType() ||
2054              Decl->getASTContext().getTypeSize(Ty) == 0;
2055   }
2056   return false;
2057 }
2058 
2059 static bool HasSameBase(const LValue &A, const LValue &B) {
2060   if (!A.getLValueBase())
2061     return !B.getLValueBase();
2062   if (!B.getLValueBase())
2063     return false;
2064 
2065   if (A.getLValueBase().getOpaqueValue() !=
2066       B.getLValueBase().getOpaqueValue())
2067     return false;
2068 
2069   return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2070          A.getLValueVersion() == B.getLValueVersion();
2071 }
2072 
2073 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2074   assert(Base && "no location for a null lvalue");
2075   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2076 
2077   // For a parameter, find the corresponding call stack frame (if it still
2078   // exists), and point at the parameter of the function definition we actually
2079   // invoked.
2080   if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2081     unsigned Idx = PVD->getFunctionScopeIndex();
2082     for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2083       if (F->Arguments.CallIndex == Base.getCallIndex() &&
2084           F->Arguments.Version == Base.getVersion() && F->Callee &&
2085           Idx < F->Callee->getNumParams()) {
2086         VD = F->Callee->getParamDecl(Idx);
2087         break;
2088       }
2089     }
2090   }
2091 
2092   if (VD)
2093     Info.Note(VD->getLocation(), diag::note_declared_at);
2094   else if (const Expr *E = Base.dyn_cast<const Expr*>())
2095     Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2096   else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2097     // FIXME: Produce a note for dangling pointers too.
2098     if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA))
2099       Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2100                 diag::note_constexpr_dynamic_alloc_here);
2101   }
2102   // We have no information to show for a typeid(T) object.
2103 }
2104 
2105 enum class CheckEvaluationResultKind {
2106   ConstantExpression,
2107   FullyInitialized,
2108 };
2109 
2110 /// Materialized temporaries that we've already checked to determine if they're
2111 /// initializsed by a constant expression.
2112 using CheckedTemporaries =
2113     llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
2114 
2115 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2116                                   EvalInfo &Info, SourceLocation DiagLoc,
2117                                   QualType Type, const APValue &Value,
2118                                   ConstantExprKind Kind,
2119                                   SourceLocation SubobjectLoc,
2120                                   CheckedTemporaries &CheckedTemps);
2121 
2122 /// Check that this reference or pointer core constant expression is a valid
2123 /// value for an address or reference constant expression. Return true if we
2124 /// can fold this expression, whether or not it's a constant expression.
2125 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2126                                           QualType Type, const LValue &LVal,
2127                                           ConstantExprKind Kind,
2128                                           CheckedTemporaries &CheckedTemps) {
2129   bool IsReferenceType = Type->isReferenceType();
2130 
2131   APValue::LValueBase Base = LVal.getLValueBase();
2132   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2133 
2134   const Expr *BaseE = Base.dyn_cast<const Expr *>();
2135   const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2136 
2137   // Additional restrictions apply in a template argument. We only enforce the
2138   // C++20 restrictions here; additional syntactic and semantic restrictions
2139   // are applied elsewhere.
2140   if (isTemplateArgument(Kind)) {
2141     int InvalidBaseKind = -1;
2142     StringRef Ident;
2143     if (Base.is<TypeInfoLValue>())
2144       InvalidBaseKind = 0;
2145     else if (isa_and_nonnull<StringLiteral>(BaseE))
2146       InvalidBaseKind = 1;
2147     else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2148              isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2149       InvalidBaseKind = 2;
2150     else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2151       InvalidBaseKind = 3;
2152       Ident = PE->getIdentKindName();
2153     }
2154 
2155     if (InvalidBaseKind != -1) {
2156       Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2157           << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2158           << Ident;
2159       return false;
2160     }
2161   }
2162 
2163   if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD)) {
2164     if (FD->isConsteval()) {
2165       Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2166           << !Type->isAnyPointerType();
2167       Info.Note(FD->getLocation(), diag::note_declared_at);
2168       return false;
2169     }
2170   }
2171 
2172   // Check that the object is a global. Note that the fake 'this' object we
2173   // manufacture when checking potential constant expressions is conservatively
2174   // assumed to be global here.
2175   if (!IsGlobalLValue(Base)) {
2176     if (Info.getLangOpts().CPlusPlus11) {
2177       const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2178       Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2179         << IsReferenceType << !Designator.Entries.empty()
2180         << !!VD << VD;
2181 
2182       auto *VarD = dyn_cast_or_null<VarDecl>(VD);
2183       if (VarD && VarD->isConstexpr()) {
2184         // Non-static local constexpr variables have unintuitive semantics:
2185         //   constexpr int a = 1;
2186         //   constexpr const int *p = &a;
2187         // ... is invalid because the address of 'a' is not constant. Suggest
2188         // adding a 'static' in this case.
2189         Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2190             << VarD
2191             << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2192       } else {
2193         NoteLValueLocation(Info, Base);
2194       }
2195     } else {
2196       Info.FFDiag(Loc);
2197     }
2198     // Don't allow references to temporaries to escape.
2199     return false;
2200   }
2201   assert((Info.checkingPotentialConstantExpression() ||
2202           LVal.getLValueCallIndex() == 0) &&
2203          "have call index for global lvalue");
2204 
2205   if (Base.is<DynamicAllocLValue>()) {
2206     Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2207         << IsReferenceType << !Designator.Entries.empty();
2208     NoteLValueLocation(Info, Base);
2209     return false;
2210   }
2211 
2212   if (BaseVD) {
2213     if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2214       // Check if this is a thread-local variable.
2215       if (Var->getTLSKind())
2216         // FIXME: Diagnostic!
2217         return false;
2218 
2219       // A dllimport variable never acts like a constant, unless we're
2220       // evaluating a value for use only in name mangling.
2221       if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2222         // FIXME: Diagnostic!
2223         return false;
2224 
2225       // In CUDA/HIP device compilation, only device side variables have
2226       // constant addresses.
2227       if (Info.getCtx().getLangOpts().CUDA &&
2228           Info.getCtx().getLangOpts().CUDAIsDevice &&
2229           Info.getCtx().CUDAConstantEvalCtx.NoWrongSidedVars) {
2230         if ((!Var->hasAttr<CUDADeviceAttr>() &&
2231              !Var->hasAttr<CUDAConstantAttr>() &&
2232              !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2233              !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
2234             Var->hasAttr<HIPManagedAttr>())
2235           return false;
2236       }
2237     }
2238     if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2239       // __declspec(dllimport) must be handled very carefully:
2240       // We must never initialize an expression with the thunk in C++.
2241       // Doing otherwise would allow the same id-expression to yield
2242       // different addresses for the same function in different translation
2243       // units.  However, this means that we must dynamically initialize the
2244       // expression with the contents of the import address table at runtime.
2245       //
2246       // The C language has no notion of ODR; furthermore, it has no notion of
2247       // dynamic initialization.  This means that we are permitted to
2248       // perform initialization with the address of the thunk.
2249       if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2250           FD->hasAttr<DLLImportAttr>())
2251         // FIXME: Diagnostic!
2252         return false;
2253     }
2254   } else if (const auto *MTE =
2255                  dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2256     if (CheckedTemps.insert(MTE).second) {
2257       QualType TempType = getType(Base);
2258       if (TempType.isDestructedType()) {
2259         Info.FFDiag(MTE->getExprLoc(),
2260                     diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2261             << TempType;
2262         return false;
2263       }
2264 
2265       APValue *V = MTE->getOrCreateValue(false);
2266       assert(V && "evasluation result refers to uninitialised temporary");
2267       if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2268                                  Info, MTE->getExprLoc(), TempType, *V,
2269                                  Kind, SourceLocation(), CheckedTemps))
2270         return false;
2271     }
2272   }
2273 
2274   // Allow address constant expressions to be past-the-end pointers. This is
2275   // an extension: the standard requires them to point to an object.
2276   if (!IsReferenceType)
2277     return true;
2278 
2279   // A reference constant expression must refer to an object.
2280   if (!Base) {
2281     // FIXME: diagnostic
2282     Info.CCEDiag(Loc);
2283     return true;
2284   }
2285 
2286   // Does this refer one past the end of some object?
2287   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2288     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2289       << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2290     NoteLValueLocation(Info, Base);
2291   }
2292 
2293   return true;
2294 }
2295 
2296 /// Member pointers are constant expressions unless they point to a
2297 /// non-virtual dllimport member function.
2298 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2299                                                  SourceLocation Loc,
2300                                                  QualType Type,
2301                                                  const APValue &Value,
2302                                                  ConstantExprKind Kind) {
2303   const ValueDecl *Member = Value.getMemberPointerDecl();
2304   const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2305   if (!FD)
2306     return true;
2307   if (FD->isConsteval()) {
2308     Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2309     Info.Note(FD->getLocation(), diag::note_declared_at);
2310     return false;
2311   }
2312   return isForManglingOnly(Kind) || FD->isVirtual() ||
2313          !FD->hasAttr<DLLImportAttr>();
2314 }
2315 
2316 /// Check that this core constant expression is of literal type, and if not,
2317 /// produce an appropriate diagnostic.
2318 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2319                              const LValue *This = nullptr) {
2320   if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2321     return true;
2322 
2323   // C++1y: A constant initializer for an object o [...] may also invoke
2324   // constexpr constructors for o and its subobjects even if those objects
2325   // are of non-literal class types.
2326   //
2327   // C++11 missed this detail for aggregates, so classes like this:
2328   //   struct foo_t { union { int i; volatile int j; } u; };
2329   // are not (obviously) initializable like so:
2330   //   __attribute__((__require_constant_initialization__))
2331   //   static const foo_t x = {{0}};
2332   // because "i" is a subobject with non-literal initialization (due to the
2333   // volatile member of the union). See:
2334   //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2335   // Therefore, we use the C++1y behavior.
2336   if (This && Info.EvaluatingDecl == This->getLValueBase())
2337     return true;
2338 
2339   // Prvalue constant expressions must be of literal types.
2340   if (Info.getLangOpts().CPlusPlus11)
2341     Info.FFDiag(E, diag::note_constexpr_nonliteral)
2342       << E->getType();
2343   else
2344     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2345   return false;
2346 }
2347 
2348 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2349                                   EvalInfo &Info, SourceLocation DiagLoc,
2350                                   QualType Type, const APValue &Value,
2351                                   ConstantExprKind Kind,
2352                                   SourceLocation SubobjectLoc,
2353                                   CheckedTemporaries &CheckedTemps) {
2354   if (!Value.hasValue()) {
2355     Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2356       << true << Type;
2357     if (SubobjectLoc.isValid())
2358       Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2359     return false;
2360   }
2361 
2362   // We allow _Atomic(T) to be initialized from anything that T can be
2363   // initialized from.
2364   if (const AtomicType *AT = Type->getAs<AtomicType>())
2365     Type = AT->getValueType();
2366 
2367   // Core issue 1454: For a literal constant expression of array or class type,
2368   // each subobject of its value shall have been initialized by a constant
2369   // expression.
2370   if (Value.isArray()) {
2371     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2372     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2373       if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2374                                  Value.getArrayInitializedElt(I), Kind,
2375                                  SubobjectLoc, CheckedTemps))
2376         return false;
2377     }
2378     if (!Value.hasArrayFiller())
2379       return true;
2380     return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2381                                  Value.getArrayFiller(), Kind, SubobjectLoc,
2382                                  CheckedTemps);
2383   }
2384   if (Value.isUnion() && Value.getUnionField()) {
2385     return CheckEvaluationResult(
2386         CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2387         Value.getUnionValue(), Kind, Value.getUnionField()->getLocation(),
2388         CheckedTemps);
2389   }
2390   if (Value.isStruct()) {
2391     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2392     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2393       unsigned BaseIndex = 0;
2394       for (const CXXBaseSpecifier &BS : CD->bases()) {
2395         if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2396                                    Value.getStructBase(BaseIndex), Kind,
2397                                    BS.getBeginLoc(), CheckedTemps))
2398           return false;
2399         ++BaseIndex;
2400       }
2401     }
2402     for (const auto *I : RD->fields()) {
2403       if (I->isUnnamedBitfield())
2404         continue;
2405 
2406       if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2407                                  Value.getStructField(I->getFieldIndex()),
2408                                  Kind, I->getLocation(), CheckedTemps))
2409         return false;
2410     }
2411   }
2412 
2413   if (Value.isLValue() &&
2414       CERK == CheckEvaluationResultKind::ConstantExpression) {
2415     LValue LVal;
2416     LVal.setFrom(Info.Ctx, Value);
2417     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2418                                          CheckedTemps);
2419   }
2420 
2421   if (Value.isMemberPointer() &&
2422       CERK == CheckEvaluationResultKind::ConstantExpression)
2423     return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2424 
2425   // Everything else is fine.
2426   return true;
2427 }
2428 
2429 /// Check that this core constant expression value is a valid value for a
2430 /// constant expression. If not, report an appropriate diagnostic. Does not
2431 /// check that the expression is of literal type.
2432 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2433                                     QualType Type, const APValue &Value,
2434                                     ConstantExprKind Kind) {
2435   // Nothing to check for a constant expression of type 'cv void'.
2436   if (Type->isVoidType())
2437     return true;
2438 
2439   CheckedTemporaries CheckedTemps;
2440   return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2441                                Info, DiagLoc, Type, Value, Kind,
2442                                SourceLocation(), CheckedTemps);
2443 }
2444 
2445 /// Check that this evaluated value is fully-initialized and can be loaded by
2446 /// an lvalue-to-rvalue conversion.
2447 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2448                                   QualType Type, const APValue &Value) {
2449   CheckedTemporaries CheckedTemps;
2450   return CheckEvaluationResult(
2451       CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2452       ConstantExprKind::Normal, SourceLocation(), CheckedTemps);
2453 }
2454 
2455 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2456 /// "the allocated storage is deallocated within the evaluation".
2457 static bool CheckMemoryLeaks(EvalInfo &Info) {
2458   if (!Info.HeapAllocs.empty()) {
2459     // We can still fold to a constant despite a compile-time memory leak,
2460     // so long as the heap allocation isn't referenced in the result (we check
2461     // that in CheckConstantExpression).
2462     Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2463                  diag::note_constexpr_memory_leak)
2464         << unsigned(Info.HeapAllocs.size() - 1);
2465   }
2466   return true;
2467 }
2468 
2469 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2470   // A null base expression indicates a null pointer.  These are always
2471   // evaluatable, and they are false unless the offset is zero.
2472   if (!Value.getLValueBase()) {
2473     Result = !Value.getLValueOffset().isZero();
2474     return true;
2475   }
2476 
2477   // We have a non-null base.  These are generally known to be true, but if it's
2478   // a weak declaration it can be null at runtime.
2479   Result = true;
2480   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2481   return !Decl || !Decl->isWeak();
2482 }
2483 
2484 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2485   switch (Val.getKind()) {
2486   case APValue::None:
2487   case APValue::Indeterminate:
2488     return false;
2489   case APValue::Int:
2490     Result = Val.getInt().getBoolValue();
2491     return true;
2492   case APValue::FixedPoint:
2493     Result = Val.getFixedPoint().getBoolValue();
2494     return true;
2495   case APValue::Float:
2496     Result = !Val.getFloat().isZero();
2497     return true;
2498   case APValue::ComplexInt:
2499     Result = Val.getComplexIntReal().getBoolValue() ||
2500              Val.getComplexIntImag().getBoolValue();
2501     return true;
2502   case APValue::ComplexFloat:
2503     Result = !Val.getComplexFloatReal().isZero() ||
2504              !Val.getComplexFloatImag().isZero();
2505     return true;
2506   case APValue::LValue:
2507     return EvalPointerValueAsBool(Val, Result);
2508   case APValue::MemberPointer:
2509     Result = Val.getMemberPointerDecl();
2510     return true;
2511   case APValue::Vector:
2512   case APValue::Array:
2513   case APValue::Struct:
2514   case APValue::Union:
2515   case APValue::AddrLabelDiff:
2516     return false;
2517   }
2518 
2519   llvm_unreachable("unknown APValue kind");
2520 }
2521 
2522 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2523                                        EvalInfo &Info) {
2524   assert(!E->isValueDependent());
2525   assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2526   APValue Val;
2527   if (!Evaluate(Val, Info, E))
2528     return false;
2529   return HandleConversionToBool(Val, Result);
2530 }
2531 
2532 template<typename T>
2533 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2534                            const T &SrcValue, QualType DestType) {
2535   Info.CCEDiag(E, diag::note_constexpr_overflow)
2536     << SrcValue << DestType;
2537   return Info.noteUndefinedBehavior();
2538 }
2539 
2540 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2541                                  QualType SrcType, const APFloat &Value,
2542                                  QualType DestType, APSInt &Result) {
2543   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2544   // Determine whether we are converting to unsigned or signed.
2545   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2546 
2547   Result = APSInt(DestWidth, !DestSigned);
2548   bool ignored;
2549   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2550       & APFloat::opInvalidOp)
2551     return HandleOverflow(Info, E, Value, DestType);
2552   return true;
2553 }
2554 
2555 /// Get rounding mode to use in evaluation of the specified expression.
2556 ///
2557 /// If rounding mode is unknown at compile time, still try to evaluate the
2558 /// expression. If the result is exact, it does not depend on rounding mode.
2559 /// So return "tonearest" mode instead of "dynamic".
2560 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
2561   llvm::RoundingMode RM =
2562       E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2563   if (RM == llvm::RoundingMode::Dynamic)
2564     RM = llvm::RoundingMode::NearestTiesToEven;
2565   return RM;
2566 }
2567 
2568 /// Check if the given evaluation result is allowed for constant evaluation.
2569 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2570                                      APFloat::opStatus St) {
2571   // In a constant context, assume that any dynamic rounding mode or FP
2572   // exception state matches the default floating-point environment.
2573   if (Info.InConstantContext)
2574     return true;
2575 
2576   FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2577   if ((St & APFloat::opInexact) &&
2578       FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2579     // Inexact result means that it depends on rounding mode. If the requested
2580     // mode is dynamic, the evaluation cannot be made in compile time.
2581     Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2582     return false;
2583   }
2584 
2585   if ((St != APFloat::opOK) &&
2586       (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2587        FPO.getExceptionMode() != LangOptions::FPE_Ignore ||
2588        FPO.getAllowFEnvAccess())) {
2589     Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2590     return false;
2591   }
2592 
2593   if ((St & APFloat::opStatus::opInvalidOp) &&
2594       FPO.getExceptionMode() != LangOptions::FPE_Ignore) {
2595     // There is no usefully definable result.
2596     Info.FFDiag(E);
2597     return false;
2598   }
2599 
2600   // FIXME: if:
2601   // - evaluation triggered other FP exception, and
2602   // - exception mode is not "ignore", and
2603   // - the expression being evaluated is not a part of global variable
2604   //   initializer,
2605   // the evaluation probably need to be rejected.
2606   return true;
2607 }
2608 
2609 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2610                                    QualType SrcType, QualType DestType,
2611                                    APFloat &Result) {
2612   assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E));
2613   llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2614   APFloat::opStatus St;
2615   APFloat Value = Result;
2616   bool ignored;
2617   St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2618   return checkFloatingPointResult(Info, E, St);
2619 }
2620 
2621 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2622                                  QualType DestType, QualType SrcType,
2623                                  const APSInt &Value) {
2624   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2625   // Figure out if this is a truncate, extend or noop cast.
2626   // If the input is signed, do a sign extend, noop, or truncate.
2627   APSInt Result = Value.extOrTrunc(DestWidth);
2628   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2629   if (DestType->isBooleanType())
2630     Result = Value.getBoolValue();
2631   return Result;
2632 }
2633 
2634 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2635                                  const FPOptions FPO,
2636                                  QualType SrcType, const APSInt &Value,
2637                                  QualType DestType, APFloat &Result) {
2638   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2639   APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(),
2640        APFloat::rmNearestTiesToEven);
2641   if (!Info.InConstantContext && St != llvm::APFloatBase::opOK &&
2642       FPO.isFPConstrained()) {
2643     Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2644     return false;
2645   }
2646   return true;
2647 }
2648 
2649 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2650                                   APValue &Value, const FieldDecl *FD) {
2651   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2652 
2653   if (!Value.isInt()) {
2654     // Trying to store a pointer-cast-to-integer into a bitfield.
2655     // FIXME: In this case, we should provide the diagnostic for casting
2656     // a pointer to an integer.
2657     assert(Value.isLValue() && "integral value neither int nor lvalue?");
2658     Info.FFDiag(E);
2659     return false;
2660   }
2661 
2662   APSInt &Int = Value.getInt();
2663   unsigned OldBitWidth = Int.getBitWidth();
2664   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2665   if (NewBitWidth < OldBitWidth)
2666     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2667   return true;
2668 }
2669 
2670 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2671                                   llvm::APInt &Res) {
2672   APValue SVal;
2673   if (!Evaluate(SVal, Info, E))
2674     return false;
2675   if (SVal.isInt()) {
2676     Res = SVal.getInt();
2677     return true;
2678   }
2679   if (SVal.isFloat()) {
2680     Res = SVal.getFloat().bitcastToAPInt();
2681     return true;
2682   }
2683   if (SVal.isVector()) {
2684     QualType VecTy = E->getType();
2685     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2686     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2687     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2688     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2689     Res = llvm::APInt::getZero(VecSize);
2690     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2691       APValue &Elt = SVal.getVectorElt(i);
2692       llvm::APInt EltAsInt;
2693       if (Elt.isInt()) {
2694         EltAsInt = Elt.getInt();
2695       } else if (Elt.isFloat()) {
2696         EltAsInt = Elt.getFloat().bitcastToAPInt();
2697       } else {
2698         // Don't try to handle vectors of anything other than int or float
2699         // (not sure if it's possible to hit this case).
2700         Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2701         return false;
2702       }
2703       unsigned BaseEltSize = EltAsInt.getBitWidth();
2704       if (BigEndian)
2705         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2706       else
2707         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2708     }
2709     return true;
2710   }
2711   // Give up if the input isn't an int, float, or vector.  For example, we
2712   // reject "(v4i16)(intptr_t)&a".
2713   Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2714   return false;
2715 }
2716 
2717 /// Perform the given integer operation, which is known to need at most BitWidth
2718 /// bits, and check for overflow in the original type (if that type was not an
2719 /// unsigned type).
2720 template<typename Operation>
2721 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2722                                  const APSInt &LHS, const APSInt &RHS,
2723                                  unsigned BitWidth, Operation Op,
2724                                  APSInt &Result) {
2725   if (LHS.isUnsigned()) {
2726     Result = Op(LHS, RHS);
2727     return true;
2728   }
2729 
2730   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2731   Result = Value.trunc(LHS.getBitWidth());
2732   if (Result.extend(BitWidth) != Value) {
2733     if (Info.checkingForUndefinedBehavior())
2734       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2735                                        diag::warn_integer_constant_overflow)
2736           << toString(Result, 10) << E->getType();
2737     return HandleOverflow(Info, E, Value, E->getType());
2738   }
2739   return true;
2740 }
2741 
2742 /// Perform the given binary integer operation.
2743 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2744                               BinaryOperatorKind Opcode, APSInt RHS,
2745                               APSInt &Result) {
2746   switch (Opcode) {
2747   default:
2748     Info.FFDiag(E);
2749     return false;
2750   case BO_Mul:
2751     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2752                                 std::multiplies<APSInt>(), Result);
2753   case BO_Add:
2754     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2755                                 std::plus<APSInt>(), Result);
2756   case BO_Sub:
2757     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2758                                 std::minus<APSInt>(), Result);
2759   case BO_And: Result = LHS & RHS; return true;
2760   case BO_Xor: Result = LHS ^ RHS; return true;
2761   case BO_Or:  Result = LHS | RHS; return true;
2762   case BO_Div:
2763   case BO_Rem:
2764     if (RHS == 0) {
2765       Info.FFDiag(E, diag::note_expr_divide_by_zero);
2766       return false;
2767     }
2768     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2769     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2770     // this operation and gives the two's complement result.
2771     if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2772         LHS.isMinSignedValue())
2773       return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2774                             E->getType());
2775     return true;
2776   case BO_Shl: {
2777     if (Info.getLangOpts().OpenCL)
2778       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2779       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2780                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2781                     RHS.isUnsigned());
2782     else if (RHS.isSigned() && RHS.isNegative()) {
2783       // During constant-folding, a negative shift is an opposite shift. Such
2784       // a shift is not a constant expression.
2785       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2786       RHS = -RHS;
2787       goto shift_right;
2788     }
2789   shift_left:
2790     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2791     // the shifted type.
2792     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2793     if (SA != RHS) {
2794       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2795         << RHS << E->getType() << LHS.getBitWidth();
2796     } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2797       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2798       // operand, and must not overflow the corresponding unsigned type.
2799       // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2800       // E1 x 2^E2 module 2^N.
2801       if (LHS.isNegative())
2802         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2803       else if (LHS.countLeadingZeros() < SA)
2804         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2805     }
2806     Result = LHS << SA;
2807     return true;
2808   }
2809   case BO_Shr: {
2810     if (Info.getLangOpts().OpenCL)
2811       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2812       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2813                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2814                     RHS.isUnsigned());
2815     else if (RHS.isSigned() && RHS.isNegative()) {
2816       // During constant-folding, a negative shift is an opposite shift. Such a
2817       // shift is not a constant expression.
2818       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2819       RHS = -RHS;
2820       goto shift_left;
2821     }
2822   shift_right:
2823     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2824     // shifted type.
2825     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2826     if (SA != RHS)
2827       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2828         << RHS << E->getType() << LHS.getBitWidth();
2829     Result = LHS >> SA;
2830     return true;
2831   }
2832 
2833   case BO_LT: Result = LHS < RHS; return true;
2834   case BO_GT: Result = LHS > RHS; return true;
2835   case BO_LE: Result = LHS <= RHS; return true;
2836   case BO_GE: Result = LHS >= RHS; return true;
2837   case BO_EQ: Result = LHS == RHS; return true;
2838   case BO_NE: Result = LHS != RHS; return true;
2839   case BO_Cmp:
2840     llvm_unreachable("BO_Cmp should be handled elsewhere");
2841   }
2842 }
2843 
2844 /// Perform the given binary floating-point operation, in-place, on LHS.
2845 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2846                                   APFloat &LHS, BinaryOperatorKind Opcode,
2847                                   const APFloat &RHS) {
2848   llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2849   APFloat::opStatus St;
2850   switch (Opcode) {
2851   default:
2852     Info.FFDiag(E);
2853     return false;
2854   case BO_Mul:
2855     St = LHS.multiply(RHS, RM);
2856     break;
2857   case BO_Add:
2858     St = LHS.add(RHS, RM);
2859     break;
2860   case BO_Sub:
2861     St = LHS.subtract(RHS, RM);
2862     break;
2863   case BO_Div:
2864     // [expr.mul]p4:
2865     //   If the second operand of / or % is zero the behavior is undefined.
2866     if (RHS.isZero())
2867       Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2868     St = LHS.divide(RHS, RM);
2869     break;
2870   }
2871 
2872   // [expr.pre]p4:
2873   //   If during the evaluation of an expression, the result is not
2874   //   mathematically defined [...], the behavior is undefined.
2875   // FIXME: C++ rules require us to not conform to IEEE 754 here.
2876   if (LHS.isNaN()) {
2877     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2878     return Info.noteUndefinedBehavior();
2879   }
2880 
2881   return checkFloatingPointResult(Info, E, St);
2882 }
2883 
2884 static bool handleLogicalOpForVector(const APInt &LHSValue,
2885                                      BinaryOperatorKind Opcode,
2886                                      const APInt &RHSValue, APInt &Result) {
2887   bool LHS = (LHSValue != 0);
2888   bool RHS = (RHSValue != 0);
2889 
2890   if (Opcode == BO_LAnd)
2891     Result = LHS && RHS;
2892   else
2893     Result = LHS || RHS;
2894   return true;
2895 }
2896 static bool handleLogicalOpForVector(const APFloat &LHSValue,
2897                                      BinaryOperatorKind Opcode,
2898                                      const APFloat &RHSValue, APInt &Result) {
2899   bool LHS = !LHSValue.isZero();
2900   bool RHS = !RHSValue.isZero();
2901 
2902   if (Opcode == BO_LAnd)
2903     Result = LHS && RHS;
2904   else
2905     Result = LHS || RHS;
2906   return true;
2907 }
2908 
2909 static bool handleLogicalOpForVector(const APValue &LHSValue,
2910                                      BinaryOperatorKind Opcode,
2911                                      const APValue &RHSValue, APInt &Result) {
2912   // The result is always an int type, however operands match the first.
2913   if (LHSValue.getKind() == APValue::Int)
2914     return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2915                                     RHSValue.getInt(), Result);
2916   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2917   return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2918                                   RHSValue.getFloat(), Result);
2919 }
2920 
2921 template <typename APTy>
2922 static bool
2923 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
2924                                const APTy &RHSValue, APInt &Result) {
2925   switch (Opcode) {
2926   default:
2927     llvm_unreachable("unsupported binary operator");
2928   case BO_EQ:
2929     Result = (LHSValue == RHSValue);
2930     break;
2931   case BO_NE:
2932     Result = (LHSValue != RHSValue);
2933     break;
2934   case BO_LT:
2935     Result = (LHSValue < RHSValue);
2936     break;
2937   case BO_GT:
2938     Result = (LHSValue > RHSValue);
2939     break;
2940   case BO_LE:
2941     Result = (LHSValue <= RHSValue);
2942     break;
2943   case BO_GE:
2944     Result = (LHSValue >= RHSValue);
2945     break;
2946   }
2947 
2948   // The boolean operations on these vector types use an instruction that
2949   // results in a mask of '-1' for the 'truth' value.  Ensure that we negate 1
2950   // to -1 to make sure that we produce the correct value.
2951   Result.negate();
2952 
2953   return true;
2954 }
2955 
2956 static bool handleCompareOpForVector(const APValue &LHSValue,
2957                                      BinaryOperatorKind Opcode,
2958                                      const APValue &RHSValue, APInt &Result) {
2959   // The result is always an int type, however operands match the first.
2960   if (LHSValue.getKind() == APValue::Int)
2961     return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
2962                                           RHSValue.getInt(), Result);
2963   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2964   return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
2965                                         RHSValue.getFloat(), Result);
2966 }
2967 
2968 // Perform binary operations for vector types, in place on the LHS.
2969 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
2970                                     BinaryOperatorKind Opcode,
2971                                     APValue &LHSValue,
2972                                     const APValue &RHSValue) {
2973   assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
2974          "Operation not supported on vector types");
2975 
2976   const auto *VT = E->getType()->castAs<VectorType>();
2977   unsigned NumElements = VT->getNumElements();
2978   QualType EltTy = VT->getElementType();
2979 
2980   // In the cases (typically C as I've observed) where we aren't evaluating
2981   // constexpr but are checking for cases where the LHS isn't yet evaluatable,
2982   // just give up.
2983   if (!LHSValue.isVector()) {
2984     assert(LHSValue.isLValue() &&
2985            "A vector result that isn't a vector OR uncalculated LValue");
2986     Info.FFDiag(E);
2987     return false;
2988   }
2989 
2990   assert(LHSValue.getVectorLength() == NumElements &&
2991          RHSValue.getVectorLength() == NumElements && "Different vector sizes");
2992 
2993   SmallVector<APValue, 4> ResultElements;
2994 
2995   for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
2996     APValue LHSElt = LHSValue.getVectorElt(EltNum);
2997     APValue RHSElt = RHSValue.getVectorElt(EltNum);
2998 
2999     if (EltTy->isIntegerType()) {
3000       APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3001                        EltTy->isUnsignedIntegerType()};
3002       bool Success = true;
3003 
3004       if (BinaryOperator::isLogicalOp(Opcode))
3005         Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3006       else if (BinaryOperator::isComparisonOp(Opcode))
3007         Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3008       else
3009         Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3010                                     RHSElt.getInt(), EltResult);
3011 
3012       if (!Success) {
3013         Info.FFDiag(E);
3014         return false;
3015       }
3016       ResultElements.emplace_back(EltResult);
3017 
3018     } else if (EltTy->isFloatingType()) {
3019       assert(LHSElt.getKind() == APValue::Float &&
3020              RHSElt.getKind() == APValue::Float &&
3021              "Mismatched LHS/RHS/Result Type");
3022       APFloat LHSFloat = LHSElt.getFloat();
3023 
3024       if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3025                                  RHSElt.getFloat())) {
3026         Info.FFDiag(E);
3027         return false;
3028       }
3029 
3030       ResultElements.emplace_back(LHSFloat);
3031     }
3032   }
3033 
3034   LHSValue = APValue(ResultElements.data(), ResultElements.size());
3035   return true;
3036 }
3037 
3038 /// Cast an lvalue referring to a base subobject to a derived class, by
3039 /// truncating the lvalue's path to the given length.
3040 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3041                                const RecordDecl *TruncatedType,
3042                                unsigned TruncatedElements) {
3043   SubobjectDesignator &D = Result.Designator;
3044 
3045   // Check we actually point to a derived class object.
3046   if (TruncatedElements == D.Entries.size())
3047     return true;
3048   assert(TruncatedElements >= D.MostDerivedPathLength &&
3049          "not casting to a derived class");
3050   if (!Result.checkSubobject(Info, E, CSK_Derived))
3051     return false;
3052 
3053   // Truncate the path to the subobject, and remove any derived-to-base offsets.
3054   const RecordDecl *RD = TruncatedType;
3055   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3056     if (RD->isInvalidDecl()) return false;
3057     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3058     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3059     if (isVirtualBaseClass(D.Entries[I]))
3060       Result.Offset -= Layout.getVBaseClassOffset(Base);
3061     else
3062       Result.Offset -= Layout.getBaseClassOffset(Base);
3063     RD = Base;
3064   }
3065   D.Entries.resize(TruncatedElements);
3066   return true;
3067 }
3068 
3069 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3070                                    const CXXRecordDecl *Derived,
3071                                    const CXXRecordDecl *Base,
3072                                    const ASTRecordLayout *RL = nullptr) {
3073   if (!RL) {
3074     if (Derived->isInvalidDecl()) return false;
3075     RL = &Info.Ctx.getASTRecordLayout(Derived);
3076   }
3077 
3078   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3079   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3080   return true;
3081 }
3082 
3083 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3084                              const CXXRecordDecl *DerivedDecl,
3085                              const CXXBaseSpecifier *Base) {
3086   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3087 
3088   if (!Base->isVirtual())
3089     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3090 
3091   SubobjectDesignator &D = Obj.Designator;
3092   if (D.Invalid)
3093     return false;
3094 
3095   // Extract most-derived object and corresponding type.
3096   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3097   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3098     return false;
3099 
3100   // Find the virtual base class.
3101   if (DerivedDecl->isInvalidDecl()) return false;
3102   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3103   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3104   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3105   return true;
3106 }
3107 
3108 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3109                                  QualType Type, LValue &Result) {
3110   for (CastExpr::path_const_iterator PathI = E->path_begin(),
3111                                      PathE = E->path_end();
3112        PathI != PathE; ++PathI) {
3113     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3114                           *PathI))
3115       return false;
3116     Type = (*PathI)->getType();
3117   }
3118   return true;
3119 }
3120 
3121 /// Cast an lvalue referring to a derived class to a known base subobject.
3122 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3123                             const CXXRecordDecl *DerivedRD,
3124                             const CXXRecordDecl *BaseRD) {
3125   CXXBasePaths Paths(/*FindAmbiguities=*/false,
3126                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
3127   if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3128     llvm_unreachable("Class must be derived from the passed in base class!");
3129 
3130   for (CXXBasePathElement &Elem : Paths.front())
3131     if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3132       return false;
3133   return true;
3134 }
3135 
3136 /// Update LVal to refer to the given field, which must be a member of the type
3137 /// currently described by LVal.
3138 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3139                                const FieldDecl *FD,
3140                                const ASTRecordLayout *RL = nullptr) {
3141   if (!RL) {
3142     if (FD->getParent()->isInvalidDecl()) return false;
3143     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3144   }
3145 
3146   unsigned I = FD->getFieldIndex();
3147   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3148   LVal.addDecl(Info, E, FD);
3149   return true;
3150 }
3151 
3152 /// Update LVal to refer to the given indirect field.
3153 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3154                                        LValue &LVal,
3155                                        const IndirectFieldDecl *IFD) {
3156   for (const auto *C : IFD->chain())
3157     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3158       return false;
3159   return true;
3160 }
3161 
3162 /// Get the size of the given type in char units.
3163 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
3164                          QualType Type, CharUnits &Size) {
3165   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3166   // extension.
3167   if (Type->isVoidType() || Type->isFunctionType()) {
3168     Size = CharUnits::One();
3169     return true;
3170   }
3171 
3172   if (Type->isDependentType()) {
3173     Info.FFDiag(Loc);
3174     return false;
3175   }
3176 
3177   if (!Type->isConstantSizeType()) {
3178     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3179     // FIXME: Better diagnostic.
3180     Info.FFDiag(Loc);
3181     return false;
3182   }
3183 
3184   Size = Info.Ctx.getTypeSizeInChars(Type);
3185   return true;
3186 }
3187 
3188 /// Update a pointer value to model pointer arithmetic.
3189 /// \param Info - Information about the ongoing evaluation.
3190 /// \param E - The expression being evaluated, for diagnostic purposes.
3191 /// \param LVal - The pointer value to be updated.
3192 /// \param EltTy - The pointee type represented by LVal.
3193 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3194 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3195                                         LValue &LVal, QualType EltTy,
3196                                         APSInt Adjustment) {
3197   CharUnits SizeOfPointee;
3198   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3199     return false;
3200 
3201   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3202   return true;
3203 }
3204 
3205 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3206                                         LValue &LVal, QualType EltTy,
3207                                         int64_t Adjustment) {
3208   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3209                                      APSInt::get(Adjustment));
3210 }
3211 
3212 /// Update an lvalue to refer to a component of a complex number.
3213 /// \param Info - Information about the ongoing evaluation.
3214 /// \param LVal - The lvalue to be updated.
3215 /// \param EltTy - The complex number's component type.
3216 /// \param Imag - False for the real component, true for the imaginary.
3217 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3218                                        LValue &LVal, QualType EltTy,
3219                                        bool Imag) {
3220   if (Imag) {
3221     CharUnits SizeOfComponent;
3222     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3223       return false;
3224     LVal.Offset += SizeOfComponent;
3225   }
3226   LVal.addComplex(Info, E, EltTy, Imag);
3227   return true;
3228 }
3229 
3230 /// Try to evaluate the initializer for a variable declaration.
3231 ///
3232 /// \param Info   Information about the ongoing evaluation.
3233 /// \param E      An expression to be used when printing diagnostics.
3234 /// \param VD     The variable whose initializer should be obtained.
3235 /// \param Version The version of the variable within the frame.
3236 /// \param Frame  The frame in which the variable was created. Must be null
3237 ///               if this variable is not local to the evaluation.
3238 /// \param Result Filled in with a pointer to the value of the variable.
3239 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3240                                 const VarDecl *VD, CallStackFrame *Frame,
3241                                 unsigned Version, APValue *&Result) {
3242   APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3243 
3244   // If this is a local variable, dig out its value.
3245   if (Frame) {
3246     Result = Frame->getTemporary(VD, Version);
3247     if (Result)
3248       return true;
3249 
3250     if (!isa<ParmVarDecl>(VD)) {
3251       // Assume variables referenced within a lambda's call operator that were
3252       // not declared within the call operator are captures and during checking
3253       // of a potential constant expression, assume they are unknown constant
3254       // expressions.
3255       assert(isLambdaCallOperator(Frame->Callee) &&
3256              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3257              "missing value for local variable");
3258       if (Info.checkingPotentialConstantExpression())
3259         return false;
3260       // FIXME: This diagnostic is bogus; we do support captures. Is this code
3261       // still reachable at all?
3262       Info.FFDiag(E->getBeginLoc(),
3263                   diag::note_unimplemented_constexpr_lambda_feature_ast)
3264           << "captures not currently allowed";
3265       return false;
3266     }
3267   }
3268 
3269   // If we're currently evaluating the initializer of this declaration, use that
3270   // in-flight value.
3271   if (Info.EvaluatingDecl == Base) {
3272     Result = Info.EvaluatingDeclValue;
3273     return true;
3274   }
3275 
3276   if (isa<ParmVarDecl>(VD)) {
3277     // Assume parameters of a potential constant expression are usable in
3278     // constant expressions.
3279     if (!Info.checkingPotentialConstantExpression() ||
3280         !Info.CurrentCall->Callee ||
3281         !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3282       if (Info.getLangOpts().CPlusPlus11) {
3283         Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3284             << VD;
3285         NoteLValueLocation(Info, Base);
3286       } else {
3287         Info.FFDiag(E);
3288       }
3289     }
3290     return false;
3291   }
3292 
3293   // Dig out the initializer, and use the declaration which it's attached to.
3294   // FIXME: We should eventually check whether the variable has a reachable
3295   // initializing declaration.
3296   const Expr *Init = VD->getAnyInitializer(VD);
3297   if (!Init) {
3298     // Don't diagnose during potential constant expression checking; an
3299     // initializer might be added later.
3300     if (!Info.checkingPotentialConstantExpression()) {
3301       Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3302         << VD;
3303       NoteLValueLocation(Info, Base);
3304     }
3305     return false;
3306   }
3307 
3308   if (Init->isValueDependent()) {
3309     // The DeclRefExpr is not value-dependent, but the variable it refers to
3310     // has a value-dependent initializer. This should only happen in
3311     // constant-folding cases, where the variable is not actually of a suitable
3312     // type for use in a constant expression (otherwise the DeclRefExpr would
3313     // have been value-dependent too), so diagnose that.
3314     assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3315     if (!Info.checkingPotentialConstantExpression()) {
3316       Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3317                          ? diag::note_constexpr_ltor_non_constexpr
3318                          : diag::note_constexpr_ltor_non_integral, 1)
3319           << VD << VD->getType();
3320       NoteLValueLocation(Info, Base);
3321     }
3322     return false;
3323   }
3324 
3325   // Check that we can fold the initializer. In C++, we will have already done
3326   // this in the cases where it matters for conformance.
3327   SmallVector<PartialDiagnosticAt, 8> Notes;
3328   if (!VD->evaluateValue(Notes)) {
3329     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
3330               Notes.size() + 1) << VD;
3331     NoteLValueLocation(Info, Base);
3332     Info.addNotes(Notes);
3333     return false;
3334   }
3335 
3336   // Check that the variable is actually usable in constant expressions. For a
3337   // const integral variable or a reference, we might have a non-constant
3338   // initializer that we can nonetheless evaluate the initializer for. Such
3339   // variables are not usable in constant expressions. In C++98, the
3340   // initializer also syntactically needs to be an ICE.
3341   //
3342   // FIXME: We don't diagnose cases that aren't potentially usable in constant
3343   // expressions here; doing so would regress diagnostics for things like
3344   // reading from a volatile constexpr variable.
3345   if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3346        VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||
3347       ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3348        !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3349     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3350     NoteLValueLocation(Info, Base);
3351   }
3352 
3353   // Never use the initializer of a weak variable, not even for constant
3354   // folding. We can't be sure that this is the definition that will be used.
3355   if (VD->isWeak()) {
3356     Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3357     NoteLValueLocation(Info, Base);
3358     return false;
3359   }
3360 
3361   Result = VD->getEvaluatedValue();
3362   return true;
3363 }
3364 
3365 /// Get the base index of the given base class within an APValue representing
3366 /// the given derived class.
3367 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3368                              const CXXRecordDecl *Base) {
3369   Base = Base->getCanonicalDecl();
3370   unsigned Index = 0;
3371   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3372          E = Derived->bases_end(); I != E; ++I, ++Index) {
3373     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3374       return Index;
3375   }
3376 
3377   llvm_unreachable("base class missing from derived class's bases list");
3378 }
3379 
3380 /// Extract the value of a character from a string literal.
3381 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3382                                             uint64_t Index) {
3383   assert(!isa<SourceLocExpr>(Lit) &&
3384          "SourceLocExpr should have already been converted to a StringLiteral");
3385 
3386   // FIXME: Support MakeStringConstant
3387   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3388     std::string Str;
3389     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3390     assert(Index <= Str.size() && "Index too large");
3391     return APSInt::getUnsigned(Str.c_str()[Index]);
3392   }
3393 
3394   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3395     Lit = PE->getFunctionName();
3396   const StringLiteral *S = cast<StringLiteral>(Lit);
3397   const ConstantArrayType *CAT =
3398       Info.Ctx.getAsConstantArrayType(S->getType());
3399   assert(CAT && "string literal isn't an array");
3400   QualType CharType = CAT->getElementType();
3401   assert(CharType->isIntegerType() && "unexpected character type");
3402 
3403   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3404                CharType->isUnsignedIntegerType());
3405   if (Index < S->getLength())
3406     Value = S->getCodeUnit(Index);
3407   return Value;
3408 }
3409 
3410 // Expand a string literal into an array of characters.
3411 //
3412 // FIXME: This is inefficient; we should probably introduce something similar
3413 // to the LLVM ConstantDataArray to make this cheaper.
3414 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3415                                 APValue &Result,
3416                                 QualType AllocType = QualType()) {
3417   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3418       AllocType.isNull() ? S->getType() : AllocType);
3419   assert(CAT && "string literal isn't an array");
3420   QualType CharType = CAT->getElementType();
3421   assert(CharType->isIntegerType() && "unexpected character type");
3422 
3423   unsigned Elts = CAT->getSize().getZExtValue();
3424   Result = APValue(APValue::UninitArray(),
3425                    std::min(S->getLength(), Elts), Elts);
3426   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3427                CharType->isUnsignedIntegerType());
3428   if (Result.hasArrayFiller())
3429     Result.getArrayFiller() = APValue(Value);
3430   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3431     Value = S->getCodeUnit(I);
3432     Result.getArrayInitializedElt(I) = APValue(Value);
3433   }
3434 }
3435 
3436 // Expand an array so that it has more than Index filled elements.
3437 static void expandArray(APValue &Array, unsigned Index) {
3438   unsigned Size = Array.getArraySize();
3439   assert(Index < Size);
3440 
3441   // Always at least double the number of elements for which we store a value.
3442   unsigned OldElts = Array.getArrayInitializedElts();
3443   unsigned NewElts = std::max(Index+1, OldElts * 2);
3444   NewElts = std::min(Size, std::max(NewElts, 8u));
3445 
3446   // Copy the data across.
3447   APValue NewValue(APValue::UninitArray(), NewElts, Size);
3448   for (unsigned I = 0; I != OldElts; ++I)
3449     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3450   for (unsigned I = OldElts; I != NewElts; ++I)
3451     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3452   if (NewValue.hasArrayFiller())
3453     NewValue.getArrayFiller() = Array.getArrayFiller();
3454   Array.swap(NewValue);
3455 }
3456 
3457 /// Determine whether a type would actually be read by an lvalue-to-rvalue
3458 /// conversion. If it's of class type, we may assume that the copy operation
3459 /// is trivial. Note that this is never true for a union type with fields
3460 /// (because the copy always "reads" the active member) and always true for
3461 /// a non-class type.
3462 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3463 static bool isReadByLvalueToRvalueConversion(QualType T) {
3464   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3465   return !RD || isReadByLvalueToRvalueConversion(RD);
3466 }
3467 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3468   // FIXME: A trivial copy of a union copies the object representation, even if
3469   // the union is empty.
3470   if (RD->isUnion())
3471     return !RD->field_empty();
3472   if (RD->isEmpty())
3473     return false;
3474 
3475   for (auto *Field : RD->fields())
3476     if (!Field->isUnnamedBitfield() &&
3477         isReadByLvalueToRvalueConversion(Field->getType()))
3478       return true;
3479 
3480   for (auto &BaseSpec : RD->bases())
3481     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3482       return true;
3483 
3484   return false;
3485 }
3486 
3487 /// Diagnose an attempt to read from any unreadable field within the specified
3488 /// type, which might be a class type.
3489 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3490                                   QualType T) {
3491   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3492   if (!RD)
3493     return false;
3494 
3495   if (!RD->hasMutableFields())
3496     return false;
3497 
3498   for (auto *Field : RD->fields()) {
3499     // If we're actually going to read this field in some way, then it can't
3500     // be mutable. If we're in a union, then assigning to a mutable field
3501     // (even an empty one) can change the active member, so that's not OK.
3502     // FIXME: Add core issue number for the union case.
3503     if (Field->isMutable() &&
3504         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3505       Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3506       Info.Note(Field->getLocation(), diag::note_declared_at);
3507       return true;
3508     }
3509 
3510     if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3511       return true;
3512   }
3513 
3514   for (auto &BaseSpec : RD->bases())
3515     if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3516       return true;
3517 
3518   // All mutable fields were empty, and thus not actually read.
3519   return false;
3520 }
3521 
3522 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3523                                         APValue::LValueBase Base,
3524                                         bool MutableSubobject = false) {
3525   // A temporary or transient heap allocation we created.
3526   if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3527     return true;
3528 
3529   switch (Info.IsEvaluatingDecl) {
3530   case EvalInfo::EvaluatingDeclKind::None:
3531     return false;
3532 
3533   case EvalInfo::EvaluatingDeclKind::Ctor:
3534     // The variable whose initializer we're evaluating.
3535     if (Info.EvaluatingDecl == Base)
3536       return true;
3537 
3538     // A temporary lifetime-extended by the variable whose initializer we're
3539     // evaluating.
3540     if (auto *BaseE = Base.dyn_cast<const Expr *>())
3541       if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3542         return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3543     return false;
3544 
3545   case EvalInfo::EvaluatingDeclKind::Dtor:
3546     // C++2a [expr.const]p6:
3547     //   [during constant destruction] the lifetime of a and its non-mutable
3548     //   subobjects (but not its mutable subobjects) [are] considered to start
3549     //   within e.
3550     if (MutableSubobject || Base != Info.EvaluatingDecl)
3551       return false;
3552     // FIXME: We can meaningfully extend this to cover non-const objects, but
3553     // we will need special handling: we should be able to access only
3554     // subobjects of such objects that are themselves declared const.
3555     QualType T = getType(Base);
3556     return T.isConstQualified() || T->isReferenceType();
3557   }
3558 
3559   llvm_unreachable("unknown evaluating decl kind");
3560 }
3561 
3562 namespace {
3563 /// A handle to a complete object (an object that is not a subobject of
3564 /// another object).
3565 struct CompleteObject {
3566   /// The identity of the object.
3567   APValue::LValueBase Base;
3568   /// The value of the complete object.
3569   APValue *Value;
3570   /// The type of the complete object.
3571   QualType Type;
3572 
3573   CompleteObject() : Value(nullptr) {}
3574   CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3575       : Base(Base), Value(Value), Type(Type) {}
3576 
3577   bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3578     // If this isn't a "real" access (eg, if it's just accessing the type
3579     // info), allow it. We assume the type doesn't change dynamically for
3580     // subobjects of constexpr objects (even though we'd hit UB here if it
3581     // did). FIXME: Is this right?
3582     if (!isAnyAccess(AK))
3583       return true;
3584 
3585     // In C++14 onwards, it is permitted to read a mutable member whose
3586     // lifetime began within the evaluation.
3587     // FIXME: Should we also allow this in C++11?
3588     if (!Info.getLangOpts().CPlusPlus14)
3589       return false;
3590     return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3591   }
3592 
3593   explicit operator bool() const { return !Type.isNull(); }
3594 };
3595 } // end anonymous namespace
3596 
3597 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3598                                  bool IsMutable = false) {
3599   // C++ [basic.type.qualifier]p1:
3600   // - A const object is an object of type const T or a non-mutable subobject
3601   //   of a const object.
3602   if (ObjType.isConstQualified() && !IsMutable)
3603     SubobjType.addConst();
3604   // - A volatile object is an object of type const T or a subobject of a
3605   //   volatile object.
3606   if (ObjType.isVolatileQualified())
3607     SubobjType.addVolatile();
3608   return SubobjType;
3609 }
3610 
3611 /// Find the designated sub-object of an rvalue.
3612 template<typename SubobjectHandler>
3613 typename SubobjectHandler::result_type
3614 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3615               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3616   if (Sub.Invalid)
3617     // A diagnostic will have already been produced.
3618     return handler.failed();
3619   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3620     if (Info.getLangOpts().CPlusPlus11)
3621       Info.FFDiag(E, Sub.isOnePastTheEnd()
3622                          ? diag::note_constexpr_access_past_end
3623                          : diag::note_constexpr_access_unsized_array)
3624           << handler.AccessKind;
3625     else
3626       Info.FFDiag(E);
3627     return handler.failed();
3628   }
3629 
3630   APValue *O = Obj.Value;
3631   QualType ObjType = Obj.Type;
3632   const FieldDecl *LastField = nullptr;
3633   const FieldDecl *VolatileField = nullptr;
3634 
3635   // Walk the designator's path to find the subobject.
3636   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3637     // Reading an indeterminate value is undefined, but assigning over one is OK.
3638     if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3639         (O->isIndeterminate() &&
3640          !isValidIndeterminateAccess(handler.AccessKind))) {
3641       if (!Info.checkingPotentialConstantExpression())
3642         Info.FFDiag(E, diag::note_constexpr_access_uninit)
3643             << handler.AccessKind << O->isIndeterminate();
3644       return handler.failed();
3645     }
3646 
3647     // C++ [class.ctor]p5, C++ [class.dtor]p5:
3648     //    const and volatile semantics are not applied on an object under
3649     //    {con,de}struction.
3650     if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3651         ObjType->isRecordType() &&
3652         Info.isEvaluatingCtorDtor(
3653             Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3654                                          Sub.Entries.begin() + I)) !=
3655                           ConstructionPhase::None) {
3656       ObjType = Info.Ctx.getCanonicalType(ObjType);
3657       ObjType.removeLocalConst();
3658       ObjType.removeLocalVolatile();
3659     }
3660 
3661     // If this is our last pass, check that the final object type is OK.
3662     if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3663       // Accesses to volatile objects are prohibited.
3664       if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3665         if (Info.getLangOpts().CPlusPlus) {
3666           int DiagKind;
3667           SourceLocation Loc;
3668           const NamedDecl *Decl = nullptr;
3669           if (VolatileField) {
3670             DiagKind = 2;
3671             Loc = VolatileField->getLocation();
3672             Decl = VolatileField;
3673           } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3674             DiagKind = 1;
3675             Loc = VD->getLocation();
3676             Decl = VD;
3677           } else {
3678             DiagKind = 0;
3679             if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3680               Loc = E->getExprLoc();
3681           }
3682           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3683               << handler.AccessKind << DiagKind << Decl;
3684           Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3685         } else {
3686           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3687         }
3688         return handler.failed();
3689       }
3690 
3691       // If we are reading an object of class type, there may still be more
3692       // things we need to check: if there are any mutable subobjects, we
3693       // cannot perform this read. (This only happens when performing a trivial
3694       // copy or assignment.)
3695       if (ObjType->isRecordType() &&
3696           !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3697           diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3698         return handler.failed();
3699     }
3700 
3701     if (I == N) {
3702       if (!handler.found(*O, ObjType))
3703         return false;
3704 
3705       // If we modified a bit-field, truncate it to the right width.
3706       if (isModification(handler.AccessKind) &&
3707           LastField && LastField->isBitField() &&
3708           !truncateBitfieldValue(Info, E, *O, LastField))
3709         return false;
3710 
3711       return true;
3712     }
3713 
3714     LastField = nullptr;
3715     if (ObjType->isArrayType()) {
3716       // Next subobject is an array element.
3717       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3718       assert(CAT && "vla in literal type?");
3719       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3720       if (CAT->getSize().ule(Index)) {
3721         // Note, it should not be possible to form a pointer with a valid
3722         // designator which points more than one past the end of the array.
3723         if (Info.getLangOpts().CPlusPlus11)
3724           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3725             << handler.AccessKind;
3726         else
3727           Info.FFDiag(E);
3728         return handler.failed();
3729       }
3730 
3731       ObjType = CAT->getElementType();
3732 
3733       if (O->getArrayInitializedElts() > Index)
3734         O = &O->getArrayInitializedElt(Index);
3735       else if (!isRead(handler.AccessKind)) {
3736         expandArray(*O, Index);
3737         O = &O->getArrayInitializedElt(Index);
3738       } else
3739         O = &O->getArrayFiller();
3740     } else if (ObjType->isAnyComplexType()) {
3741       // Next subobject is a complex number.
3742       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3743       if (Index > 1) {
3744         if (Info.getLangOpts().CPlusPlus11)
3745           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3746             << handler.AccessKind;
3747         else
3748           Info.FFDiag(E);
3749         return handler.failed();
3750       }
3751 
3752       ObjType = getSubobjectType(
3753           ObjType, ObjType->castAs<ComplexType>()->getElementType());
3754 
3755       assert(I == N - 1 && "extracting subobject of scalar?");
3756       if (O->isComplexInt()) {
3757         return handler.found(Index ? O->getComplexIntImag()
3758                                    : O->getComplexIntReal(), ObjType);
3759       } else {
3760         assert(O->isComplexFloat());
3761         return handler.found(Index ? O->getComplexFloatImag()
3762                                    : O->getComplexFloatReal(), ObjType);
3763       }
3764     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3765       if (Field->isMutable() &&
3766           !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3767         Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3768           << handler.AccessKind << Field;
3769         Info.Note(Field->getLocation(), diag::note_declared_at);
3770         return handler.failed();
3771       }
3772 
3773       // Next subobject is a class, struct or union field.
3774       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3775       if (RD->isUnion()) {
3776         const FieldDecl *UnionField = O->getUnionField();
3777         if (!UnionField ||
3778             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3779           if (I == N - 1 && handler.AccessKind == AK_Construct) {
3780             // Placement new onto an inactive union member makes it active.
3781             O->setUnion(Field, APValue());
3782           } else {
3783             // FIXME: If O->getUnionValue() is absent, report that there's no
3784             // active union member rather than reporting the prior active union
3785             // member. We'll need to fix nullptr_t to not use APValue() as its
3786             // representation first.
3787             Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3788                 << handler.AccessKind << Field << !UnionField << UnionField;
3789             return handler.failed();
3790           }
3791         }
3792         O = &O->getUnionValue();
3793       } else
3794         O = &O->getStructField(Field->getFieldIndex());
3795 
3796       ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3797       LastField = Field;
3798       if (Field->getType().isVolatileQualified())
3799         VolatileField = Field;
3800     } else {
3801       // Next subobject is a base class.
3802       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3803       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3804       O = &O->getStructBase(getBaseIndex(Derived, Base));
3805 
3806       ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3807     }
3808   }
3809 }
3810 
3811 namespace {
3812 struct ExtractSubobjectHandler {
3813   EvalInfo &Info;
3814   const Expr *E;
3815   APValue &Result;
3816   const AccessKinds AccessKind;
3817 
3818   typedef bool result_type;
3819   bool failed() { return false; }
3820   bool found(APValue &Subobj, QualType SubobjType) {
3821     Result = Subobj;
3822     if (AccessKind == AK_ReadObjectRepresentation)
3823       return true;
3824     return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3825   }
3826   bool found(APSInt &Value, QualType SubobjType) {
3827     Result = APValue(Value);
3828     return true;
3829   }
3830   bool found(APFloat &Value, QualType SubobjType) {
3831     Result = APValue(Value);
3832     return true;
3833   }
3834 };
3835 } // end anonymous namespace
3836 
3837 /// Extract the designated sub-object of an rvalue.
3838 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3839                              const CompleteObject &Obj,
3840                              const SubobjectDesignator &Sub, APValue &Result,
3841                              AccessKinds AK = AK_Read) {
3842   assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3843   ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3844   return findSubobject(Info, E, Obj, Sub, Handler);
3845 }
3846 
3847 namespace {
3848 struct ModifySubobjectHandler {
3849   EvalInfo &Info;
3850   APValue &NewVal;
3851   const Expr *E;
3852 
3853   typedef bool result_type;
3854   static const AccessKinds AccessKind = AK_Assign;
3855 
3856   bool checkConst(QualType QT) {
3857     // Assigning to a const object has undefined behavior.
3858     if (QT.isConstQualified()) {
3859       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3860       return false;
3861     }
3862     return true;
3863   }
3864 
3865   bool failed() { return false; }
3866   bool found(APValue &Subobj, QualType SubobjType) {
3867     if (!checkConst(SubobjType))
3868       return false;
3869     // We've been given ownership of NewVal, so just swap it in.
3870     Subobj.swap(NewVal);
3871     return true;
3872   }
3873   bool found(APSInt &Value, QualType SubobjType) {
3874     if (!checkConst(SubobjType))
3875       return false;
3876     if (!NewVal.isInt()) {
3877       // Maybe trying to write a cast pointer value into a complex?
3878       Info.FFDiag(E);
3879       return false;
3880     }
3881     Value = NewVal.getInt();
3882     return true;
3883   }
3884   bool found(APFloat &Value, QualType SubobjType) {
3885     if (!checkConst(SubobjType))
3886       return false;
3887     Value = NewVal.getFloat();
3888     return true;
3889   }
3890 };
3891 } // end anonymous namespace
3892 
3893 const AccessKinds ModifySubobjectHandler::AccessKind;
3894 
3895 /// Update the designated sub-object of an rvalue to the given value.
3896 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3897                             const CompleteObject &Obj,
3898                             const SubobjectDesignator &Sub,
3899                             APValue &NewVal) {
3900   ModifySubobjectHandler Handler = { Info, NewVal, E };
3901   return findSubobject(Info, E, Obj, Sub, Handler);
3902 }
3903 
3904 /// Find the position where two subobject designators diverge, or equivalently
3905 /// the length of the common initial subsequence.
3906 static unsigned FindDesignatorMismatch(QualType ObjType,
3907                                        const SubobjectDesignator &A,
3908                                        const SubobjectDesignator &B,
3909                                        bool &WasArrayIndex) {
3910   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3911   for (/**/; I != N; ++I) {
3912     if (!ObjType.isNull() &&
3913         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3914       // Next subobject is an array element.
3915       if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3916         WasArrayIndex = true;
3917         return I;
3918       }
3919       if (ObjType->isAnyComplexType())
3920         ObjType = ObjType->castAs<ComplexType>()->getElementType();
3921       else
3922         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3923     } else {
3924       if (A.Entries[I].getAsBaseOrMember() !=
3925           B.Entries[I].getAsBaseOrMember()) {
3926         WasArrayIndex = false;
3927         return I;
3928       }
3929       if (const FieldDecl *FD = getAsField(A.Entries[I]))
3930         // Next subobject is a field.
3931         ObjType = FD->getType();
3932       else
3933         // Next subobject is a base class.
3934         ObjType = QualType();
3935     }
3936   }
3937   WasArrayIndex = false;
3938   return I;
3939 }
3940 
3941 /// Determine whether the given subobject designators refer to elements of the
3942 /// same array object.
3943 static bool AreElementsOfSameArray(QualType ObjType,
3944                                    const SubobjectDesignator &A,
3945                                    const SubobjectDesignator &B) {
3946   if (A.Entries.size() != B.Entries.size())
3947     return false;
3948 
3949   bool IsArray = A.MostDerivedIsArrayElement;
3950   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3951     // A is a subobject of the array element.
3952     return false;
3953 
3954   // If A (and B) designates an array element, the last entry will be the array
3955   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3956   // of length 1' case, and the entire path must match.
3957   bool WasArrayIndex;
3958   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3959   return CommonLength >= A.Entries.size() - IsArray;
3960 }
3961 
3962 /// Find the complete object to which an LValue refers.
3963 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3964                                          AccessKinds AK, const LValue &LVal,
3965                                          QualType LValType) {
3966   if (LVal.InvalidBase) {
3967     Info.FFDiag(E);
3968     return CompleteObject();
3969   }
3970 
3971   if (!LVal.Base) {
3972     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3973     return CompleteObject();
3974   }
3975 
3976   CallStackFrame *Frame = nullptr;
3977   unsigned Depth = 0;
3978   if (LVal.getLValueCallIndex()) {
3979     std::tie(Frame, Depth) =
3980         Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3981     if (!Frame) {
3982       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3983         << AK << LVal.Base.is<const ValueDecl*>();
3984       NoteLValueLocation(Info, LVal.Base);
3985       return CompleteObject();
3986     }
3987   }
3988 
3989   bool IsAccess = isAnyAccess(AK);
3990 
3991   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3992   // is not a constant expression (even if the object is non-volatile). We also
3993   // apply this rule to C++98, in order to conform to the expected 'volatile'
3994   // semantics.
3995   if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
3996     if (Info.getLangOpts().CPlusPlus)
3997       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3998         << AK << LValType;
3999     else
4000       Info.FFDiag(E);
4001     return CompleteObject();
4002   }
4003 
4004   // Compute value storage location and type of base object.
4005   APValue *BaseVal = nullptr;
4006   QualType BaseType = getType(LVal.Base);
4007 
4008   if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4009       lifetimeStartedInEvaluation(Info, LVal.Base)) {
4010     // This is the object whose initializer we're evaluating, so its lifetime
4011     // started in the current evaluation.
4012     BaseVal = Info.EvaluatingDeclValue;
4013   } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4014     // Allow reading from a GUID declaration.
4015     if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4016       if (isModification(AK)) {
4017         // All the remaining cases do not permit modification of the object.
4018         Info.FFDiag(E, diag::note_constexpr_modify_global);
4019         return CompleteObject();
4020       }
4021       APValue &V = GD->getAsAPValue();
4022       if (V.isAbsent()) {
4023         Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4024             << GD->getType();
4025         return CompleteObject();
4026       }
4027       return CompleteObject(LVal.Base, &V, GD->getType());
4028     }
4029 
4030     // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4031     if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4032       if (isModification(AK)) {
4033         Info.FFDiag(E, diag::note_constexpr_modify_global);
4034         return CompleteObject();
4035       }
4036       return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4037                             GCD->getType());
4038     }
4039 
4040     // Allow reading from template parameter objects.
4041     if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4042       if (isModification(AK)) {
4043         Info.FFDiag(E, diag::note_constexpr_modify_global);
4044         return CompleteObject();
4045       }
4046       return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4047                             TPO->getType());
4048     }
4049 
4050     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4051     // In C++11, constexpr, non-volatile variables initialized with constant
4052     // expressions are constant expressions too. Inside constexpr functions,
4053     // parameters are constant expressions even if they're non-const.
4054     // In C++1y, objects local to a constant expression (those with a Frame) are
4055     // both readable and writable inside constant expressions.
4056     // In C, such things can also be folded, although they are not ICEs.
4057     const VarDecl *VD = dyn_cast<VarDecl>(D);
4058     if (VD) {
4059       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4060         VD = VDef;
4061     }
4062     if (!VD || VD->isInvalidDecl()) {
4063       Info.FFDiag(E);
4064       return CompleteObject();
4065     }
4066 
4067     bool IsConstant = BaseType.isConstant(Info.Ctx);
4068 
4069     // Unless we're looking at a local variable or argument in a constexpr call,
4070     // the variable we're reading must be const.
4071     if (!Frame) {
4072       if (IsAccess && isa<ParmVarDecl>(VD)) {
4073         // Access of a parameter that's not associated with a frame isn't going
4074         // to work out, but we can leave it to evaluateVarDeclInit to provide a
4075         // suitable diagnostic.
4076       } else if (Info.getLangOpts().CPlusPlus14 &&
4077                  lifetimeStartedInEvaluation(Info, LVal.Base)) {
4078         // OK, we can read and modify an object if we're in the process of
4079         // evaluating its initializer, because its lifetime began in this
4080         // evaluation.
4081       } else if (isModification(AK)) {
4082         // All the remaining cases do not permit modification of the object.
4083         Info.FFDiag(E, diag::note_constexpr_modify_global);
4084         return CompleteObject();
4085       } else if (VD->isConstexpr()) {
4086         // OK, we can read this variable.
4087       } else if (BaseType->isIntegralOrEnumerationType()) {
4088         if (!IsConstant) {
4089           if (!IsAccess)
4090             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4091           if (Info.getLangOpts().CPlusPlus) {
4092             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4093             Info.Note(VD->getLocation(), diag::note_declared_at);
4094           } else {
4095             Info.FFDiag(E);
4096           }
4097           return CompleteObject();
4098         }
4099       } else if (!IsAccess) {
4100         return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4101       } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
4102                  BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4103         // This variable might end up being constexpr. Don't diagnose it yet.
4104       } else if (IsConstant) {
4105         // Keep evaluating to see what we can do. In particular, we support
4106         // folding of const floating-point types, in order to make static const
4107         // data members of such types (supported as an extension) more useful.
4108         if (Info.getLangOpts().CPlusPlus) {
4109           Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4110                               ? diag::note_constexpr_ltor_non_constexpr
4111                               : diag::note_constexpr_ltor_non_integral, 1)
4112               << VD << BaseType;
4113           Info.Note(VD->getLocation(), diag::note_declared_at);
4114         } else {
4115           Info.CCEDiag(E);
4116         }
4117       } else {
4118         // Never allow reading a non-const value.
4119         if (Info.getLangOpts().CPlusPlus) {
4120           Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4121                              ? diag::note_constexpr_ltor_non_constexpr
4122                              : diag::note_constexpr_ltor_non_integral, 1)
4123               << VD << BaseType;
4124           Info.Note(VD->getLocation(), diag::note_declared_at);
4125         } else {
4126           Info.FFDiag(E);
4127         }
4128         return CompleteObject();
4129       }
4130     }
4131 
4132     if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
4133       return CompleteObject();
4134   } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4135     Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
4136     if (!Alloc) {
4137       Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4138       return CompleteObject();
4139     }
4140     return CompleteObject(LVal.Base, &(*Alloc)->Value,
4141                           LVal.Base.getDynamicAllocType());
4142   } else {
4143     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4144 
4145     if (!Frame) {
4146       if (const MaterializeTemporaryExpr *MTE =
4147               dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4148         assert(MTE->getStorageDuration() == SD_Static &&
4149                "should have a frame for a non-global materialized temporary");
4150 
4151         // C++20 [expr.const]p4: [DR2126]
4152         //   An object or reference is usable in constant expressions if it is
4153         //   - a temporary object of non-volatile const-qualified literal type
4154         //     whose lifetime is extended to that of a variable that is usable
4155         //     in constant expressions
4156         //
4157         // C++20 [expr.const]p5:
4158         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4159         //   - a non-volatile glvalue that refers to an object that is usable
4160         //     in constant expressions, or
4161         //   - a non-volatile glvalue of literal type that refers to a
4162         //     non-volatile object whose lifetime began within the evaluation
4163         //     of E;
4164         //
4165         // C++11 misses the 'began within the evaluation of e' check and
4166         // instead allows all temporaries, including things like:
4167         //   int &&r = 1;
4168         //   int x = ++r;
4169         //   constexpr int k = r;
4170         // Therefore we use the C++14-onwards rules in C++11 too.
4171         //
4172         // Note that temporaries whose lifetimes began while evaluating a
4173         // variable's constructor are not usable while evaluating the
4174         // corresponding destructor, not even if they're of const-qualified
4175         // types.
4176         if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4177             !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4178           if (!IsAccess)
4179             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4180           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4181           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4182           return CompleteObject();
4183         }
4184 
4185         BaseVal = MTE->getOrCreateValue(false);
4186         assert(BaseVal && "got reference to unevaluated temporary");
4187       } else {
4188         if (!IsAccess)
4189           return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4190         APValue Val;
4191         LVal.moveInto(Val);
4192         Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4193             << AK
4194             << Val.getAsString(Info.Ctx,
4195                                Info.Ctx.getLValueReferenceType(LValType));
4196         NoteLValueLocation(Info, LVal.Base);
4197         return CompleteObject();
4198       }
4199     } else {
4200       BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4201       assert(BaseVal && "missing value for temporary");
4202     }
4203   }
4204 
4205   // In C++14, we can't safely access any mutable state when we might be
4206   // evaluating after an unmodeled side effect. Parameters are modeled as state
4207   // in the caller, but aren't visible once the call returns, so they can be
4208   // modified in a speculatively-evaluated call.
4209   //
4210   // FIXME: Not all local state is mutable. Allow local constant subobjects
4211   // to be read here (but take care with 'mutable' fields).
4212   unsigned VisibleDepth = Depth;
4213   if (llvm::isa_and_nonnull<ParmVarDecl>(
4214           LVal.Base.dyn_cast<const ValueDecl *>()))
4215     ++VisibleDepth;
4216   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4217        Info.EvalStatus.HasSideEffects) ||
4218       (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4219     return CompleteObject();
4220 
4221   return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4222 }
4223 
4224 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4225 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4226 /// glvalue referred to by an entity of reference type.
4227 ///
4228 /// \param Info - Information about the ongoing evaluation.
4229 /// \param Conv - The expression for which we are performing the conversion.
4230 ///               Used for diagnostics.
4231 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4232 ///               case of a non-class type).
4233 /// \param LVal - The glvalue on which we are attempting to perform this action.
4234 /// \param RVal - The produced value will be placed here.
4235 /// \param WantObjectRepresentation - If true, we're looking for the object
4236 ///               representation rather than the value, and in particular,
4237 ///               there is no requirement that the result be fully initialized.
4238 static bool
4239 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
4240                                const LValue &LVal, APValue &RVal,
4241                                bool WantObjectRepresentation = false) {
4242   if (LVal.Designator.Invalid)
4243     return false;
4244 
4245   // Check for special cases where there is no existing APValue to look at.
4246   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4247 
4248   AccessKinds AK =
4249       WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4250 
4251   if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4252     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4253       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4254       // initializer until now for such expressions. Such an expression can't be
4255       // an ICE in C, so this only matters for fold.
4256       if (Type.isVolatileQualified()) {
4257         Info.FFDiag(Conv);
4258         return false;
4259       }
4260 
4261       APValue Lit;
4262       if (!Evaluate(Lit, Info, CLE->getInitializer()))
4263         return false;
4264 
4265       // According to GCC info page:
4266       //
4267       // 6.28 Compound Literals
4268       //
4269       // As an optimization, G++ sometimes gives array compound literals longer
4270       // lifetimes: when the array either appears outside a function or has a
4271       // const-qualified type. If foo and its initializer had elements of type
4272       // char *const rather than char *, or if foo were a global variable, the
4273       // array would have static storage duration. But it is probably safest
4274       // just to avoid the use of array compound literals in C++ code.
4275       //
4276       // Obey that rule by checking constness for converted array types.
4277 
4278       QualType CLETy = CLE->getType();
4279       if (CLETy->isArrayType() && !Type->isArrayType()) {
4280         if (!CLETy.isConstant(Info.Ctx)) {
4281           Info.FFDiag(Conv);
4282           Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4283           return false;
4284         }
4285       }
4286 
4287       CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4288       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4289     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4290       // Special-case character extraction so we don't have to construct an
4291       // APValue for the whole string.
4292       assert(LVal.Designator.Entries.size() <= 1 &&
4293              "Can only read characters from string literals");
4294       if (LVal.Designator.Entries.empty()) {
4295         // Fail for now for LValue to RValue conversion of an array.
4296         // (This shouldn't show up in C/C++, but it could be triggered by a
4297         // weird EvaluateAsRValue call from a tool.)
4298         Info.FFDiag(Conv);
4299         return false;
4300       }
4301       if (LVal.Designator.isOnePastTheEnd()) {
4302         if (Info.getLangOpts().CPlusPlus11)
4303           Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4304         else
4305           Info.FFDiag(Conv);
4306         return false;
4307       }
4308       uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4309       RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4310       return true;
4311     }
4312   }
4313 
4314   CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4315   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4316 }
4317 
4318 /// Perform an assignment of Val to LVal. Takes ownership of Val.
4319 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4320                              QualType LValType, APValue &Val) {
4321   if (LVal.Designator.Invalid)
4322     return false;
4323 
4324   if (!Info.getLangOpts().CPlusPlus14) {
4325     Info.FFDiag(E);
4326     return false;
4327   }
4328 
4329   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4330   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4331 }
4332 
4333 namespace {
4334 struct CompoundAssignSubobjectHandler {
4335   EvalInfo &Info;
4336   const CompoundAssignOperator *E;
4337   QualType PromotedLHSType;
4338   BinaryOperatorKind Opcode;
4339   const APValue &RHS;
4340 
4341   static const AccessKinds AccessKind = AK_Assign;
4342 
4343   typedef bool result_type;
4344 
4345   bool checkConst(QualType QT) {
4346     // Assigning to a const object has undefined behavior.
4347     if (QT.isConstQualified()) {
4348       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4349       return false;
4350     }
4351     return true;
4352   }
4353 
4354   bool failed() { return false; }
4355   bool found(APValue &Subobj, QualType SubobjType) {
4356     switch (Subobj.getKind()) {
4357     case APValue::Int:
4358       return found(Subobj.getInt(), SubobjType);
4359     case APValue::Float:
4360       return found(Subobj.getFloat(), SubobjType);
4361     case APValue::ComplexInt:
4362     case APValue::ComplexFloat:
4363       // FIXME: Implement complex compound assignment.
4364       Info.FFDiag(E);
4365       return false;
4366     case APValue::LValue:
4367       return foundPointer(Subobj, SubobjType);
4368     case APValue::Vector:
4369       return foundVector(Subobj, SubobjType);
4370     default:
4371       // FIXME: can this happen?
4372       Info.FFDiag(E);
4373       return false;
4374     }
4375   }
4376 
4377   bool foundVector(APValue &Value, QualType SubobjType) {
4378     if (!checkConst(SubobjType))
4379       return false;
4380 
4381     if (!SubobjType->isVectorType()) {
4382       Info.FFDiag(E);
4383       return false;
4384     }
4385     return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4386   }
4387 
4388   bool found(APSInt &Value, QualType SubobjType) {
4389     if (!checkConst(SubobjType))
4390       return false;
4391 
4392     if (!SubobjType->isIntegerType()) {
4393       // We don't support compound assignment on integer-cast-to-pointer
4394       // values.
4395       Info.FFDiag(E);
4396       return false;
4397     }
4398 
4399     if (RHS.isInt()) {
4400       APSInt LHS =
4401           HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4402       if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4403         return false;
4404       Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4405       return true;
4406     } else if (RHS.isFloat()) {
4407       const FPOptions FPO = E->getFPFeaturesInEffect(
4408                                     Info.Ctx.getLangOpts());
4409       APFloat FValue(0.0);
4410       return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4411                                   PromotedLHSType, FValue) &&
4412              handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4413              HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4414                                   Value);
4415     }
4416 
4417     Info.FFDiag(E);
4418     return false;
4419   }
4420   bool found(APFloat &Value, QualType SubobjType) {
4421     return checkConst(SubobjType) &&
4422            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4423                                   Value) &&
4424            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4425            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4426   }
4427   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4428     if (!checkConst(SubobjType))
4429       return false;
4430 
4431     QualType PointeeType;
4432     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4433       PointeeType = PT->getPointeeType();
4434 
4435     if (PointeeType.isNull() || !RHS.isInt() ||
4436         (Opcode != BO_Add && Opcode != BO_Sub)) {
4437       Info.FFDiag(E);
4438       return false;
4439     }
4440 
4441     APSInt Offset = RHS.getInt();
4442     if (Opcode == BO_Sub)
4443       negateAsSigned(Offset);
4444 
4445     LValue LVal;
4446     LVal.setFrom(Info.Ctx, Subobj);
4447     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4448       return false;
4449     LVal.moveInto(Subobj);
4450     return true;
4451   }
4452 };
4453 } // end anonymous namespace
4454 
4455 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4456 
4457 /// Perform a compound assignment of LVal <op>= RVal.
4458 static bool handleCompoundAssignment(EvalInfo &Info,
4459                                      const CompoundAssignOperator *E,
4460                                      const LValue &LVal, QualType LValType,
4461                                      QualType PromotedLValType,
4462                                      BinaryOperatorKind Opcode,
4463                                      const APValue &RVal) {
4464   if (LVal.Designator.Invalid)
4465     return false;
4466 
4467   if (!Info.getLangOpts().CPlusPlus14) {
4468     Info.FFDiag(E);
4469     return false;
4470   }
4471 
4472   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4473   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4474                                              RVal };
4475   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4476 }
4477 
4478 namespace {
4479 struct IncDecSubobjectHandler {
4480   EvalInfo &Info;
4481   const UnaryOperator *E;
4482   AccessKinds AccessKind;
4483   APValue *Old;
4484 
4485   typedef bool result_type;
4486 
4487   bool checkConst(QualType QT) {
4488     // Assigning to a const object has undefined behavior.
4489     if (QT.isConstQualified()) {
4490       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4491       return false;
4492     }
4493     return true;
4494   }
4495 
4496   bool failed() { return false; }
4497   bool found(APValue &Subobj, QualType SubobjType) {
4498     // Stash the old value. Also clear Old, so we don't clobber it later
4499     // if we're post-incrementing a complex.
4500     if (Old) {
4501       *Old = Subobj;
4502       Old = nullptr;
4503     }
4504 
4505     switch (Subobj.getKind()) {
4506     case APValue::Int:
4507       return found(Subobj.getInt(), SubobjType);
4508     case APValue::Float:
4509       return found(Subobj.getFloat(), SubobjType);
4510     case APValue::ComplexInt:
4511       return found(Subobj.getComplexIntReal(),
4512                    SubobjType->castAs<ComplexType>()->getElementType()
4513                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4514     case APValue::ComplexFloat:
4515       return found(Subobj.getComplexFloatReal(),
4516                    SubobjType->castAs<ComplexType>()->getElementType()
4517                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4518     case APValue::LValue:
4519       return foundPointer(Subobj, SubobjType);
4520     default:
4521       // FIXME: can this happen?
4522       Info.FFDiag(E);
4523       return false;
4524     }
4525   }
4526   bool found(APSInt &Value, QualType SubobjType) {
4527     if (!checkConst(SubobjType))
4528       return false;
4529 
4530     if (!SubobjType->isIntegerType()) {
4531       // We don't support increment / decrement on integer-cast-to-pointer
4532       // values.
4533       Info.FFDiag(E);
4534       return false;
4535     }
4536 
4537     if (Old) *Old = APValue(Value);
4538 
4539     // bool arithmetic promotes to int, and the conversion back to bool
4540     // doesn't reduce mod 2^n, so special-case it.
4541     if (SubobjType->isBooleanType()) {
4542       if (AccessKind == AK_Increment)
4543         Value = 1;
4544       else
4545         Value = !Value;
4546       return true;
4547     }
4548 
4549     bool WasNegative = Value.isNegative();
4550     if (AccessKind == AK_Increment) {
4551       ++Value;
4552 
4553       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4554         APSInt ActualValue(Value, /*IsUnsigned*/true);
4555         return HandleOverflow(Info, E, ActualValue, SubobjType);
4556       }
4557     } else {
4558       --Value;
4559 
4560       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4561         unsigned BitWidth = Value.getBitWidth();
4562         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4563         ActualValue.setBit(BitWidth);
4564         return HandleOverflow(Info, E, ActualValue, SubobjType);
4565       }
4566     }
4567     return true;
4568   }
4569   bool found(APFloat &Value, QualType SubobjType) {
4570     if (!checkConst(SubobjType))
4571       return false;
4572 
4573     if (Old) *Old = APValue(Value);
4574 
4575     APFloat One(Value.getSemantics(), 1);
4576     if (AccessKind == AK_Increment)
4577       Value.add(One, APFloat::rmNearestTiesToEven);
4578     else
4579       Value.subtract(One, APFloat::rmNearestTiesToEven);
4580     return true;
4581   }
4582   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4583     if (!checkConst(SubobjType))
4584       return false;
4585 
4586     QualType PointeeType;
4587     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4588       PointeeType = PT->getPointeeType();
4589     else {
4590       Info.FFDiag(E);
4591       return false;
4592     }
4593 
4594     LValue LVal;
4595     LVal.setFrom(Info.Ctx, Subobj);
4596     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4597                                      AccessKind == AK_Increment ? 1 : -1))
4598       return false;
4599     LVal.moveInto(Subobj);
4600     return true;
4601   }
4602 };
4603 } // end anonymous namespace
4604 
4605 /// Perform an increment or decrement on LVal.
4606 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4607                          QualType LValType, bool IsIncrement, APValue *Old) {
4608   if (LVal.Designator.Invalid)
4609     return false;
4610 
4611   if (!Info.getLangOpts().CPlusPlus14) {
4612     Info.FFDiag(E);
4613     return false;
4614   }
4615 
4616   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4617   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4618   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4619   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4620 }
4621 
4622 /// Build an lvalue for the object argument of a member function call.
4623 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4624                                    LValue &This) {
4625   if (Object->getType()->isPointerType() && Object->isPRValue())
4626     return EvaluatePointer(Object, This, Info);
4627 
4628   if (Object->isGLValue())
4629     return EvaluateLValue(Object, This, Info);
4630 
4631   if (Object->getType()->isLiteralType(Info.Ctx))
4632     return EvaluateTemporary(Object, This, Info);
4633 
4634   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4635   return false;
4636 }
4637 
4638 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
4639 /// lvalue referring to the result.
4640 ///
4641 /// \param Info - Information about the ongoing evaluation.
4642 /// \param LV - An lvalue referring to the base of the member pointer.
4643 /// \param RHS - The member pointer expression.
4644 /// \param IncludeMember - Specifies whether the member itself is included in
4645 ///        the resulting LValue subobject designator. This is not possible when
4646 ///        creating a bound member function.
4647 /// \return The field or method declaration to which the member pointer refers,
4648 ///         or 0 if evaluation fails.
4649 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4650                                                   QualType LVType,
4651                                                   LValue &LV,
4652                                                   const Expr *RHS,
4653                                                   bool IncludeMember = true) {
4654   MemberPtr MemPtr;
4655   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4656     return nullptr;
4657 
4658   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4659   // member value, the behavior is undefined.
4660   if (!MemPtr.getDecl()) {
4661     // FIXME: Specific diagnostic.
4662     Info.FFDiag(RHS);
4663     return nullptr;
4664   }
4665 
4666   if (MemPtr.isDerivedMember()) {
4667     // This is a member of some derived class. Truncate LV appropriately.
4668     // The end of the derived-to-base path for the base object must match the
4669     // derived-to-base path for the member pointer.
4670     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4671         LV.Designator.Entries.size()) {
4672       Info.FFDiag(RHS);
4673       return nullptr;
4674     }
4675     unsigned PathLengthToMember =
4676         LV.Designator.Entries.size() - MemPtr.Path.size();
4677     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4678       const CXXRecordDecl *LVDecl = getAsBaseClass(
4679           LV.Designator.Entries[PathLengthToMember + I]);
4680       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4681       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4682         Info.FFDiag(RHS);
4683         return nullptr;
4684       }
4685     }
4686 
4687     // Truncate the lvalue to the appropriate derived class.
4688     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4689                             PathLengthToMember))
4690       return nullptr;
4691   } else if (!MemPtr.Path.empty()) {
4692     // Extend the LValue path with the member pointer's path.
4693     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4694                                   MemPtr.Path.size() + IncludeMember);
4695 
4696     // Walk down to the appropriate base class.
4697     if (const PointerType *PT = LVType->getAs<PointerType>())
4698       LVType = PT->getPointeeType();
4699     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4700     assert(RD && "member pointer access on non-class-type expression");
4701     // The first class in the path is that of the lvalue.
4702     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4703       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4704       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4705         return nullptr;
4706       RD = Base;
4707     }
4708     // Finally cast to the class containing the member.
4709     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4710                                 MemPtr.getContainingRecord()))
4711       return nullptr;
4712   }
4713 
4714   // Add the member. Note that we cannot build bound member functions here.
4715   if (IncludeMember) {
4716     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4717       if (!HandleLValueMember(Info, RHS, LV, FD))
4718         return nullptr;
4719     } else if (const IndirectFieldDecl *IFD =
4720                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4721       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4722         return nullptr;
4723     } else {
4724       llvm_unreachable("can't construct reference to bound member function");
4725     }
4726   }
4727 
4728   return MemPtr.getDecl();
4729 }
4730 
4731 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4732                                                   const BinaryOperator *BO,
4733                                                   LValue &LV,
4734                                                   bool IncludeMember = true) {
4735   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4736 
4737   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4738     if (Info.noteFailure()) {
4739       MemberPtr MemPtr;
4740       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4741     }
4742     return nullptr;
4743   }
4744 
4745   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4746                                    BO->getRHS(), IncludeMember);
4747 }
4748 
4749 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4750 /// the provided lvalue, which currently refers to the base object.
4751 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4752                                     LValue &Result) {
4753   SubobjectDesignator &D = Result.Designator;
4754   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4755     return false;
4756 
4757   QualType TargetQT = E->getType();
4758   if (const PointerType *PT = TargetQT->getAs<PointerType>())
4759     TargetQT = PT->getPointeeType();
4760 
4761   // Check this cast lands within the final derived-to-base subobject path.
4762   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4763     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4764       << D.MostDerivedType << TargetQT;
4765     return false;
4766   }
4767 
4768   // Check the type of the final cast. We don't need to check the path,
4769   // since a cast can only be formed if the path is unique.
4770   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4771   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4772   const CXXRecordDecl *FinalType;
4773   if (NewEntriesSize == D.MostDerivedPathLength)
4774     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4775   else
4776     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4777   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4778     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4779       << D.MostDerivedType << TargetQT;
4780     return false;
4781   }
4782 
4783   // Truncate the lvalue to the appropriate derived class.
4784   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4785 }
4786 
4787 /// Get the value to use for a default-initialized object of type T.
4788 /// Return false if it encounters something invalid.
4789 static bool getDefaultInitValue(QualType T, APValue &Result) {
4790   bool Success = true;
4791   if (auto *RD = T->getAsCXXRecordDecl()) {
4792     if (RD->isInvalidDecl()) {
4793       Result = APValue();
4794       return false;
4795     }
4796     if (RD->isUnion()) {
4797       Result = APValue((const FieldDecl *)nullptr);
4798       return true;
4799     }
4800     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4801                      std::distance(RD->field_begin(), RD->field_end()));
4802 
4803     unsigned Index = 0;
4804     for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4805                                                   End = RD->bases_end();
4806          I != End; ++I, ++Index)
4807       Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index));
4808 
4809     for (const auto *I : RD->fields()) {
4810       if (I->isUnnamedBitfield())
4811         continue;
4812       Success &= getDefaultInitValue(I->getType(),
4813                                      Result.getStructField(I->getFieldIndex()));
4814     }
4815     return Success;
4816   }
4817 
4818   if (auto *AT =
4819           dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4820     Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4821     if (Result.hasArrayFiller())
4822       Success &=
4823           getDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
4824 
4825     return Success;
4826   }
4827 
4828   Result = APValue::IndeterminateValue();
4829   return true;
4830 }
4831 
4832 namespace {
4833 enum EvalStmtResult {
4834   /// Evaluation failed.
4835   ESR_Failed,
4836   /// Hit a 'return' statement.
4837   ESR_Returned,
4838   /// Evaluation succeeded.
4839   ESR_Succeeded,
4840   /// Hit a 'continue' statement.
4841   ESR_Continue,
4842   /// Hit a 'break' statement.
4843   ESR_Break,
4844   /// Still scanning for 'case' or 'default' statement.
4845   ESR_CaseNotFound
4846 };
4847 }
4848 
4849 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4850   // We don't need to evaluate the initializer for a static local.
4851   if (!VD->hasLocalStorage())
4852     return true;
4853 
4854   LValue Result;
4855   APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
4856                                                    ScopeKind::Block, Result);
4857 
4858   const Expr *InitE = VD->getInit();
4859   if (!InitE) {
4860     if (VD->getType()->isDependentType())
4861       return Info.noteSideEffect();
4862     return getDefaultInitValue(VD->getType(), Val);
4863   }
4864   if (InitE->isValueDependent())
4865     return false;
4866 
4867   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4868     // Wipe out any partially-computed value, to allow tracking that this
4869     // evaluation failed.
4870     Val = APValue();
4871     return false;
4872   }
4873 
4874   return true;
4875 }
4876 
4877 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4878   bool OK = true;
4879 
4880   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4881     OK &= EvaluateVarDecl(Info, VD);
4882 
4883   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4884     for (auto *BD : DD->bindings())
4885       if (auto *VD = BD->getHoldingVar())
4886         OK &= EvaluateDecl(Info, VD);
4887 
4888   return OK;
4889 }
4890 
4891 static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
4892   assert(E->isValueDependent());
4893   if (Info.noteSideEffect())
4894     return true;
4895   assert(E->containsErrors() && "valid value-dependent expression should never "
4896                                 "reach invalid code path.");
4897   return false;
4898 }
4899 
4900 /// Evaluate a condition (either a variable declaration or an expression).
4901 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4902                          const Expr *Cond, bool &Result) {
4903   if (Cond->isValueDependent())
4904     return false;
4905   FullExpressionRAII Scope(Info);
4906   if (CondDecl && !EvaluateDecl(Info, CondDecl))
4907     return false;
4908   if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4909     return false;
4910   return Scope.destroy();
4911 }
4912 
4913 namespace {
4914 /// A location where the result (returned value) of evaluating a
4915 /// statement should be stored.
4916 struct StmtResult {
4917   /// The APValue that should be filled in with the returned value.
4918   APValue &Value;
4919   /// The location containing the result, if any (used to support RVO).
4920   const LValue *Slot;
4921 };
4922 
4923 struct TempVersionRAII {
4924   CallStackFrame &Frame;
4925 
4926   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4927     Frame.pushTempVersion();
4928   }
4929 
4930   ~TempVersionRAII() {
4931     Frame.popTempVersion();
4932   }
4933 };
4934 
4935 }
4936 
4937 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4938                                    const Stmt *S,
4939                                    const SwitchCase *SC = nullptr);
4940 
4941 /// Evaluate the body of a loop, and translate the result as appropriate.
4942 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4943                                        const Stmt *Body,
4944                                        const SwitchCase *Case = nullptr) {
4945   BlockScopeRAII Scope(Info);
4946 
4947   EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4948   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4949     ESR = ESR_Failed;
4950 
4951   switch (ESR) {
4952   case ESR_Break:
4953     return ESR_Succeeded;
4954   case ESR_Succeeded:
4955   case ESR_Continue:
4956     return ESR_Continue;
4957   case ESR_Failed:
4958   case ESR_Returned:
4959   case ESR_CaseNotFound:
4960     return ESR;
4961   }
4962   llvm_unreachable("Invalid EvalStmtResult!");
4963 }
4964 
4965 /// Evaluate a switch statement.
4966 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4967                                      const SwitchStmt *SS) {
4968   BlockScopeRAII Scope(Info);
4969 
4970   // Evaluate the switch condition.
4971   APSInt Value;
4972   {
4973     if (const Stmt *Init = SS->getInit()) {
4974       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4975       if (ESR != ESR_Succeeded) {
4976         if (ESR != ESR_Failed && !Scope.destroy())
4977           ESR = ESR_Failed;
4978         return ESR;
4979       }
4980     }
4981 
4982     FullExpressionRAII CondScope(Info);
4983     if (SS->getConditionVariable() &&
4984         !EvaluateDecl(Info, SS->getConditionVariable()))
4985       return ESR_Failed;
4986     if (SS->getCond()->isValueDependent()) {
4987       if (!EvaluateDependentExpr(SS->getCond(), Info))
4988         return ESR_Failed;
4989     } else {
4990       if (!EvaluateInteger(SS->getCond(), Value, Info))
4991         return ESR_Failed;
4992     }
4993     if (!CondScope.destroy())
4994       return ESR_Failed;
4995   }
4996 
4997   // Find the switch case corresponding to the value of the condition.
4998   // FIXME: Cache this lookup.
4999   const SwitchCase *Found = nullptr;
5000   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
5001        SC = SC->getNextSwitchCase()) {
5002     if (isa<DefaultStmt>(SC)) {
5003       Found = SC;
5004       continue;
5005     }
5006 
5007     const CaseStmt *CS = cast<CaseStmt>(SC);
5008     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
5009     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
5010                               : LHS;
5011     if (LHS <= Value && Value <= RHS) {
5012       Found = SC;
5013       break;
5014     }
5015   }
5016 
5017   if (!Found)
5018     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5019 
5020   // Search the switch body for the switch case and evaluate it from there.
5021   EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5022   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5023     return ESR_Failed;
5024 
5025   switch (ESR) {
5026   case ESR_Break:
5027     return ESR_Succeeded;
5028   case ESR_Succeeded:
5029   case ESR_Continue:
5030   case ESR_Failed:
5031   case ESR_Returned:
5032     return ESR;
5033   case ESR_CaseNotFound:
5034     // This can only happen if the switch case is nested within a statement
5035     // expression. We have no intention of supporting that.
5036     Info.FFDiag(Found->getBeginLoc(),
5037                 diag::note_constexpr_stmt_expr_unsupported);
5038     return ESR_Failed;
5039   }
5040   llvm_unreachable("Invalid EvalStmtResult!");
5041 }
5042 
5043 static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5044   // An expression E is a core constant expression unless the evaluation of E
5045   // would evaluate one of the following: [C++2b] - a control flow that passes
5046   // through a declaration of a variable with static or thread storage duration.
5047   if (VD->isLocalVarDecl() && VD->isStaticLocal()) {
5048     Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5049         << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5050     return false;
5051   }
5052   return true;
5053 }
5054 
5055 // Evaluate a statement.
5056 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5057                                    const Stmt *S, const SwitchCase *Case) {
5058   if (!Info.nextStep(S))
5059     return ESR_Failed;
5060 
5061   // If we're hunting down a 'case' or 'default' label, recurse through
5062   // substatements until we hit the label.
5063   if (Case) {
5064     switch (S->getStmtClass()) {
5065     case Stmt::CompoundStmtClass:
5066       // FIXME: Precompute which substatement of a compound statement we
5067       // would jump to, and go straight there rather than performing a
5068       // linear scan each time.
5069     case Stmt::LabelStmtClass:
5070     case Stmt::AttributedStmtClass:
5071     case Stmt::DoStmtClass:
5072       break;
5073 
5074     case Stmt::CaseStmtClass:
5075     case Stmt::DefaultStmtClass:
5076       if (Case == S)
5077         Case = nullptr;
5078       break;
5079 
5080     case Stmt::IfStmtClass: {
5081       // FIXME: Precompute which side of an 'if' we would jump to, and go
5082       // straight there rather than scanning both sides.
5083       const IfStmt *IS = cast<IfStmt>(S);
5084 
5085       // Wrap the evaluation in a block scope, in case it's a DeclStmt
5086       // preceded by our switch label.
5087       BlockScopeRAII Scope(Info);
5088 
5089       // Step into the init statement in case it brings an (uninitialized)
5090       // variable into scope.
5091       if (const Stmt *Init = IS->getInit()) {
5092         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5093         if (ESR != ESR_CaseNotFound) {
5094           assert(ESR != ESR_Succeeded);
5095           return ESR;
5096         }
5097       }
5098 
5099       // Condition variable must be initialized if it exists.
5100       // FIXME: We can skip evaluating the body if there's a condition
5101       // variable, as there can't be any case labels within it.
5102       // (The same is true for 'for' statements.)
5103 
5104       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5105       if (ESR == ESR_Failed)
5106         return ESR;
5107       if (ESR != ESR_CaseNotFound)
5108         return Scope.destroy() ? ESR : ESR_Failed;
5109       if (!IS->getElse())
5110         return ESR_CaseNotFound;
5111 
5112       ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5113       if (ESR == ESR_Failed)
5114         return ESR;
5115       if (ESR != ESR_CaseNotFound)
5116         return Scope.destroy() ? ESR : ESR_Failed;
5117       return ESR_CaseNotFound;
5118     }
5119 
5120     case Stmt::WhileStmtClass: {
5121       EvalStmtResult ESR =
5122           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5123       if (ESR != ESR_Continue)
5124         return ESR;
5125       break;
5126     }
5127 
5128     case Stmt::ForStmtClass: {
5129       const ForStmt *FS = cast<ForStmt>(S);
5130       BlockScopeRAII Scope(Info);
5131 
5132       // Step into the init statement in case it brings an (uninitialized)
5133       // variable into scope.
5134       if (const Stmt *Init = FS->getInit()) {
5135         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5136         if (ESR != ESR_CaseNotFound) {
5137           assert(ESR != ESR_Succeeded);
5138           return ESR;
5139         }
5140       }
5141 
5142       EvalStmtResult ESR =
5143           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5144       if (ESR != ESR_Continue)
5145         return ESR;
5146       if (const auto *Inc = FS->getInc()) {
5147         if (Inc->isValueDependent()) {
5148           if (!EvaluateDependentExpr(Inc, Info))
5149             return ESR_Failed;
5150         } else {
5151           FullExpressionRAII IncScope(Info);
5152           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5153             return ESR_Failed;
5154         }
5155       }
5156       break;
5157     }
5158 
5159     case Stmt::DeclStmtClass: {
5160       // Start the lifetime of any uninitialized variables we encounter. They
5161       // might be used by the selected branch of the switch.
5162       const DeclStmt *DS = cast<DeclStmt>(S);
5163       for (const auto *D : DS->decls()) {
5164         if (const auto *VD = dyn_cast<VarDecl>(D)) {
5165           if (!CheckLocalVariableDeclaration(Info, VD))
5166             return ESR_Failed;
5167           if (VD->hasLocalStorage() && !VD->getInit())
5168             if (!EvaluateVarDecl(Info, VD))
5169               return ESR_Failed;
5170           // FIXME: If the variable has initialization that can't be jumped
5171           // over, bail out of any immediately-surrounding compound-statement
5172           // too. There can't be any case labels here.
5173         }
5174       }
5175       return ESR_CaseNotFound;
5176     }
5177 
5178     default:
5179       return ESR_CaseNotFound;
5180     }
5181   }
5182 
5183   switch (S->getStmtClass()) {
5184   default:
5185     if (const Expr *E = dyn_cast<Expr>(S)) {
5186       if (E->isValueDependent()) {
5187         if (!EvaluateDependentExpr(E, Info))
5188           return ESR_Failed;
5189       } else {
5190         // Don't bother evaluating beyond an expression-statement which couldn't
5191         // be evaluated.
5192         // FIXME: Do we need the FullExpressionRAII object here?
5193         // VisitExprWithCleanups should create one when necessary.
5194         FullExpressionRAII Scope(Info);
5195         if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5196           return ESR_Failed;
5197       }
5198       return ESR_Succeeded;
5199     }
5200 
5201     Info.FFDiag(S->getBeginLoc());
5202     return ESR_Failed;
5203 
5204   case Stmt::NullStmtClass:
5205     return ESR_Succeeded;
5206 
5207   case Stmt::DeclStmtClass: {
5208     const DeclStmt *DS = cast<DeclStmt>(S);
5209     for (const auto *D : DS->decls()) {
5210       const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
5211       if (VD && !CheckLocalVariableDeclaration(Info, VD))
5212         return ESR_Failed;
5213       // Each declaration initialization is its own full-expression.
5214       FullExpressionRAII Scope(Info);
5215       if (!EvaluateDecl(Info, D) && !Info.noteFailure())
5216         return ESR_Failed;
5217       if (!Scope.destroy())
5218         return ESR_Failed;
5219     }
5220     return ESR_Succeeded;
5221   }
5222 
5223   case Stmt::ReturnStmtClass: {
5224     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5225     FullExpressionRAII Scope(Info);
5226     if (RetExpr && RetExpr->isValueDependent()) {
5227       EvaluateDependentExpr(RetExpr, Info);
5228       // We know we returned, but we don't know what the value is.
5229       return ESR_Failed;
5230     }
5231     if (RetExpr &&
5232         !(Result.Slot
5233               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5234               : Evaluate(Result.Value, Info, RetExpr)))
5235       return ESR_Failed;
5236     return Scope.destroy() ? ESR_Returned : ESR_Failed;
5237   }
5238 
5239   case Stmt::CompoundStmtClass: {
5240     BlockScopeRAII Scope(Info);
5241 
5242     const CompoundStmt *CS = cast<CompoundStmt>(S);
5243     for (const auto *BI : CS->body()) {
5244       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5245       if (ESR == ESR_Succeeded)
5246         Case = nullptr;
5247       else if (ESR != ESR_CaseNotFound) {
5248         if (ESR != ESR_Failed && !Scope.destroy())
5249           return ESR_Failed;
5250         return ESR;
5251       }
5252     }
5253     if (Case)
5254       return ESR_CaseNotFound;
5255     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5256   }
5257 
5258   case Stmt::IfStmtClass: {
5259     const IfStmt *IS = cast<IfStmt>(S);
5260 
5261     // Evaluate the condition, as either a var decl or as an expression.
5262     BlockScopeRAII Scope(Info);
5263     if (const Stmt *Init = IS->getInit()) {
5264       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5265       if (ESR != ESR_Succeeded) {
5266         if (ESR != ESR_Failed && !Scope.destroy())
5267           return ESR_Failed;
5268         return ESR;
5269       }
5270     }
5271     bool Cond;
5272     if (IS->isConsteval()) {
5273       Cond = IS->isNonNegatedConsteval();
5274       // If we are not in a constant context, if consteval should not evaluate
5275       // to true.
5276       if (!Info.InConstantContext)
5277         Cond = !Cond;
5278     } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
5279                              Cond))
5280       return ESR_Failed;
5281 
5282     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5283       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5284       if (ESR != ESR_Succeeded) {
5285         if (ESR != ESR_Failed && !Scope.destroy())
5286           return ESR_Failed;
5287         return ESR;
5288       }
5289     }
5290     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5291   }
5292 
5293   case Stmt::WhileStmtClass: {
5294     const WhileStmt *WS = cast<WhileStmt>(S);
5295     while (true) {
5296       BlockScopeRAII Scope(Info);
5297       bool Continue;
5298       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5299                         Continue))
5300         return ESR_Failed;
5301       if (!Continue)
5302         break;
5303 
5304       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5305       if (ESR != ESR_Continue) {
5306         if (ESR != ESR_Failed && !Scope.destroy())
5307           return ESR_Failed;
5308         return ESR;
5309       }
5310       if (!Scope.destroy())
5311         return ESR_Failed;
5312     }
5313     return ESR_Succeeded;
5314   }
5315 
5316   case Stmt::DoStmtClass: {
5317     const DoStmt *DS = cast<DoStmt>(S);
5318     bool Continue;
5319     do {
5320       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5321       if (ESR != ESR_Continue)
5322         return ESR;
5323       Case = nullptr;
5324 
5325       if (DS->getCond()->isValueDependent()) {
5326         EvaluateDependentExpr(DS->getCond(), Info);
5327         // Bailout as we don't know whether to keep going or terminate the loop.
5328         return ESR_Failed;
5329       }
5330       FullExpressionRAII CondScope(Info);
5331       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5332           !CondScope.destroy())
5333         return ESR_Failed;
5334     } while (Continue);
5335     return ESR_Succeeded;
5336   }
5337 
5338   case Stmt::ForStmtClass: {
5339     const ForStmt *FS = cast<ForStmt>(S);
5340     BlockScopeRAII ForScope(Info);
5341     if (FS->getInit()) {
5342       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5343       if (ESR != ESR_Succeeded) {
5344         if (ESR != ESR_Failed && !ForScope.destroy())
5345           return ESR_Failed;
5346         return ESR;
5347       }
5348     }
5349     while (true) {
5350       BlockScopeRAII IterScope(Info);
5351       bool Continue = true;
5352       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5353                                          FS->getCond(), Continue))
5354         return ESR_Failed;
5355       if (!Continue)
5356         break;
5357 
5358       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5359       if (ESR != ESR_Continue) {
5360         if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5361           return ESR_Failed;
5362         return ESR;
5363       }
5364 
5365       if (const auto *Inc = FS->getInc()) {
5366         if (Inc->isValueDependent()) {
5367           if (!EvaluateDependentExpr(Inc, Info))
5368             return ESR_Failed;
5369         } else {
5370           FullExpressionRAII IncScope(Info);
5371           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5372             return ESR_Failed;
5373         }
5374       }
5375 
5376       if (!IterScope.destroy())
5377         return ESR_Failed;
5378     }
5379     return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5380   }
5381 
5382   case Stmt::CXXForRangeStmtClass: {
5383     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5384     BlockScopeRAII Scope(Info);
5385 
5386     // Evaluate the init-statement if present.
5387     if (FS->getInit()) {
5388       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5389       if (ESR != ESR_Succeeded) {
5390         if (ESR != ESR_Failed && !Scope.destroy())
5391           return ESR_Failed;
5392         return ESR;
5393       }
5394     }
5395 
5396     // Initialize the __range variable.
5397     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5398     if (ESR != ESR_Succeeded) {
5399       if (ESR != ESR_Failed && !Scope.destroy())
5400         return ESR_Failed;
5401       return ESR;
5402     }
5403 
5404     // In error-recovery cases it's possible to get here even if we failed to
5405     // synthesize the __begin and __end variables.
5406     if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
5407       return ESR_Failed;
5408 
5409     // Create the __begin and __end iterators.
5410     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5411     if (ESR != ESR_Succeeded) {
5412       if (ESR != ESR_Failed && !Scope.destroy())
5413         return ESR_Failed;
5414       return ESR;
5415     }
5416     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5417     if (ESR != ESR_Succeeded) {
5418       if (ESR != ESR_Failed && !Scope.destroy())
5419         return ESR_Failed;
5420       return ESR;
5421     }
5422 
5423     while (true) {
5424       // Condition: __begin != __end.
5425       {
5426         if (FS->getCond()->isValueDependent()) {
5427           EvaluateDependentExpr(FS->getCond(), Info);
5428           // We don't know whether to keep going or terminate the loop.
5429           return ESR_Failed;
5430         }
5431         bool Continue = true;
5432         FullExpressionRAII CondExpr(Info);
5433         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5434           return ESR_Failed;
5435         if (!Continue)
5436           break;
5437       }
5438 
5439       // User's variable declaration, initialized by *__begin.
5440       BlockScopeRAII InnerScope(Info);
5441       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5442       if (ESR != ESR_Succeeded) {
5443         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5444           return ESR_Failed;
5445         return ESR;
5446       }
5447 
5448       // Loop body.
5449       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5450       if (ESR != ESR_Continue) {
5451         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5452           return ESR_Failed;
5453         return ESR;
5454       }
5455       if (FS->getInc()->isValueDependent()) {
5456         if (!EvaluateDependentExpr(FS->getInc(), Info))
5457           return ESR_Failed;
5458       } else {
5459         // Increment: ++__begin
5460         if (!EvaluateIgnoredValue(Info, FS->getInc()))
5461           return ESR_Failed;
5462       }
5463 
5464       if (!InnerScope.destroy())
5465         return ESR_Failed;
5466     }
5467 
5468     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5469   }
5470 
5471   case Stmt::SwitchStmtClass:
5472     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5473 
5474   case Stmt::ContinueStmtClass:
5475     return ESR_Continue;
5476 
5477   case Stmt::BreakStmtClass:
5478     return ESR_Break;
5479 
5480   case Stmt::LabelStmtClass:
5481     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5482 
5483   case Stmt::AttributedStmtClass:
5484     // As a general principle, C++11 attributes can be ignored without
5485     // any semantic impact.
5486     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
5487                         Case);
5488 
5489   case Stmt::CaseStmtClass:
5490   case Stmt::DefaultStmtClass:
5491     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5492   case Stmt::CXXTryStmtClass:
5493     // Evaluate try blocks by evaluating all sub statements.
5494     return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5495   }
5496 }
5497 
5498 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5499 /// default constructor. If so, we'll fold it whether or not it's marked as
5500 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
5501 /// so we need special handling.
5502 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5503                                            const CXXConstructorDecl *CD,
5504                                            bool IsValueInitialization) {
5505   if (!CD->isTrivial() || !CD->isDefaultConstructor())
5506     return false;
5507 
5508   // Value-initialization does not call a trivial default constructor, so such a
5509   // call is a core constant expression whether or not the constructor is
5510   // constexpr.
5511   if (!CD->isConstexpr() && !IsValueInitialization) {
5512     if (Info.getLangOpts().CPlusPlus11) {
5513       // FIXME: If DiagDecl is an implicitly-declared special member function,
5514       // we should be much more explicit about why it's not constexpr.
5515       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5516         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5517       Info.Note(CD->getLocation(), diag::note_declared_at);
5518     } else {
5519       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5520     }
5521   }
5522   return true;
5523 }
5524 
5525 /// CheckConstexprFunction - Check that a function can be called in a constant
5526 /// expression.
5527 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5528                                    const FunctionDecl *Declaration,
5529                                    const FunctionDecl *Definition,
5530                                    const Stmt *Body) {
5531   // Potential constant expressions can contain calls to declared, but not yet
5532   // defined, constexpr functions.
5533   if (Info.checkingPotentialConstantExpression() && !Definition &&
5534       Declaration->isConstexpr())
5535     return false;
5536 
5537   // Bail out if the function declaration itself is invalid.  We will
5538   // have produced a relevant diagnostic while parsing it, so just
5539   // note the problematic sub-expression.
5540   if (Declaration->isInvalidDecl()) {
5541     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5542     return false;
5543   }
5544 
5545   // DR1872: An instantiated virtual constexpr function can't be called in a
5546   // constant expression (prior to C++20). We can still constant-fold such a
5547   // call.
5548   if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5549       cast<CXXMethodDecl>(Declaration)->isVirtual())
5550     Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5551 
5552   if (Definition && Definition->isInvalidDecl()) {
5553     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5554     return false;
5555   }
5556 
5557   // Can we evaluate this function call?
5558   if (Definition && Definition->isConstexpr() && Body)
5559     return true;
5560 
5561   if (Info.getLangOpts().CPlusPlus11) {
5562     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5563 
5564     // If this function is not constexpr because it is an inherited
5565     // non-constexpr constructor, diagnose that directly.
5566     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5567     if (CD && CD->isInheritingConstructor()) {
5568       auto *Inherited = CD->getInheritedConstructor().getConstructor();
5569       if (!Inherited->isConstexpr())
5570         DiagDecl = CD = Inherited;
5571     }
5572 
5573     // FIXME: If DiagDecl is an implicitly-declared special member function
5574     // or an inheriting constructor, we should be much more explicit about why
5575     // it's not constexpr.
5576     if (CD && CD->isInheritingConstructor())
5577       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5578         << CD->getInheritedConstructor().getConstructor()->getParent();
5579     else
5580       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5581         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5582     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5583   } else {
5584     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5585   }
5586   return false;
5587 }
5588 
5589 namespace {
5590 struct CheckDynamicTypeHandler {
5591   AccessKinds AccessKind;
5592   typedef bool result_type;
5593   bool failed() { return false; }
5594   bool found(APValue &Subobj, QualType SubobjType) { return true; }
5595   bool found(APSInt &Value, QualType SubobjType) { return true; }
5596   bool found(APFloat &Value, QualType SubobjType) { return true; }
5597 };
5598 } // end anonymous namespace
5599 
5600 /// Check that we can access the notional vptr of an object / determine its
5601 /// dynamic type.
5602 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5603                              AccessKinds AK, bool Polymorphic) {
5604   if (This.Designator.Invalid)
5605     return false;
5606 
5607   CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5608 
5609   if (!Obj)
5610     return false;
5611 
5612   if (!Obj.Value) {
5613     // The object is not usable in constant expressions, so we can't inspect
5614     // its value to see if it's in-lifetime or what the active union members
5615     // are. We can still check for a one-past-the-end lvalue.
5616     if (This.Designator.isOnePastTheEnd() ||
5617         This.Designator.isMostDerivedAnUnsizedArray()) {
5618       Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5619                          ? diag::note_constexpr_access_past_end
5620                          : diag::note_constexpr_access_unsized_array)
5621           << AK;
5622       return false;
5623     } else if (Polymorphic) {
5624       // Conservatively refuse to perform a polymorphic operation if we would
5625       // not be able to read a notional 'vptr' value.
5626       APValue Val;
5627       This.moveInto(Val);
5628       QualType StarThisType =
5629           Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5630       Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5631           << AK << Val.getAsString(Info.Ctx, StarThisType);
5632       return false;
5633     }
5634     return true;
5635   }
5636 
5637   CheckDynamicTypeHandler Handler{AK};
5638   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5639 }
5640 
5641 /// Check that the pointee of the 'this' pointer in a member function call is
5642 /// either within its lifetime or in its period of construction or destruction.
5643 static bool
5644 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5645                                      const LValue &This,
5646                                      const CXXMethodDecl *NamedMember) {
5647   return checkDynamicType(
5648       Info, E, This,
5649       isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5650 }
5651 
5652 struct DynamicType {
5653   /// The dynamic class type of the object.
5654   const CXXRecordDecl *Type;
5655   /// The corresponding path length in the lvalue.
5656   unsigned PathLength;
5657 };
5658 
5659 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5660                                              unsigned PathLength) {
5661   assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5662       Designator.Entries.size() && "invalid path length");
5663   return (PathLength == Designator.MostDerivedPathLength)
5664              ? Designator.MostDerivedType->getAsCXXRecordDecl()
5665              : getAsBaseClass(Designator.Entries[PathLength - 1]);
5666 }
5667 
5668 /// Determine the dynamic type of an object.
5669 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
5670                                                 LValue &This, AccessKinds AK) {
5671   // If we don't have an lvalue denoting an object of class type, there is no
5672   // meaningful dynamic type. (We consider objects of non-class type to have no
5673   // dynamic type.)
5674   if (!checkDynamicType(Info, E, This, AK, true))
5675     return None;
5676 
5677   // Refuse to compute a dynamic type in the presence of virtual bases. This
5678   // shouldn't happen other than in constant-folding situations, since literal
5679   // types can't have virtual bases.
5680   //
5681   // Note that consumers of DynamicType assume that the type has no virtual
5682   // bases, and will need modifications if this restriction is relaxed.
5683   const CXXRecordDecl *Class =
5684       This.Designator.MostDerivedType->getAsCXXRecordDecl();
5685   if (!Class || Class->getNumVBases()) {
5686     Info.FFDiag(E);
5687     return None;
5688   }
5689 
5690   // FIXME: For very deep class hierarchies, it might be beneficial to use a
5691   // binary search here instead. But the overwhelmingly common case is that
5692   // we're not in the middle of a constructor, so it probably doesn't matter
5693   // in practice.
5694   ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5695   for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5696        PathLength <= Path.size(); ++PathLength) {
5697     switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5698                                       Path.slice(0, PathLength))) {
5699     case ConstructionPhase::Bases:
5700     case ConstructionPhase::DestroyingBases:
5701       // We're constructing or destroying a base class. This is not the dynamic
5702       // type.
5703       break;
5704 
5705     case ConstructionPhase::None:
5706     case ConstructionPhase::AfterBases:
5707     case ConstructionPhase::AfterFields:
5708     case ConstructionPhase::Destroying:
5709       // We've finished constructing the base classes and not yet started
5710       // destroying them again, so this is the dynamic type.
5711       return DynamicType{getBaseClassType(This.Designator, PathLength),
5712                          PathLength};
5713     }
5714   }
5715 
5716   // CWG issue 1517: we're constructing a base class of the object described by
5717   // 'This', so that object has not yet begun its period of construction and
5718   // any polymorphic operation on it results in undefined behavior.
5719   Info.FFDiag(E);
5720   return None;
5721 }
5722 
5723 /// Perform virtual dispatch.
5724 static const CXXMethodDecl *HandleVirtualDispatch(
5725     EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5726     llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5727   Optional<DynamicType> DynType = ComputeDynamicType(
5728       Info, E, This,
5729       isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5730   if (!DynType)
5731     return nullptr;
5732 
5733   // Find the final overrider. It must be declared in one of the classes on the
5734   // path from the dynamic type to the static type.
5735   // FIXME: If we ever allow literal types to have virtual base classes, that
5736   // won't be true.
5737   const CXXMethodDecl *Callee = Found;
5738   unsigned PathLength = DynType->PathLength;
5739   for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5740     const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5741     const CXXMethodDecl *Overrider =
5742         Found->getCorrespondingMethodDeclaredInClass(Class, false);
5743     if (Overrider) {
5744       Callee = Overrider;
5745       break;
5746     }
5747   }
5748 
5749   // C++2a [class.abstract]p6:
5750   //   the effect of making a virtual call to a pure virtual function [...] is
5751   //   undefined
5752   if (Callee->isPure()) {
5753     Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5754     Info.Note(Callee->getLocation(), diag::note_declared_at);
5755     return nullptr;
5756   }
5757 
5758   // If necessary, walk the rest of the path to determine the sequence of
5759   // covariant adjustment steps to apply.
5760   if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5761                                        Found->getReturnType())) {
5762     CovariantAdjustmentPath.push_back(Callee->getReturnType());
5763     for (unsigned CovariantPathLength = PathLength + 1;
5764          CovariantPathLength != This.Designator.Entries.size();
5765          ++CovariantPathLength) {
5766       const CXXRecordDecl *NextClass =
5767           getBaseClassType(This.Designator, CovariantPathLength);
5768       const CXXMethodDecl *Next =
5769           Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5770       if (Next && !Info.Ctx.hasSameUnqualifiedType(
5771                       Next->getReturnType(), CovariantAdjustmentPath.back()))
5772         CovariantAdjustmentPath.push_back(Next->getReturnType());
5773     }
5774     if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5775                                          CovariantAdjustmentPath.back()))
5776       CovariantAdjustmentPath.push_back(Found->getReturnType());
5777   }
5778 
5779   // Perform 'this' adjustment.
5780   if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5781     return nullptr;
5782 
5783   return Callee;
5784 }
5785 
5786 /// Perform the adjustment from a value returned by a virtual function to
5787 /// a value of the statically expected type, which may be a pointer or
5788 /// reference to a base class of the returned type.
5789 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5790                                             APValue &Result,
5791                                             ArrayRef<QualType> Path) {
5792   assert(Result.isLValue() &&
5793          "unexpected kind of APValue for covariant return");
5794   if (Result.isNullPointer())
5795     return true;
5796 
5797   LValue LVal;
5798   LVal.setFrom(Info.Ctx, Result);
5799 
5800   const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5801   for (unsigned I = 1; I != Path.size(); ++I) {
5802     const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5803     assert(OldClass && NewClass && "unexpected kind of covariant return");
5804     if (OldClass != NewClass &&
5805         !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5806       return false;
5807     OldClass = NewClass;
5808   }
5809 
5810   LVal.moveInto(Result);
5811   return true;
5812 }
5813 
5814 /// Determine whether \p Base, which is known to be a direct base class of
5815 /// \p Derived, is a public base class.
5816 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5817                               const CXXRecordDecl *Base) {
5818   for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5819     auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5820     if (BaseClass && declaresSameEntity(BaseClass, Base))
5821       return BaseSpec.getAccessSpecifier() == AS_public;
5822   }
5823   llvm_unreachable("Base is not a direct base of Derived");
5824 }
5825 
5826 /// Apply the given dynamic cast operation on the provided lvalue.
5827 ///
5828 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
5829 /// to find a suitable target subobject.
5830 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5831                               LValue &Ptr) {
5832   // We can't do anything with a non-symbolic pointer value.
5833   SubobjectDesignator &D = Ptr.Designator;
5834   if (D.Invalid)
5835     return false;
5836 
5837   // C++ [expr.dynamic.cast]p6:
5838   //   If v is a null pointer value, the result is a null pointer value.
5839   if (Ptr.isNullPointer() && !E->isGLValue())
5840     return true;
5841 
5842   // For all the other cases, we need the pointer to point to an object within
5843   // its lifetime / period of construction / destruction, and we need to know
5844   // its dynamic type.
5845   Optional<DynamicType> DynType =
5846       ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5847   if (!DynType)
5848     return false;
5849 
5850   // C++ [expr.dynamic.cast]p7:
5851   //   If T is "pointer to cv void", then the result is a pointer to the most
5852   //   derived object
5853   if (E->getType()->isVoidPointerType())
5854     return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5855 
5856   const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5857   assert(C && "dynamic_cast target is not void pointer nor class");
5858   CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5859 
5860   auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5861     // C++ [expr.dynamic.cast]p9:
5862     if (!E->isGLValue()) {
5863       //   The value of a failed cast to pointer type is the null pointer value
5864       //   of the required result type.
5865       Ptr.setNull(Info.Ctx, E->getType());
5866       return true;
5867     }
5868 
5869     //   A failed cast to reference type throws [...] std::bad_cast.
5870     unsigned DiagKind;
5871     if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5872                    DynType->Type->isDerivedFrom(C)))
5873       DiagKind = 0;
5874     else if (!Paths || Paths->begin() == Paths->end())
5875       DiagKind = 1;
5876     else if (Paths->isAmbiguous(CQT))
5877       DiagKind = 2;
5878     else {
5879       assert(Paths->front().Access != AS_public && "why did the cast fail?");
5880       DiagKind = 3;
5881     }
5882     Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5883         << DiagKind << Ptr.Designator.getType(Info.Ctx)
5884         << Info.Ctx.getRecordType(DynType->Type)
5885         << E->getType().getUnqualifiedType();
5886     return false;
5887   };
5888 
5889   // Runtime check, phase 1:
5890   //   Walk from the base subobject towards the derived object looking for the
5891   //   target type.
5892   for (int PathLength = Ptr.Designator.Entries.size();
5893        PathLength >= (int)DynType->PathLength; --PathLength) {
5894     const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5895     if (declaresSameEntity(Class, C))
5896       return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5897     // We can only walk across public inheritance edges.
5898     if (PathLength > (int)DynType->PathLength &&
5899         !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5900                            Class))
5901       return RuntimeCheckFailed(nullptr);
5902   }
5903 
5904   // Runtime check, phase 2:
5905   //   Search the dynamic type for an unambiguous public base of type C.
5906   CXXBasePaths Paths(/*FindAmbiguities=*/true,
5907                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
5908   if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5909       Paths.front().Access == AS_public) {
5910     // Downcast to the dynamic type...
5911     if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5912       return false;
5913     // ... then upcast to the chosen base class subobject.
5914     for (CXXBasePathElement &Elem : Paths.front())
5915       if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5916         return false;
5917     return true;
5918   }
5919 
5920   // Otherwise, the runtime check fails.
5921   return RuntimeCheckFailed(&Paths);
5922 }
5923 
5924 namespace {
5925 struct StartLifetimeOfUnionMemberHandler {
5926   EvalInfo &Info;
5927   const Expr *LHSExpr;
5928   const FieldDecl *Field;
5929   bool DuringInit;
5930   bool Failed = false;
5931   static const AccessKinds AccessKind = AK_Assign;
5932 
5933   typedef bool result_type;
5934   bool failed() { return Failed; }
5935   bool found(APValue &Subobj, QualType SubobjType) {
5936     // We are supposed to perform no initialization but begin the lifetime of
5937     // the object. We interpret that as meaning to do what default
5938     // initialization of the object would do if all constructors involved were
5939     // trivial:
5940     //  * All base, non-variant member, and array element subobjects' lifetimes
5941     //    begin
5942     //  * No variant members' lifetimes begin
5943     //  * All scalar subobjects whose lifetimes begin have indeterminate values
5944     assert(SubobjType->isUnionType());
5945     if (declaresSameEntity(Subobj.getUnionField(), Field)) {
5946       // This union member is already active. If it's also in-lifetime, there's
5947       // nothing to do.
5948       if (Subobj.getUnionValue().hasValue())
5949         return true;
5950     } else if (DuringInit) {
5951       // We're currently in the process of initializing a different union
5952       // member.  If we carried on, that initialization would attempt to
5953       // store to an inactive union member, resulting in undefined behavior.
5954       Info.FFDiag(LHSExpr,
5955                   diag::note_constexpr_union_member_change_during_init);
5956       return false;
5957     }
5958     APValue Result;
5959     Failed = !getDefaultInitValue(Field->getType(), Result);
5960     Subobj.setUnion(Field, Result);
5961     return true;
5962   }
5963   bool found(APSInt &Value, QualType SubobjType) {
5964     llvm_unreachable("wrong value kind for union object");
5965   }
5966   bool found(APFloat &Value, QualType SubobjType) {
5967     llvm_unreachable("wrong value kind for union object");
5968   }
5969 };
5970 } // end anonymous namespace
5971 
5972 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5973 
5974 /// Handle a builtin simple-assignment or a call to a trivial assignment
5975 /// operator whose left-hand side might involve a union member access. If it
5976 /// does, implicitly start the lifetime of any accessed union elements per
5977 /// C++20 [class.union]5.
5978 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5979                                           const LValue &LHS) {
5980   if (LHS.InvalidBase || LHS.Designator.Invalid)
5981     return false;
5982 
5983   llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5984   // C++ [class.union]p5:
5985   //   define the set S(E) of subexpressions of E as follows:
5986   unsigned PathLength = LHS.Designator.Entries.size();
5987   for (const Expr *E = LHSExpr; E != nullptr;) {
5988     //   -- If E is of the form A.B, S(E) contains the elements of S(A)...
5989     if (auto *ME = dyn_cast<MemberExpr>(E)) {
5990       auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5991       // Note that we can't implicitly start the lifetime of a reference,
5992       // so we don't need to proceed any further if we reach one.
5993       if (!FD || FD->getType()->isReferenceType())
5994         break;
5995 
5996       //    ... and also contains A.B if B names a union member ...
5997       if (FD->getParent()->isUnion()) {
5998         //    ... of a non-class, non-array type, or of a class type with a
5999         //    trivial default constructor that is not deleted, or an array of
6000         //    such types.
6001         auto *RD =
6002             FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6003         if (!RD || RD->hasTrivialDefaultConstructor())
6004           UnionPathLengths.push_back({PathLength - 1, FD});
6005       }
6006 
6007       E = ME->getBase();
6008       --PathLength;
6009       assert(declaresSameEntity(FD,
6010                                 LHS.Designator.Entries[PathLength]
6011                                     .getAsBaseOrMember().getPointer()));
6012 
6013       //   -- If E is of the form A[B] and is interpreted as a built-in array
6014       //      subscripting operator, S(E) is [S(the array operand, if any)].
6015     } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6016       // Step over an ArrayToPointerDecay implicit cast.
6017       auto *Base = ASE->getBase()->IgnoreImplicit();
6018       if (!Base->getType()->isArrayType())
6019         break;
6020 
6021       E = Base;
6022       --PathLength;
6023 
6024     } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6025       // Step over a derived-to-base conversion.
6026       E = ICE->getSubExpr();
6027       if (ICE->getCastKind() == CK_NoOp)
6028         continue;
6029       if (ICE->getCastKind() != CK_DerivedToBase &&
6030           ICE->getCastKind() != CK_UncheckedDerivedToBase)
6031         break;
6032       // Walk path backwards as we walk up from the base to the derived class.
6033       for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
6034         --PathLength;
6035         (void)Elt;
6036         assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
6037                                   LHS.Designator.Entries[PathLength]
6038                                       .getAsBaseOrMember().getPointer()));
6039       }
6040 
6041     //   -- Otherwise, S(E) is empty.
6042     } else {
6043       break;
6044     }
6045   }
6046 
6047   // Common case: no unions' lifetimes are started.
6048   if (UnionPathLengths.empty())
6049     return true;
6050 
6051   //   if modification of X [would access an inactive union member], an object
6052   //   of the type of X is implicitly created
6053   CompleteObject Obj =
6054       findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
6055   if (!Obj)
6056     return false;
6057   for (std::pair<unsigned, const FieldDecl *> LengthAndField :
6058            llvm::reverse(UnionPathLengths)) {
6059     // Form a designator for the union object.
6060     SubobjectDesignator D = LHS.Designator;
6061     D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
6062 
6063     bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
6064                       ConstructionPhase::AfterBases;
6065     StartLifetimeOfUnionMemberHandler StartLifetime{
6066         Info, LHSExpr, LengthAndField.second, DuringInit};
6067     if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
6068       return false;
6069   }
6070 
6071   return true;
6072 }
6073 
6074 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
6075                             CallRef Call, EvalInfo &Info,
6076                             bool NonNull = false) {
6077   LValue LV;
6078   // Create the parameter slot and register its destruction. For a vararg
6079   // argument, create a temporary.
6080   // FIXME: For calling conventions that destroy parameters in the callee,
6081   // should we consider performing destruction when the function returns
6082   // instead?
6083   APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6084                    : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6085                                                        ScopeKind::Call, LV);
6086   if (!EvaluateInPlace(V, Info, LV, Arg))
6087     return false;
6088 
6089   // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6090   // undefined behavior, so is non-constant.
6091   if (NonNull && V.isLValue() && V.isNullPointer()) {
6092     Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6093     return false;
6094   }
6095 
6096   return true;
6097 }
6098 
6099 /// Evaluate the arguments to a function call.
6100 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6101                          EvalInfo &Info, const FunctionDecl *Callee,
6102                          bool RightToLeft = false) {
6103   bool Success = true;
6104   llvm::SmallBitVector ForbiddenNullArgs;
6105   if (Callee->hasAttr<NonNullAttr>()) {
6106     ForbiddenNullArgs.resize(Args.size());
6107     for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6108       if (!Attr->args_size()) {
6109         ForbiddenNullArgs.set();
6110         break;
6111       } else
6112         for (auto Idx : Attr->args()) {
6113           unsigned ASTIdx = Idx.getASTIndex();
6114           if (ASTIdx >= Args.size())
6115             continue;
6116           ForbiddenNullArgs[ASTIdx] = true;
6117         }
6118     }
6119   }
6120   for (unsigned I = 0; I < Args.size(); I++) {
6121     unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6122     const ParmVarDecl *PVD =
6123         Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6124     bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6125     if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) {
6126       // If we're checking for a potential constant expression, evaluate all
6127       // initializers even if some of them fail.
6128       if (!Info.noteFailure())
6129         return false;
6130       Success = false;
6131     }
6132   }
6133   return Success;
6134 }
6135 
6136 /// Perform a trivial copy from Param, which is the parameter of a copy or move
6137 /// constructor or assignment operator.
6138 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6139                               const Expr *E, APValue &Result,
6140                               bool CopyObjectRepresentation) {
6141   // Find the reference argument.
6142   CallStackFrame *Frame = Info.CurrentCall;
6143   APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6144   if (!RefValue) {
6145     Info.FFDiag(E);
6146     return false;
6147   }
6148 
6149   // Copy out the contents of the RHS object.
6150   LValue RefLValue;
6151   RefLValue.setFrom(Info.Ctx, *RefValue);
6152   return handleLValueToRValueConversion(
6153       Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6154       CopyObjectRepresentation);
6155 }
6156 
6157 /// Evaluate a function call.
6158 static bool HandleFunctionCall(SourceLocation CallLoc,
6159                                const FunctionDecl *Callee, const LValue *This,
6160                                ArrayRef<const Expr *> Args, CallRef Call,
6161                                const Stmt *Body, EvalInfo &Info,
6162                                APValue &Result, const LValue *ResultSlot) {
6163   if (!Info.CheckCallLimit(CallLoc))
6164     return false;
6165 
6166   CallStackFrame Frame(Info, CallLoc, Callee, This, Call);
6167 
6168   // For a trivial copy or move assignment, perform an APValue copy. This is
6169   // essential for unions, where the operations performed by the assignment
6170   // operator cannot be represented as statements.
6171   //
6172   // Skip this for non-union classes with no fields; in that case, the defaulted
6173   // copy/move does not actually read the object.
6174   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6175   if (MD && MD->isDefaulted() &&
6176       (MD->getParent()->isUnion() ||
6177        (MD->isTrivial() &&
6178         isReadByLvalueToRvalueConversion(MD->getParent())))) {
6179     assert(This &&
6180            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
6181     APValue RHSValue;
6182     if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6183                            MD->getParent()->isUnion()))
6184       return false;
6185     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
6186                           RHSValue))
6187       return false;
6188     This->moveInto(Result);
6189     return true;
6190   } else if (MD && isLambdaCallOperator(MD)) {
6191     // We're in a lambda; determine the lambda capture field maps unless we're
6192     // just constexpr checking a lambda's call operator. constexpr checking is
6193     // done before the captures have been added to the closure object (unless
6194     // we're inferring constexpr-ness), so we don't have access to them in this
6195     // case. But since we don't need the captures to constexpr check, we can
6196     // just ignore them.
6197     if (!Info.checkingPotentialConstantExpression())
6198       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6199                                         Frame.LambdaThisCaptureField);
6200   }
6201 
6202   StmtResult Ret = {Result, ResultSlot};
6203   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6204   if (ESR == ESR_Succeeded) {
6205     if (Callee->getReturnType()->isVoidType())
6206       return true;
6207     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6208   }
6209   return ESR == ESR_Returned;
6210 }
6211 
6212 /// Evaluate a constructor call.
6213 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6214                                   CallRef Call,
6215                                   const CXXConstructorDecl *Definition,
6216                                   EvalInfo &Info, APValue &Result) {
6217   SourceLocation CallLoc = E->getExprLoc();
6218   if (!Info.CheckCallLimit(CallLoc))
6219     return false;
6220 
6221   const CXXRecordDecl *RD = Definition->getParent();
6222   if (RD->getNumVBases()) {
6223     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6224     return false;
6225   }
6226 
6227   EvalInfo::EvaluatingConstructorRAII EvalObj(
6228       Info,
6229       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6230       RD->getNumBases());
6231   CallStackFrame Frame(Info, CallLoc, Definition, &This, Call);
6232 
6233   // FIXME: Creating an APValue just to hold a nonexistent return value is
6234   // wasteful.
6235   APValue RetVal;
6236   StmtResult Ret = {RetVal, nullptr};
6237 
6238   // If it's a delegating constructor, delegate.
6239   if (Definition->isDelegatingConstructor()) {
6240     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
6241     if ((*I)->getInit()->isValueDependent()) {
6242       if (!EvaluateDependentExpr((*I)->getInit(), Info))
6243         return false;
6244     } else {
6245       FullExpressionRAII InitScope(Info);
6246       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6247           !InitScope.destroy())
6248         return false;
6249     }
6250     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6251   }
6252 
6253   // For a trivial copy or move constructor, perform an APValue copy. This is
6254   // essential for unions (or classes with anonymous union members), where the
6255   // operations performed by the constructor cannot be represented by
6256   // ctor-initializers.
6257   //
6258   // Skip this for empty non-union classes; we should not perform an
6259   // lvalue-to-rvalue conversion on them because their copy constructor does not
6260   // actually read them.
6261   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6262       (Definition->getParent()->isUnion() ||
6263        (Definition->isTrivial() &&
6264         isReadByLvalueToRvalueConversion(Definition->getParent())))) {
6265     return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6266                              Definition->getParent()->isUnion());
6267   }
6268 
6269   // Reserve space for the struct members.
6270   if (!Result.hasValue()) {
6271     if (!RD->isUnion())
6272       Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6273                        std::distance(RD->field_begin(), RD->field_end()));
6274     else
6275       // A union starts with no active member.
6276       Result = APValue((const FieldDecl*)nullptr);
6277   }
6278 
6279   if (RD->isInvalidDecl()) return false;
6280   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6281 
6282   // A scope for temporaries lifetime-extended by reference members.
6283   BlockScopeRAII LifetimeExtendedScope(Info);
6284 
6285   bool Success = true;
6286   unsigned BasesSeen = 0;
6287 #ifndef NDEBUG
6288   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
6289 #endif
6290   CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
6291   auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6292     // We might be initializing the same field again if this is an indirect
6293     // field initialization.
6294     if (FieldIt == RD->field_end() ||
6295         FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6296       assert(Indirect && "fields out of order?");
6297       return;
6298     }
6299 
6300     // Default-initialize any fields with no explicit initializer.
6301     for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6302       assert(FieldIt != RD->field_end() && "missing field?");
6303       if (!FieldIt->isUnnamedBitfield())
6304         Success &= getDefaultInitValue(
6305             FieldIt->getType(),
6306             Result.getStructField(FieldIt->getFieldIndex()));
6307     }
6308     ++FieldIt;
6309   };
6310   for (const auto *I : Definition->inits()) {
6311     LValue Subobject = This;
6312     LValue SubobjectParent = This;
6313     APValue *Value = &Result;
6314 
6315     // Determine the subobject to initialize.
6316     FieldDecl *FD = nullptr;
6317     if (I->isBaseInitializer()) {
6318       QualType BaseType(I->getBaseClass(), 0);
6319 #ifndef NDEBUG
6320       // Non-virtual base classes are initialized in the order in the class
6321       // definition. We have already checked for virtual base classes.
6322       assert(!BaseIt->isVirtual() && "virtual base for literal type");
6323       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
6324              "base class initializers not in expected order");
6325       ++BaseIt;
6326 #endif
6327       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6328                                   BaseType->getAsCXXRecordDecl(), &Layout))
6329         return false;
6330       Value = &Result.getStructBase(BasesSeen++);
6331     } else if ((FD = I->getMember())) {
6332       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6333         return false;
6334       if (RD->isUnion()) {
6335         Result = APValue(FD);
6336         Value = &Result.getUnionValue();
6337       } else {
6338         SkipToField(FD, false);
6339         Value = &Result.getStructField(FD->getFieldIndex());
6340       }
6341     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6342       // Walk the indirect field decl's chain to find the object to initialize,
6343       // and make sure we've initialized every step along it.
6344       auto IndirectFieldChain = IFD->chain();
6345       for (auto *C : IndirectFieldChain) {
6346         FD = cast<FieldDecl>(C);
6347         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6348         // Switch the union field if it differs. This happens if we had
6349         // preceding zero-initialization, and we're now initializing a union
6350         // subobject other than the first.
6351         // FIXME: In this case, the values of the other subobjects are
6352         // specified, since zero-initialization sets all padding bits to zero.
6353         if (!Value->hasValue() ||
6354             (Value->isUnion() && Value->getUnionField() != FD)) {
6355           if (CD->isUnion())
6356             *Value = APValue(FD);
6357           else
6358             // FIXME: This immediately starts the lifetime of all members of
6359             // an anonymous struct. It would be preferable to strictly start
6360             // member lifetime in initialization order.
6361             Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
6362         }
6363         // Store Subobject as its parent before updating it for the last element
6364         // in the chain.
6365         if (C == IndirectFieldChain.back())
6366           SubobjectParent = Subobject;
6367         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6368           return false;
6369         if (CD->isUnion())
6370           Value = &Value->getUnionValue();
6371         else {
6372           if (C == IndirectFieldChain.front() && !RD->isUnion())
6373             SkipToField(FD, true);
6374           Value = &Value->getStructField(FD->getFieldIndex());
6375         }
6376       }
6377     } else {
6378       llvm_unreachable("unknown base initializer kind");
6379     }
6380 
6381     // Need to override This for implicit field initializers as in this case
6382     // This refers to innermost anonymous struct/union containing initializer,
6383     // not to currently constructed class.
6384     const Expr *Init = I->getInit();
6385     if (Init->isValueDependent()) {
6386       if (!EvaluateDependentExpr(Init, Info))
6387         return false;
6388     } else {
6389       ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6390                                     isa<CXXDefaultInitExpr>(Init));
6391       FullExpressionRAII InitScope(Info);
6392       if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6393           (FD && FD->isBitField() &&
6394            !truncateBitfieldValue(Info, Init, *Value, FD))) {
6395         // If we're checking for a potential constant expression, evaluate all
6396         // initializers even if some of them fail.
6397         if (!Info.noteFailure())
6398           return false;
6399         Success = false;
6400       }
6401     }
6402 
6403     // This is the point at which the dynamic type of the object becomes this
6404     // class type.
6405     if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6406       EvalObj.finishedConstructingBases();
6407   }
6408 
6409   // Default-initialize any remaining fields.
6410   if (!RD->isUnion()) {
6411     for (; FieldIt != RD->field_end(); ++FieldIt) {
6412       if (!FieldIt->isUnnamedBitfield())
6413         Success &= getDefaultInitValue(
6414             FieldIt->getType(),
6415             Result.getStructField(FieldIt->getFieldIndex()));
6416     }
6417   }
6418 
6419   EvalObj.finishedConstructingFields();
6420 
6421   return Success &&
6422          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6423          LifetimeExtendedScope.destroy();
6424 }
6425 
6426 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6427                                   ArrayRef<const Expr*> Args,
6428                                   const CXXConstructorDecl *Definition,
6429                                   EvalInfo &Info, APValue &Result) {
6430   CallScopeRAII CallScope(Info);
6431   CallRef Call = Info.CurrentCall->createCall(Definition);
6432   if (!EvaluateArgs(Args, Call, Info, Definition))
6433     return false;
6434 
6435   return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6436          CallScope.destroy();
6437 }
6438 
6439 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
6440                                   const LValue &This, APValue &Value,
6441                                   QualType T) {
6442   // Objects can only be destroyed while they're within their lifetimes.
6443   // FIXME: We have no representation for whether an object of type nullptr_t
6444   // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6445   // as indeterminate instead?
6446   if (Value.isAbsent() && !T->isNullPtrType()) {
6447     APValue Printable;
6448     This.moveInto(Printable);
6449     Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
6450       << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6451     return false;
6452   }
6453 
6454   // Invent an expression for location purposes.
6455   // FIXME: We shouldn't need to do this.
6456   OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_PRValue);
6457 
6458   // For arrays, destroy elements right-to-left.
6459   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6460     uint64_t Size = CAT->getSize().getZExtValue();
6461     QualType ElemT = CAT->getElementType();
6462 
6463     LValue ElemLV = This;
6464     ElemLV.addArray(Info, &LocE, CAT);
6465     if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6466       return false;
6467 
6468     // Ensure that we have actual array elements available to destroy; the
6469     // destructors might mutate the value, so we can't run them on the array
6470     // filler.
6471     if (Size && Size > Value.getArrayInitializedElts())
6472       expandArray(Value, Value.getArraySize() - 1);
6473 
6474     for (; Size != 0; --Size) {
6475       APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6476       if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6477           !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
6478         return false;
6479     }
6480 
6481     // End the lifetime of this array now.
6482     Value = APValue();
6483     return true;
6484   }
6485 
6486   const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6487   if (!RD) {
6488     if (T.isDestructedType()) {
6489       Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
6490       return false;
6491     }
6492 
6493     Value = APValue();
6494     return true;
6495   }
6496 
6497   if (RD->getNumVBases()) {
6498     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6499     return false;
6500   }
6501 
6502   const CXXDestructorDecl *DD = RD->getDestructor();
6503   if (!DD && !RD->hasTrivialDestructor()) {
6504     Info.FFDiag(CallLoc);
6505     return false;
6506   }
6507 
6508   if (!DD || DD->isTrivial() ||
6509       (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6510     // A trivial destructor just ends the lifetime of the object. Check for
6511     // this case before checking for a body, because we might not bother
6512     // building a body for a trivial destructor. Note that it doesn't matter
6513     // whether the destructor is constexpr in this case; all trivial
6514     // destructors are constexpr.
6515     //
6516     // If an anonymous union would be destroyed, some enclosing destructor must
6517     // have been explicitly defined, and the anonymous union destruction should
6518     // have no effect.
6519     Value = APValue();
6520     return true;
6521   }
6522 
6523   if (!Info.CheckCallLimit(CallLoc))
6524     return false;
6525 
6526   const FunctionDecl *Definition = nullptr;
6527   const Stmt *Body = DD->getBody(Definition);
6528 
6529   if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
6530     return false;
6531 
6532   CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef());
6533 
6534   // We're now in the period of destruction of this object.
6535   unsigned BasesLeft = RD->getNumBases();
6536   EvalInfo::EvaluatingDestructorRAII EvalObj(
6537       Info,
6538       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6539   if (!EvalObj.DidInsert) {
6540     // C++2a [class.dtor]p19:
6541     //   the behavior is undefined if the destructor is invoked for an object
6542     //   whose lifetime has ended
6543     // (Note that formally the lifetime ends when the period of destruction
6544     // begins, even though certain uses of the object remain valid until the
6545     // period of destruction ends.)
6546     Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
6547     return false;
6548   }
6549 
6550   // FIXME: Creating an APValue just to hold a nonexistent return value is
6551   // wasteful.
6552   APValue RetVal;
6553   StmtResult Ret = {RetVal, nullptr};
6554   if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6555     return false;
6556 
6557   // A union destructor does not implicitly destroy its members.
6558   if (RD->isUnion())
6559     return true;
6560 
6561   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6562 
6563   // We don't have a good way to iterate fields in reverse, so collect all the
6564   // fields first and then walk them backwards.
6565   SmallVector<FieldDecl*, 16> Fields(RD->fields());
6566   for (const FieldDecl *FD : llvm::reverse(Fields)) {
6567     if (FD->isUnnamedBitfield())
6568       continue;
6569 
6570     LValue Subobject = This;
6571     if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6572       return false;
6573 
6574     APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6575     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6576                                FD->getType()))
6577       return false;
6578   }
6579 
6580   if (BasesLeft != 0)
6581     EvalObj.startedDestroyingBases();
6582 
6583   // Destroy base classes in reverse order.
6584   for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6585     --BasesLeft;
6586 
6587     QualType BaseType = Base.getType();
6588     LValue Subobject = This;
6589     if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
6590                                 BaseType->getAsCXXRecordDecl(), &Layout))
6591       return false;
6592 
6593     APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
6594     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6595                                BaseType))
6596       return false;
6597   }
6598   assert(BasesLeft == 0 && "NumBases was wrong?");
6599 
6600   // The period of destruction ends now. The object is gone.
6601   Value = APValue();
6602   return true;
6603 }
6604 
6605 namespace {
6606 struct DestroyObjectHandler {
6607   EvalInfo &Info;
6608   const Expr *E;
6609   const LValue &This;
6610   const AccessKinds AccessKind;
6611 
6612   typedef bool result_type;
6613   bool failed() { return false; }
6614   bool found(APValue &Subobj, QualType SubobjType) {
6615     return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
6616                                  SubobjType);
6617   }
6618   bool found(APSInt &Value, QualType SubobjType) {
6619     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6620     return false;
6621   }
6622   bool found(APFloat &Value, QualType SubobjType) {
6623     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6624     return false;
6625   }
6626 };
6627 }
6628 
6629 /// Perform a destructor or pseudo-destructor call on the given object, which
6630 /// might in general not be a complete object.
6631 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6632                               const LValue &This, QualType ThisType) {
6633   CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6634   DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6635   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6636 }
6637 
6638 /// Destroy and end the lifetime of the given complete object.
6639 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6640                               APValue::LValueBase LVBase, APValue &Value,
6641                               QualType T) {
6642   // If we've had an unmodeled side-effect, we can't rely on mutable state
6643   // (such as the object we're about to destroy) being correct.
6644   if (Info.EvalStatus.HasSideEffects)
6645     return false;
6646 
6647   LValue LV;
6648   LV.set({LVBase});
6649   return HandleDestructionImpl(Info, Loc, LV, Value, T);
6650 }
6651 
6652 /// Perform a call to 'perator new' or to `__builtin_operator_new'.
6653 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6654                                   LValue &Result) {
6655   if (Info.checkingPotentialConstantExpression() ||
6656       Info.SpeculativeEvaluationDepth)
6657     return false;
6658 
6659   // This is permitted only within a call to std::allocator<T>::allocate.
6660   auto Caller = Info.getStdAllocatorCaller("allocate");
6661   if (!Caller) {
6662     Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
6663                                      ? diag::note_constexpr_new_untyped
6664                                      : diag::note_constexpr_new);
6665     return false;
6666   }
6667 
6668   QualType ElemType = Caller.ElemType;
6669   if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6670     Info.FFDiag(E->getExprLoc(),
6671                 diag::note_constexpr_new_not_complete_object_type)
6672         << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6673     return false;
6674   }
6675 
6676   APSInt ByteSize;
6677   if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6678     return false;
6679   bool IsNothrow = false;
6680   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6681     EvaluateIgnoredValue(Info, E->getArg(I));
6682     IsNothrow |= E->getType()->isNothrowT();
6683   }
6684 
6685   CharUnits ElemSize;
6686   if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6687     return false;
6688   APInt Size, Remainder;
6689   APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6690   APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6691   if (Remainder != 0) {
6692     // This likely indicates a bug in the implementation of 'std::allocator'.
6693     Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6694         << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6695     return false;
6696   }
6697 
6698   if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
6699     if (IsNothrow) {
6700       Result.setNull(Info.Ctx, E->getType());
6701       return true;
6702     }
6703 
6704     Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
6705     return false;
6706   }
6707 
6708   QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
6709                                                      ArrayType::Normal, 0);
6710   APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6711   *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6712   Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6713   return true;
6714 }
6715 
6716 static bool hasVirtualDestructor(QualType T) {
6717   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6718     if (CXXDestructorDecl *DD = RD->getDestructor())
6719       return DD->isVirtual();
6720   return false;
6721 }
6722 
6723 static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6724   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6725     if (CXXDestructorDecl *DD = RD->getDestructor())
6726       return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6727   return nullptr;
6728 }
6729 
6730 /// Check that the given object is a suitable pointer to a heap allocation that
6731 /// still exists and is of the right kind for the purpose of a deletion.
6732 ///
6733 /// On success, returns the heap allocation to deallocate. On failure, produces
6734 /// a diagnostic and returns None.
6735 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6736                                             const LValue &Pointer,
6737                                             DynAlloc::Kind DeallocKind) {
6738   auto PointerAsString = [&] {
6739     return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6740   };
6741 
6742   DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6743   if (!DA) {
6744     Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6745         << PointerAsString();
6746     if (Pointer.Base)
6747       NoteLValueLocation(Info, Pointer.Base);
6748     return None;
6749   }
6750 
6751   Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6752   if (!Alloc) {
6753     Info.FFDiag(E, diag::note_constexpr_double_delete);
6754     return None;
6755   }
6756 
6757   QualType AllocType = Pointer.Base.getDynamicAllocType();
6758   if (DeallocKind != (*Alloc)->getKind()) {
6759     Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6760         << DeallocKind << (*Alloc)->getKind() << AllocType;
6761     NoteLValueLocation(Info, Pointer.Base);
6762     return None;
6763   }
6764 
6765   bool Subobject = false;
6766   if (DeallocKind == DynAlloc::New) {
6767     Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6768                 Pointer.Designator.isOnePastTheEnd();
6769   } else {
6770     Subobject = Pointer.Designator.Entries.size() != 1 ||
6771                 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6772   }
6773   if (Subobject) {
6774     Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6775         << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6776     return None;
6777   }
6778 
6779   return Alloc;
6780 }
6781 
6782 // Perform a call to 'operator delete' or '__builtin_operator_delete'.
6783 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6784   if (Info.checkingPotentialConstantExpression() ||
6785       Info.SpeculativeEvaluationDepth)
6786     return false;
6787 
6788   // This is permitted only within a call to std::allocator<T>::deallocate.
6789   if (!Info.getStdAllocatorCaller("deallocate")) {
6790     Info.FFDiag(E->getExprLoc());
6791     return true;
6792   }
6793 
6794   LValue Pointer;
6795   if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6796     return false;
6797   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6798     EvaluateIgnoredValue(Info, E->getArg(I));
6799 
6800   if (Pointer.Designator.Invalid)
6801     return false;
6802 
6803   // Deleting a null pointer would have no effect, but it's not permitted by
6804   // std::allocator<T>::deallocate's contract.
6805   if (Pointer.isNullPointer()) {
6806     Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
6807     return true;
6808   }
6809 
6810   if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6811     return false;
6812 
6813   Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6814   return true;
6815 }
6816 
6817 //===----------------------------------------------------------------------===//
6818 // Generic Evaluation
6819 //===----------------------------------------------------------------------===//
6820 namespace {
6821 
6822 class BitCastBuffer {
6823   // FIXME: We're going to need bit-level granularity when we support
6824   // bit-fields.
6825   // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6826   // we don't support a host or target where that is the case. Still, we should
6827   // use a more generic type in case we ever do.
6828   SmallVector<Optional<unsigned char>, 32> Bytes;
6829 
6830   static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6831                 "Need at least 8 bit unsigned char");
6832 
6833   bool TargetIsLittleEndian;
6834 
6835 public:
6836   BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6837       : Bytes(Width.getQuantity()),
6838         TargetIsLittleEndian(TargetIsLittleEndian) {}
6839 
6840   LLVM_NODISCARD
6841   bool readObject(CharUnits Offset, CharUnits Width,
6842                   SmallVectorImpl<unsigned char> &Output) const {
6843     for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6844       // If a byte of an integer is uninitialized, then the whole integer is
6845       // uninitialized.
6846       if (!Bytes[I.getQuantity()])
6847         return false;
6848       Output.push_back(*Bytes[I.getQuantity()]);
6849     }
6850     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6851       std::reverse(Output.begin(), Output.end());
6852     return true;
6853   }
6854 
6855   void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6856     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6857       std::reverse(Input.begin(), Input.end());
6858 
6859     size_t Index = 0;
6860     for (unsigned char Byte : Input) {
6861       assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
6862       Bytes[Offset.getQuantity() + Index] = Byte;
6863       ++Index;
6864     }
6865   }
6866 
6867   size_t size() { return Bytes.size(); }
6868 };
6869 
6870 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6871 /// target would represent the value at runtime.
6872 class APValueToBufferConverter {
6873   EvalInfo &Info;
6874   BitCastBuffer Buffer;
6875   const CastExpr *BCE;
6876 
6877   APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6878                            const CastExpr *BCE)
6879       : Info(Info),
6880         Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6881         BCE(BCE) {}
6882 
6883   bool visit(const APValue &Val, QualType Ty) {
6884     return visit(Val, Ty, CharUnits::fromQuantity(0));
6885   }
6886 
6887   // Write out Val with type Ty into Buffer starting at Offset.
6888   bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6889     assert((size_t)Offset.getQuantity() <= Buffer.size());
6890 
6891     // As a special case, nullptr_t has an indeterminate value.
6892     if (Ty->isNullPtrType())
6893       return true;
6894 
6895     // Dig through Src to find the byte at SrcOffset.
6896     switch (Val.getKind()) {
6897     case APValue::Indeterminate:
6898     case APValue::None:
6899       return true;
6900 
6901     case APValue::Int:
6902       return visitInt(Val.getInt(), Ty, Offset);
6903     case APValue::Float:
6904       return visitFloat(Val.getFloat(), Ty, Offset);
6905     case APValue::Array:
6906       return visitArray(Val, Ty, Offset);
6907     case APValue::Struct:
6908       return visitRecord(Val, Ty, Offset);
6909 
6910     case APValue::ComplexInt:
6911     case APValue::ComplexFloat:
6912     case APValue::Vector:
6913     case APValue::FixedPoint:
6914       // FIXME: We should support these.
6915 
6916     case APValue::Union:
6917     case APValue::MemberPointer:
6918     case APValue::AddrLabelDiff: {
6919       Info.FFDiag(BCE->getBeginLoc(),
6920                   diag::note_constexpr_bit_cast_unsupported_type)
6921           << Ty;
6922       return false;
6923     }
6924 
6925     case APValue::LValue:
6926       llvm_unreachable("LValue subobject in bit_cast?");
6927     }
6928     llvm_unreachable("Unhandled APValue::ValueKind");
6929   }
6930 
6931   bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
6932     const RecordDecl *RD = Ty->getAsRecordDecl();
6933     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6934 
6935     // Visit the base classes.
6936     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6937       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6938         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6939         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6940 
6941         if (!visitRecord(Val.getStructBase(I), BS.getType(),
6942                          Layout.getBaseClassOffset(BaseDecl) + Offset))
6943           return false;
6944       }
6945     }
6946 
6947     // Visit the fields.
6948     unsigned FieldIdx = 0;
6949     for (FieldDecl *FD : RD->fields()) {
6950       if (FD->isBitField()) {
6951         Info.FFDiag(BCE->getBeginLoc(),
6952                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6953         return false;
6954       }
6955 
6956       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6957 
6958       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
6959              "only bit-fields can have sub-char alignment");
6960       CharUnits FieldOffset =
6961           Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
6962       QualType FieldTy = FD->getType();
6963       if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
6964         return false;
6965       ++FieldIdx;
6966     }
6967 
6968     return true;
6969   }
6970 
6971   bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
6972     const auto *CAT =
6973         dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
6974     if (!CAT)
6975       return false;
6976 
6977     CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
6978     unsigned NumInitializedElts = Val.getArrayInitializedElts();
6979     unsigned ArraySize = Val.getArraySize();
6980     // First, initialize the initialized elements.
6981     for (unsigned I = 0; I != NumInitializedElts; ++I) {
6982       const APValue &SubObj = Val.getArrayInitializedElt(I);
6983       if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
6984         return false;
6985     }
6986 
6987     // Next, initialize the rest of the array using the filler.
6988     if (Val.hasArrayFiller()) {
6989       const APValue &Filler = Val.getArrayFiller();
6990       for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
6991         if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
6992           return false;
6993       }
6994     }
6995 
6996     return true;
6997   }
6998 
6999   bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
7000     APSInt AdjustedVal = Val;
7001     unsigned Width = AdjustedVal.getBitWidth();
7002     if (Ty->isBooleanType()) {
7003       Width = Info.Ctx.getTypeSize(Ty);
7004       AdjustedVal = AdjustedVal.extend(Width);
7005     }
7006 
7007     SmallVector<unsigned char, 8> Bytes(Width / 8);
7008     llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
7009     Buffer.writeObject(Offset, Bytes);
7010     return true;
7011   }
7012 
7013   bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
7014     APSInt AsInt(Val.bitcastToAPInt());
7015     return visitInt(AsInt, Ty, Offset);
7016   }
7017 
7018 public:
7019   static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
7020                                          const CastExpr *BCE) {
7021     CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
7022     APValueToBufferConverter Converter(Info, DstSize, BCE);
7023     if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
7024       return None;
7025     return Converter.Buffer;
7026   }
7027 };
7028 
7029 /// Write an BitCastBuffer into an APValue.
7030 class BufferToAPValueConverter {
7031   EvalInfo &Info;
7032   const BitCastBuffer &Buffer;
7033   const CastExpr *BCE;
7034 
7035   BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
7036                            const CastExpr *BCE)
7037       : Info(Info), Buffer(Buffer), BCE(BCE) {}
7038 
7039   // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
7040   // with an invalid type, so anything left is a deficiency on our part (FIXME).
7041   // Ideally this will be unreachable.
7042   llvm::NoneType unsupportedType(QualType Ty) {
7043     Info.FFDiag(BCE->getBeginLoc(),
7044                 diag::note_constexpr_bit_cast_unsupported_type)
7045         << Ty;
7046     return None;
7047   }
7048 
7049   llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) {
7050     Info.FFDiag(BCE->getBeginLoc(),
7051                 diag::note_constexpr_bit_cast_unrepresentable_value)
7052         << Ty << toString(Val, /*Radix=*/10);
7053     return None;
7054   }
7055 
7056   Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
7057                           const EnumType *EnumSugar = nullptr) {
7058     if (T->isNullPtrType()) {
7059       uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
7060       return APValue((Expr *)nullptr,
7061                      /*Offset=*/CharUnits::fromQuantity(NullValue),
7062                      APValue::NoLValuePath{}, /*IsNullPtr=*/true);
7063     }
7064 
7065     CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
7066 
7067     // Work around floating point types that contain unused padding bytes. This
7068     // is really just `long double` on x86, which is the only fundamental type
7069     // with padding bytes.
7070     if (T->isRealFloatingType()) {
7071       const llvm::fltSemantics &Semantics =
7072           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7073       unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
7074       assert(NumBits % 8 == 0);
7075       CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
7076       if (NumBytes != SizeOf)
7077         SizeOf = NumBytes;
7078     }
7079 
7080     SmallVector<uint8_t, 8> Bytes;
7081     if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
7082       // If this is std::byte or unsigned char, then its okay to store an
7083       // indeterminate value.
7084       bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
7085       bool IsUChar =
7086           !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
7087                          T->isSpecificBuiltinType(BuiltinType::Char_U));
7088       if (!IsStdByte && !IsUChar) {
7089         QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
7090         Info.FFDiag(BCE->getExprLoc(),
7091                     diag::note_constexpr_bit_cast_indet_dest)
7092             << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
7093         return None;
7094       }
7095 
7096       return APValue::IndeterminateValue();
7097     }
7098 
7099     APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
7100     llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
7101 
7102     if (T->isIntegralOrEnumerationType()) {
7103       Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7104 
7105       unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
7106       if (IntWidth != Val.getBitWidth()) {
7107         APSInt Truncated = Val.trunc(IntWidth);
7108         if (Truncated.extend(Val.getBitWidth()) != Val)
7109           return unrepresentableValue(QualType(T, 0), Val);
7110         Val = Truncated;
7111       }
7112 
7113       return APValue(Val);
7114     }
7115 
7116     if (T->isRealFloatingType()) {
7117       const llvm::fltSemantics &Semantics =
7118           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7119       return APValue(APFloat(Semantics, Val));
7120     }
7121 
7122     return unsupportedType(QualType(T, 0));
7123   }
7124 
7125   Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7126     const RecordDecl *RD = RTy->getAsRecordDecl();
7127     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7128 
7129     unsigned NumBases = 0;
7130     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7131       NumBases = CXXRD->getNumBases();
7132 
7133     APValue ResultVal(APValue::UninitStruct(), NumBases,
7134                       std::distance(RD->field_begin(), RD->field_end()));
7135 
7136     // Visit the base classes.
7137     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7138       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7139         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7140         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7141         if (BaseDecl->isEmpty() ||
7142             Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
7143           continue;
7144 
7145         Optional<APValue> SubObj = visitType(
7146             BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7147         if (!SubObj)
7148           return None;
7149         ResultVal.getStructBase(I) = *SubObj;
7150       }
7151     }
7152 
7153     // Visit the fields.
7154     unsigned FieldIdx = 0;
7155     for (FieldDecl *FD : RD->fields()) {
7156       // FIXME: We don't currently support bit-fields. A lot of the logic for
7157       // this is in CodeGen, so we need to factor it around.
7158       if (FD->isBitField()) {
7159         Info.FFDiag(BCE->getBeginLoc(),
7160                     diag::note_constexpr_bit_cast_unsupported_bitfield);
7161         return None;
7162       }
7163 
7164       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7165       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
7166 
7167       CharUnits FieldOffset =
7168           CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7169           Offset;
7170       QualType FieldTy = FD->getType();
7171       Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7172       if (!SubObj)
7173         return None;
7174       ResultVal.getStructField(FieldIdx) = *SubObj;
7175       ++FieldIdx;
7176     }
7177 
7178     return ResultVal;
7179   }
7180 
7181   Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7182     QualType RepresentationType = Ty->getDecl()->getIntegerType();
7183     assert(!RepresentationType.isNull() &&
7184            "enum forward decl should be caught by Sema");
7185     const auto *AsBuiltin =
7186         RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7187     // Recurse into the underlying type. Treat std::byte transparently as
7188     // unsigned char.
7189     return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7190   }
7191 
7192   Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7193     size_t Size = Ty->getSize().getLimitedValue();
7194     CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7195 
7196     APValue ArrayValue(APValue::UninitArray(), Size, Size);
7197     for (size_t I = 0; I != Size; ++I) {
7198       Optional<APValue> ElementValue =
7199           visitType(Ty->getElementType(), Offset + I * ElementWidth);
7200       if (!ElementValue)
7201         return None;
7202       ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7203     }
7204 
7205     return ArrayValue;
7206   }
7207 
7208   Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7209     return unsupportedType(QualType(Ty, 0));
7210   }
7211 
7212   Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7213     QualType Can = Ty.getCanonicalType();
7214 
7215     switch (Can->getTypeClass()) {
7216 #define TYPE(Class, Base)                                                      \
7217   case Type::Class:                                                            \
7218     return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7219 #define ABSTRACT_TYPE(Class, Base)
7220 #define NON_CANONICAL_TYPE(Class, Base)                                        \
7221   case Type::Class:                                                            \
7222     llvm_unreachable("non-canonical type should be impossible!");
7223 #define DEPENDENT_TYPE(Class, Base)                                            \
7224   case Type::Class:                                                            \
7225     llvm_unreachable(                                                          \
7226         "dependent types aren't supported in the constant evaluator!");
7227 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)                            \
7228   case Type::Class:                                                            \
7229     llvm_unreachable("either dependent or not canonical!");
7230 #include "clang/AST/TypeNodes.inc"
7231     }
7232     llvm_unreachable("Unhandled Type::TypeClass");
7233   }
7234 
7235 public:
7236   // Pull out a full value of type DstType.
7237   static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7238                                    const CastExpr *BCE) {
7239     BufferToAPValueConverter Converter(Info, Buffer, BCE);
7240     return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7241   }
7242 };
7243 
7244 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7245                                                  QualType Ty, EvalInfo *Info,
7246                                                  const ASTContext &Ctx,
7247                                                  bool CheckingDest) {
7248   Ty = Ty.getCanonicalType();
7249 
7250   auto diag = [&](int Reason) {
7251     if (Info)
7252       Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7253           << CheckingDest << (Reason == 4) << Reason;
7254     return false;
7255   };
7256   auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7257     if (Info)
7258       Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7259           << NoteTy << Construct << Ty;
7260     return false;
7261   };
7262 
7263   if (Ty->isUnionType())
7264     return diag(0);
7265   if (Ty->isPointerType())
7266     return diag(1);
7267   if (Ty->isMemberPointerType())
7268     return diag(2);
7269   if (Ty.isVolatileQualified())
7270     return diag(3);
7271 
7272   if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7273     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7274       for (CXXBaseSpecifier &BS : CXXRD->bases())
7275         if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7276                                                   CheckingDest))
7277           return note(1, BS.getType(), BS.getBeginLoc());
7278     }
7279     for (FieldDecl *FD : Record->fields()) {
7280       if (FD->getType()->isReferenceType())
7281         return diag(4);
7282       if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7283                                                 CheckingDest))
7284         return note(0, FD->getType(), FD->getBeginLoc());
7285     }
7286   }
7287 
7288   if (Ty->isArrayType() &&
7289       !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7290                                             Info, Ctx, CheckingDest))
7291     return false;
7292 
7293   return true;
7294 }
7295 
7296 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
7297                                              const ASTContext &Ctx,
7298                                              const CastExpr *BCE) {
7299   bool DestOK = checkBitCastConstexprEligibilityType(
7300       BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
7301   bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
7302                                 BCE->getBeginLoc(),
7303                                 BCE->getSubExpr()->getType(), Info, Ctx, false);
7304   return SourceOK;
7305 }
7306 
7307 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7308                                         APValue &SourceValue,
7309                                         const CastExpr *BCE) {
7310   assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7311          "no host or target supports non 8-bit chars");
7312   assert(SourceValue.isLValue() &&
7313          "LValueToRValueBitcast requires an lvalue operand!");
7314 
7315   if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
7316     return false;
7317 
7318   LValue SourceLValue;
7319   APValue SourceRValue;
7320   SourceLValue.setFrom(Info.Ctx, SourceValue);
7321   if (!handleLValueToRValueConversion(
7322           Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
7323           SourceRValue, /*WantObjectRepresentation=*/true))
7324     return false;
7325 
7326   // Read out SourceValue into a char buffer.
7327   Optional<BitCastBuffer> Buffer =
7328       APValueToBufferConverter::convert(Info, SourceRValue, BCE);
7329   if (!Buffer)
7330     return false;
7331 
7332   // Write out the buffer into a new APValue.
7333   Optional<APValue> MaybeDestValue =
7334       BufferToAPValueConverter::convert(Info, *Buffer, BCE);
7335   if (!MaybeDestValue)
7336     return false;
7337 
7338   DestValue = std::move(*MaybeDestValue);
7339   return true;
7340 }
7341 
7342 template <class Derived>
7343 class ExprEvaluatorBase
7344   : public ConstStmtVisitor<Derived, bool> {
7345 private:
7346   Derived &getDerived() { return static_cast<Derived&>(*this); }
7347   bool DerivedSuccess(const APValue &V, const Expr *E) {
7348     return getDerived().Success(V, E);
7349   }
7350   bool DerivedZeroInitialization(const Expr *E) {
7351     return getDerived().ZeroInitialization(E);
7352   }
7353 
7354   // Check whether a conditional operator with a non-constant condition is a
7355   // potential constant expression. If neither arm is a potential constant
7356   // expression, then the conditional operator is not either.
7357   template<typename ConditionalOperator>
7358   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7359     assert(Info.checkingPotentialConstantExpression());
7360 
7361     // Speculatively evaluate both arms.
7362     SmallVector<PartialDiagnosticAt, 8> Diag;
7363     {
7364       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7365       StmtVisitorTy::Visit(E->getFalseExpr());
7366       if (Diag.empty())
7367         return;
7368     }
7369 
7370     {
7371       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7372       Diag.clear();
7373       StmtVisitorTy::Visit(E->getTrueExpr());
7374       if (Diag.empty())
7375         return;
7376     }
7377 
7378     Error(E, diag::note_constexpr_conditional_never_const);
7379   }
7380 
7381 
7382   template<typename ConditionalOperator>
7383   bool HandleConditionalOperator(const ConditionalOperator *E) {
7384     bool BoolResult;
7385     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7386       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7387         CheckPotentialConstantConditional(E);
7388         return false;
7389       }
7390       if (Info.noteFailure()) {
7391         StmtVisitorTy::Visit(E->getTrueExpr());
7392         StmtVisitorTy::Visit(E->getFalseExpr());
7393       }
7394       return false;
7395     }
7396 
7397     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
7398     return StmtVisitorTy::Visit(EvalExpr);
7399   }
7400 
7401 protected:
7402   EvalInfo &Info;
7403   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
7404   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
7405 
7406   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7407     return Info.CCEDiag(E, D);
7408   }
7409 
7410   bool ZeroInitialization(const Expr *E) { return Error(E); }
7411 
7412 public:
7413   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
7414 
7415   EvalInfo &getEvalInfo() { return Info; }
7416 
7417   /// Report an evaluation error. This should only be called when an error is
7418   /// first discovered. When propagating an error, just return false.
7419   bool Error(const Expr *E, diag::kind D) {
7420     Info.FFDiag(E, D);
7421     return false;
7422   }
7423   bool Error(const Expr *E) {
7424     return Error(E, diag::note_invalid_subexpr_in_const_expr);
7425   }
7426 
7427   bool VisitStmt(const Stmt *) {
7428     llvm_unreachable("Expression evaluator should not be called on stmts");
7429   }
7430   bool VisitExpr(const Expr *E) {
7431     return Error(E);
7432   }
7433 
7434   bool VisitConstantExpr(const ConstantExpr *E) {
7435     if (E->hasAPValueResult())
7436       return DerivedSuccess(E->getAPValueResult(), E);
7437 
7438     return StmtVisitorTy::Visit(E->getSubExpr());
7439   }
7440 
7441   bool VisitParenExpr(const ParenExpr *E)
7442     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7443   bool VisitUnaryExtension(const UnaryOperator *E)
7444     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7445   bool VisitUnaryPlus(const UnaryOperator *E)
7446     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7447   bool VisitChooseExpr(const ChooseExpr *E)
7448     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
7449   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
7450     { return StmtVisitorTy::Visit(E->getResultExpr()); }
7451   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
7452     { return StmtVisitorTy::Visit(E->getReplacement()); }
7453   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7454     TempVersionRAII RAII(*Info.CurrentCall);
7455     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7456     return StmtVisitorTy::Visit(E->getExpr());
7457   }
7458   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7459     TempVersionRAII RAII(*Info.CurrentCall);
7460     // The initializer may not have been parsed yet, or might be erroneous.
7461     if (!E->getExpr())
7462       return Error(E);
7463     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7464     return StmtVisitorTy::Visit(E->getExpr());
7465   }
7466 
7467   bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7468     FullExpressionRAII Scope(Info);
7469     return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
7470   }
7471 
7472   // Temporaries are registered when created, so we don't care about
7473   // CXXBindTemporaryExpr.
7474   bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7475     return StmtVisitorTy::Visit(E->getSubExpr());
7476   }
7477 
7478   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7479     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7480     return static_cast<Derived*>(this)->VisitCastExpr(E);
7481   }
7482   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7483     if (!Info.Ctx.getLangOpts().CPlusPlus20)
7484       CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
7485     return static_cast<Derived*>(this)->VisitCastExpr(E);
7486   }
7487   bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7488     return static_cast<Derived*>(this)->VisitCastExpr(E);
7489   }
7490 
7491   bool VisitBinaryOperator(const BinaryOperator *E) {
7492     switch (E->getOpcode()) {
7493     default:
7494       return Error(E);
7495 
7496     case BO_Comma:
7497       VisitIgnoredValue(E->getLHS());
7498       return StmtVisitorTy::Visit(E->getRHS());
7499 
7500     case BO_PtrMemD:
7501     case BO_PtrMemI: {
7502       LValue Obj;
7503       if (!HandleMemberPointerAccess(Info, E, Obj))
7504         return false;
7505       APValue Result;
7506       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7507         return false;
7508       return DerivedSuccess(Result, E);
7509     }
7510     }
7511   }
7512 
7513   bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
7514     return StmtVisitorTy::Visit(E->getSemanticForm());
7515   }
7516 
7517   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7518     // Evaluate and cache the common expression. We treat it as a temporary,
7519     // even though it's not quite the same thing.
7520     LValue CommonLV;
7521     if (!Evaluate(Info.CurrentCall->createTemporary(
7522                       E->getOpaqueValue(),
7523                       getStorageType(Info.Ctx, E->getOpaqueValue()),
7524                       ScopeKind::FullExpression, CommonLV),
7525                   Info, E->getCommon()))
7526       return false;
7527 
7528     return HandleConditionalOperator(E);
7529   }
7530 
7531   bool VisitConditionalOperator(const ConditionalOperator *E) {
7532     bool IsBcpCall = false;
7533     // If the condition (ignoring parens) is a __builtin_constant_p call,
7534     // the result is a constant expression if it can be folded without
7535     // side-effects. This is an important GNU extension. See GCC PR38377
7536     // for discussion.
7537     if (const CallExpr *CallCE =
7538           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7539       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7540         IsBcpCall = true;
7541 
7542     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7543     // constant expression; we can't check whether it's potentially foldable.
7544     // FIXME: We should instead treat __builtin_constant_p as non-constant if
7545     // it would return 'false' in this mode.
7546     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
7547       return false;
7548 
7549     FoldConstant Fold(Info, IsBcpCall);
7550     if (!HandleConditionalOperator(E)) {
7551       Fold.keepDiagnostics();
7552       return false;
7553     }
7554 
7555     return true;
7556   }
7557 
7558   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7559     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
7560       return DerivedSuccess(*Value, E);
7561 
7562     const Expr *Source = E->getSourceExpr();
7563     if (!Source)
7564       return Error(E);
7565     if (Source == E) {
7566       assert(0 && "OpaqueValueExpr recursively refers to itself");
7567       return Error(E);
7568     }
7569     return StmtVisitorTy::Visit(Source);
7570   }
7571 
7572   bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7573     for (const Expr *SemE : E->semantics()) {
7574       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7575         // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7576         // result expression: there could be two different LValues that would
7577         // refer to the same object in that case, and we can't model that.
7578         if (SemE == E->getResultExpr())
7579           return Error(E);
7580 
7581         // Unique OVEs get evaluated if and when we encounter them when
7582         // emitting the rest of the semantic form, rather than eagerly.
7583         if (OVE->isUnique())
7584           continue;
7585 
7586         LValue LV;
7587         if (!Evaluate(Info.CurrentCall->createTemporary(
7588                           OVE, getStorageType(Info.Ctx, OVE),
7589                           ScopeKind::FullExpression, LV),
7590                       Info, OVE->getSourceExpr()))
7591           return false;
7592       } else if (SemE == E->getResultExpr()) {
7593         if (!StmtVisitorTy::Visit(SemE))
7594           return false;
7595       } else {
7596         if (!EvaluateIgnoredValue(Info, SemE))
7597           return false;
7598       }
7599     }
7600     return true;
7601   }
7602 
7603   bool VisitCallExpr(const CallExpr *E) {
7604     APValue Result;
7605     if (!handleCallExpr(E, Result, nullptr))
7606       return false;
7607     return DerivedSuccess(Result, E);
7608   }
7609 
7610   bool handleCallExpr(const CallExpr *E, APValue &Result,
7611                      const LValue *ResultSlot) {
7612     CallScopeRAII CallScope(Info);
7613 
7614     const Expr *Callee = E->getCallee()->IgnoreParens();
7615     QualType CalleeType = Callee->getType();
7616 
7617     const FunctionDecl *FD = nullptr;
7618     LValue *This = nullptr, ThisVal;
7619     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
7620     bool HasQualifier = false;
7621 
7622     CallRef Call;
7623 
7624     // Extract function decl and 'this' pointer from the callee.
7625     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7626       const CXXMethodDecl *Member = nullptr;
7627       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7628         // Explicit bound member calls, such as x.f() or p->g();
7629         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7630           return false;
7631         Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7632         if (!Member)
7633           return Error(Callee);
7634         This = &ThisVal;
7635         HasQualifier = ME->hasQualifier();
7636       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
7637         // Indirect bound member calls ('.*' or '->*').
7638         const ValueDecl *D =
7639             HandleMemberPointerAccess(Info, BE, ThisVal, false);
7640         if (!D)
7641           return false;
7642         Member = dyn_cast<CXXMethodDecl>(D);
7643         if (!Member)
7644           return Error(Callee);
7645         This = &ThisVal;
7646       } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7647         if (!Info.getLangOpts().CPlusPlus20)
7648           Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7649         return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7650                HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7651       } else
7652         return Error(Callee);
7653       FD = Member;
7654     } else if (CalleeType->isFunctionPointerType()) {
7655       LValue CalleeLV;
7656       if (!EvaluatePointer(Callee, CalleeLV, Info))
7657         return false;
7658 
7659       if (!CalleeLV.getLValueOffset().isZero())
7660         return Error(Callee);
7661       FD = dyn_cast_or_null<FunctionDecl>(
7662           CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
7663       if (!FD)
7664         return Error(Callee);
7665       // Don't call function pointers which have been cast to some other type.
7666       // Per DR (no number yet), the caller and callee can differ in noexcept.
7667       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7668         CalleeType->getPointeeType(), FD->getType())) {
7669         return Error(E);
7670       }
7671 
7672       // For an (overloaded) assignment expression, evaluate the RHS before the
7673       // LHS.
7674       auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
7675       if (OCE && OCE->isAssignmentOp()) {
7676         assert(Args.size() == 2 && "wrong number of arguments in assignment");
7677         Call = Info.CurrentCall->createCall(FD);
7678         if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call,
7679                           Info, FD, /*RightToLeft=*/true))
7680           return false;
7681       }
7682 
7683       // Overloaded operator calls to member functions are represented as normal
7684       // calls with '*this' as the first argument.
7685       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7686       if (MD && !MD->isStatic()) {
7687         // FIXME: When selecting an implicit conversion for an overloaded
7688         // operator delete, we sometimes try to evaluate calls to conversion
7689         // operators without a 'this' parameter!
7690         if (Args.empty())
7691           return Error(E);
7692 
7693         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7694           return false;
7695         This = &ThisVal;
7696 
7697         // If this is syntactically a simple assignment using a trivial
7698         // assignment operator, start the lifetimes of union members as needed,
7699         // per C++20 [class.union]5.
7700         if (Info.getLangOpts().CPlusPlus20 && OCE &&
7701             OCE->getOperator() == OO_Equal && MD->isTrivial() &&
7702             !HandleUnionActiveMemberChange(Info, Args[0], ThisVal))
7703           return false;
7704 
7705         Args = Args.slice(1);
7706       } else if (MD && MD->isLambdaStaticInvoker()) {
7707         // Map the static invoker for the lambda back to the call operator.
7708         // Conveniently, we don't have to slice out the 'this' argument (as is
7709         // being done for the non-static case), since a static member function
7710         // doesn't have an implicit argument passed in.
7711         const CXXRecordDecl *ClosureClass = MD->getParent();
7712         assert(
7713             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7714             "Number of captures must be zero for conversion to function-ptr");
7715 
7716         const CXXMethodDecl *LambdaCallOp =
7717             ClosureClass->getLambdaCallOperator();
7718 
7719         // Set 'FD', the function that will be called below, to the call
7720         // operator.  If the closure object represents a generic lambda, find
7721         // the corresponding specialization of the call operator.
7722 
7723         if (ClosureClass->isGenericLambda()) {
7724           assert(MD->isFunctionTemplateSpecialization() &&
7725                  "A generic lambda's static-invoker function must be a "
7726                  "template specialization");
7727           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7728           FunctionTemplateDecl *CallOpTemplate =
7729               LambdaCallOp->getDescribedFunctionTemplate();
7730           void *InsertPos = nullptr;
7731           FunctionDecl *CorrespondingCallOpSpecialization =
7732               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7733           assert(CorrespondingCallOpSpecialization &&
7734                  "We must always have a function call operator specialization "
7735                  "that corresponds to our static invoker specialization");
7736           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7737         } else
7738           FD = LambdaCallOp;
7739       } else if (FD->isReplaceableGlobalAllocationFunction()) {
7740         if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7741             FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7742           LValue Ptr;
7743           if (!HandleOperatorNewCall(Info, E, Ptr))
7744             return false;
7745           Ptr.moveInto(Result);
7746           return CallScope.destroy();
7747         } else {
7748           return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
7749         }
7750       }
7751     } else
7752       return Error(E);
7753 
7754     // Evaluate the arguments now if we've not already done so.
7755     if (!Call) {
7756       Call = Info.CurrentCall->createCall(FD);
7757       if (!EvaluateArgs(Args, Call, Info, FD))
7758         return false;
7759     }
7760 
7761     SmallVector<QualType, 4> CovariantAdjustmentPath;
7762     if (This) {
7763       auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7764       if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
7765         // Perform virtual dispatch, if necessary.
7766         FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
7767                                    CovariantAdjustmentPath);
7768         if (!FD)
7769           return false;
7770       } else {
7771         // Check that the 'this' pointer points to an object of the right type.
7772         // FIXME: If this is an assignment operator call, we may need to change
7773         // the active union member before we check this.
7774         if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
7775           return false;
7776       }
7777     }
7778 
7779     // Destructor calls are different enough that they have their own codepath.
7780     if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
7781       assert(This && "no 'this' pointer for destructor call");
7782       return HandleDestruction(Info, E, *This,
7783                                Info.Ctx.getRecordType(DD->getParent())) &&
7784              CallScope.destroy();
7785     }
7786 
7787     const FunctionDecl *Definition = nullptr;
7788     Stmt *Body = FD->getBody(Definition);
7789 
7790     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
7791         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call,
7792                             Body, Info, Result, ResultSlot))
7793       return false;
7794 
7795     if (!CovariantAdjustmentPath.empty() &&
7796         !HandleCovariantReturnAdjustment(Info, E, Result,
7797                                          CovariantAdjustmentPath))
7798       return false;
7799 
7800     return CallScope.destroy();
7801   }
7802 
7803   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7804     return StmtVisitorTy::Visit(E->getInitializer());
7805   }
7806   bool VisitInitListExpr(const InitListExpr *E) {
7807     if (E->getNumInits() == 0)
7808       return DerivedZeroInitialization(E);
7809     if (E->getNumInits() == 1)
7810       return StmtVisitorTy::Visit(E->getInit(0));
7811     return Error(E);
7812   }
7813   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
7814     return DerivedZeroInitialization(E);
7815   }
7816   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
7817     return DerivedZeroInitialization(E);
7818   }
7819   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
7820     return DerivedZeroInitialization(E);
7821   }
7822 
7823   /// A member expression where the object is a prvalue is itself a prvalue.
7824   bool VisitMemberExpr(const MemberExpr *E) {
7825     assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
7826            "missing temporary materialization conversion");
7827     assert(!E->isArrow() && "missing call to bound member function?");
7828 
7829     APValue Val;
7830     if (!Evaluate(Val, Info, E->getBase()))
7831       return false;
7832 
7833     QualType BaseTy = E->getBase()->getType();
7834 
7835     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
7836     if (!FD) return Error(E);
7837     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
7838     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7839            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7840 
7841     // Note: there is no lvalue base here. But this case should only ever
7842     // happen in C or in C++98, where we cannot be evaluating a constexpr
7843     // constructor, which is the only case the base matters.
7844     CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
7845     SubobjectDesignator Designator(BaseTy);
7846     Designator.addDeclUnchecked(FD);
7847 
7848     APValue Result;
7849     return extractSubobject(Info, E, Obj, Designator, Result) &&
7850            DerivedSuccess(Result, E);
7851   }
7852 
7853   bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
7854     APValue Val;
7855     if (!Evaluate(Val, Info, E->getBase()))
7856       return false;
7857 
7858     if (Val.isVector()) {
7859       SmallVector<uint32_t, 4> Indices;
7860       E->getEncodedElementAccess(Indices);
7861       if (Indices.size() == 1) {
7862         // Return scalar.
7863         return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
7864       } else {
7865         // Construct new APValue vector.
7866         SmallVector<APValue, 4> Elts;
7867         for (unsigned I = 0; I < Indices.size(); ++I) {
7868           Elts.push_back(Val.getVectorElt(Indices[I]));
7869         }
7870         APValue VecResult(Elts.data(), Indices.size());
7871         return DerivedSuccess(VecResult, E);
7872       }
7873     }
7874 
7875     return false;
7876   }
7877 
7878   bool VisitCastExpr(const CastExpr *E) {
7879     switch (E->getCastKind()) {
7880     default:
7881       break;
7882 
7883     case CK_AtomicToNonAtomic: {
7884       APValue AtomicVal;
7885       // This does not need to be done in place even for class/array types:
7886       // atomic-to-non-atomic conversion implies copying the object
7887       // representation.
7888       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
7889         return false;
7890       return DerivedSuccess(AtomicVal, E);
7891     }
7892 
7893     case CK_NoOp:
7894     case CK_UserDefinedConversion:
7895       return StmtVisitorTy::Visit(E->getSubExpr());
7896 
7897     case CK_LValueToRValue: {
7898       LValue LVal;
7899       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
7900         return false;
7901       APValue RVal;
7902       // Note, we use the subexpression's type in order to retain cv-qualifiers.
7903       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7904                                           LVal, RVal))
7905         return false;
7906       return DerivedSuccess(RVal, E);
7907     }
7908     case CK_LValueToRValueBitCast: {
7909       APValue DestValue, SourceValue;
7910       if (!Evaluate(SourceValue, Info, E->getSubExpr()))
7911         return false;
7912       if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
7913         return false;
7914       return DerivedSuccess(DestValue, E);
7915     }
7916 
7917     case CK_AddressSpaceConversion: {
7918       APValue Value;
7919       if (!Evaluate(Value, Info, E->getSubExpr()))
7920         return false;
7921       return DerivedSuccess(Value, E);
7922     }
7923     }
7924 
7925     return Error(E);
7926   }
7927 
7928   bool VisitUnaryPostInc(const UnaryOperator *UO) {
7929     return VisitUnaryPostIncDec(UO);
7930   }
7931   bool VisitUnaryPostDec(const UnaryOperator *UO) {
7932     return VisitUnaryPostIncDec(UO);
7933   }
7934   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
7935     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7936       return Error(UO);
7937 
7938     LValue LVal;
7939     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
7940       return false;
7941     APValue RVal;
7942     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
7943                       UO->isIncrementOp(), &RVal))
7944       return false;
7945     return DerivedSuccess(RVal, UO);
7946   }
7947 
7948   bool VisitStmtExpr(const StmtExpr *E) {
7949     // We will have checked the full-expressions inside the statement expression
7950     // when they were completed, and don't need to check them again now.
7951     llvm::SaveAndRestore<bool> NotCheckingForUB(
7952         Info.CheckingForUndefinedBehavior, false);
7953 
7954     const CompoundStmt *CS = E->getSubStmt();
7955     if (CS->body_empty())
7956       return true;
7957 
7958     BlockScopeRAII Scope(Info);
7959     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
7960                                            BE = CS->body_end();
7961          /**/; ++BI) {
7962       if (BI + 1 == BE) {
7963         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
7964         if (!FinalExpr) {
7965           Info.FFDiag((*BI)->getBeginLoc(),
7966                       diag::note_constexpr_stmt_expr_unsupported);
7967           return false;
7968         }
7969         return this->Visit(FinalExpr) && Scope.destroy();
7970       }
7971 
7972       APValue ReturnValue;
7973       StmtResult Result = { ReturnValue, nullptr };
7974       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
7975       if (ESR != ESR_Succeeded) {
7976         // FIXME: If the statement-expression terminated due to 'return',
7977         // 'break', or 'continue', it would be nice to propagate that to
7978         // the outer statement evaluation rather than bailing out.
7979         if (ESR != ESR_Failed)
7980           Info.FFDiag((*BI)->getBeginLoc(),
7981                       diag::note_constexpr_stmt_expr_unsupported);
7982         return false;
7983       }
7984     }
7985 
7986     llvm_unreachable("Return from function from the loop above.");
7987   }
7988 
7989   /// Visit a value which is evaluated, but whose value is ignored.
7990   void VisitIgnoredValue(const Expr *E) {
7991     EvaluateIgnoredValue(Info, E);
7992   }
7993 
7994   /// Potentially visit a MemberExpr's base expression.
7995   void VisitIgnoredBaseExpression(const Expr *E) {
7996     // While MSVC doesn't evaluate the base expression, it does diagnose the
7997     // presence of side-effecting behavior.
7998     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
7999       return;
8000     VisitIgnoredValue(E);
8001   }
8002 };
8003 
8004 } // namespace
8005 
8006 //===----------------------------------------------------------------------===//
8007 // Common base class for lvalue and temporary evaluation.
8008 //===----------------------------------------------------------------------===//
8009 namespace {
8010 template<class Derived>
8011 class LValueExprEvaluatorBase
8012   : public ExprEvaluatorBase<Derived> {
8013 protected:
8014   LValue &Result;
8015   bool InvalidBaseOK;
8016   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
8017   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
8018 
8019   bool Success(APValue::LValueBase B) {
8020     Result.set(B);
8021     return true;
8022   }
8023 
8024   bool evaluatePointer(const Expr *E, LValue &Result) {
8025     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
8026   }
8027 
8028 public:
8029   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
8030       : ExprEvaluatorBaseTy(Info), Result(Result),
8031         InvalidBaseOK(InvalidBaseOK) {}
8032 
8033   bool Success(const APValue &V, const Expr *E) {
8034     Result.setFrom(this->Info.Ctx, V);
8035     return true;
8036   }
8037 
8038   bool VisitMemberExpr(const MemberExpr *E) {
8039     // Handle non-static data members.
8040     QualType BaseTy;
8041     bool EvalOK;
8042     if (E->isArrow()) {
8043       EvalOK = evaluatePointer(E->getBase(), Result);
8044       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
8045     } else if (E->getBase()->isPRValue()) {
8046       assert(E->getBase()->getType()->isRecordType());
8047       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
8048       BaseTy = E->getBase()->getType();
8049     } else {
8050       EvalOK = this->Visit(E->getBase());
8051       BaseTy = E->getBase()->getType();
8052     }
8053     if (!EvalOK) {
8054       if (!InvalidBaseOK)
8055         return false;
8056       Result.setInvalid(E);
8057       return true;
8058     }
8059 
8060     const ValueDecl *MD = E->getMemberDecl();
8061     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
8062       assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8063              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8064       (void)BaseTy;
8065       if (!HandleLValueMember(this->Info, E, Result, FD))
8066         return false;
8067     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
8068       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
8069         return false;
8070     } else
8071       return this->Error(E);
8072 
8073     if (MD->getType()->isReferenceType()) {
8074       APValue RefValue;
8075       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
8076                                           RefValue))
8077         return false;
8078       return Success(RefValue, E);
8079     }
8080     return true;
8081   }
8082 
8083   bool VisitBinaryOperator(const BinaryOperator *E) {
8084     switch (E->getOpcode()) {
8085     default:
8086       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8087 
8088     case BO_PtrMemD:
8089     case BO_PtrMemI:
8090       return HandleMemberPointerAccess(this->Info, E, Result);
8091     }
8092   }
8093 
8094   bool VisitCastExpr(const CastExpr *E) {
8095     switch (E->getCastKind()) {
8096     default:
8097       return ExprEvaluatorBaseTy::VisitCastExpr(E);
8098 
8099     case CK_DerivedToBase:
8100     case CK_UncheckedDerivedToBase:
8101       if (!this->Visit(E->getSubExpr()))
8102         return false;
8103 
8104       // Now figure out the necessary offset to add to the base LV to get from
8105       // the derived class to the base class.
8106       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8107                                   Result);
8108     }
8109   }
8110 };
8111 }
8112 
8113 //===----------------------------------------------------------------------===//
8114 // LValue Evaluation
8115 //
8116 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8117 // function designators (in C), decl references to void objects (in C), and
8118 // temporaries (if building with -Wno-address-of-temporary).
8119 //
8120 // LValue evaluation produces values comprising a base expression of one of the
8121 // following types:
8122 // - Declarations
8123 //  * VarDecl
8124 //  * FunctionDecl
8125 // - Literals
8126 //  * CompoundLiteralExpr in C (and in global scope in C++)
8127 //  * StringLiteral
8128 //  * PredefinedExpr
8129 //  * ObjCStringLiteralExpr
8130 //  * ObjCEncodeExpr
8131 //  * AddrLabelExpr
8132 //  * BlockExpr
8133 //  * CallExpr for a MakeStringConstant builtin
8134 // - typeid(T) expressions, as TypeInfoLValues
8135 // - Locals and temporaries
8136 //  * MaterializeTemporaryExpr
8137 //  * Any Expr, with a CallIndex indicating the function in which the temporary
8138 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
8139 //    from the AST (FIXME).
8140 //  * A MaterializeTemporaryExpr that has static storage duration, with no
8141 //    CallIndex, for a lifetime-extended temporary.
8142 //  * The ConstantExpr that is currently being evaluated during evaluation of an
8143 //    immediate invocation.
8144 // plus an offset in bytes.
8145 //===----------------------------------------------------------------------===//
8146 namespace {
8147 class LValueExprEvaluator
8148   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8149 public:
8150   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8151     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8152 
8153   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8154   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8155 
8156   bool VisitCallExpr(const CallExpr *E);
8157   bool VisitDeclRefExpr(const DeclRefExpr *E);
8158   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8159   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8160   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8161   bool VisitMemberExpr(const MemberExpr *E);
8162   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
8163   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8164   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8165   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8166   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8167   bool VisitUnaryDeref(const UnaryOperator *E);
8168   bool VisitUnaryReal(const UnaryOperator *E);
8169   bool VisitUnaryImag(const UnaryOperator *E);
8170   bool VisitUnaryPreInc(const UnaryOperator *UO) {
8171     return VisitUnaryPreIncDec(UO);
8172   }
8173   bool VisitUnaryPreDec(const UnaryOperator *UO) {
8174     return VisitUnaryPreIncDec(UO);
8175   }
8176   bool VisitBinAssign(const BinaryOperator *BO);
8177   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8178 
8179   bool VisitCastExpr(const CastExpr *E) {
8180     switch (E->getCastKind()) {
8181     default:
8182       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8183 
8184     case CK_LValueBitCast:
8185       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8186       if (!Visit(E->getSubExpr()))
8187         return false;
8188       Result.Designator.setInvalid();
8189       return true;
8190 
8191     case CK_BaseToDerived:
8192       if (!Visit(E->getSubExpr()))
8193         return false;
8194       return HandleBaseToDerivedCast(Info, E, Result);
8195 
8196     case CK_Dynamic:
8197       if (!Visit(E->getSubExpr()))
8198         return false;
8199       return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8200     }
8201   }
8202 };
8203 } // end anonymous namespace
8204 
8205 /// Evaluate an expression as an lvalue. This can be legitimately called on
8206 /// expressions which are not glvalues, in three cases:
8207 ///  * function designators in C, and
8208 ///  * "extern void" objects
8209 ///  * @selector() expressions in Objective-C
8210 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
8211                            bool InvalidBaseOK) {
8212   assert(!E->isValueDependent());
8213   assert(E->isGLValue() || E->getType()->isFunctionType() ||
8214          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
8215   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8216 }
8217 
8218 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
8219   const NamedDecl *D = E->getDecl();
8220   if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl,
8221           UnnamedGlobalConstantDecl>(D))
8222     return Success(cast<ValueDecl>(D));
8223   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
8224     return VisitVarDecl(E, VD);
8225   if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
8226     return Visit(BD->getBinding());
8227   return Error(E);
8228 }
8229 
8230 
8231 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
8232 
8233   // If we are within a lambda's call operator, check whether the 'VD' referred
8234   // to within 'E' actually represents a lambda-capture that maps to a
8235   // data-member/field within the closure object, and if so, evaluate to the
8236   // field or what the field refers to.
8237   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
8238       isa<DeclRefExpr>(E) &&
8239       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
8240     // We don't always have a complete capture-map when checking or inferring if
8241     // the function call operator meets the requirements of a constexpr function
8242     // - but we don't need to evaluate the captures to determine constexprness
8243     // (dcl.constexpr C++17).
8244     if (Info.checkingPotentialConstantExpression())
8245       return false;
8246 
8247     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
8248       // Start with 'Result' referring to the complete closure object...
8249       Result = *Info.CurrentCall->This;
8250       // ... then update it to refer to the field of the closure object
8251       // that represents the capture.
8252       if (!HandleLValueMember(Info, E, Result, FD))
8253         return false;
8254       // And if the field is of reference type, update 'Result' to refer to what
8255       // the field refers to.
8256       if (FD->getType()->isReferenceType()) {
8257         APValue RVal;
8258         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
8259                                             RVal))
8260           return false;
8261         Result.setFrom(Info.Ctx, RVal);
8262       }
8263       return true;
8264     }
8265   }
8266 
8267   CallStackFrame *Frame = nullptr;
8268   unsigned Version = 0;
8269   if (VD->hasLocalStorage()) {
8270     // Only if a local variable was declared in the function currently being
8271     // evaluated, do we expect to be able to find its value in the current
8272     // frame. (Otherwise it was likely declared in an enclosing context and
8273     // could either have a valid evaluatable value (for e.g. a constexpr
8274     // variable) or be ill-formed (and trigger an appropriate evaluation
8275     // diagnostic)).
8276     CallStackFrame *CurrFrame = Info.CurrentCall;
8277     if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
8278       // Function parameters are stored in some caller's frame. (Usually the
8279       // immediate caller, but for an inherited constructor they may be more
8280       // distant.)
8281       if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
8282         if (CurrFrame->Arguments) {
8283           VD = CurrFrame->Arguments.getOrigParam(PVD);
8284           Frame =
8285               Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
8286           Version = CurrFrame->Arguments.Version;
8287         }
8288       } else {
8289         Frame = CurrFrame;
8290         Version = CurrFrame->getCurrentTemporaryVersion(VD);
8291       }
8292     }
8293   }
8294 
8295   if (!VD->getType()->isReferenceType()) {
8296     if (Frame) {
8297       Result.set({VD, Frame->Index, Version});
8298       return true;
8299     }
8300     return Success(VD);
8301   }
8302 
8303   if (!Info.getLangOpts().CPlusPlus11) {
8304     Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
8305         << VD << VD->getType();
8306     Info.Note(VD->getLocation(), diag::note_declared_at);
8307   }
8308 
8309   APValue *V;
8310   if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
8311     return false;
8312   if (!V->hasValue()) {
8313     // FIXME: Is it possible for V to be indeterminate here? If so, we should
8314     // adjust the diagnostic to say that.
8315     if (!Info.checkingPotentialConstantExpression())
8316       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
8317     return false;
8318   }
8319   return Success(*V, E);
8320 }
8321 
8322 bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {
8323   switch (E->getBuiltinCallee()) {
8324   case Builtin::BIas_const:
8325   case Builtin::BIforward:
8326   case Builtin::BImove:
8327   case Builtin::BImove_if_noexcept:
8328     if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())
8329       return Visit(E->getArg(0));
8330     break;
8331   }
8332 
8333   return ExprEvaluatorBaseTy::VisitCallExpr(E);
8334 }
8335 
8336 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
8337     const MaterializeTemporaryExpr *E) {
8338   // Walk through the expression to find the materialized temporary itself.
8339   SmallVector<const Expr *, 2> CommaLHSs;
8340   SmallVector<SubobjectAdjustment, 2> Adjustments;
8341   const Expr *Inner =
8342       E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
8343 
8344   // If we passed any comma operators, evaluate their LHSs.
8345   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
8346     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
8347       return false;
8348 
8349   // A materialized temporary with static storage duration can appear within the
8350   // result of a constant expression evaluation, so we need to preserve its
8351   // value for use outside this evaluation.
8352   APValue *Value;
8353   if (E->getStorageDuration() == SD_Static) {
8354     // FIXME: What about SD_Thread?
8355     Value = E->getOrCreateValue(true);
8356     *Value = APValue();
8357     Result.set(E);
8358   } else {
8359     Value = &Info.CurrentCall->createTemporary(
8360         E, E->getType(),
8361         E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
8362                                                      : ScopeKind::Block,
8363         Result);
8364   }
8365 
8366   QualType Type = Inner->getType();
8367 
8368   // Materialize the temporary itself.
8369   if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
8370     *Value = APValue();
8371     return false;
8372   }
8373 
8374   // Adjust our lvalue to refer to the desired subobject.
8375   for (unsigned I = Adjustments.size(); I != 0; /**/) {
8376     --I;
8377     switch (Adjustments[I].Kind) {
8378     case SubobjectAdjustment::DerivedToBaseAdjustment:
8379       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
8380                                 Type, Result))
8381         return false;
8382       Type = Adjustments[I].DerivedToBase.BasePath->getType();
8383       break;
8384 
8385     case SubobjectAdjustment::FieldAdjustment:
8386       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
8387         return false;
8388       Type = Adjustments[I].Field->getType();
8389       break;
8390 
8391     case SubobjectAdjustment::MemberPointerAdjustment:
8392       if (!HandleMemberPointerAccess(this->Info, Type, Result,
8393                                      Adjustments[I].Ptr.RHS))
8394         return false;
8395       Type = Adjustments[I].Ptr.MPT->getPointeeType();
8396       break;
8397     }
8398   }
8399 
8400   return true;
8401 }
8402 
8403 bool
8404 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8405   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
8406          "lvalue compound literal in c++?");
8407   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
8408   // only see this when folding in C, so there's no standard to follow here.
8409   return Success(E);
8410 }
8411 
8412 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
8413   TypeInfoLValue TypeInfo;
8414 
8415   if (!E->isPotentiallyEvaluated()) {
8416     if (E->isTypeOperand())
8417       TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
8418     else
8419       TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
8420   } else {
8421     if (!Info.Ctx.getLangOpts().CPlusPlus20) {
8422       Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
8423         << E->getExprOperand()->getType()
8424         << E->getExprOperand()->getSourceRange();
8425     }
8426 
8427     if (!Visit(E->getExprOperand()))
8428       return false;
8429 
8430     Optional<DynamicType> DynType =
8431         ComputeDynamicType(Info, E, Result, AK_TypeId);
8432     if (!DynType)
8433       return false;
8434 
8435     TypeInfo =
8436         TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
8437   }
8438 
8439   return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
8440 }
8441 
8442 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
8443   return Success(E->getGuidDecl());
8444 }
8445 
8446 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
8447   // Handle static data members.
8448   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
8449     VisitIgnoredBaseExpression(E->getBase());
8450     return VisitVarDecl(E, VD);
8451   }
8452 
8453   // Handle static member functions.
8454   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
8455     if (MD->isStatic()) {
8456       VisitIgnoredBaseExpression(E->getBase());
8457       return Success(MD);
8458     }
8459   }
8460 
8461   // Handle non-static data members.
8462   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
8463 }
8464 
8465 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
8466   // FIXME: Deal with vectors as array subscript bases.
8467   if (E->getBase()->getType()->isVectorType() ||
8468       E->getBase()->getType()->isVLSTBuiltinType())
8469     return Error(E);
8470 
8471   APSInt Index;
8472   bool Success = true;
8473 
8474   // C++17's rules require us to evaluate the LHS first, regardless of which
8475   // side is the base.
8476   for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
8477     if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
8478                                 : !EvaluateInteger(SubExpr, Index, Info)) {
8479       if (!Info.noteFailure())
8480         return false;
8481       Success = false;
8482     }
8483   }
8484 
8485   return Success &&
8486          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
8487 }
8488 
8489 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
8490   return evaluatePointer(E->getSubExpr(), Result);
8491 }
8492 
8493 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8494   if (!Visit(E->getSubExpr()))
8495     return false;
8496   // __real is a no-op on scalar lvalues.
8497   if (E->getSubExpr()->getType()->isAnyComplexType())
8498     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
8499   return true;
8500 }
8501 
8502 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8503   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
8504          "lvalue __imag__ on scalar?");
8505   if (!Visit(E->getSubExpr()))
8506     return false;
8507   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
8508   return true;
8509 }
8510 
8511 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
8512   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8513     return Error(UO);
8514 
8515   if (!this->Visit(UO->getSubExpr()))
8516     return false;
8517 
8518   return handleIncDec(
8519       this->Info, UO, Result, UO->getSubExpr()->getType(),
8520       UO->isIncrementOp(), nullptr);
8521 }
8522 
8523 bool LValueExprEvaluator::VisitCompoundAssignOperator(
8524     const CompoundAssignOperator *CAO) {
8525   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8526     return Error(CAO);
8527 
8528   bool Success = true;
8529 
8530   // C++17 onwards require that we evaluate the RHS first.
8531   APValue RHS;
8532   if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
8533     if (!Info.noteFailure())
8534       return false;
8535     Success = false;
8536   }
8537 
8538   // The overall lvalue result is the result of evaluating the LHS.
8539   if (!this->Visit(CAO->getLHS()) || !Success)
8540     return false;
8541 
8542   return handleCompoundAssignment(
8543       this->Info, CAO,
8544       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
8545       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
8546 }
8547 
8548 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
8549   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8550     return Error(E);
8551 
8552   bool Success = true;
8553 
8554   // C++17 onwards require that we evaluate the RHS first.
8555   APValue NewVal;
8556   if (!Evaluate(NewVal, this->Info, E->getRHS())) {
8557     if (!Info.noteFailure())
8558       return false;
8559     Success = false;
8560   }
8561 
8562   if (!this->Visit(E->getLHS()) || !Success)
8563     return false;
8564 
8565   if (Info.getLangOpts().CPlusPlus20 &&
8566       !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
8567     return false;
8568 
8569   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
8570                           NewVal);
8571 }
8572 
8573 //===----------------------------------------------------------------------===//
8574 // Pointer Evaluation
8575 //===----------------------------------------------------------------------===//
8576 
8577 /// Attempts to compute the number of bytes available at the pointer
8578 /// returned by a function with the alloc_size attribute. Returns true if we
8579 /// were successful. Places an unsigned number into `Result`.
8580 ///
8581 /// This expects the given CallExpr to be a call to a function with an
8582 /// alloc_size attribute.
8583 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8584                                             const CallExpr *Call,
8585                                             llvm::APInt &Result) {
8586   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
8587 
8588   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
8589   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
8590   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
8591   if (Call->getNumArgs() <= SizeArgNo)
8592     return false;
8593 
8594   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
8595     Expr::EvalResult ExprResult;
8596     if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
8597       return false;
8598     Into = ExprResult.Val.getInt();
8599     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
8600       return false;
8601     Into = Into.zext(BitsInSizeT);
8602     return true;
8603   };
8604 
8605   APSInt SizeOfElem;
8606   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
8607     return false;
8608 
8609   if (!AllocSize->getNumElemsParam().isValid()) {
8610     Result = std::move(SizeOfElem);
8611     return true;
8612   }
8613 
8614   APSInt NumberOfElems;
8615   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
8616   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
8617     return false;
8618 
8619   bool Overflow;
8620   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
8621   if (Overflow)
8622     return false;
8623 
8624   Result = std::move(BytesAvailable);
8625   return true;
8626 }
8627 
8628 /// Convenience function. LVal's base must be a call to an alloc_size
8629 /// function.
8630 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8631                                             const LValue &LVal,
8632                                             llvm::APInt &Result) {
8633   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8634          "Can't get the size of a non alloc_size function");
8635   const auto *Base = LVal.getLValueBase().get<const Expr *>();
8636   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
8637   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
8638 }
8639 
8640 /// Attempts to evaluate the given LValueBase as the result of a call to
8641 /// a function with the alloc_size attribute. If it was possible to do so, this
8642 /// function will return true, make Result's Base point to said function call,
8643 /// and mark Result's Base as invalid.
8644 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
8645                                       LValue &Result) {
8646   if (Base.isNull())
8647     return false;
8648 
8649   // Because we do no form of static analysis, we only support const variables.
8650   //
8651   // Additionally, we can't support parameters, nor can we support static
8652   // variables (in the latter case, use-before-assign isn't UB; in the former,
8653   // we have no clue what they'll be assigned to).
8654   const auto *VD =
8655       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
8656   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
8657     return false;
8658 
8659   const Expr *Init = VD->getAnyInitializer();
8660   if (!Init || Init->getType().isNull())
8661     return false;
8662 
8663   const Expr *E = Init->IgnoreParens();
8664   if (!tryUnwrapAllocSizeCall(E))
8665     return false;
8666 
8667   // Store E instead of E unwrapped so that the type of the LValue's base is
8668   // what the user wanted.
8669   Result.setInvalid(E);
8670 
8671   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
8672   Result.addUnsizedArray(Info, E, Pointee);
8673   return true;
8674 }
8675 
8676 namespace {
8677 class PointerExprEvaluator
8678   : public ExprEvaluatorBase<PointerExprEvaluator> {
8679   LValue &Result;
8680   bool InvalidBaseOK;
8681 
8682   bool Success(const Expr *E) {
8683     Result.set(E);
8684     return true;
8685   }
8686 
8687   bool evaluateLValue(const Expr *E, LValue &Result) {
8688     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
8689   }
8690 
8691   bool evaluatePointer(const Expr *E, LValue &Result) {
8692     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
8693   }
8694 
8695   bool visitNonBuiltinCallExpr(const CallExpr *E);
8696 public:
8697 
8698   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
8699       : ExprEvaluatorBaseTy(info), Result(Result),
8700         InvalidBaseOK(InvalidBaseOK) {}
8701 
8702   bool Success(const APValue &V, const Expr *E) {
8703     Result.setFrom(Info.Ctx, V);
8704     return true;
8705   }
8706   bool ZeroInitialization(const Expr *E) {
8707     Result.setNull(Info.Ctx, E->getType());
8708     return true;
8709   }
8710 
8711   bool VisitBinaryOperator(const BinaryOperator *E);
8712   bool VisitCastExpr(const CastExpr* E);
8713   bool VisitUnaryAddrOf(const UnaryOperator *E);
8714   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
8715       { return Success(E); }
8716   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
8717     if (E->isExpressibleAsConstantInitializer())
8718       return Success(E);
8719     if (Info.noteFailure())
8720       EvaluateIgnoredValue(Info, E->getSubExpr());
8721     return Error(E);
8722   }
8723   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
8724       { return Success(E); }
8725   bool VisitCallExpr(const CallExpr *E);
8726   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
8727   bool VisitBlockExpr(const BlockExpr *E) {
8728     if (!E->getBlockDecl()->hasCaptures())
8729       return Success(E);
8730     return Error(E);
8731   }
8732   bool VisitCXXThisExpr(const CXXThisExpr *E) {
8733     // Can't look at 'this' when checking a potential constant expression.
8734     if (Info.checkingPotentialConstantExpression())
8735       return false;
8736     if (!Info.CurrentCall->This) {
8737       if (Info.getLangOpts().CPlusPlus11)
8738         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
8739       else
8740         Info.FFDiag(E);
8741       return false;
8742     }
8743     Result = *Info.CurrentCall->This;
8744     // If we are inside a lambda's call operator, the 'this' expression refers
8745     // to the enclosing '*this' object (either by value or reference) which is
8746     // either copied into the closure object's field that represents the '*this'
8747     // or refers to '*this'.
8748     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
8749       // Ensure we actually have captured 'this'. (an error will have
8750       // been previously reported if not).
8751       if (!Info.CurrentCall->LambdaThisCaptureField)
8752         return false;
8753 
8754       // Update 'Result' to refer to the data member/field of the closure object
8755       // that represents the '*this' capture.
8756       if (!HandleLValueMember(Info, E, Result,
8757                              Info.CurrentCall->LambdaThisCaptureField))
8758         return false;
8759       // If we captured '*this' by reference, replace the field with its referent.
8760       if (Info.CurrentCall->LambdaThisCaptureField->getType()
8761               ->isPointerType()) {
8762         APValue RVal;
8763         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
8764                                             RVal))
8765           return false;
8766 
8767         Result.setFrom(Info.Ctx, RVal);
8768       }
8769     }
8770     return true;
8771   }
8772 
8773   bool VisitCXXNewExpr(const CXXNewExpr *E);
8774 
8775   bool VisitSourceLocExpr(const SourceLocExpr *E) {
8776     assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
8777     APValue LValResult = E->EvaluateInContext(
8778         Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8779     Result.setFrom(Info.Ctx, LValResult);
8780     return true;
8781   }
8782 
8783   bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
8784     std::string ResultStr = E->ComputeName(Info.Ctx);
8785 
8786     QualType CharTy = Info.Ctx.CharTy.withConst();
8787     APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
8788                ResultStr.size() + 1);
8789     QualType ArrayTy = Info.Ctx.getConstantArrayType(CharTy, Size, nullptr,
8790                                                      ArrayType::Normal, 0);
8791 
8792     StringLiteral *SL =
8793         StringLiteral::Create(Info.Ctx, ResultStr, StringLiteral::Ordinary,
8794                               /*Pascal*/ false, ArrayTy, E->getLocation());
8795 
8796     evaluateLValue(SL, Result);
8797     Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
8798     return true;
8799   }
8800 
8801   // FIXME: Missing: @protocol, @selector
8802 };
8803 } // end anonymous namespace
8804 
8805 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
8806                             bool InvalidBaseOK) {
8807   assert(!E->isValueDependent());
8808   assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
8809   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8810 }
8811 
8812 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8813   if (E->getOpcode() != BO_Add &&
8814       E->getOpcode() != BO_Sub)
8815     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8816 
8817   const Expr *PExp = E->getLHS();
8818   const Expr *IExp = E->getRHS();
8819   if (IExp->getType()->isPointerType())
8820     std::swap(PExp, IExp);
8821 
8822   bool EvalPtrOK = evaluatePointer(PExp, Result);
8823   if (!EvalPtrOK && !Info.noteFailure())
8824     return false;
8825 
8826   llvm::APSInt Offset;
8827   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
8828     return false;
8829 
8830   if (E->getOpcode() == BO_Sub)
8831     negateAsSigned(Offset);
8832 
8833   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
8834   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
8835 }
8836 
8837 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8838   return evaluateLValue(E->getSubExpr(), Result);
8839 }
8840 
8841 // Is the provided decl 'std::source_location::current'?
8842 static bool IsDeclSourceLocationCurrent(const FunctionDecl *FD) {
8843   if (!FD)
8844     return false;
8845   const IdentifierInfo *FnII = FD->getIdentifier();
8846   if (!FnII || !FnII->isStr("current"))
8847     return false;
8848 
8849   const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
8850   if (!RD)
8851     return false;
8852 
8853   const IdentifierInfo *ClassII = RD->getIdentifier();
8854   return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
8855 }
8856 
8857 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8858   const Expr *SubExpr = E->getSubExpr();
8859 
8860   switch (E->getCastKind()) {
8861   default:
8862     break;
8863   case CK_BitCast:
8864   case CK_CPointerToObjCPointerCast:
8865   case CK_BlockPointerToObjCPointerCast:
8866   case CK_AnyPointerToBlockPointerCast:
8867   case CK_AddressSpaceConversion:
8868     if (!Visit(SubExpr))
8869       return false;
8870     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
8871     // permitted in constant expressions in C++11. Bitcasts from cv void* are
8872     // also static_casts, but we disallow them as a resolution to DR1312.
8873     if (!E->getType()->isVoidPointerType()) {
8874       // In some circumstances, we permit casting from void* to cv1 T*, when the
8875       // actual pointee object is actually a cv2 T.
8876       bool VoidPtrCastMaybeOK =
8877           !Result.InvalidBase && !Result.Designator.Invalid &&
8878           !Result.IsNullPtr &&
8879           Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
8880                                           E->getType()->getPointeeType());
8881       // 1. We'll allow it in std::allocator::allocate, and anything which that
8882       //    calls.
8883       // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
8884       //    <source_location> header. Fixed in GCC 12 and later (2022-04-??).
8885       //    We'll allow it in the body of std::source_location::current.  GCC's
8886       //    implementation had a parameter of type `void*`, and casts from
8887       //    that back to `const __impl*` in its body.
8888       if (VoidPtrCastMaybeOK &&
8889           (Info.getStdAllocatorCaller("allocate") ||
8890            IsDeclSourceLocationCurrent(Info.CurrentCall->Callee))) {
8891         // Permitted.
8892       } else {
8893         Result.Designator.setInvalid();
8894         if (SubExpr->getType()->isVoidPointerType())
8895           CCEDiag(E, diag::note_constexpr_invalid_cast)
8896             << 3 << SubExpr->getType();
8897         else
8898           CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8899       }
8900     }
8901     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
8902       ZeroInitialization(E);
8903     return true;
8904 
8905   case CK_DerivedToBase:
8906   case CK_UncheckedDerivedToBase:
8907     if (!evaluatePointer(E->getSubExpr(), Result))
8908       return false;
8909     if (!Result.Base && Result.Offset.isZero())
8910       return true;
8911 
8912     // Now figure out the necessary offset to add to the base LV to get from
8913     // the derived class to the base class.
8914     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
8915                                   castAs<PointerType>()->getPointeeType(),
8916                                 Result);
8917 
8918   case CK_BaseToDerived:
8919     if (!Visit(E->getSubExpr()))
8920       return false;
8921     if (!Result.Base && Result.Offset.isZero())
8922       return true;
8923     return HandleBaseToDerivedCast(Info, E, Result);
8924 
8925   case CK_Dynamic:
8926     if (!Visit(E->getSubExpr()))
8927       return false;
8928     return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8929 
8930   case CK_NullToPointer:
8931     VisitIgnoredValue(E->getSubExpr());
8932     return ZeroInitialization(E);
8933 
8934   case CK_IntegralToPointer: {
8935     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8936 
8937     APValue Value;
8938     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
8939       break;
8940 
8941     if (Value.isInt()) {
8942       unsigned Size = Info.Ctx.getTypeSize(E->getType());
8943       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
8944       Result.Base = (Expr*)nullptr;
8945       Result.InvalidBase = false;
8946       Result.Offset = CharUnits::fromQuantity(N);
8947       Result.Designator.setInvalid();
8948       Result.IsNullPtr = false;
8949       return true;
8950     } else {
8951       // Cast is of an lvalue, no need to change value.
8952       Result.setFrom(Info.Ctx, Value);
8953       return true;
8954     }
8955   }
8956 
8957   case CK_ArrayToPointerDecay: {
8958     if (SubExpr->isGLValue()) {
8959       if (!evaluateLValue(SubExpr, Result))
8960         return false;
8961     } else {
8962       APValue &Value = Info.CurrentCall->createTemporary(
8963           SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
8964       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
8965         return false;
8966     }
8967     // The result is a pointer to the first element of the array.
8968     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
8969     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
8970       Result.addArray(Info, E, CAT);
8971     else
8972       Result.addUnsizedArray(Info, E, AT->getElementType());
8973     return true;
8974   }
8975 
8976   case CK_FunctionToPointerDecay:
8977     return evaluateLValue(SubExpr, Result);
8978 
8979   case CK_LValueToRValue: {
8980     LValue LVal;
8981     if (!evaluateLValue(E->getSubExpr(), LVal))
8982       return false;
8983 
8984     APValue RVal;
8985     // Note, we use the subexpression's type in order to retain cv-qualifiers.
8986     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8987                                         LVal, RVal))
8988       return InvalidBaseOK &&
8989              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
8990     return Success(RVal, E);
8991   }
8992   }
8993 
8994   return ExprEvaluatorBaseTy::VisitCastExpr(E);
8995 }
8996 
8997 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
8998                                 UnaryExprOrTypeTrait ExprKind) {
8999   // C++ [expr.alignof]p3:
9000   //     When alignof is applied to a reference type, the result is the
9001   //     alignment of the referenced type.
9002   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
9003     T = Ref->getPointeeType();
9004 
9005   if (T.getQualifiers().hasUnaligned())
9006     return CharUnits::One();
9007 
9008   const bool AlignOfReturnsPreferred =
9009       Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
9010 
9011   // __alignof is defined to return the preferred alignment.
9012   // Before 8, clang returned the preferred alignment for alignof and _Alignof
9013   // as well.
9014   if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
9015     return Info.Ctx.toCharUnitsFromBits(
9016       Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
9017   // alignof and _Alignof are defined to return the ABI alignment.
9018   else if (ExprKind == UETT_AlignOf)
9019     return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
9020   else
9021     llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
9022 }
9023 
9024 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
9025                                 UnaryExprOrTypeTrait ExprKind) {
9026   E = E->IgnoreParens();
9027 
9028   // The kinds of expressions that we have special-case logic here for
9029   // should be kept up to date with the special checks for those
9030   // expressions in Sema.
9031 
9032   // alignof decl is always accepted, even if it doesn't make sense: we default
9033   // to 1 in those cases.
9034   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9035     return Info.Ctx.getDeclAlign(DRE->getDecl(),
9036                                  /*RefAsPointee*/true);
9037 
9038   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
9039     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
9040                                  /*RefAsPointee*/true);
9041 
9042   return GetAlignOfType(Info, E->getType(), ExprKind);
9043 }
9044 
9045 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
9046   if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
9047     return Info.Ctx.getDeclAlign(VD);
9048   if (const auto *E = Value.Base.dyn_cast<const Expr *>())
9049     return GetAlignOfExpr(Info, E, UETT_AlignOf);
9050   return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
9051 }
9052 
9053 /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
9054 /// __builtin_is_aligned and __builtin_assume_aligned.
9055 static bool getAlignmentArgument(const Expr *E, QualType ForType,
9056                                  EvalInfo &Info, APSInt &Alignment) {
9057   if (!EvaluateInteger(E, Alignment, Info))
9058     return false;
9059   if (Alignment < 0 || !Alignment.isPowerOf2()) {
9060     Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
9061     return false;
9062   }
9063   unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
9064   APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
9065   if (APSInt::compareValues(Alignment, MaxValue) > 0) {
9066     Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
9067         << MaxValue << ForType << Alignment;
9068     return false;
9069   }
9070   // Ensure both alignment and source value have the same bit width so that we
9071   // don't assert when computing the resulting value.
9072   APSInt ExtAlignment =
9073       APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
9074   assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
9075          "Alignment should not be changed by ext/trunc");
9076   Alignment = ExtAlignment;
9077   assert(Alignment.getBitWidth() == SrcWidth);
9078   return true;
9079 }
9080 
9081 // To be clear: this happily visits unsupported builtins. Better name welcomed.
9082 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
9083   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
9084     return true;
9085 
9086   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
9087     return false;
9088 
9089   Result.setInvalid(E);
9090   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
9091   Result.addUnsizedArray(Info, E, PointeeTy);
9092   return true;
9093 }
9094 
9095 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
9096   if (IsConstantCall(E))
9097     return Success(E);
9098 
9099   if (unsigned BuiltinOp = E->getBuiltinCallee())
9100     return VisitBuiltinCallExpr(E, BuiltinOp);
9101 
9102   return visitNonBuiltinCallExpr(E);
9103 }
9104 
9105 // Determine if T is a character type for which we guarantee that
9106 // sizeof(T) == 1.
9107 static bool isOneByteCharacterType(QualType T) {
9108   return T->isCharType() || T->isChar8Type();
9109 }
9110 
9111 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
9112                                                 unsigned BuiltinOp) {
9113   switch (BuiltinOp) {
9114   case Builtin::BIaddressof:
9115   case Builtin::BI__addressof:
9116   case Builtin::BI__builtin_addressof:
9117     return evaluateLValue(E->getArg(0), Result);
9118   case Builtin::BI__builtin_assume_aligned: {
9119     // We need to be very careful here because: if the pointer does not have the
9120     // asserted alignment, then the behavior is undefined, and undefined
9121     // behavior is non-constant.
9122     if (!evaluatePointer(E->getArg(0), Result))
9123       return false;
9124 
9125     LValue OffsetResult(Result);
9126     APSInt Alignment;
9127     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9128                               Alignment))
9129       return false;
9130     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
9131 
9132     if (E->getNumArgs() > 2) {
9133       APSInt Offset;
9134       if (!EvaluateInteger(E->getArg(2), Offset, Info))
9135         return false;
9136 
9137       int64_t AdditionalOffset = -Offset.getZExtValue();
9138       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
9139     }
9140 
9141     // If there is a base object, then it must have the correct alignment.
9142     if (OffsetResult.Base) {
9143       CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
9144 
9145       if (BaseAlignment < Align) {
9146         Result.Designator.setInvalid();
9147         // FIXME: Add support to Diagnostic for long / long long.
9148         CCEDiag(E->getArg(0),
9149                 diag::note_constexpr_baa_insufficient_alignment) << 0
9150           << (unsigned)BaseAlignment.getQuantity()
9151           << (unsigned)Align.getQuantity();
9152         return false;
9153       }
9154     }
9155 
9156     // The offset must also have the correct alignment.
9157     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
9158       Result.Designator.setInvalid();
9159 
9160       (OffsetResult.Base
9161            ? CCEDiag(E->getArg(0),
9162                      diag::note_constexpr_baa_insufficient_alignment) << 1
9163            : CCEDiag(E->getArg(0),
9164                      diag::note_constexpr_baa_value_insufficient_alignment))
9165         << (int)OffsetResult.Offset.getQuantity()
9166         << (unsigned)Align.getQuantity();
9167       return false;
9168     }
9169 
9170     return true;
9171   }
9172   case Builtin::BI__builtin_align_up:
9173   case Builtin::BI__builtin_align_down: {
9174     if (!evaluatePointer(E->getArg(0), Result))
9175       return false;
9176     APSInt Alignment;
9177     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9178                               Alignment))
9179       return false;
9180     CharUnits BaseAlignment = getBaseAlignment(Info, Result);
9181     CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
9182     // For align_up/align_down, we can return the same value if the alignment
9183     // is known to be greater or equal to the requested value.
9184     if (PtrAlign.getQuantity() >= Alignment)
9185       return true;
9186 
9187     // The alignment could be greater than the minimum at run-time, so we cannot
9188     // infer much about the resulting pointer value. One case is possible:
9189     // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
9190     // can infer the correct index if the requested alignment is smaller than
9191     // the base alignment so we can perform the computation on the offset.
9192     if (BaseAlignment.getQuantity() >= Alignment) {
9193       assert(Alignment.getBitWidth() <= 64 &&
9194              "Cannot handle > 64-bit address-space");
9195       uint64_t Alignment64 = Alignment.getZExtValue();
9196       CharUnits NewOffset = CharUnits::fromQuantity(
9197           BuiltinOp == Builtin::BI__builtin_align_down
9198               ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
9199               : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
9200       Result.adjustOffset(NewOffset - Result.Offset);
9201       // TODO: diagnose out-of-bounds values/only allow for arrays?
9202       return true;
9203     }
9204     // Otherwise, we cannot constant-evaluate the result.
9205     Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
9206         << Alignment;
9207     return false;
9208   }
9209   case Builtin::BI__builtin_operator_new:
9210     return HandleOperatorNewCall(Info, E, Result);
9211   case Builtin::BI__builtin_launder:
9212     return evaluatePointer(E->getArg(0), Result);
9213   case Builtin::BIstrchr:
9214   case Builtin::BIwcschr:
9215   case Builtin::BImemchr:
9216   case Builtin::BIwmemchr:
9217     if (Info.getLangOpts().CPlusPlus11)
9218       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9219         << /*isConstexpr*/0 << /*isConstructor*/0
9220         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9221     else
9222       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9223     LLVM_FALLTHROUGH;
9224   case Builtin::BI__builtin_strchr:
9225   case Builtin::BI__builtin_wcschr:
9226   case Builtin::BI__builtin_memchr:
9227   case Builtin::BI__builtin_char_memchr:
9228   case Builtin::BI__builtin_wmemchr: {
9229     if (!Visit(E->getArg(0)))
9230       return false;
9231     APSInt Desired;
9232     if (!EvaluateInteger(E->getArg(1), Desired, Info))
9233       return false;
9234     uint64_t MaxLength = uint64_t(-1);
9235     if (BuiltinOp != Builtin::BIstrchr &&
9236         BuiltinOp != Builtin::BIwcschr &&
9237         BuiltinOp != Builtin::BI__builtin_strchr &&
9238         BuiltinOp != Builtin::BI__builtin_wcschr) {
9239       APSInt N;
9240       if (!EvaluateInteger(E->getArg(2), N, Info))
9241         return false;
9242       MaxLength = N.getExtValue();
9243     }
9244     // We cannot find the value if there are no candidates to match against.
9245     if (MaxLength == 0u)
9246       return ZeroInitialization(E);
9247     if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9248         Result.Designator.Invalid)
9249       return false;
9250     QualType CharTy = Result.Designator.getType(Info.Ctx);
9251     bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
9252                      BuiltinOp == Builtin::BI__builtin_memchr;
9253     assert(IsRawByte ||
9254            Info.Ctx.hasSameUnqualifiedType(
9255                CharTy, E->getArg(0)->getType()->getPointeeType()));
9256     // Pointers to const void may point to objects of incomplete type.
9257     if (IsRawByte && CharTy->isIncompleteType()) {
9258       Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
9259       return false;
9260     }
9261     // Give up on byte-oriented matching against multibyte elements.
9262     // FIXME: We can compare the bytes in the correct order.
9263     if (IsRawByte && !isOneByteCharacterType(CharTy)) {
9264       Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
9265           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
9266           << CharTy;
9267       return false;
9268     }
9269     // Figure out what value we're actually looking for (after converting to
9270     // the corresponding unsigned type if necessary).
9271     uint64_t DesiredVal;
9272     bool StopAtNull = false;
9273     switch (BuiltinOp) {
9274     case Builtin::BIstrchr:
9275     case Builtin::BI__builtin_strchr:
9276       // strchr compares directly to the passed integer, and therefore
9277       // always fails if given an int that is not a char.
9278       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
9279                                                   E->getArg(1)->getType(),
9280                                                   Desired),
9281                                Desired))
9282         return ZeroInitialization(E);
9283       StopAtNull = true;
9284       LLVM_FALLTHROUGH;
9285     case Builtin::BImemchr:
9286     case Builtin::BI__builtin_memchr:
9287     case Builtin::BI__builtin_char_memchr:
9288       // memchr compares by converting both sides to unsigned char. That's also
9289       // correct for strchr if we get this far (to cope with plain char being
9290       // unsigned in the strchr case).
9291       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
9292       break;
9293 
9294     case Builtin::BIwcschr:
9295     case Builtin::BI__builtin_wcschr:
9296       StopAtNull = true;
9297       LLVM_FALLTHROUGH;
9298     case Builtin::BIwmemchr:
9299     case Builtin::BI__builtin_wmemchr:
9300       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
9301       DesiredVal = Desired.getZExtValue();
9302       break;
9303     }
9304 
9305     for (; MaxLength; --MaxLength) {
9306       APValue Char;
9307       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
9308           !Char.isInt())
9309         return false;
9310       if (Char.getInt().getZExtValue() == DesiredVal)
9311         return true;
9312       if (StopAtNull && !Char.getInt())
9313         break;
9314       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
9315         return false;
9316     }
9317     // Not found: return nullptr.
9318     return ZeroInitialization(E);
9319   }
9320 
9321   case Builtin::BImemcpy:
9322   case Builtin::BImemmove:
9323   case Builtin::BIwmemcpy:
9324   case Builtin::BIwmemmove:
9325     if (Info.getLangOpts().CPlusPlus11)
9326       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9327         << /*isConstexpr*/0 << /*isConstructor*/0
9328         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9329     else
9330       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9331     LLVM_FALLTHROUGH;
9332   case Builtin::BI__builtin_memcpy:
9333   case Builtin::BI__builtin_memmove:
9334   case Builtin::BI__builtin_wmemcpy:
9335   case Builtin::BI__builtin_wmemmove: {
9336     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
9337                  BuiltinOp == Builtin::BIwmemmove ||
9338                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
9339                  BuiltinOp == Builtin::BI__builtin_wmemmove;
9340     bool Move = BuiltinOp == Builtin::BImemmove ||
9341                 BuiltinOp == Builtin::BIwmemmove ||
9342                 BuiltinOp == Builtin::BI__builtin_memmove ||
9343                 BuiltinOp == Builtin::BI__builtin_wmemmove;
9344 
9345     // The result of mem* is the first argument.
9346     if (!Visit(E->getArg(0)))
9347       return false;
9348     LValue Dest = Result;
9349 
9350     LValue Src;
9351     if (!EvaluatePointer(E->getArg(1), Src, Info))
9352       return false;
9353 
9354     APSInt N;
9355     if (!EvaluateInteger(E->getArg(2), N, Info))
9356       return false;
9357     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
9358 
9359     // If the size is zero, we treat this as always being a valid no-op.
9360     // (Even if one of the src and dest pointers is null.)
9361     if (!N)
9362       return true;
9363 
9364     // Otherwise, if either of the operands is null, we can't proceed. Don't
9365     // try to determine the type of the copied objects, because there aren't
9366     // any.
9367     if (!Src.Base || !Dest.Base) {
9368       APValue Val;
9369       (!Src.Base ? Src : Dest).moveInto(Val);
9370       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
9371           << Move << WChar << !!Src.Base
9372           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
9373       return false;
9374     }
9375     if (Src.Designator.Invalid || Dest.Designator.Invalid)
9376       return false;
9377 
9378     // We require that Src and Dest are both pointers to arrays of
9379     // trivially-copyable type. (For the wide version, the designator will be
9380     // invalid if the designated object is not a wchar_t.)
9381     QualType T = Dest.Designator.getType(Info.Ctx);
9382     QualType SrcT = Src.Designator.getType(Info.Ctx);
9383     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
9384       // FIXME: Consider using our bit_cast implementation to support this.
9385       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
9386       return false;
9387     }
9388     if (T->isIncompleteType()) {
9389       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
9390       return false;
9391     }
9392     if (!T.isTriviallyCopyableType(Info.Ctx)) {
9393       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
9394       return false;
9395     }
9396 
9397     // Figure out how many T's we're copying.
9398     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
9399     if (!WChar) {
9400       uint64_t Remainder;
9401       llvm::APInt OrigN = N;
9402       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
9403       if (Remainder) {
9404         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9405             << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
9406             << (unsigned)TSize;
9407         return false;
9408       }
9409     }
9410 
9411     // Check that the copying will remain within the arrays, just so that we
9412     // can give a more meaningful diagnostic. This implicitly also checks that
9413     // N fits into 64 bits.
9414     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
9415     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
9416     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
9417       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9418           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
9419           << toString(N, 10, /*Signed*/false);
9420       return false;
9421     }
9422     uint64_t NElems = N.getZExtValue();
9423     uint64_t NBytes = NElems * TSize;
9424 
9425     // Check for overlap.
9426     int Direction = 1;
9427     if (HasSameBase(Src, Dest)) {
9428       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
9429       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
9430       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
9431         // Dest is inside the source region.
9432         if (!Move) {
9433           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9434           return false;
9435         }
9436         // For memmove and friends, copy backwards.
9437         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
9438             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
9439           return false;
9440         Direction = -1;
9441       } else if (!Move && SrcOffset >= DestOffset &&
9442                  SrcOffset - DestOffset < NBytes) {
9443         // Src is inside the destination region for memcpy: invalid.
9444         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9445         return false;
9446       }
9447     }
9448 
9449     while (true) {
9450       APValue Val;
9451       // FIXME: Set WantObjectRepresentation to true if we're copying a
9452       // char-like type?
9453       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
9454           !handleAssignment(Info, E, Dest, T, Val))
9455         return false;
9456       // Do not iterate past the last element; if we're copying backwards, that
9457       // might take us off the start of the array.
9458       if (--NElems == 0)
9459         return true;
9460       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
9461           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
9462         return false;
9463     }
9464   }
9465 
9466   default:
9467     break;
9468   }
9469 
9470   return visitNonBuiltinCallExpr(E);
9471 }
9472 
9473 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9474                                      APValue &Result, const InitListExpr *ILE,
9475                                      QualType AllocType);
9476 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
9477                                           APValue &Result,
9478                                           const CXXConstructExpr *CCE,
9479                                           QualType AllocType);
9480 
9481 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
9482   if (!Info.getLangOpts().CPlusPlus20)
9483     Info.CCEDiag(E, diag::note_constexpr_new);
9484 
9485   // We cannot speculatively evaluate a delete expression.
9486   if (Info.SpeculativeEvaluationDepth)
9487     return false;
9488 
9489   FunctionDecl *OperatorNew = E->getOperatorNew();
9490 
9491   bool IsNothrow = false;
9492   bool IsPlacement = false;
9493   if (OperatorNew->isReservedGlobalPlacementOperator() &&
9494       Info.CurrentCall->isStdFunction() && !E->isArray()) {
9495     // FIXME Support array placement new.
9496     assert(E->getNumPlacementArgs() == 1);
9497     if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
9498       return false;
9499     if (Result.Designator.Invalid)
9500       return false;
9501     IsPlacement = true;
9502   } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
9503     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
9504         << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
9505     return false;
9506   } else if (E->getNumPlacementArgs()) {
9507     // The only new-placement list we support is of the form (std::nothrow).
9508     //
9509     // FIXME: There is no restriction on this, but it's not clear that any
9510     // other form makes any sense. We get here for cases such as:
9511     //
9512     //   new (std::align_val_t{N}) X(int)
9513     //
9514     // (which should presumably be valid only if N is a multiple of
9515     // alignof(int), and in any case can't be deallocated unless N is
9516     // alignof(X) and X has new-extended alignment).
9517     if (E->getNumPlacementArgs() != 1 ||
9518         !E->getPlacementArg(0)->getType()->isNothrowT())
9519       return Error(E, diag::note_constexpr_new_placement);
9520 
9521     LValue Nothrow;
9522     if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
9523       return false;
9524     IsNothrow = true;
9525   }
9526 
9527   const Expr *Init = E->getInitializer();
9528   const InitListExpr *ResizedArrayILE = nullptr;
9529   const CXXConstructExpr *ResizedArrayCCE = nullptr;
9530   bool ValueInit = false;
9531 
9532   QualType AllocType = E->getAllocatedType();
9533   if (Optional<const Expr *> ArraySize = E->getArraySize()) {
9534     const Expr *Stripped = *ArraySize;
9535     for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
9536          Stripped = ICE->getSubExpr())
9537       if (ICE->getCastKind() != CK_NoOp &&
9538           ICE->getCastKind() != CK_IntegralCast)
9539         break;
9540 
9541     llvm::APSInt ArrayBound;
9542     if (!EvaluateInteger(Stripped, ArrayBound, Info))
9543       return false;
9544 
9545     // C++ [expr.new]p9:
9546     //   The expression is erroneous if:
9547     //   -- [...] its value before converting to size_t [or] applying the
9548     //      second standard conversion sequence is less than zero
9549     if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
9550       if (IsNothrow)
9551         return ZeroInitialization(E);
9552 
9553       Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
9554           << ArrayBound << (*ArraySize)->getSourceRange();
9555       return false;
9556     }
9557 
9558     //   -- its value is such that the size of the allocated object would
9559     //      exceed the implementation-defined limit
9560     if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
9561                                                 ArrayBound) >
9562         ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
9563       if (IsNothrow)
9564         return ZeroInitialization(E);
9565 
9566       Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
9567         << ArrayBound << (*ArraySize)->getSourceRange();
9568       return false;
9569     }
9570 
9571     //   -- the new-initializer is a braced-init-list and the number of
9572     //      array elements for which initializers are provided [...]
9573     //      exceeds the number of elements to initialize
9574     if (!Init) {
9575       // No initialization is performed.
9576     } else if (isa<CXXScalarValueInitExpr>(Init) ||
9577                isa<ImplicitValueInitExpr>(Init)) {
9578       ValueInit = true;
9579     } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
9580       ResizedArrayCCE = CCE;
9581     } else {
9582       auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
9583       assert(CAT && "unexpected type for array initializer");
9584 
9585       unsigned Bits =
9586           std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
9587       llvm::APInt InitBound = CAT->getSize().zext(Bits);
9588       llvm::APInt AllocBound = ArrayBound.zext(Bits);
9589       if (InitBound.ugt(AllocBound)) {
9590         if (IsNothrow)
9591           return ZeroInitialization(E);
9592 
9593         Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
9594             << toString(AllocBound, 10, /*Signed=*/false)
9595             << toString(InitBound, 10, /*Signed=*/false)
9596             << (*ArraySize)->getSourceRange();
9597         return false;
9598       }
9599 
9600       // If the sizes differ, we must have an initializer list, and we need
9601       // special handling for this case when we initialize.
9602       if (InitBound != AllocBound)
9603         ResizedArrayILE = cast<InitListExpr>(Init);
9604     }
9605 
9606     AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
9607                                               ArrayType::Normal, 0);
9608   } else {
9609     assert(!AllocType->isArrayType() &&
9610            "array allocation with non-array new");
9611   }
9612 
9613   APValue *Val;
9614   if (IsPlacement) {
9615     AccessKinds AK = AK_Construct;
9616     struct FindObjectHandler {
9617       EvalInfo &Info;
9618       const Expr *E;
9619       QualType AllocType;
9620       const AccessKinds AccessKind;
9621       APValue *Value;
9622 
9623       typedef bool result_type;
9624       bool failed() { return false; }
9625       bool found(APValue &Subobj, QualType SubobjType) {
9626         // FIXME: Reject the cases where [basic.life]p8 would not permit the
9627         // old name of the object to be used to name the new object.
9628         if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
9629           Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
9630             SubobjType << AllocType;
9631           return false;
9632         }
9633         Value = &Subobj;
9634         return true;
9635       }
9636       bool found(APSInt &Value, QualType SubobjType) {
9637         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9638         return false;
9639       }
9640       bool found(APFloat &Value, QualType SubobjType) {
9641         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9642         return false;
9643       }
9644     } Handler = {Info, E, AllocType, AK, nullptr};
9645 
9646     CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
9647     if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
9648       return false;
9649 
9650     Val = Handler.Value;
9651 
9652     // [basic.life]p1:
9653     //   The lifetime of an object o of type T ends when [...] the storage
9654     //   which the object occupies is [...] reused by an object that is not
9655     //   nested within o (6.6.2).
9656     *Val = APValue();
9657   } else {
9658     // Perform the allocation and obtain a pointer to the resulting object.
9659     Val = Info.createHeapAlloc(E, AllocType, Result);
9660     if (!Val)
9661       return false;
9662   }
9663 
9664   if (ValueInit) {
9665     ImplicitValueInitExpr VIE(AllocType);
9666     if (!EvaluateInPlace(*Val, Info, Result, &VIE))
9667       return false;
9668   } else if (ResizedArrayILE) {
9669     if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
9670                                   AllocType))
9671       return false;
9672   } else if (ResizedArrayCCE) {
9673     if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
9674                                        AllocType))
9675       return false;
9676   } else if (Init) {
9677     if (!EvaluateInPlace(*Val, Info, Result, Init))
9678       return false;
9679   } else if (!getDefaultInitValue(AllocType, *Val)) {
9680     return false;
9681   }
9682 
9683   // Array new returns a pointer to the first element, not a pointer to the
9684   // array.
9685   if (auto *AT = AllocType->getAsArrayTypeUnsafe())
9686     Result.addArray(Info, E, cast<ConstantArrayType>(AT));
9687 
9688   return true;
9689 }
9690 //===----------------------------------------------------------------------===//
9691 // Member Pointer Evaluation
9692 //===----------------------------------------------------------------------===//
9693 
9694 namespace {
9695 class MemberPointerExprEvaluator
9696   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
9697   MemberPtr &Result;
9698 
9699   bool Success(const ValueDecl *D) {
9700     Result = MemberPtr(D);
9701     return true;
9702   }
9703 public:
9704 
9705   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
9706     : ExprEvaluatorBaseTy(Info), Result(Result) {}
9707 
9708   bool Success(const APValue &V, const Expr *E) {
9709     Result.setFrom(V);
9710     return true;
9711   }
9712   bool ZeroInitialization(const Expr *E) {
9713     return Success((const ValueDecl*)nullptr);
9714   }
9715 
9716   bool VisitCastExpr(const CastExpr *E);
9717   bool VisitUnaryAddrOf(const UnaryOperator *E);
9718 };
9719 } // end anonymous namespace
9720 
9721 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
9722                                   EvalInfo &Info) {
9723   assert(!E->isValueDependent());
9724   assert(E->isPRValue() && E->getType()->isMemberPointerType());
9725   return MemberPointerExprEvaluator(Info, Result).Visit(E);
9726 }
9727 
9728 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9729   switch (E->getCastKind()) {
9730   default:
9731     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9732 
9733   case CK_NullToMemberPointer:
9734     VisitIgnoredValue(E->getSubExpr());
9735     return ZeroInitialization(E);
9736 
9737   case CK_BaseToDerivedMemberPointer: {
9738     if (!Visit(E->getSubExpr()))
9739       return false;
9740     if (E->path_empty())
9741       return true;
9742     // Base-to-derived member pointer casts store the path in derived-to-base
9743     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
9744     // the wrong end of the derived->base arc, so stagger the path by one class.
9745     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
9746     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
9747          PathI != PathE; ++PathI) {
9748       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9749       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
9750       if (!Result.castToDerived(Derived))
9751         return Error(E);
9752     }
9753     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
9754     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
9755       return Error(E);
9756     return true;
9757   }
9758 
9759   case CK_DerivedToBaseMemberPointer:
9760     if (!Visit(E->getSubExpr()))
9761       return false;
9762     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9763          PathE = E->path_end(); PathI != PathE; ++PathI) {
9764       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9765       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9766       if (!Result.castToBase(Base))
9767         return Error(E);
9768     }
9769     return true;
9770   }
9771 }
9772 
9773 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9774   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
9775   // member can be formed.
9776   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
9777 }
9778 
9779 //===----------------------------------------------------------------------===//
9780 // Record Evaluation
9781 //===----------------------------------------------------------------------===//
9782 
9783 namespace {
9784   class RecordExprEvaluator
9785   : public ExprEvaluatorBase<RecordExprEvaluator> {
9786     const LValue &This;
9787     APValue &Result;
9788   public:
9789 
9790     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
9791       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
9792 
9793     bool Success(const APValue &V, const Expr *E) {
9794       Result = V;
9795       return true;
9796     }
9797     bool ZeroInitialization(const Expr *E) {
9798       return ZeroInitialization(E, E->getType());
9799     }
9800     bool ZeroInitialization(const Expr *E, QualType T);
9801 
9802     bool VisitCallExpr(const CallExpr *E) {
9803       return handleCallExpr(E, Result, &This);
9804     }
9805     bool VisitCastExpr(const CastExpr *E);
9806     bool VisitInitListExpr(const InitListExpr *E);
9807     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9808       return VisitCXXConstructExpr(E, E->getType());
9809     }
9810     bool VisitLambdaExpr(const LambdaExpr *E);
9811     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
9812     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
9813     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
9814     bool VisitBinCmp(const BinaryOperator *E);
9815   };
9816 }
9817 
9818 /// Perform zero-initialization on an object of non-union class type.
9819 /// C++11 [dcl.init]p5:
9820 ///  To zero-initialize an object or reference of type T means:
9821 ///    [...]
9822 ///    -- if T is a (possibly cv-qualified) non-union class type,
9823 ///       each non-static data member and each base-class subobject is
9824 ///       zero-initialized
9825 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
9826                                           const RecordDecl *RD,
9827                                           const LValue &This, APValue &Result) {
9828   assert(!RD->isUnion() && "Expected non-union class type");
9829   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
9830   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
9831                    std::distance(RD->field_begin(), RD->field_end()));
9832 
9833   if (RD->isInvalidDecl()) return false;
9834   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9835 
9836   if (CD) {
9837     unsigned Index = 0;
9838     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
9839            End = CD->bases_end(); I != End; ++I, ++Index) {
9840       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
9841       LValue Subobject = This;
9842       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
9843         return false;
9844       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
9845                                          Result.getStructBase(Index)))
9846         return false;
9847     }
9848   }
9849 
9850   for (const auto *I : RD->fields()) {
9851     // -- if T is a reference type, no initialization is performed.
9852     if (I->isUnnamedBitfield() || I->getType()->isReferenceType())
9853       continue;
9854 
9855     LValue Subobject = This;
9856     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
9857       return false;
9858 
9859     ImplicitValueInitExpr VIE(I->getType());
9860     if (!EvaluateInPlace(
9861           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
9862       return false;
9863   }
9864 
9865   return true;
9866 }
9867 
9868 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
9869   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
9870   if (RD->isInvalidDecl()) return false;
9871   if (RD->isUnion()) {
9872     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
9873     // object's first non-static named data member is zero-initialized
9874     RecordDecl::field_iterator I = RD->field_begin();
9875     while (I != RD->field_end() && (*I)->isUnnamedBitfield())
9876       ++I;
9877     if (I == RD->field_end()) {
9878       Result = APValue((const FieldDecl*)nullptr);
9879       return true;
9880     }
9881 
9882     LValue Subobject = This;
9883     if (!HandleLValueMember(Info, E, Subobject, *I))
9884       return false;
9885     Result = APValue(*I);
9886     ImplicitValueInitExpr VIE(I->getType());
9887     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
9888   }
9889 
9890   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
9891     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
9892     return false;
9893   }
9894 
9895   return HandleClassZeroInitialization(Info, E, RD, This, Result);
9896 }
9897 
9898 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
9899   switch (E->getCastKind()) {
9900   default:
9901     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9902 
9903   case CK_ConstructorConversion:
9904     return Visit(E->getSubExpr());
9905 
9906   case CK_DerivedToBase:
9907   case CK_UncheckedDerivedToBase: {
9908     APValue DerivedObject;
9909     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
9910       return false;
9911     if (!DerivedObject.isStruct())
9912       return Error(E->getSubExpr());
9913 
9914     // Derived-to-base rvalue conversion: just slice off the derived part.
9915     APValue *Value = &DerivedObject;
9916     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
9917     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9918          PathE = E->path_end(); PathI != PathE; ++PathI) {
9919       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
9920       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9921       Value = &Value->getStructBase(getBaseIndex(RD, Base));
9922       RD = Base;
9923     }
9924     Result = *Value;
9925     return true;
9926   }
9927   }
9928 }
9929 
9930 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9931   if (E->isTransparent())
9932     return Visit(E->getInit(0));
9933 
9934   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
9935   if (RD->isInvalidDecl()) return false;
9936   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9937   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
9938 
9939   EvalInfo::EvaluatingConstructorRAII EvalObj(
9940       Info,
9941       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
9942       CXXRD && CXXRD->getNumBases());
9943 
9944   if (RD->isUnion()) {
9945     const FieldDecl *Field = E->getInitializedFieldInUnion();
9946     Result = APValue(Field);
9947     if (!Field)
9948       return true;
9949 
9950     // If the initializer list for a union does not contain any elements, the
9951     // first element of the union is value-initialized.
9952     // FIXME: The element should be initialized from an initializer list.
9953     //        Is this difference ever observable for initializer lists which
9954     //        we don't build?
9955     ImplicitValueInitExpr VIE(Field->getType());
9956     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
9957 
9958     LValue Subobject = This;
9959     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
9960       return false;
9961 
9962     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9963     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9964                                   isa<CXXDefaultInitExpr>(InitExpr));
9965 
9966     if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
9967       if (Field->isBitField())
9968         return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
9969                                      Field);
9970       return true;
9971     }
9972 
9973     return false;
9974   }
9975 
9976   if (!Result.hasValue())
9977     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
9978                      std::distance(RD->field_begin(), RD->field_end()));
9979   unsigned ElementNo = 0;
9980   bool Success = true;
9981 
9982   // Initialize base classes.
9983   if (CXXRD && CXXRD->getNumBases()) {
9984     for (const auto &Base : CXXRD->bases()) {
9985       assert(ElementNo < E->getNumInits() && "missing init for base class");
9986       const Expr *Init = E->getInit(ElementNo);
9987 
9988       LValue Subobject = This;
9989       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
9990         return false;
9991 
9992       APValue &FieldVal = Result.getStructBase(ElementNo);
9993       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
9994         if (!Info.noteFailure())
9995           return false;
9996         Success = false;
9997       }
9998       ++ElementNo;
9999     }
10000 
10001     EvalObj.finishedConstructingBases();
10002   }
10003 
10004   // Initialize members.
10005   for (const auto *Field : RD->fields()) {
10006     // Anonymous bit-fields are not considered members of the class for
10007     // purposes of aggregate initialization.
10008     if (Field->isUnnamedBitfield())
10009       continue;
10010 
10011     LValue Subobject = This;
10012 
10013     bool HaveInit = ElementNo < E->getNumInits();
10014 
10015     // FIXME: Diagnostics here should point to the end of the initializer
10016     // list, not the start.
10017     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
10018                             Subobject, Field, &Layout))
10019       return false;
10020 
10021     // Perform an implicit value-initialization for members beyond the end of
10022     // the initializer list.
10023     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
10024     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
10025 
10026     if (Field->getType()->isIncompleteArrayType()) {
10027       if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {
10028         if (!CAT->getSize().isZero()) {
10029           // Bail out for now. This might sort of "work", but the rest of the
10030           // code isn't really prepared to handle it.
10031           Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array);
10032           return false;
10033         }
10034       }
10035     }
10036 
10037     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10038     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10039                                   isa<CXXDefaultInitExpr>(Init));
10040 
10041     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10042     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
10043         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
10044                                                        FieldVal, Field))) {
10045       if (!Info.noteFailure())
10046         return false;
10047       Success = false;
10048     }
10049   }
10050 
10051   EvalObj.finishedConstructingFields();
10052 
10053   return Success;
10054 }
10055 
10056 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10057                                                 QualType T) {
10058   // Note that E's type is not necessarily the type of our class here; we might
10059   // be initializing an array element instead.
10060   const CXXConstructorDecl *FD = E->getConstructor();
10061   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
10062 
10063   bool ZeroInit = E->requiresZeroInitialization();
10064   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
10065     // If we've already performed zero-initialization, we're already done.
10066     if (Result.hasValue())
10067       return true;
10068 
10069     if (ZeroInit)
10070       return ZeroInitialization(E, T);
10071 
10072     return getDefaultInitValue(T, Result);
10073   }
10074 
10075   const FunctionDecl *Definition = nullptr;
10076   auto Body = FD->getBody(Definition);
10077 
10078   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10079     return false;
10080 
10081   // Avoid materializing a temporary for an elidable copy/move constructor.
10082   if (E->isElidable() && !ZeroInit) {
10083     // FIXME: This only handles the simplest case, where the source object
10084     //        is passed directly as the first argument to the constructor.
10085     //        This should also handle stepping though implicit casts and
10086     //        and conversion sequences which involve two steps, with a
10087     //        conversion operator followed by a converting constructor.
10088     const Expr *SrcObj = E->getArg(0);
10089     assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
10090     assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
10091     if (const MaterializeTemporaryExpr *ME =
10092             dyn_cast<MaterializeTemporaryExpr>(SrcObj))
10093       return Visit(ME->getSubExpr());
10094   }
10095 
10096   if (ZeroInit && !ZeroInitialization(E, T))
10097     return false;
10098 
10099   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
10100   return HandleConstructorCall(E, This, Args,
10101                                cast<CXXConstructorDecl>(Definition), Info,
10102                                Result);
10103 }
10104 
10105 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
10106     const CXXInheritedCtorInitExpr *E) {
10107   if (!Info.CurrentCall) {
10108     assert(Info.checkingPotentialConstantExpression());
10109     return false;
10110   }
10111 
10112   const CXXConstructorDecl *FD = E->getConstructor();
10113   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
10114     return false;
10115 
10116   const FunctionDecl *Definition = nullptr;
10117   auto Body = FD->getBody(Definition);
10118 
10119   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10120     return false;
10121 
10122   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
10123                                cast<CXXConstructorDecl>(Definition), Info,
10124                                Result);
10125 }
10126 
10127 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
10128     const CXXStdInitializerListExpr *E) {
10129   const ConstantArrayType *ArrayType =
10130       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
10131 
10132   LValue Array;
10133   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
10134     return false;
10135 
10136   // Get a pointer to the first element of the array.
10137   Array.addArray(Info, E, ArrayType);
10138 
10139   auto InvalidType = [&] {
10140     Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
10141       << E->getType();
10142     return false;
10143   };
10144 
10145   // FIXME: Perform the checks on the field types in SemaInit.
10146   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
10147   RecordDecl::field_iterator Field = Record->field_begin();
10148   if (Field == Record->field_end())
10149     return InvalidType();
10150 
10151   // Start pointer.
10152   if (!Field->getType()->isPointerType() ||
10153       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10154                             ArrayType->getElementType()))
10155     return InvalidType();
10156 
10157   // FIXME: What if the initializer_list type has base classes, etc?
10158   Result = APValue(APValue::UninitStruct(), 0, 2);
10159   Array.moveInto(Result.getStructField(0));
10160 
10161   if (++Field == Record->field_end())
10162     return InvalidType();
10163 
10164   if (Field->getType()->isPointerType() &&
10165       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10166                            ArrayType->getElementType())) {
10167     // End pointer.
10168     if (!HandleLValueArrayAdjustment(Info, E, Array,
10169                                      ArrayType->getElementType(),
10170                                      ArrayType->getSize().getZExtValue()))
10171       return false;
10172     Array.moveInto(Result.getStructField(1));
10173   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
10174     // Length.
10175     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
10176   else
10177     return InvalidType();
10178 
10179   if (++Field != Record->field_end())
10180     return InvalidType();
10181 
10182   return true;
10183 }
10184 
10185 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
10186   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
10187   if (ClosureClass->isInvalidDecl())
10188     return false;
10189 
10190   const size_t NumFields =
10191       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
10192 
10193   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
10194                                             E->capture_init_end()) &&
10195          "The number of lambda capture initializers should equal the number of "
10196          "fields within the closure type");
10197 
10198   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
10199   // Iterate through all the lambda's closure object's fields and initialize
10200   // them.
10201   auto *CaptureInitIt = E->capture_init_begin();
10202   bool Success = true;
10203   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
10204   for (const auto *Field : ClosureClass->fields()) {
10205     assert(CaptureInitIt != E->capture_init_end());
10206     // Get the initializer for this field
10207     Expr *const CurFieldInit = *CaptureInitIt++;
10208 
10209     // If there is no initializer, either this is a VLA or an error has
10210     // occurred.
10211     if (!CurFieldInit)
10212       return Error(E);
10213 
10214     LValue Subobject = This;
10215 
10216     if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
10217       return false;
10218 
10219     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10220     if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
10221       if (!Info.keepEvaluatingAfterFailure())
10222         return false;
10223       Success = false;
10224     }
10225   }
10226   return Success;
10227 }
10228 
10229 static bool EvaluateRecord(const Expr *E, const LValue &This,
10230                            APValue &Result, EvalInfo &Info) {
10231   assert(!E->isValueDependent());
10232   assert(E->isPRValue() && E->getType()->isRecordType() &&
10233          "can't evaluate expression as a record rvalue");
10234   return RecordExprEvaluator(Info, This, Result).Visit(E);
10235 }
10236 
10237 //===----------------------------------------------------------------------===//
10238 // Temporary Evaluation
10239 //
10240 // Temporaries are represented in the AST as rvalues, but generally behave like
10241 // lvalues. The full-object of which the temporary is a subobject is implicitly
10242 // materialized so that a reference can bind to it.
10243 //===----------------------------------------------------------------------===//
10244 namespace {
10245 class TemporaryExprEvaluator
10246   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
10247 public:
10248   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
10249     LValueExprEvaluatorBaseTy(Info, Result, false) {}
10250 
10251   /// Visit an expression which constructs the value of this temporary.
10252   bool VisitConstructExpr(const Expr *E) {
10253     APValue &Value = Info.CurrentCall->createTemporary(
10254         E, E->getType(), ScopeKind::FullExpression, Result);
10255     return EvaluateInPlace(Value, Info, Result, E);
10256   }
10257 
10258   bool VisitCastExpr(const CastExpr *E) {
10259     switch (E->getCastKind()) {
10260     default:
10261       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
10262 
10263     case CK_ConstructorConversion:
10264       return VisitConstructExpr(E->getSubExpr());
10265     }
10266   }
10267   bool VisitInitListExpr(const InitListExpr *E) {
10268     return VisitConstructExpr(E);
10269   }
10270   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10271     return VisitConstructExpr(E);
10272   }
10273   bool VisitCallExpr(const CallExpr *E) {
10274     return VisitConstructExpr(E);
10275   }
10276   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
10277     return VisitConstructExpr(E);
10278   }
10279   bool VisitLambdaExpr(const LambdaExpr *E) {
10280     return VisitConstructExpr(E);
10281   }
10282 };
10283 } // end anonymous namespace
10284 
10285 /// Evaluate an expression of record type as a temporary.
10286 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
10287   assert(!E->isValueDependent());
10288   assert(E->isPRValue() && E->getType()->isRecordType());
10289   return TemporaryExprEvaluator(Info, Result).Visit(E);
10290 }
10291 
10292 //===----------------------------------------------------------------------===//
10293 // Vector Evaluation
10294 //===----------------------------------------------------------------------===//
10295 
10296 namespace {
10297   class VectorExprEvaluator
10298   : public ExprEvaluatorBase<VectorExprEvaluator> {
10299     APValue &Result;
10300   public:
10301 
10302     VectorExprEvaluator(EvalInfo &info, APValue &Result)
10303       : ExprEvaluatorBaseTy(info), Result(Result) {}
10304 
10305     bool Success(ArrayRef<APValue> V, const Expr *E) {
10306       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
10307       // FIXME: remove this APValue copy.
10308       Result = APValue(V.data(), V.size());
10309       return true;
10310     }
10311     bool Success(const APValue &V, const Expr *E) {
10312       assert(V.isVector());
10313       Result = V;
10314       return true;
10315     }
10316     bool ZeroInitialization(const Expr *E);
10317 
10318     bool VisitUnaryReal(const UnaryOperator *E)
10319       { return Visit(E->getSubExpr()); }
10320     bool VisitCastExpr(const CastExpr* E);
10321     bool VisitInitListExpr(const InitListExpr *E);
10322     bool VisitUnaryImag(const UnaryOperator *E);
10323     bool VisitBinaryOperator(const BinaryOperator *E);
10324     bool VisitUnaryOperator(const UnaryOperator *E);
10325     // FIXME: Missing: conditional operator (for GNU
10326     //                 conditional select), shufflevector, ExtVectorElementExpr
10327   };
10328 } // end anonymous namespace
10329 
10330 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
10331   assert(E->isPRValue() && E->getType()->isVectorType() &&
10332          "not a vector prvalue");
10333   return VectorExprEvaluator(Info, Result).Visit(E);
10334 }
10335 
10336 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
10337   const VectorType *VTy = E->getType()->castAs<VectorType>();
10338   unsigned NElts = VTy->getNumElements();
10339 
10340   const Expr *SE = E->getSubExpr();
10341   QualType SETy = SE->getType();
10342 
10343   switch (E->getCastKind()) {
10344   case CK_VectorSplat: {
10345     APValue Val = APValue();
10346     if (SETy->isIntegerType()) {
10347       APSInt IntResult;
10348       if (!EvaluateInteger(SE, IntResult, Info))
10349         return false;
10350       Val = APValue(std::move(IntResult));
10351     } else if (SETy->isRealFloatingType()) {
10352       APFloat FloatResult(0.0);
10353       if (!EvaluateFloat(SE, FloatResult, Info))
10354         return false;
10355       Val = APValue(std::move(FloatResult));
10356     } else {
10357       return Error(E);
10358     }
10359 
10360     // Splat and create vector APValue.
10361     SmallVector<APValue, 4> Elts(NElts, Val);
10362     return Success(Elts, E);
10363   }
10364   case CK_BitCast: {
10365     // Evaluate the operand into an APInt we can extract from.
10366     llvm::APInt SValInt;
10367     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
10368       return false;
10369     // Extract the elements
10370     QualType EltTy = VTy->getElementType();
10371     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
10372     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
10373     SmallVector<APValue, 4> Elts;
10374     if (EltTy->isRealFloatingType()) {
10375       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
10376       unsigned FloatEltSize = EltSize;
10377       if (&Sem == &APFloat::x87DoubleExtended())
10378         FloatEltSize = 80;
10379       for (unsigned i = 0; i < NElts; i++) {
10380         llvm::APInt Elt;
10381         if (BigEndian)
10382           Elt = SValInt.rotl(i * EltSize + FloatEltSize).trunc(FloatEltSize);
10383         else
10384           Elt = SValInt.rotr(i * EltSize).trunc(FloatEltSize);
10385         Elts.push_back(APValue(APFloat(Sem, Elt)));
10386       }
10387     } else if (EltTy->isIntegerType()) {
10388       for (unsigned i = 0; i < NElts; i++) {
10389         llvm::APInt Elt;
10390         if (BigEndian)
10391           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
10392         else
10393           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
10394         Elts.push_back(APValue(APSInt(Elt, !EltTy->isSignedIntegerType())));
10395       }
10396     } else {
10397       return Error(E);
10398     }
10399     return Success(Elts, E);
10400   }
10401   default:
10402     return ExprEvaluatorBaseTy::VisitCastExpr(E);
10403   }
10404 }
10405 
10406 bool
10407 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10408   const VectorType *VT = E->getType()->castAs<VectorType>();
10409   unsigned NumInits = E->getNumInits();
10410   unsigned NumElements = VT->getNumElements();
10411 
10412   QualType EltTy = VT->getElementType();
10413   SmallVector<APValue, 4> Elements;
10414 
10415   // The number of initializers can be less than the number of
10416   // vector elements. For OpenCL, this can be due to nested vector
10417   // initialization. For GCC compatibility, missing trailing elements
10418   // should be initialized with zeroes.
10419   unsigned CountInits = 0, CountElts = 0;
10420   while (CountElts < NumElements) {
10421     // Handle nested vector initialization.
10422     if (CountInits < NumInits
10423         && E->getInit(CountInits)->getType()->isVectorType()) {
10424       APValue v;
10425       if (!EvaluateVector(E->getInit(CountInits), v, Info))
10426         return Error(E);
10427       unsigned vlen = v.getVectorLength();
10428       for (unsigned j = 0; j < vlen; j++)
10429         Elements.push_back(v.getVectorElt(j));
10430       CountElts += vlen;
10431     } else if (EltTy->isIntegerType()) {
10432       llvm::APSInt sInt(32);
10433       if (CountInits < NumInits) {
10434         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
10435           return false;
10436       } else // trailing integer zero.
10437         sInt = Info.Ctx.MakeIntValue(0, EltTy);
10438       Elements.push_back(APValue(sInt));
10439       CountElts++;
10440     } else {
10441       llvm::APFloat f(0.0);
10442       if (CountInits < NumInits) {
10443         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
10444           return false;
10445       } else // trailing float zero.
10446         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
10447       Elements.push_back(APValue(f));
10448       CountElts++;
10449     }
10450     CountInits++;
10451   }
10452   return Success(Elements, E);
10453 }
10454 
10455 bool
10456 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
10457   const auto *VT = E->getType()->castAs<VectorType>();
10458   QualType EltTy = VT->getElementType();
10459   APValue ZeroElement;
10460   if (EltTy->isIntegerType())
10461     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
10462   else
10463     ZeroElement =
10464         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
10465 
10466   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
10467   return Success(Elements, E);
10468 }
10469 
10470 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
10471   VisitIgnoredValue(E->getSubExpr());
10472   return ZeroInitialization(E);
10473 }
10474 
10475 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10476   BinaryOperatorKind Op = E->getOpcode();
10477   assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
10478          "Operation not supported on vector types");
10479 
10480   if (Op == BO_Comma)
10481     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10482 
10483   Expr *LHS = E->getLHS();
10484   Expr *RHS = E->getRHS();
10485 
10486   assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
10487          "Must both be vector types");
10488   // Checking JUST the types are the same would be fine, except shifts don't
10489   // need to have their types be the same (since you always shift by an int).
10490   assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
10491              E->getType()->castAs<VectorType>()->getNumElements() &&
10492          RHS->getType()->castAs<VectorType>()->getNumElements() ==
10493              E->getType()->castAs<VectorType>()->getNumElements() &&
10494          "All operands must be the same size.");
10495 
10496   APValue LHSValue;
10497   APValue RHSValue;
10498   bool LHSOK = Evaluate(LHSValue, Info, LHS);
10499   if (!LHSOK && !Info.noteFailure())
10500     return false;
10501   if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
10502     return false;
10503 
10504   if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
10505     return false;
10506 
10507   return Success(LHSValue, E);
10508 }
10509 
10510 static llvm::Optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
10511                                                          QualType ResultTy,
10512                                                          UnaryOperatorKind Op,
10513                                                          APValue Elt) {
10514   switch (Op) {
10515   case UO_Plus:
10516     // Nothing to do here.
10517     return Elt;
10518   case UO_Minus:
10519     if (Elt.getKind() == APValue::Int) {
10520       Elt.getInt().negate();
10521     } else {
10522       assert(Elt.getKind() == APValue::Float &&
10523              "Vector can only be int or float type");
10524       Elt.getFloat().changeSign();
10525     }
10526     return Elt;
10527   case UO_Not:
10528     // This is only valid for integral types anyway, so we don't have to handle
10529     // float here.
10530     assert(Elt.getKind() == APValue::Int &&
10531            "Vector operator ~ can only be int");
10532     Elt.getInt().flipAllBits();
10533     return Elt;
10534   case UO_LNot: {
10535     if (Elt.getKind() == APValue::Int) {
10536       Elt.getInt() = !Elt.getInt();
10537       // operator ! on vectors returns -1 for 'truth', so negate it.
10538       Elt.getInt().negate();
10539       return Elt;
10540     }
10541     assert(Elt.getKind() == APValue::Float &&
10542            "Vector can only be int or float type");
10543     // Float types result in an int of the same size, but -1 for true, or 0 for
10544     // false.
10545     APSInt EltResult{Ctx.getIntWidth(ResultTy),
10546                      ResultTy->isUnsignedIntegerType()};
10547     if (Elt.getFloat().isZero())
10548       EltResult.setAllBits();
10549     else
10550       EltResult.clearAllBits();
10551 
10552     return APValue{EltResult};
10553   }
10554   default:
10555     // FIXME: Implement the rest of the unary operators.
10556     return llvm::None;
10557   }
10558 }
10559 
10560 bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10561   Expr *SubExpr = E->getSubExpr();
10562   const auto *VD = SubExpr->getType()->castAs<VectorType>();
10563   // This result element type differs in the case of negating a floating point
10564   // vector, since the result type is the a vector of the equivilant sized
10565   // integer.
10566   const QualType ResultEltTy = VD->getElementType();
10567   UnaryOperatorKind Op = E->getOpcode();
10568 
10569   APValue SubExprValue;
10570   if (!Evaluate(SubExprValue, Info, SubExpr))
10571     return false;
10572 
10573   // FIXME: This vector evaluator someday needs to be changed to be LValue
10574   // aware/keep LValue information around, rather than dealing with just vector
10575   // types directly. Until then, we cannot handle cases where the operand to
10576   // these unary operators is an LValue. The only case I've been able to see
10577   // cause this is operator++ assigning to a member expression (only valid in
10578   // altivec compilations) in C mode, so this shouldn't limit us too much.
10579   if (SubExprValue.isLValue())
10580     return false;
10581 
10582   assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
10583          "Vector length doesn't match type?");
10584 
10585   SmallVector<APValue, 4> ResultElements;
10586   for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
10587     llvm::Optional<APValue> Elt = handleVectorUnaryOperator(
10588         Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
10589     if (!Elt)
10590       return false;
10591     ResultElements.push_back(*Elt);
10592   }
10593   return Success(APValue(ResultElements.data(), ResultElements.size()), E);
10594 }
10595 
10596 //===----------------------------------------------------------------------===//
10597 // Array Evaluation
10598 //===----------------------------------------------------------------------===//
10599 
10600 namespace {
10601   class ArrayExprEvaluator
10602   : public ExprEvaluatorBase<ArrayExprEvaluator> {
10603     const LValue &This;
10604     APValue &Result;
10605   public:
10606 
10607     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
10608       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
10609 
10610     bool Success(const APValue &V, const Expr *E) {
10611       assert(V.isArray() && "expected array");
10612       Result = V;
10613       return true;
10614     }
10615 
10616     bool ZeroInitialization(const Expr *E) {
10617       const ConstantArrayType *CAT =
10618           Info.Ctx.getAsConstantArrayType(E->getType());
10619       if (!CAT) {
10620         if (E->getType()->isIncompleteArrayType()) {
10621           // We can be asked to zero-initialize a flexible array member; this
10622           // is represented as an ImplicitValueInitExpr of incomplete array
10623           // type. In this case, the array has zero elements.
10624           Result = APValue(APValue::UninitArray(), 0, 0);
10625           return true;
10626         }
10627         // FIXME: We could handle VLAs here.
10628         return Error(E);
10629       }
10630 
10631       Result = APValue(APValue::UninitArray(), 0,
10632                        CAT->getSize().getZExtValue());
10633       if (!Result.hasArrayFiller())
10634         return true;
10635 
10636       // Zero-initialize all elements.
10637       LValue Subobject = This;
10638       Subobject.addArray(Info, E, CAT);
10639       ImplicitValueInitExpr VIE(CAT->getElementType());
10640       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
10641     }
10642 
10643     bool VisitCallExpr(const CallExpr *E) {
10644       return handleCallExpr(E, Result, &This);
10645     }
10646     bool VisitInitListExpr(const InitListExpr *E,
10647                            QualType AllocType = QualType());
10648     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
10649     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
10650     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
10651                                const LValue &Subobject,
10652                                APValue *Value, QualType Type);
10653     bool VisitStringLiteral(const StringLiteral *E,
10654                             QualType AllocType = QualType()) {
10655       expandStringLiteral(Info, E, Result, AllocType);
10656       return true;
10657     }
10658   };
10659 } // end anonymous namespace
10660 
10661 static bool EvaluateArray(const Expr *E, const LValue &This,
10662                           APValue &Result, EvalInfo &Info) {
10663   assert(!E->isValueDependent());
10664   assert(E->isPRValue() && E->getType()->isArrayType() &&
10665          "not an array prvalue");
10666   return ArrayExprEvaluator(Info, This, Result).Visit(E);
10667 }
10668 
10669 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10670                                      APValue &Result, const InitListExpr *ILE,
10671                                      QualType AllocType) {
10672   assert(!ILE->isValueDependent());
10673   assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
10674          "not an array prvalue");
10675   return ArrayExprEvaluator(Info, This, Result)
10676       .VisitInitListExpr(ILE, AllocType);
10677 }
10678 
10679 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10680                                           APValue &Result,
10681                                           const CXXConstructExpr *CCE,
10682                                           QualType AllocType) {
10683   assert(!CCE->isValueDependent());
10684   assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
10685          "not an array prvalue");
10686   return ArrayExprEvaluator(Info, This, Result)
10687       .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
10688 }
10689 
10690 // Return true iff the given array filler may depend on the element index.
10691 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
10692   // For now, just allow non-class value-initialization and initialization
10693   // lists comprised of them.
10694   if (isa<ImplicitValueInitExpr>(FillerExpr))
10695     return false;
10696   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
10697     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
10698       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
10699         return true;
10700     }
10701     return false;
10702   }
10703   return true;
10704 }
10705 
10706 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
10707                                            QualType AllocType) {
10708   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
10709       AllocType.isNull() ? E->getType() : AllocType);
10710   if (!CAT)
10711     return Error(E);
10712 
10713   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
10714   // an appropriately-typed string literal enclosed in braces.
10715   if (E->isStringLiteralInit()) {
10716     auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
10717     // FIXME: Support ObjCEncodeExpr here once we support it in
10718     // ArrayExprEvaluator generally.
10719     if (!SL)
10720       return Error(E);
10721     return VisitStringLiteral(SL, AllocType);
10722   }
10723   // Any other transparent list init will need proper handling of the
10724   // AllocType; we can't just recurse to the inner initializer.
10725   assert(!E->isTransparent() &&
10726          "transparent array list initialization is not string literal init?");
10727 
10728   bool Success = true;
10729 
10730   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
10731          "zero-initialized array shouldn't have any initialized elts");
10732   APValue Filler;
10733   if (Result.isArray() && Result.hasArrayFiller())
10734     Filler = Result.getArrayFiller();
10735 
10736   unsigned NumEltsToInit = E->getNumInits();
10737   unsigned NumElts = CAT->getSize().getZExtValue();
10738   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
10739 
10740   // If the initializer might depend on the array index, run it for each
10741   // array element.
10742   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
10743     NumEltsToInit = NumElts;
10744 
10745   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
10746                           << NumEltsToInit << ".\n");
10747 
10748   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
10749 
10750   // If the array was previously zero-initialized, preserve the
10751   // zero-initialized values.
10752   if (Filler.hasValue()) {
10753     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
10754       Result.getArrayInitializedElt(I) = Filler;
10755     if (Result.hasArrayFiller())
10756       Result.getArrayFiller() = Filler;
10757   }
10758 
10759   LValue Subobject = This;
10760   Subobject.addArray(Info, E, CAT);
10761   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
10762     const Expr *Init =
10763         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
10764     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10765                          Info, Subobject, Init) ||
10766         !HandleLValueArrayAdjustment(Info, Init, Subobject,
10767                                      CAT->getElementType(), 1)) {
10768       if (!Info.noteFailure())
10769         return false;
10770       Success = false;
10771     }
10772   }
10773 
10774   if (!Result.hasArrayFiller())
10775     return Success;
10776 
10777   // If we get here, we have a trivial filler, which we can just evaluate
10778   // once and splat over the rest of the array elements.
10779   assert(FillerExpr && "no array filler for incomplete init list");
10780   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
10781                          FillerExpr) && Success;
10782 }
10783 
10784 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
10785   LValue CommonLV;
10786   if (E->getCommonExpr() &&
10787       !Evaluate(Info.CurrentCall->createTemporary(
10788                     E->getCommonExpr(),
10789                     getStorageType(Info.Ctx, E->getCommonExpr()),
10790                     ScopeKind::FullExpression, CommonLV),
10791                 Info, E->getCommonExpr()->getSourceExpr()))
10792     return false;
10793 
10794   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
10795 
10796   uint64_t Elements = CAT->getSize().getZExtValue();
10797   Result = APValue(APValue::UninitArray(), Elements, Elements);
10798 
10799   LValue Subobject = This;
10800   Subobject.addArray(Info, E, CAT);
10801 
10802   bool Success = true;
10803   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
10804     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10805                          Info, Subobject, E->getSubExpr()) ||
10806         !HandleLValueArrayAdjustment(Info, E, Subobject,
10807                                      CAT->getElementType(), 1)) {
10808       if (!Info.noteFailure())
10809         return false;
10810       Success = false;
10811     }
10812   }
10813 
10814   return Success;
10815 }
10816 
10817 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
10818   return VisitCXXConstructExpr(E, This, &Result, E->getType());
10819 }
10820 
10821 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10822                                                const LValue &Subobject,
10823                                                APValue *Value,
10824                                                QualType Type) {
10825   bool HadZeroInit = Value->hasValue();
10826 
10827   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
10828     unsigned FinalSize = CAT->getSize().getZExtValue();
10829 
10830     // Preserve the array filler if we had prior zero-initialization.
10831     APValue Filler =
10832       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
10833                                              : APValue();
10834 
10835     *Value = APValue(APValue::UninitArray(), 0, FinalSize);
10836     if (FinalSize == 0)
10837       return true;
10838 
10839     LValue ArrayElt = Subobject;
10840     ArrayElt.addArray(Info, E, CAT);
10841     // We do the whole initialization in two passes, first for just one element,
10842     // then for the whole array. It's possible we may find out we can't do const
10843     // init in the first pass, in which case we avoid allocating a potentially
10844     // large array. We don't do more passes because expanding array requires
10845     // copying the data, which is wasteful.
10846     for (const unsigned N : {1u, FinalSize}) {
10847       unsigned OldElts = Value->getArrayInitializedElts();
10848       if (OldElts == N)
10849         break;
10850 
10851       // Expand the array to appropriate size.
10852       APValue NewValue(APValue::UninitArray(), N, FinalSize);
10853       for (unsigned I = 0; I < OldElts; ++I)
10854         NewValue.getArrayInitializedElt(I).swap(
10855             Value->getArrayInitializedElt(I));
10856       Value->swap(NewValue);
10857 
10858       if (HadZeroInit)
10859         for (unsigned I = OldElts; I < N; ++I)
10860           Value->getArrayInitializedElt(I) = Filler;
10861 
10862       // Initialize the elements.
10863       for (unsigned I = OldElts; I < N; ++I) {
10864         if (!VisitCXXConstructExpr(E, ArrayElt,
10865                                    &Value->getArrayInitializedElt(I),
10866                                    CAT->getElementType()) ||
10867             !HandleLValueArrayAdjustment(Info, E, ArrayElt,
10868                                          CAT->getElementType(), 1))
10869           return false;
10870         // When checking for const initilization any diagnostic is considered
10871         // an error.
10872         if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
10873             !Info.keepEvaluatingAfterFailure())
10874           return false;
10875       }
10876     }
10877 
10878     return true;
10879   }
10880 
10881   if (!Type->isRecordType())
10882     return Error(E);
10883 
10884   return RecordExprEvaluator(Info, Subobject, *Value)
10885              .VisitCXXConstructExpr(E, Type);
10886 }
10887 
10888 //===----------------------------------------------------------------------===//
10889 // Integer Evaluation
10890 //
10891 // As a GNU extension, we support casting pointers to sufficiently-wide integer
10892 // types and back in constant folding. Integer values are thus represented
10893 // either as an integer-valued APValue, or as an lvalue-valued APValue.
10894 //===----------------------------------------------------------------------===//
10895 
10896 namespace {
10897 class IntExprEvaluator
10898         : public ExprEvaluatorBase<IntExprEvaluator> {
10899   APValue &Result;
10900 public:
10901   IntExprEvaluator(EvalInfo &info, APValue &result)
10902       : ExprEvaluatorBaseTy(info), Result(result) {}
10903 
10904   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
10905     assert(E->getType()->isIntegralOrEnumerationType() &&
10906            "Invalid evaluation result.");
10907     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
10908            "Invalid evaluation result.");
10909     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10910            "Invalid evaluation result.");
10911     Result = APValue(SI);
10912     return true;
10913   }
10914   bool Success(const llvm::APSInt &SI, const Expr *E) {
10915     return Success(SI, E, Result);
10916   }
10917 
10918   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
10919     assert(E->getType()->isIntegralOrEnumerationType() &&
10920            "Invalid evaluation result.");
10921     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10922            "Invalid evaluation result.");
10923     Result = APValue(APSInt(I));
10924     Result.getInt().setIsUnsigned(
10925                             E->getType()->isUnsignedIntegerOrEnumerationType());
10926     return true;
10927   }
10928   bool Success(const llvm::APInt &I, const Expr *E) {
10929     return Success(I, E, Result);
10930   }
10931 
10932   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
10933     assert(E->getType()->isIntegralOrEnumerationType() &&
10934            "Invalid evaluation result.");
10935     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
10936     return true;
10937   }
10938   bool Success(uint64_t Value, const Expr *E) {
10939     return Success(Value, E, Result);
10940   }
10941 
10942   bool Success(CharUnits Size, const Expr *E) {
10943     return Success(Size.getQuantity(), E);
10944   }
10945 
10946   bool Success(const APValue &V, const Expr *E) {
10947     if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
10948       Result = V;
10949       return true;
10950     }
10951     return Success(V.getInt(), E);
10952   }
10953 
10954   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
10955 
10956   //===--------------------------------------------------------------------===//
10957   //                            Visitor Methods
10958   //===--------------------------------------------------------------------===//
10959 
10960   bool VisitIntegerLiteral(const IntegerLiteral *E) {
10961     return Success(E->getValue(), E);
10962   }
10963   bool VisitCharacterLiteral(const CharacterLiteral *E) {
10964     return Success(E->getValue(), E);
10965   }
10966 
10967   bool CheckReferencedDecl(const Expr *E, const Decl *D);
10968   bool VisitDeclRefExpr(const DeclRefExpr *E) {
10969     if (CheckReferencedDecl(E, E->getDecl()))
10970       return true;
10971 
10972     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
10973   }
10974   bool VisitMemberExpr(const MemberExpr *E) {
10975     if (CheckReferencedDecl(E, E->getMemberDecl())) {
10976       VisitIgnoredBaseExpression(E->getBase());
10977       return true;
10978     }
10979 
10980     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
10981   }
10982 
10983   bool VisitCallExpr(const CallExpr *E);
10984   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
10985   bool VisitBinaryOperator(const BinaryOperator *E);
10986   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
10987   bool VisitUnaryOperator(const UnaryOperator *E);
10988 
10989   bool VisitCastExpr(const CastExpr* E);
10990   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
10991 
10992   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
10993     return Success(E->getValue(), E);
10994   }
10995 
10996   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
10997     return Success(E->getValue(), E);
10998   }
10999 
11000   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
11001     if (Info.ArrayInitIndex == uint64_t(-1)) {
11002       // We were asked to evaluate this subexpression independent of the
11003       // enclosing ArrayInitLoopExpr. We can't do that.
11004       Info.FFDiag(E);
11005       return false;
11006     }
11007     return Success(Info.ArrayInitIndex, E);
11008   }
11009 
11010   // Note, GNU defines __null as an integer, not a pointer.
11011   bool VisitGNUNullExpr(const GNUNullExpr *E) {
11012     return ZeroInitialization(E);
11013   }
11014 
11015   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
11016     return Success(E->getValue(), E);
11017   }
11018 
11019   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
11020     return Success(E->getValue(), E);
11021   }
11022 
11023   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
11024     return Success(E->getValue(), E);
11025   }
11026 
11027   bool VisitUnaryReal(const UnaryOperator *E);
11028   bool VisitUnaryImag(const UnaryOperator *E);
11029 
11030   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
11031   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
11032   bool VisitSourceLocExpr(const SourceLocExpr *E);
11033   bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
11034   bool VisitRequiresExpr(const RequiresExpr *E);
11035   // FIXME: Missing: array subscript of vector, member of vector
11036 };
11037 
11038 class FixedPointExprEvaluator
11039     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
11040   APValue &Result;
11041 
11042  public:
11043   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
11044       : ExprEvaluatorBaseTy(info), Result(result) {}
11045 
11046   bool Success(const llvm::APInt &I, const Expr *E) {
11047     return Success(
11048         APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
11049   }
11050 
11051   bool Success(uint64_t Value, const Expr *E) {
11052     return Success(
11053         APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
11054   }
11055 
11056   bool Success(const APValue &V, const Expr *E) {
11057     return Success(V.getFixedPoint(), E);
11058   }
11059 
11060   bool Success(const APFixedPoint &V, const Expr *E) {
11061     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
11062     assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11063            "Invalid evaluation result.");
11064     Result = APValue(V);
11065     return true;
11066   }
11067 
11068   //===--------------------------------------------------------------------===//
11069   //                            Visitor Methods
11070   //===--------------------------------------------------------------------===//
11071 
11072   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
11073     return Success(E->getValue(), E);
11074   }
11075 
11076   bool VisitCastExpr(const CastExpr *E);
11077   bool VisitUnaryOperator(const UnaryOperator *E);
11078   bool VisitBinaryOperator(const BinaryOperator *E);
11079 };
11080 } // end anonymous namespace
11081 
11082 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
11083 /// produce either the integer value or a pointer.
11084 ///
11085 /// GCC has a heinous extension which folds casts between pointer types and
11086 /// pointer-sized integral types. We support this by allowing the evaluation of
11087 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
11088 /// Some simple arithmetic on such values is supported (they are treated much
11089 /// like char*).
11090 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
11091                                     EvalInfo &Info) {
11092   assert(!E->isValueDependent());
11093   assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
11094   return IntExprEvaluator(Info, Result).Visit(E);
11095 }
11096 
11097 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
11098   assert(!E->isValueDependent());
11099   APValue Val;
11100   if (!EvaluateIntegerOrLValue(E, Val, Info))
11101     return false;
11102   if (!Val.isInt()) {
11103     // FIXME: It would be better to produce the diagnostic for casting
11104     //        a pointer to an integer.
11105     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11106     return false;
11107   }
11108   Result = Val.getInt();
11109   return true;
11110 }
11111 
11112 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
11113   APValue Evaluated = E->EvaluateInContext(
11114       Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
11115   return Success(Evaluated, E);
11116 }
11117 
11118 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
11119                                EvalInfo &Info) {
11120   assert(!E->isValueDependent());
11121   if (E->getType()->isFixedPointType()) {
11122     APValue Val;
11123     if (!FixedPointExprEvaluator(Info, Val).Visit(E))
11124       return false;
11125     if (!Val.isFixedPoint())
11126       return false;
11127 
11128     Result = Val.getFixedPoint();
11129     return true;
11130   }
11131   return false;
11132 }
11133 
11134 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
11135                                         EvalInfo &Info) {
11136   assert(!E->isValueDependent());
11137   if (E->getType()->isIntegerType()) {
11138     auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
11139     APSInt Val;
11140     if (!EvaluateInteger(E, Val, Info))
11141       return false;
11142     Result = APFixedPoint(Val, FXSema);
11143     return true;
11144   } else if (E->getType()->isFixedPointType()) {
11145     return EvaluateFixedPoint(E, Result, Info);
11146   }
11147   return false;
11148 }
11149 
11150 /// Check whether the given declaration can be directly converted to an integral
11151 /// rvalue. If not, no diagnostic is produced; there are other things we can
11152 /// try.
11153 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
11154   // Enums are integer constant exprs.
11155   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
11156     // Check for signedness/width mismatches between E type and ECD value.
11157     bool SameSign = (ECD->getInitVal().isSigned()
11158                      == E->getType()->isSignedIntegerOrEnumerationType());
11159     bool SameWidth = (ECD->getInitVal().getBitWidth()
11160                       == Info.Ctx.getIntWidth(E->getType()));
11161     if (SameSign && SameWidth)
11162       return Success(ECD->getInitVal(), E);
11163     else {
11164       // Get rid of mismatch (otherwise Success assertions will fail)
11165       // by computing a new value matching the type of E.
11166       llvm::APSInt Val = ECD->getInitVal();
11167       if (!SameSign)
11168         Val.setIsSigned(!ECD->getInitVal().isSigned());
11169       if (!SameWidth)
11170         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
11171       return Success(Val, E);
11172     }
11173   }
11174   return false;
11175 }
11176 
11177 /// Values returned by __builtin_classify_type, chosen to match the values
11178 /// produced by GCC's builtin.
11179 enum class GCCTypeClass {
11180   None = -1,
11181   Void = 0,
11182   Integer = 1,
11183   // GCC reserves 2 for character types, but instead classifies them as
11184   // integers.
11185   Enum = 3,
11186   Bool = 4,
11187   Pointer = 5,
11188   // GCC reserves 6 for references, but appears to never use it (because
11189   // expressions never have reference type, presumably).
11190   PointerToDataMember = 7,
11191   RealFloat = 8,
11192   Complex = 9,
11193   // GCC reserves 10 for functions, but does not use it since GCC version 6 due
11194   // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
11195   // GCC claims to reserve 11 for pointers to member functions, but *actually*
11196   // uses 12 for that purpose, same as for a class or struct. Maybe it
11197   // internally implements a pointer to member as a struct?  Who knows.
11198   PointerToMemberFunction = 12, // Not a bug, see above.
11199   ClassOrStruct = 12,
11200   Union = 13,
11201   // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
11202   // decay to pointer. (Prior to version 6 it was only used in C++ mode).
11203   // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
11204   // literals.
11205 };
11206 
11207 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11208 /// as GCC.
11209 static GCCTypeClass
11210 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
11211   assert(!T->isDependentType() && "unexpected dependent type");
11212 
11213   QualType CanTy = T.getCanonicalType();
11214   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
11215 
11216   switch (CanTy->getTypeClass()) {
11217 #define TYPE(ID, BASE)
11218 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
11219 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
11220 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
11221 #include "clang/AST/TypeNodes.inc"
11222   case Type::Auto:
11223   case Type::DeducedTemplateSpecialization:
11224       llvm_unreachable("unexpected non-canonical or dependent type");
11225 
11226   case Type::Builtin:
11227     switch (BT->getKind()) {
11228 #define BUILTIN_TYPE(ID, SINGLETON_ID)
11229 #define SIGNED_TYPE(ID, SINGLETON_ID) \
11230     case BuiltinType::ID: return GCCTypeClass::Integer;
11231 #define FLOATING_TYPE(ID, SINGLETON_ID) \
11232     case BuiltinType::ID: return GCCTypeClass::RealFloat;
11233 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
11234     case BuiltinType::ID: break;
11235 #include "clang/AST/BuiltinTypes.def"
11236     case BuiltinType::Void:
11237       return GCCTypeClass::Void;
11238 
11239     case BuiltinType::Bool:
11240       return GCCTypeClass::Bool;
11241 
11242     case BuiltinType::Char_U:
11243     case BuiltinType::UChar:
11244     case BuiltinType::WChar_U:
11245     case BuiltinType::Char8:
11246     case BuiltinType::Char16:
11247     case BuiltinType::Char32:
11248     case BuiltinType::UShort:
11249     case BuiltinType::UInt:
11250     case BuiltinType::ULong:
11251     case BuiltinType::ULongLong:
11252     case BuiltinType::UInt128:
11253       return GCCTypeClass::Integer;
11254 
11255     case BuiltinType::UShortAccum:
11256     case BuiltinType::UAccum:
11257     case BuiltinType::ULongAccum:
11258     case BuiltinType::UShortFract:
11259     case BuiltinType::UFract:
11260     case BuiltinType::ULongFract:
11261     case BuiltinType::SatUShortAccum:
11262     case BuiltinType::SatUAccum:
11263     case BuiltinType::SatULongAccum:
11264     case BuiltinType::SatUShortFract:
11265     case BuiltinType::SatUFract:
11266     case BuiltinType::SatULongFract:
11267       return GCCTypeClass::None;
11268 
11269     case BuiltinType::NullPtr:
11270 
11271     case BuiltinType::ObjCId:
11272     case BuiltinType::ObjCClass:
11273     case BuiltinType::ObjCSel:
11274 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
11275     case BuiltinType::Id:
11276 #include "clang/Basic/OpenCLImageTypes.def"
11277 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
11278     case BuiltinType::Id:
11279 #include "clang/Basic/OpenCLExtensionTypes.def"
11280     case BuiltinType::OCLSampler:
11281     case BuiltinType::OCLEvent:
11282     case BuiltinType::OCLClkEvent:
11283     case BuiltinType::OCLQueue:
11284     case BuiltinType::OCLReserveID:
11285 #define SVE_TYPE(Name, Id, SingletonId) \
11286     case BuiltinType::Id:
11287 #include "clang/Basic/AArch64SVEACLETypes.def"
11288 #define PPC_VECTOR_TYPE(Name, Id, Size) \
11289     case BuiltinType::Id:
11290 #include "clang/Basic/PPCTypes.def"
11291 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
11292 #include "clang/Basic/RISCVVTypes.def"
11293       return GCCTypeClass::None;
11294 
11295     case BuiltinType::Dependent:
11296       llvm_unreachable("unexpected dependent type");
11297     };
11298     llvm_unreachable("unexpected placeholder type");
11299 
11300   case Type::Enum:
11301     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
11302 
11303   case Type::Pointer:
11304   case Type::ConstantArray:
11305   case Type::VariableArray:
11306   case Type::IncompleteArray:
11307   case Type::FunctionNoProto:
11308   case Type::FunctionProto:
11309     return GCCTypeClass::Pointer;
11310 
11311   case Type::MemberPointer:
11312     return CanTy->isMemberDataPointerType()
11313                ? GCCTypeClass::PointerToDataMember
11314                : GCCTypeClass::PointerToMemberFunction;
11315 
11316   case Type::Complex:
11317     return GCCTypeClass::Complex;
11318 
11319   case Type::Record:
11320     return CanTy->isUnionType() ? GCCTypeClass::Union
11321                                 : GCCTypeClass::ClassOrStruct;
11322 
11323   case Type::Atomic:
11324     // GCC classifies _Atomic T the same as T.
11325     return EvaluateBuiltinClassifyType(
11326         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
11327 
11328   case Type::BlockPointer:
11329   case Type::Vector:
11330   case Type::ExtVector:
11331   case Type::ConstantMatrix:
11332   case Type::ObjCObject:
11333   case Type::ObjCInterface:
11334   case Type::ObjCObjectPointer:
11335   case Type::Pipe:
11336   case Type::BitInt:
11337     // GCC classifies vectors as None. We follow its lead and classify all
11338     // other types that don't fit into the regular classification the same way.
11339     return GCCTypeClass::None;
11340 
11341   case Type::LValueReference:
11342   case Type::RValueReference:
11343     llvm_unreachable("invalid type for expression");
11344   }
11345 
11346   llvm_unreachable("unexpected type class");
11347 }
11348 
11349 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11350 /// as GCC.
11351 static GCCTypeClass
11352 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
11353   // If no argument was supplied, default to None. This isn't
11354   // ideal, however it is what gcc does.
11355   if (E->getNumArgs() == 0)
11356     return GCCTypeClass::None;
11357 
11358   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
11359   // being an ICE, but still folds it to a constant using the type of the first
11360   // argument.
11361   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
11362 }
11363 
11364 /// EvaluateBuiltinConstantPForLValue - Determine the result of
11365 /// __builtin_constant_p when applied to the given pointer.
11366 ///
11367 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
11368 /// or it points to the first character of a string literal.
11369 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
11370   APValue::LValueBase Base = LV.getLValueBase();
11371   if (Base.isNull()) {
11372     // A null base is acceptable.
11373     return true;
11374   } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
11375     if (!isa<StringLiteral>(E))
11376       return false;
11377     return LV.getLValueOffset().isZero();
11378   } else if (Base.is<TypeInfoLValue>()) {
11379     // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
11380     // evaluate to true.
11381     return true;
11382   } else {
11383     // Any other base is not constant enough for GCC.
11384     return false;
11385   }
11386 }
11387 
11388 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
11389 /// GCC as we can manage.
11390 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
11391   // This evaluation is not permitted to have side-effects, so evaluate it in
11392   // a speculative evaluation context.
11393   SpeculativeEvaluationRAII SpeculativeEval(Info);
11394 
11395   // Constant-folding is always enabled for the operand of __builtin_constant_p
11396   // (even when the enclosing evaluation context otherwise requires a strict
11397   // language-specific constant expression).
11398   FoldConstant Fold(Info, true);
11399 
11400   QualType ArgType = Arg->getType();
11401 
11402   // __builtin_constant_p always has one operand. The rules which gcc follows
11403   // are not precisely documented, but are as follows:
11404   //
11405   //  - If the operand is of integral, floating, complex or enumeration type,
11406   //    and can be folded to a known value of that type, it returns 1.
11407   //  - If the operand can be folded to a pointer to the first character
11408   //    of a string literal (or such a pointer cast to an integral type)
11409   //    or to a null pointer or an integer cast to a pointer, it returns 1.
11410   //
11411   // Otherwise, it returns 0.
11412   //
11413   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
11414   // its support for this did not work prior to GCC 9 and is not yet well
11415   // understood.
11416   if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
11417       ArgType->isAnyComplexType() || ArgType->isPointerType() ||
11418       ArgType->isNullPtrType()) {
11419     APValue V;
11420     if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
11421       Fold.keepDiagnostics();
11422       return false;
11423     }
11424 
11425     // For a pointer (possibly cast to integer), there are special rules.
11426     if (V.getKind() == APValue::LValue)
11427       return EvaluateBuiltinConstantPForLValue(V);
11428 
11429     // Otherwise, any constant value is good enough.
11430     return V.hasValue();
11431   }
11432 
11433   // Anything else isn't considered to be sufficiently constant.
11434   return false;
11435 }
11436 
11437 /// Retrieves the "underlying object type" of the given expression,
11438 /// as used by __builtin_object_size.
11439 static QualType getObjectType(APValue::LValueBase B) {
11440   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
11441     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
11442       return VD->getType();
11443   } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
11444     if (isa<CompoundLiteralExpr>(E))
11445       return E->getType();
11446   } else if (B.is<TypeInfoLValue>()) {
11447     return B.getTypeInfoType();
11448   } else if (B.is<DynamicAllocLValue>()) {
11449     return B.getDynamicAllocType();
11450   }
11451 
11452   return QualType();
11453 }
11454 
11455 /// A more selective version of E->IgnoreParenCasts for
11456 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
11457 /// to change the type of E.
11458 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
11459 ///
11460 /// Always returns an RValue with a pointer representation.
11461 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
11462   assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
11463 
11464   auto *NoParens = E->IgnoreParens();
11465   auto *Cast = dyn_cast<CastExpr>(NoParens);
11466   if (Cast == nullptr)
11467     return NoParens;
11468 
11469   // We only conservatively allow a few kinds of casts, because this code is
11470   // inherently a simple solution that seeks to support the common case.
11471   auto CastKind = Cast->getCastKind();
11472   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
11473       CastKind != CK_AddressSpaceConversion)
11474     return NoParens;
11475 
11476   auto *SubExpr = Cast->getSubExpr();
11477   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
11478     return NoParens;
11479   return ignorePointerCastsAndParens(SubExpr);
11480 }
11481 
11482 /// Checks to see if the given LValue's Designator is at the end of the LValue's
11483 /// record layout. e.g.
11484 ///   struct { struct { int a, b; } fst, snd; } obj;
11485 ///   obj.fst   // no
11486 ///   obj.snd   // yes
11487 ///   obj.fst.a // no
11488 ///   obj.fst.b // no
11489 ///   obj.snd.a // no
11490 ///   obj.snd.b // yes
11491 ///
11492 /// Please note: this function is specialized for how __builtin_object_size
11493 /// views "objects".
11494 ///
11495 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
11496 /// correct result, it will always return true.
11497 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
11498   assert(!LVal.Designator.Invalid);
11499 
11500   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
11501     const RecordDecl *Parent = FD->getParent();
11502     Invalid = Parent->isInvalidDecl();
11503     if (Invalid || Parent->isUnion())
11504       return true;
11505     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
11506     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
11507   };
11508 
11509   auto &Base = LVal.getLValueBase();
11510   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
11511     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
11512       bool Invalid;
11513       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11514         return Invalid;
11515     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
11516       for (auto *FD : IFD->chain()) {
11517         bool Invalid;
11518         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
11519           return Invalid;
11520       }
11521     }
11522   }
11523 
11524   unsigned I = 0;
11525   QualType BaseType = getType(Base);
11526   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
11527     // If we don't know the array bound, conservatively assume we're looking at
11528     // the final array element.
11529     ++I;
11530     if (BaseType->isIncompleteArrayType())
11531       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
11532     else
11533       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
11534   }
11535 
11536   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
11537     const auto &Entry = LVal.Designator.Entries[I];
11538     if (BaseType->isArrayType()) {
11539       // Because __builtin_object_size treats arrays as objects, we can ignore
11540       // the index iff this is the last array in the Designator.
11541       if (I + 1 == E)
11542         return true;
11543       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
11544       uint64_t Index = Entry.getAsArrayIndex();
11545       if (Index + 1 != CAT->getSize())
11546         return false;
11547       BaseType = CAT->getElementType();
11548     } else if (BaseType->isAnyComplexType()) {
11549       const auto *CT = BaseType->castAs<ComplexType>();
11550       uint64_t Index = Entry.getAsArrayIndex();
11551       if (Index != 1)
11552         return false;
11553       BaseType = CT->getElementType();
11554     } else if (auto *FD = getAsField(Entry)) {
11555       bool Invalid;
11556       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11557         return Invalid;
11558       BaseType = FD->getType();
11559     } else {
11560       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
11561       return false;
11562     }
11563   }
11564   return true;
11565 }
11566 
11567 /// Tests to see if the LValue has a user-specified designator (that isn't
11568 /// necessarily valid). Note that this always returns 'true' if the LValue has
11569 /// an unsized array as its first designator entry, because there's currently no
11570 /// way to tell if the user typed *foo or foo[0].
11571 static bool refersToCompleteObject(const LValue &LVal) {
11572   if (LVal.Designator.Invalid)
11573     return false;
11574 
11575   if (!LVal.Designator.Entries.empty())
11576     return LVal.Designator.isMostDerivedAnUnsizedArray();
11577 
11578   if (!LVal.InvalidBase)
11579     return true;
11580 
11581   // If `E` is a MemberExpr, then the first part of the designator is hiding in
11582   // the LValueBase.
11583   const auto *E = LVal.Base.dyn_cast<const Expr *>();
11584   return !E || !isa<MemberExpr>(E);
11585 }
11586 
11587 /// Attempts to detect a user writing into a piece of memory that's impossible
11588 /// to figure out the size of by just using types.
11589 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
11590   const SubobjectDesignator &Designator = LVal.Designator;
11591   // Notes:
11592   // - Users can only write off of the end when we have an invalid base. Invalid
11593   //   bases imply we don't know where the memory came from.
11594   // - We used to be a bit more aggressive here; we'd only be conservative if
11595   //   the array at the end was flexible, or if it had 0 or 1 elements. This
11596   //   broke some common standard library extensions (PR30346), but was
11597   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
11598   //   with some sort of list. OTOH, it seems that GCC is always
11599   //   conservative with the last element in structs (if it's an array), so our
11600   //   current behavior is more compatible than an explicit list approach would
11601   //   be.
11602   int StrictFlexArraysLevel = Ctx.getLangOpts().StrictFlexArrays;
11603   return LVal.InvalidBase &&
11604          Designator.Entries.size() == Designator.MostDerivedPathLength &&
11605          Designator.MostDerivedIsArrayElement &&
11606          (Designator.isMostDerivedAnUnsizedArray() ||
11607           Designator.getMostDerivedArraySize() == 0 ||
11608           (Designator.getMostDerivedArraySize() == 1 &&
11609            StrictFlexArraysLevel < 2) ||
11610           StrictFlexArraysLevel == 0) &&
11611          isDesignatorAtObjectEnd(Ctx, LVal);
11612 }
11613 
11614 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
11615 /// Fails if the conversion would cause loss of precision.
11616 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
11617                                             CharUnits &Result) {
11618   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
11619   if (Int.ugt(CharUnitsMax))
11620     return false;
11621   Result = CharUnits::fromQuantity(Int.getZExtValue());
11622   return true;
11623 }
11624 
11625 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
11626 /// determine how many bytes exist from the beginning of the object to either
11627 /// the end of the current subobject, or the end of the object itself, depending
11628 /// on what the LValue looks like + the value of Type.
11629 ///
11630 /// If this returns false, the value of Result is undefined.
11631 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
11632                                unsigned Type, const LValue &LVal,
11633                                CharUnits &EndOffset) {
11634   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
11635 
11636   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
11637     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
11638       return false;
11639     return HandleSizeof(Info, ExprLoc, Ty, Result);
11640   };
11641 
11642   // We want to evaluate the size of the entire object. This is a valid fallback
11643   // for when Type=1 and the designator is invalid, because we're asked for an
11644   // upper-bound.
11645   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
11646     // Type=3 wants a lower bound, so we can't fall back to this.
11647     if (Type == 3 && !DetermineForCompleteObject)
11648       return false;
11649 
11650     llvm::APInt APEndOffset;
11651     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11652         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11653       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11654 
11655     if (LVal.InvalidBase)
11656       return false;
11657 
11658     QualType BaseTy = getObjectType(LVal.getLValueBase());
11659     return CheckedHandleSizeof(BaseTy, EndOffset);
11660   }
11661 
11662   // We want to evaluate the size of a subobject.
11663   const SubobjectDesignator &Designator = LVal.Designator;
11664 
11665   // The following is a moderately common idiom in C:
11666   //
11667   // struct Foo { int a; char c[1]; };
11668   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
11669   // strcpy(&F->c[0], Bar);
11670   //
11671   // In order to not break too much legacy code, we need to support it.
11672   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
11673     // If we can resolve this to an alloc_size call, we can hand that back,
11674     // because we know for certain how many bytes there are to write to.
11675     llvm::APInt APEndOffset;
11676     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11677         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11678       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11679 
11680     // If we cannot determine the size of the initial allocation, then we can't
11681     // given an accurate upper-bound. However, we are still able to give
11682     // conservative lower-bounds for Type=3.
11683     if (Type == 1)
11684       return false;
11685   }
11686 
11687   CharUnits BytesPerElem;
11688   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
11689     return false;
11690 
11691   // According to the GCC documentation, we want the size of the subobject
11692   // denoted by the pointer. But that's not quite right -- what we actually
11693   // want is the size of the immediately-enclosing array, if there is one.
11694   int64_t ElemsRemaining;
11695   if (Designator.MostDerivedIsArrayElement &&
11696       Designator.Entries.size() == Designator.MostDerivedPathLength) {
11697     uint64_t ArraySize = Designator.getMostDerivedArraySize();
11698     uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
11699     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
11700   } else {
11701     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
11702   }
11703 
11704   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
11705   return true;
11706 }
11707 
11708 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
11709 /// returns true and stores the result in @p Size.
11710 ///
11711 /// If @p WasError is non-null, this will report whether the failure to evaluate
11712 /// is to be treated as an Error in IntExprEvaluator.
11713 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
11714                                          EvalInfo &Info, uint64_t &Size) {
11715   // Determine the denoted object.
11716   LValue LVal;
11717   {
11718     // The operand of __builtin_object_size is never evaluated for side-effects.
11719     // If there are any, but we can determine the pointed-to object anyway, then
11720     // ignore the side-effects.
11721     SpeculativeEvaluationRAII SpeculativeEval(Info);
11722     IgnoreSideEffectsRAII Fold(Info);
11723 
11724     if (E->isGLValue()) {
11725       // It's possible for us to be given GLValues if we're called via
11726       // Expr::tryEvaluateObjectSize.
11727       APValue RVal;
11728       if (!EvaluateAsRValue(Info, E, RVal))
11729         return false;
11730       LVal.setFrom(Info.Ctx, RVal);
11731     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
11732                                 /*InvalidBaseOK=*/true))
11733       return false;
11734   }
11735 
11736   // If we point to before the start of the object, there are no accessible
11737   // bytes.
11738   if (LVal.getLValueOffset().isNegative()) {
11739     Size = 0;
11740     return true;
11741   }
11742 
11743   CharUnits EndOffset;
11744   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
11745     return false;
11746 
11747   // If we've fallen outside of the end offset, just pretend there's nothing to
11748   // write to/read from.
11749   if (EndOffset <= LVal.getLValueOffset())
11750     Size = 0;
11751   else
11752     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
11753   return true;
11754 }
11755 
11756 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
11757   if (unsigned BuiltinOp = E->getBuiltinCallee())
11758     return VisitBuiltinCallExpr(E, BuiltinOp);
11759 
11760   return ExprEvaluatorBaseTy::VisitCallExpr(E);
11761 }
11762 
11763 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
11764                                      APValue &Val, APSInt &Alignment) {
11765   QualType SrcTy = E->getArg(0)->getType();
11766   if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
11767     return false;
11768   // Even though we are evaluating integer expressions we could get a pointer
11769   // argument for the __builtin_is_aligned() case.
11770   if (SrcTy->isPointerType()) {
11771     LValue Ptr;
11772     if (!EvaluatePointer(E->getArg(0), Ptr, Info))
11773       return false;
11774     Ptr.moveInto(Val);
11775   } else if (!SrcTy->isIntegralOrEnumerationType()) {
11776     Info.FFDiag(E->getArg(0));
11777     return false;
11778   } else {
11779     APSInt SrcInt;
11780     if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
11781       return false;
11782     assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
11783            "Bit widths must be the same");
11784     Val = APValue(SrcInt);
11785   }
11786   assert(Val.hasValue());
11787   return true;
11788 }
11789 
11790 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
11791                                             unsigned BuiltinOp) {
11792   switch (BuiltinOp) {
11793   default:
11794     return ExprEvaluatorBaseTy::VisitCallExpr(E);
11795 
11796   case Builtin::BI__builtin_dynamic_object_size:
11797   case Builtin::BI__builtin_object_size: {
11798     // The type was checked when we built the expression.
11799     unsigned Type =
11800         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11801     assert(Type <= 3 && "unexpected type");
11802 
11803     uint64_t Size;
11804     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
11805       return Success(Size, E);
11806 
11807     if (E->getArg(0)->HasSideEffects(Info.Ctx))
11808       return Success((Type & 2) ? 0 : -1, E);
11809 
11810     // Expression had no side effects, but we couldn't statically determine the
11811     // size of the referenced object.
11812     switch (Info.EvalMode) {
11813     case EvalInfo::EM_ConstantExpression:
11814     case EvalInfo::EM_ConstantFold:
11815     case EvalInfo::EM_IgnoreSideEffects:
11816       // Leave it to IR generation.
11817       return Error(E);
11818     case EvalInfo::EM_ConstantExpressionUnevaluated:
11819       // Reduce it to a constant now.
11820       return Success((Type & 2) ? 0 : -1, E);
11821     }
11822 
11823     llvm_unreachable("unexpected EvalMode");
11824   }
11825 
11826   case Builtin::BI__builtin_os_log_format_buffer_size: {
11827     analyze_os_log::OSLogBufferLayout Layout;
11828     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
11829     return Success(Layout.size().getQuantity(), E);
11830   }
11831 
11832   case Builtin::BI__builtin_is_aligned: {
11833     APValue Src;
11834     APSInt Alignment;
11835     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11836       return false;
11837     if (Src.isLValue()) {
11838       // If we evaluated a pointer, check the minimum known alignment.
11839       LValue Ptr;
11840       Ptr.setFrom(Info.Ctx, Src);
11841       CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
11842       CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
11843       // We can return true if the known alignment at the computed offset is
11844       // greater than the requested alignment.
11845       assert(PtrAlign.isPowerOfTwo());
11846       assert(Alignment.isPowerOf2());
11847       if (PtrAlign.getQuantity() >= Alignment)
11848         return Success(1, E);
11849       // If the alignment is not known to be sufficient, some cases could still
11850       // be aligned at run time. However, if the requested alignment is less or
11851       // equal to the base alignment and the offset is not aligned, we know that
11852       // the run-time value can never be aligned.
11853       if (BaseAlignment.getQuantity() >= Alignment &&
11854           PtrAlign.getQuantity() < Alignment)
11855         return Success(0, E);
11856       // Otherwise we can't infer whether the value is sufficiently aligned.
11857       // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
11858       //  in cases where we can't fully evaluate the pointer.
11859       Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
11860           << Alignment;
11861       return false;
11862     }
11863     assert(Src.isInt());
11864     return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
11865   }
11866   case Builtin::BI__builtin_align_up: {
11867     APValue Src;
11868     APSInt Alignment;
11869     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11870       return false;
11871     if (!Src.isInt())
11872       return Error(E);
11873     APSInt AlignedVal =
11874         APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
11875                Src.getInt().isUnsigned());
11876     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11877     return Success(AlignedVal, E);
11878   }
11879   case Builtin::BI__builtin_align_down: {
11880     APValue Src;
11881     APSInt Alignment;
11882     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11883       return false;
11884     if (!Src.isInt())
11885       return Error(E);
11886     APSInt AlignedVal =
11887         APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
11888     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11889     return Success(AlignedVal, E);
11890   }
11891 
11892   case Builtin::BI__builtin_bitreverse8:
11893   case Builtin::BI__builtin_bitreverse16:
11894   case Builtin::BI__builtin_bitreverse32:
11895   case Builtin::BI__builtin_bitreverse64: {
11896     APSInt Val;
11897     if (!EvaluateInteger(E->getArg(0), Val, Info))
11898       return false;
11899 
11900     return Success(Val.reverseBits(), E);
11901   }
11902 
11903   case Builtin::BI__builtin_bswap16:
11904   case Builtin::BI__builtin_bswap32:
11905   case Builtin::BI__builtin_bswap64: {
11906     APSInt Val;
11907     if (!EvaluateInteger(E->getArg(0), Val, Info))
11908       return false;
11909 
11910     return Success(Val.byteSwap(), E);
11911   }
11912 
11913   case Builtin::BI__builtin_classify_type:
11914     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
11915 
11916   case Builtin::BI__builtin_clrsb:
11917   case Builtin::BI__builtin_clrsbl:
11918   case Builtin::BI__builtin_clrsbll: {
11919     APSInt Val;
11920     if (!EvaluateInteger(E->getArg(0), Val, Info))
11921       return false;
11922 
11923     return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
11924   }
11925 
11926   case Builtin::BI__builtin_clz:
11927   case Builtin::BI__builtin_clzl:
11928   case Builtin::BI__builtin_clzll:
11929   case Builtin::BI__builtin_clzs: {
11930     APSInt Val;
11931     if (!EvaluateInteger(E->getArg(0), Val, Info))
11932       return false;
11933     if (!Val)
11934       return Error(E);
11935 
11936     return Success(Val.countLeadingZeros(), E);
11937   }
11938 
11939   case Builtin::BI__builtin_constant_p: {
11940     const Expr *Arg = E->getArg(0);
11941     if (EvaluateBuiltinConstantP(Info, Arg))
11942       return Success(true, E);
11943     if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
11944       // Outside a constant context, eagerly evaluate to false in the presence
11945       // of side-effects in order to avoid -Wunsequenced false-positives in
11946       // a branch on __builtin_constant_p(expr).
11947       return Success(false, E);
11948     }
11949     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11950     return false;
11951   }
11952 
11953   case Builtin::BI__builtin_is_constant_evaluated: {
11954     const auto *Callee = Info.CurrentCall->getCallee();
11955     if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
11956         (Info.CallStackDepth == 1 ||
11957          (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
11958           Callee->getIdentifier() &&
11959           Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
11960       // FIXME: Find a better way to avoid duplicated diagnostics.
11961       if (Info.EvalStatus.Diag)
11962         Info.report((Info.CallStackDepth == 1) ? E->getExprLoc()
11963                                                : Info.CurrentCall->CallLoc,
11964                     diag::warn_is_constant_evaluated_always_true_constexpr)
11965             << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
11966                                          : "std::is_constant_evaluated");
11967     }
11968 
11969     return Success(Info.InConstantContext, E);
11970   }
11971 
11972   case Builtin::BI__builtin_ctz:
11973   case Builtin::BI__builtin_ctzl:
11974   case Builtin::BI__builtin_ctzll:
11975   case Builtin::BI__builtin_ctzs: {
11976     APSInt Val;
11977     if (!EvaluateInteger(E->getArg(0), Val, Info))
11978       return false;
11979     if (!Val)
11980       return Error(E);
11981 
11982     return Success(Val.countTrailingZeros(), E);
11983   }
11984 
11985   case Builtin::BI__builtin_eh_return_data_regno: {
11986     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11987     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
11988     return Success(Operand, E);
11989   }
11990 
11991   case Builtin::BI__builtin_expect:
11992   case Builtin::BI__builtin_expect_with_probability:
11993     return Visit(E->getArg(0));
11994 
11995   case Builtin::BI__builtin_ffs:
11996   case Builtin::BI__builtin_ffsl:
11997   case Builtin::BI__builtin_ffsll: {
11998     APSInt Val;
11999     if (!EvaluateInteger(E->getArg(0), Val, Info))
12000       return false;
12001 
12002     unsigned N = Val.countTrailingZeros();
12003     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
12004   }
12005 
12006   case Builtin::BI__builtin_fpclassify: {
12007     APFloat Val(0.0);
12008     if (!EvaluateFloat(E->getArg(5), Val, Info))
12009       return false;
12010     unsigned Arg;
12011     switch (Val.getCategory()) {
12012     case APFloat::fcNaN: Arg = 0; break;
12013     case APFloat::fcInfinity: Arg = 1; break;
12014     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
12015     case APFloat::fcZero: Arg = 4; break;
12016     }
12017     return Visit(E->getArg(Arg));
12018   }
12019 
12020   case Builtin::BI__builtin_isinf_sign: {
12021     APFloat Val(0.0);
12022     return EvaluateFloat(E->getArg(0), Val, Info) &&
12023            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
12024   }
12025 
12026   case Builtin::BI__builtin_isinf: {
12027     APFloat Val(0.0);
12028     return EvaluateFloat(E->getArg(0), Val, Info) &&
12029            Success(Val.isInfinity() ? 1 : 0, E);
12030   }
12031 
12032   case Builtin::BI__builtin_isfinite: {
12033     APFloat Val(0.0);
12034     return EvaluateFloat(E->getArg(0), Val, Info) &&
12035            Success(Val.isFinite() ? 1 : 0, E);
12036   }
12037 
12038   case Builtin::BI__builtin_isnan: {
12039     APFloat Val(0.0);
12040     return EvaluateFloat(E->getArg(0), Val, Info) &&
12041            Success(Val.isNaN() ? 1 : 0, E);
12042   }
12043 
12044   case Builtin::BI__builtin_isnormal: {
12045     APFloat Val(0.0);
12046     return EvaluateFloat(E->getArg(0), Val, Info) &&
12047            Success(Val.isNormal() ? 1 : 0, E);
12048   }
12049 
12050   case Builtin::BI__builtin_parity:
12051   case Builtin::BI__builtin_parityl:
12052   case Builtin::BI__builtin_parityll: {
12053     APSInt Val;
12054     if (!EvaluateInteger(E->getArg(0), Val, Info))
12055       return false;
12056 
12057     return Success(Val.countPopulation() % 2, E);
12058   }
12059 
12060   case Builtin::BI__builtin_popcount:
12061   case Builtin::BI__builtin_popcountl:
12062   case Builtin::BI__builtin_popcountll: {
12063     APSInt Val;
12064     if (!EvaluateInteger(E->getArg(0), Val, Info))
12065       return false;
12066 
12067     return Success(Val.countPopulation(), E);
12068   }
12069 
12070   case Builtin::BI__builtin_rotateleft8:
12071   case Builtin::BI__builtin_rotateleft16:
12072   case Builtin::BI__builtin_rotateleft32:
12073   case Builtin::BI__builtin_rotateleft64:
12074   case Builtin::BI_rotl8: // Microsoft variants of rotate right
12075   case Builtin::BI_rotl16:
12076   case Builtin::BI_rotl:
12077   case Builtin::BI_lrotl:
12078   case Builtin::BI_rotl64: {
12079     APSInt Val, Amt;
12080     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
12081         !EvaluateInteger(E->getArg(1), Amt, Info))
12082       return false;
12083 
12084     return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
12085   }
12086 
12087   case Builtin::BI__builtin_rotateright8:
12088   case Builtin::BI__builtin_rotateright16:
12089   case Builtin::BI__builtin_rotateright32:
12090   case Builtin::BI__builtin_rotateright64:
12091   case Builtin::BI_rotr8: // Microsoft variants of rotate right
12092   case Builtin::BI_rotr16:
12093   case Builtin::BI_rotr:
12094   case Builtin::BI_lrotr:
12095   case Builtin::BI_rotr64: {
12096     APSInt Val, Amt;
12097     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
12098         !EvaluateInteger(E->getArg(1), Amt, Info))
12099       return false;
12100 
12101     return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
12102   }
12103 
12104   case Builtin::BIstrlen:
12105   case Builtin::BIwcslen:
12106     // A call to strlen is not a constant expression.
12107     if (Info.getLangOpts().CPlusPlus11)
12108       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
12109         << /*isConstexpr*/0 << /*isConstructor*/0
12110         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
12111     else
12112       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12113     LLVM_FALLTHROUGH;
12114   case Builtin::BI__builtin_strlen:
12115   case Builtin::BI__builtin_wcslen: {
12116     // As an extension, we support __builtin_strlen() as a constant expression,
12117     // and support folding strlen() to a constant.
12118     uint64_t StrLen;
12119     if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
12120       return Success(StrLen, E);
12121     return false;
12122   }
12123 
12124   case Builtin::BIstrcmp:
12125   case Builtin::BIwcscmp:
12126   case Builtin::BIstrncmp:
12127   case Builtin::BIwcsncmp:
12128   case Builtin::BImemcmp:
12129   case Builtin::BIbcmp:
12130   case Builtin::BIwmemcmp:
12131     // A call to strlen is not a constant expression.
12132     if (Info.getLangOpts().CPlusPlus11)
12133       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
12134         << /*isConstexpr*/0 << /*isConstructor*/0
12135         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
12136     else
12137       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12138     LLVM_FALLTHROUGH;
12139   case Builtin::BI__builtin_strcmp:
12140   case Builtin::BI__builtin_wcscmp:
12141   case Builtin::BI__builtin_strncmp:
12142   case Builtin::BI__builtin_wcsncmp:
12143   case Builtin::BI__builtin_memcmp:
12144   case Builtin::BI__builtin_bcmp:
12145   case Builtin::BI__builtin_wmemcmp: {
12146     LValue String1, String2;
12147     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
12148         !EvaluatePointer(E->getArg(1), String2, Info))
12149       return false;
12150 
12151     uint64_t MaxLength = uint64_t(-1);
12152     if (BuiltinOp != Builtin::BIstrcmp &&
12153         BuiltinOp != Builtin::BIwcscmp &&
12154         BuiltinOp != Builtin::BI__builtin_strcmp &&
12155         BuiltinOp != Builtin::BI__builtin_wcscmp) {
12156       APSInt N;
12157       if (!EvaluateInteger(E->getArg(2), N, Info))
12158         return false;
12159       MaxLength = N.getExtValue();
12160     }
12161 
12162     // Empty substrings compare equal by definition.
12163     if (MaxLength == 0u)
12164       return Success(0, E);
12165 
12166     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
12167         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
12168         String1.Designator.Invalid || String2.Designator.Invalid)
12169       return false;
12170 
12171     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
12172     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
12173 
12174     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
12175                      BuiltinOp == Builtin::BIbcmp ||
12176                      BuiltinOp == Builtin::BI__builtin_memcmp ||
12177                      BuiltinOp == Builtin::BI__builtin_bcmp;
12178 
12179     assert(IsRawByte ||
12180            (Info.Ctx.hasSameUnqualifiedType(
12181                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
12182             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
12183 
12184     // For memcmp, allow comparing any arrays of '[[un]signed] char' or
12185     // 'char8_t', but no other types.
12186     if (IsRawByte &&
12187         !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
12188       // FIXME: Consider using our bit_cast implementation to support this.
12189       Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
12190           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
12191           << CharTy1 << CharTy2;
12192       return false;
12193     }
12194 
12195     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
12196       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
12197              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
12198              Char1.isInt() && Char2.isInt();
12199     };
12200     const auto &AdvanceElems = [&] {
12201       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
12202              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
12203     };
12204 
12205     bool StopAtNull =
12206         (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
12207          BuiltinOp != Builtin::BIwmemcmp &&
12208          BuiltinOp != Builtin::BI__builtin_memcmp &&
12209          BuiltinOp != Builtin::BI__builtin_bcmp &&
12210          BuiltinOp != Builtin::BI__builtin_wmemcmp);
12211     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
12212                   BuiltinOp == Builtin::BIwcsncmp ||
12213                   BuiltinOp == Builtin::BIwmemcmp ||
12214                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
12215                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
12216                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
12217 
12218     for (; MaxLength; --MaxLength) {
12219       APValue Char1, Char2;
12220       if (!ReadCurElems(Char1, Char2))
12221         return false;
12222       if (Char1.getInt().ne(Char2.getInt())) {
12223         if (IsWide) // wmemcmp compares with wchar_t signedness.
12224           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
12225         // memcmp always compares unsigned chars.
12226         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
12227       }
12228       if (StopAtNull && !Char1.getInt())
12229         return Success(0, E);
12230       assert(!(StopAtNull && !Char2.getInt()));
12231       if (!AdvanceElems())
12232         return false;
12233     }
12234     // We hit the strncmp / memcmp limit.
12235     return Success(0, E);
12236   }
12237 
12238   case Builtin::BI__atomic_always_lock_free:
12239   case Builtin::BI__atomic_is_lock_free:
12240   case Builtin::BI__c11_atomic_is_lock_free: {
12241     APSInt SizeVal;
12242     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
12243       return false;
12244 
12245     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
12246     // of two less than or equal to the maximum inline atomic width, we know it
12247     // is lock-free.  If the size isn't a power of two, or greater than the
12248     // maximum alignment where we promote atomics, we know it is not lock-free
12249     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
12250     // the answer can only be determined at runtime; for example, 16-byte
12251     // atomics have lock-free implementations on some, but not all,
12252     // x86-64 processors.
12253 
12254     // Check power-of-two.
12255     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
12256     if (Size.isPowerOfTwo()) {
12257       // Check against inlining width.
12258       unsigned InlineWidthBits =
12259           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
12260       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
12261         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
12262             Size == CharUnits::One() ||
12263             E->getArg(1)->isNullPointerConstant(Info.Ctx,
12264                                                 Expr::NPC_NeverValueDependent))
12265           // OK, we will inline appropriately-aligned operations of this size,
12266           // and _Atomic(T) is appropriately-aligned.
12267           return Success(1, E);
12268 
12269         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
12270           castAs<PointerType>()->getPointeeType();
12271         if (!PointeeType->isIncompleteType() &&
12272             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
12273           // OK, we will inline operations on this object.
12274           return Success(1, E);
12275         }
12276       }
12277     }
12278 
12279     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
12280         Success(0, E) : Error(E);
12281   }
12282   case Builtin::BI__builtin_add_overflow:
12283   case Builtin::BI__builtin_sub_overflow:
12284   case Builtin::BI__builtin_mul_overflow:
12285   case Builtin::BI__builtin_sadd_overflow:
12286   case Builtin::BI__builtin_uadd_overflow:
12287   case Builtin::BI__builtin_uaddl_overflow:
12288   case Builtin::BI__builtin_uaddll_overflow:
12289   case Builtin::BI__builtin_usub_overflow:
12290   case Builtin::BI__builtin_usubl_overflow:
12291   case Builtin::BI__builtin_usubll_overflow:
12292   case Builtin::BI__builtin_umul_overflow:
12293   case Builtin::BI__builtin_umull_overflow:
12294   case Builtin::BI__builtin_umulll_overflow:
12295   case Builtin::BI__builtin_saddl_overflow:
12296   case Builtin::BI__builtin_saddll_overflow:
12297   case Builtin::BI__builtin_ssub_overflow:
12298   case Builtin::BI__builtin_ssubl_overflow:
12299   case Builtin::BI__builtin_ssubll_overflow:
12300   case Builtin::BI__builtin_smul_overflow:
12301   case Builtin::BI__builtin_smull_overflow:
12302   case Builtin::BI__builtin_smulll_overflow: {
12303     LValue ResultLValue;
12304     APSInt LHS, RHS;
12305 
12306     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
12307     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
12308         !EvaluateInteger(E->getArg(1), RHS, Info) ||
12309         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
12310       return false;
12311 
12312     APSInt Result;
12313     bool DidOverflow = false;
12314 
12315     // If the types don't have to match, enlarge all 3 to the largest of them.
12316     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12317         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12318         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12319       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
12320                       ResultType->isSignedIntegerOrEnumerationType();
12321       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
12322                       ResultType->isSignedIntegerOrEnumerationType();
12323       uint64_t LHSSize = LHS.getBitWidth();
12324       uint64_t RHSSize = RHS.getBitWidth();
12325       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
12326       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
12327 
12328       // Add an additional bit if the signedness isn't uniformly agreed to. We
12329       // could do this ONLY if there is a signed and an unsigned that both have
12330       // MaxBits, but the code to check that is pretty nasty.  The issue will be
12331       // caught in the shrink-to-result later anyway.
12332       if (IsSigned && !AllSigned)
12333         ++MaxBits;
12334 
12335       LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
12336       RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
12337       Result = APSInt(MaxBits, !IsSigned);
12338     }
12339 
12340     // Find largest int.
12341     switch (BuiltinOp) {
12342     default:
12343       llvm_unreachable("Invalid value for BuiltinOp");
12344     case Builtin::BI__builtin_add_overflow:
12345     case Builtin::BI__builtin_sadd_overflow:
12346     case Builtin::BI__builtin_saddl_overflow:
12347     case Builtin::BI__builtin_saddll_overflow:
12348     case Builtin::BI__builtin_uadd_overflow:
12349     case Builtin::BI__builtin_uaddl_overflow:
12350     case Builtin::BI__builtin_uaddll_overflow:
12351       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
12352                               : LHS.uadd_ov(RHS, DidOverflow);
12353       break;
12354     case Builtin::BI__builtin_sub_overflow:
12355     case Builtin::BI__builtin_ssub_overflow:
12356     case Builtin::BI__builtin_ssubl_overflow:
12357     case Builtin::BI__builtin_ssubll_overflow:
12358     case Builtin::BI__builtin_usub_overflow:
12359     case Builtin::BI__builtin_usubl_overflow:
12360     case Builtin::BI__builtin_usubll_overflow:
12361       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
12362                               : LHS.usub_ov(RHS, DidOverflow);
12363       break;
12364     case Builtin::BI__builtin_mul_overflow:
12365     case Builtin::BI__builtin_smul_overflow:
12366     case Builtin::BI__builtin_smull_overflow:
12367     case Builtin::BI__builtin_smulll_overflow:
12368     case Builtin::BI__builtin_umul_overflow:
12369     case Builtin::BI__builtin_umull_overflow:
12370     case Builtin::BI__builtin_umulll_overflow:
12371       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
12372                               : LHS.umul_ov(RHS, DidOverflow);
12373       break;
12374     }
12375 
12376     // In the case where multiple sizes are allowed, truncate and see if
12377     // the values are the same.
12378     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12379         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12380         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12381       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
12382       // since it will give us the behavior of a TruncOrSelf in the case where
12383       // its parameter <= its size.  We previously set Result to be at least the
12384       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
12385       // will work exactly like TruncOrSelf.
12386       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
12387       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
12388 
12389       if (!APSInt::isSameValue(Temp, Result))
12390         DidOverflow = true;
12391       Result = Temp;
12392     }
12393 
12394     APValue APV{Result};
12395     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
12396       return false;
12397     return Success(DidOverflow, E);
12398   }
12399   }
12400 }
12401 
12402 /// Determine whether this is a pointer past the end of the complete
12403 /// object referred to by the lvalue.
12404 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
12405                                             const LValue &LV) {
12406   // A null pointer can be viewed as being "past the end" but we don't
12407   // choose to look at it that way here.
12408   if (!LV.getLValueBase())
12409     return false;
12410 
12411   // If the designator is valid and refers to a subobject, we're not pointing
12412   // past the end.
12413   if (!LV.getLValueDesignator().Invalid &&
12414       !LV.getLValueDesignator().isOnePastTheEnd())
12415     return false;
12416 
12417   // A pointer to an incomplete type might be past-the-end if the type's size is
12418   // zero.  We cannot tell because the type is incomplete.
12419   QualType Ty = getType(LV.getLValueBase());
12420   if (Ty->isIncompleteType())
12421     return true;
12422 
12423   // We're a past-the-end pointer if we point to the byte after the object,
12424   // no matter what our type or path is.
12425   auto Size = Ctx.getTypeSizeInChars(Ty);
12426   return LV.getLValueOffset() == Size;
12427 }
12428 
12429 namespace {
12430 
12431 /// Data recursive integer evaluator of certain binary operators.
12432 ///
12433 /// We use a data recursive algorithm for binary operators so that we are able
12434 /// to handle extreme cases of chained binary operators without causing stack
12435 /// overflow.
12436 class DataRecursiveIntBinOpEvaluator {
12437   struct EvalResult {
12438     APValue Val;
12439     bool Failed;
12440 
12441     EvalResult() : Failed(false) { }
12442 
12443     void swap(EvalResult &RHS) {
12444       Val.swap(RHS.Val);
12445       Failed = RHS.Failed;
12446       RHS.Failed = false;
12447     }
12448   };
12449 
12450   struct Job {
12451     const Expr *E;
12452     EvalResult LHSResult; // meaningful only for binary operator expression.
12453     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
12454 
12455     Job() = default;
12456     Job(Job &&) = default;
12457 
12458     void startSpeculativeEval(EvalInfo &Info) {
12459       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
12460     }
12461 
12462   private:
12463     SpeculativeEvaluationRAII SpecEvalRAII;
12464   };
12465 
12466   SmallVector<Job, 16> Queue;
12467 
12468   IntExprEvaluator &IntEval;
12469   EvalInfo &Info;
12470   APValue &FinalResult;
12471 
12472 public:
12473   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
12474     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
12475 
12476   /// True if \param E is a binary operator that we are going to handle
12477   /// data recursively.
12478   /// We handle binary operators that are comma, logical, or that have operands
12479   /// with integral or enumeration type.
12480   static bool shouldEnqueue(const BinaryOperator *E) {
12481     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
12482            (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() &&
12483             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12484             E->getRHS()->getType()->isIntegralOrEnumerationType());
12485   }
12486 
12487   bool Traverse(const BinaryOperator *E) {
12488     enqueue(E);
12489     EvalResult PrevResult;
12490     while (!Queue.empty())
12491       process(PrevResult);
12492 
12493     if (PrevResult.Failed) return false;
12494 
12495     FinalResult.swap(PrevResult.Val);
12496     return true;
12497   }
12498 
12499 private:
12500   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
12501     return IntEval.Success(Value, E, Result);
12502   }
12503   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
12504     return IntEval.Success(Value, E, Result);
12505   }
12506   bool Error(const Expr *E) {
12507     return IntEval.Error(E);
12508   }
12509   bool Error(const Expr *E, diag::kind D) {
12510     return IntEval.Error(E, D);
12511   }
12512 
12513   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
12514     return Info.CCEDiag(E, D);
12515   }
12516 
12517   // Returns true if visiting the RHS is necessary, false otherwise.
12518   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12519                          bool &SuppressRHSDiags);
12520 
12521   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12522                   const BinaryOperator *E, APValue &Result);
12523 
12524   void EvaluateExpr(const Expr *E, EvalResult &Result) {
12525     Result.Failed = !Evaluate(Result.Val, Info, E);
12526     if (Result.Failed)
12527       Result.Val = APValue();
12528   }
12529 
12530   void process(EvalResult &Result);
12531 
12532   void enqueue(const Expr *E) {
12533     E = E->IgnoreParens();
12534     Queue.resize(Queue.size()+1);
12535     Queue.back().E = E;
12536     Queue.back().Kind = Job::AnyExprKind;
12537   }
12538 };
12539 
12540 }
12541 
12542 bool DataRecursiveIntBinOpEvaluator::
12543        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12544                          bool &SuppressRHSDiags) {
12545   if (E->getOpcode() == BO_Comma) {
12546     // Ignore LHS but note if we could not evaluate it.
12547     if (LHSResult.Failed)
12548       return Info.noteSideEffect();
12549     return true;
12550   }
12551 
12552   if (E->isLogicalOp()) {
12553     bool LHSAsBool;
12554     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
12555       // We were able to evaluate the LHS, see if we can get away with not
12556       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
12557       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
12558         Success(LHSAsBool, E, LHSResult.Val);
12559         return false; // Ignore RHS
12560       }
12561     } else {
12562       LHSResult.Failed = true;
12563 
12564       // Since we weren't able to evaluate the left hand side, it
12565       // might have had side effects.
12566       if (!Info.noteSideEffect())
12567         return false;
12568 
12569       // We can't evaluate the LHS; however, sometimes the result
12570       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12571       // Don't ignore RHS and suppress diagnostics from this arm.
12572       SuppressRHSDiags = true;
12573     }
12574 
12575     return true;
12576   }
12577 
12578   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12579          E->getRHS()->getType()->isIntegralOrEnumerationType());
12580 
12581   if (LHSResult.Failed && !Info.noteFailure())
12582     return false; // Ignore RHS;
12583 
12584   return true;
12585 }
12586 
12587 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
12588                                     bool IsSub) {
12589   // Compute the new offset in the appropriate width, wrapping at 64 bits.
12590   // FIXME: When compiling for a 32-bit target, we should use 32-bit
12591   // offsets.
12592   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
12593   CharUnits &Offset = LVal.getLValueOffset();
12594   uint64_t Offset64 = Offset.getQuantity();
12595   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
12596   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
12597                                          : Offset64 + Index64);
12598 }
12599 
12600 bool DataRecursiveIntBinOpEvaluator::
12601        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12602                   const BinaryOperator *E, APValue &Result) {
12603   if (E->getOpcode() == BO_Comma) {
12604     if (RHSResult.Failed)
12605       return false;
12606     Result = RHSResult.Val;
12607     return true;
12608   }
12609 
12610   if (E->isLogicalOp()) {
12611     bool lhsResult, rhsResult;
12612     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
12613     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
12614 
12615     if (LHSIsOK) {
12616       if (RHSIsOK) {
12617         if (E->getOpcode() == BO_LOr)
12618           return Success(lhsResult || rhsResult, E, Result);
12619         else
12620           return Success(lhsResult && rhsResult, E, Result);
12621       }
12622     } else {
12623       if (RHSIsOK) {
12624         // We can't evaluate the LHS; however, sometimes the result
12625         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12626         if (rhsResult == (E->getOpcode() == BO_LOr))
12627           return Success(rhsResult, E, Result);
12628       }
12629     }
12630 
12631     return false;
12632   }
12633 
12634   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12635          E->getRHS()->getType()->isIntegralOrEnumerationType());
12636 
12637   if (LHSResult.Failed || RHSResult.Failed)
12638     return false;
12639 
12640   const APValue &LHSVal = LHSResult.Val;
12641   const APValue &RHSVal = RHSResult.Val;
12642 
12643   // Handle cases like (unsigned long)&a + 4.
12644   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
12645     Result = LHSVal;
12646     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
12647     return true;
12648   }
12649 
12650   // Handle cases like 4 + (unsigned long)&a
12651   if (E->getOpcode() == BO_Add &&
12652       RHSVal.isLValue() && LHSVal.isInt()) {
12653     Result = RHSVal;
12654     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
12655     return true;
12656   }
12657 
12658   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
12659     // Handle (intptr_t)&&A - (intptr_t)&&B.
12660     if (!LHSVal.getLValueOffset().isZero() ||
12661         !RHSVal.getLValueOffset().isZero())
12662       return false;
12663     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
12664     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
12665     if (!LHSExpr || !RHSExpr)
12666       return false;
12667     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12668     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12669     if (!LHSAddrExpr || !RHSAddrExpr)
12670       return false;
12671     // Make sure both labels come from the same function.
12672     if (LHSAddrExpr->getLabel()->getDeclContext() !=
12673         RHSAddrExpr->getLabel()->getDeclContext())
12674       return false;
12675     Result = APValue(LHSAddrExpr, RHSAddrExpr);
12676     return true;
12677   }
12678 
12679   // All the remaining cases expect both operands to be an integer
12680   if (!LHSVal.isInt() || !RHSVal.isInt())
12681     return Error(E);
12682 
12683   // Set up the width and signedness manually, in case it can't be deduced
12684   // from the operation we're performing.
12685   // FIXME: Don't do this in the cases where we can deduce it.
12686   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
12687                E->getType()->isUnsignedIntegerOrEnumerationType());
12688   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
12689                          RHSVal.getInt(), Value))
12690     return false;
12691   return Success(Value, E, Result);
12692 }
12693 
12694 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
12695   Job &job = Queue.back();
12696 
12697   switch (job.Kind) {
12698     case Job::AnyExprKind: {
12699       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
12700         if (shouldEnqueue(Bop)) {
12701           job.Kind = Job::BinOpKind;
12702           enqueue(Bop->getLHS());
12703           return;
12704         }
12705       }
12706 
12707       EvaluateExpr(job.E, Result);
12708       Queue.pop_back();
12709       return;
12710     }
12711 
12712     case Job::BinOpKind: {
12713       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12714       bool SuppressRHSDiags = false;
12715       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
12716         Queue.pop_back();
12717         return;
12718       }
12719       if (SuppressRHSDiags)
12720         job.startSpeculativeEval(Info);
12721       job.LHSResult.swap(Result);
12722       job.Kind = Job::BinOpVisitedLHSKind;
12723       enqueue(Bop->getRHS());
12724       return;
12725     }
12726 
12727     case Job::BinOpVisitedLHSKind: {
12728       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12729       EvalResult RHS;
12730       RHS.swap(Result);
12731       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
12732       Queue.pop_back();
12733       return;
12734     }
12735   }
12736 
12737   llvm_unreachable("Invalid Job::Kind!");
12738 }
12739 
12740 namespace {
12741 enum class CmpResult {
12742   Unequal,
12743   Less,
12744   Equal,
12745   Greater,
12746   Unordered,
12747 };
12748 }
12749 
12750 template <class SuccessCB, class AfterCB>
12751 static bool
12752 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
12753                                  SuccessCB &&Success, AfterCB &&DoAfter) {
12754   assert(!E->isValueDependent());
12755   assert(E->isComparisonOp() && "expected comparison operator");
12756   assert((E->getOpcode() == BO_Cmp ||
12757           E->getType()->isIntegralOrEnumerationType()) &&
12758          "unsupported binary expression evaluation");
12759   auto Error = [&](const Expr *E) {
12760     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12761     return false;
12762   };
12763 
12764   bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
12765   bool IsEquality = E->isEqualityOp();
12766 
12767   QualType LHSTy = E->getLHS()->getType();
12768   QualType RHSTy = E->getRHS()->getType();
12769 
12770   if (LHSTy->isIntegralOrEnumerationType() &&
12771       RHSTy->isIntegralOrEnumerationType()) {
12772     APSInt LHS, RHS;
12773     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
12774     if (!LHSOK && !Info.noteFailure())
12775       return false;
12776     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
12777       return false;
12778     if (LHS < RHS)
12779       return Success(CmpResult::Less, E);
12780     if (LHS > RHS)
12781       return Success(CmpResult::Greater, E);
12782     return Success(CmpResult::Equal, E);
12783   }
12784 
12785   if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
12786     APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
12787     APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
12788 
12789     bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
12790     if (!LHSOK && !Info.noteFailure())
12791       return false;
12792     if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
12793       return false;
12794     if (LHSFX < RHSFX)
12795       return Success(CmpResult::Less, E);
12796     if (LHSFX > RHSFX)
12797       return Success(CmpResult::Greater, E);
12798     return Success(CmpResult::Equal, E);
12799   }
12800 
12801   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
12802     ComplexValue LHS, RHS;
12803     bool LHSOK;
12804     if (E->isAssignmentOp()) {
12805       LValue LV;
12806       EvaluateLValue(E->getLHS(), LV, Info);
12807       LHSOK = false;
12808     } else if (LHSTy->isRealFloatingType()) {
12809       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
12810       if (LHSOK) {
12811         LHS.makeComplexFloat();
12812         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
12813       }
12814     } else {
12815       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
12816     }
12817     if (!LHSOK && !Info.noteFailure())
12818       return false;
12819 
12820     if (E->getRHS()->getType()->isRealFloatingType()) {
12821       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
12822         return false;
12823       RHS.makeComplexFloat();
12824       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
12825     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
12826       return false;
12827 
12828     if (LHS.isComplexFloat()) {
12829       APFloat::cmpResult CR_r =
12830         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
12831       APFloat::cmpResult CR_i =
12832         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
12833       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
12834       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12835     } else {
12836       assert(IsEquality && "invalid complex comparison");
12837       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
12838                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
12839       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12840     }
12841   }
12842 
12843   if (LHSTy->isRealFloatingType() &&
12844       RHSTy->isRealFloatingType()) {
12845     APFloat RHS(0.0), LHS(0.0);
12846 
12847     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
12848     if (!LHSOK && !Info.noteFailure())
12849       return false;
12850 
12851     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
12852       return false;
12853 
12854     assert(E->isComparisonOp() && "Invalid binary operator!");
12855     llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
12856     if (!Info.InConstantContext &&
12857         APFloatCmpResult == APFloat::cmpUnordered &&
12858         E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
12859       // Note: Compares may raise invalid in some cases involving NaN or sNaN.
12860       Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
12861       return false;
12862     }
12863     auto GetCmpRes = [&]() {
12864       switch (APFloatCmpResult) {
12865       case APFloat::cmpEqual:
12866         return CmpResult::Equal;
12867       case APFloat::cmpLessThan:
12868         return CmpResult::Less;
12869       case APFloat::cmpGreaterThan:
12870         return CmpResult::Greater;
12871       case APFloat::cmpUnordered:
12872         return CmpResult::Unordered;
12873       }
12874       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
12875     };
12876     return Success(GetCmpRes(), E);
12877   }
12878 
12879   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
12880     LValue LHSValue, RHSValue;
12881 
12882     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12883     if (!LHSOK && !Info.noteFailure())
12884       return false;
12885 
12886     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12887       return false;
12888 
12889     // Reject differing bases from the normal codepath; we special-case
12890     // comparisons to null.
12891     if (!HasSameBase(LHSValue, RHSValue)) {
12892       // Inequalities and subtractions between unrelated pointers have
12893       // unspecified or undefined behavior.
12894       if (!IsEquality) {
12895         Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified);
12896         return false;
12897       }
12898       // A constant address may compare equal to the address of a symbol.
12899       // The one exception is that address of an object cannot compare equal
12900       // to a null pointer constant.
12901       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
12902           (!RHSValue.Base && !RHSValue.Offset.isZero()))
12903         return Error(E);
12904       // It's implementation-defined whether distinct literals will have
12905       // distinct addresses. In clang, the result of such a comparison is
12906       // unspecified, so it is not a constant expression. However, we do know
12907       // that the address of a literal will be non-null.
12908       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
12909           LHSValue.Base && RHSValue.Base)
12910         return Error(E);
12911       // We can't tell whether weak symbols will end up pointing to the same
12912       // object.
12913       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
12914         return Error(E);
12915       // We can't compare the address of the start of one object with the
12916       // past-the-end address of another object, per C++ DR1652.
12917       if ((LHSValue.Base && LHSValue.Offset.isZero() &&
12918            isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
12919           (RHSValue.Base && RHSValue.Offset.isZero() &&
12920            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
12921         return Error(E);
12922       // We can't tell whether an object is at the same address as another
12923       // zero sized object.
12924       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
12925           (LHSValue.Base && isZeroSized(RHSValue)))
12926         return Error(E);
12927       return Success(CmpResult::Unequal, E);
12928     }
12929 
12930     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12931     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12932 
12933     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12934     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12935 
12936     // C++11 [expr.rel]p3:
12937     //   Pointers to void (after pointer conversions) can be compared, with a
12938     //   result defined as follows: If both pointers represent the same
12939     //   address or are both the null pointer value, the result is true if the
12940     //   operator is <= or >= and false otherwise; otherwise the result is
12941     //   unspecified.
12942     // We interpret this as applying to pointers to *cv* void.
12943     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
12944       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
12945 
12946     // C++11 [expr.rel]p2:
12947     // - If two pointers point to non-static data members of the same object,
12948     //   or to subobjects or array elements fo such members, recursively, the
12949     //   pointer to the later declared member compares greater provided the
12950     //   two members have the same access control and provided their class is
12951     //   not a union.
12952     //   [...]
12953     // - Otherwise pointer comparisons are unspecified.
12954     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
12955       bool WasArrayIndex;
12956       unsigned Mismatch = FindDesignatorMismatch(
12957           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
12958       // At the point where the designators diverge, the comparison has a
12959       // specified value if:
12960       //  - we are comparing array indices
12961       //  - we are comparing fields of a union, or fields with the same access
12962       // Otherwise, the result is unspecified and thus the comparison is not a
12963       // constant expression.
12964       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
12965           Mismatch < RHSDesignator.Entries.size()) {
12966         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
12967         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
12968         if (!LF && !RF)
12969           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
12970         else if (!LF)
12971           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12972               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
12973               << RF->getParent() << RF;
12974         else if (!RF)
12975           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12976               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
12977               << LF->getParent() << LF;
12978         else if (!LF->getParent()->isUnion() &&
12979                  LF->getAccess() != RF->getAccess())
12980           Info.CCEDiag(E,
12981                        diag::note_constexpr_pointer_comparison_differing_access)
12982               << LF << LF->getAccess() << RF << RF->getAccess()
12983               << LF->getParent();
12984       }
12985     }
12986 
12987     // The comparison here must be unsigned, and performed with the same
12988     // width as the pointer.
12989     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
12990     uint64_t CompareLHS = LHSOffset.getQuantity();
12991     uint64_t CompareRHS = RHSOffset.getQuantity();
12992     assert(PtrSize <= 64 && "Unexpected pointer width");
12993     uint64_t Mask = ~0ULL >> (64 - PtrSize);
12994     CompareLHS &= Mask;
12995     CompareRHS &= Mask;
12996 
12997     // If there is a base and this is a relational operator, we can only
12998     // compare pointers within the object in question; otherwise, the result
12999     // depends on where the object is located in memory.
13000     if (!LHSValue.Base.isNull() && IsRelational) {
13001       QualType BaseTy = getType(LHSValue.Base);
13002       if (BaseTy->isIncompleteType())
13003         return Error(E);
13004       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
13005       uint64_t OffsetLimit = Size.getQuantity();
13006       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
13007         return Error(E);
13008     }
13009 
13010     if (CompareLHS < CompareRHS)
13011       return Success(CmpResult::Less, E);
13012     if (CompareLHS > CompareRHS)
13013       return Success(CmpResult::Greater, E);
13014     return Success(CmpResult::Equal, E);
13015   }
13016 
13017   if (LHSTy->isMemberPointerType()) {
13018     assert(IsEquality && "unexpected member pointer operation");
13019     assert(RHSTy->isMemberPointerType() && "invalid comparison");
13020 
13021     MemberPtr LHSValue, RHSValue;
13022 
13023     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
13024     if (!LHSOK && !Info.noteFailure())
13025       return false;
13026 
13027     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13028       return false;
13029 
13030     // C++11 [expr.eq]p2:
13031     //   If both operands are null, they compare equal. Otherwise if only one is
13032     //   null, they compare unequal.
13033     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
13034       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
13035       return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
13036     }
13037 
13038     //   Otherwise if either is a pointer to a virtual member function, the
13039     //   result is unspecified.
13040     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
13041       if (MD->isVirtual())
13042         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
13043     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
13044       if (MD->isVirtual())
13045         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
13046 
13047     //   Otherwise they compare equal if and only if they would refer to the
13048     //   same member of the same most derived object or the same subobject if
13049     //   they were dereferenced with a hypothetical object of the associated
13050     //   class type.
13051     bool Equal = LHSValue == RHSValue;
13052     return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
13053   }
13054 
13055   if (LHSTy->isNullPtrType()) {
13056     assert(E->isComparisonOp() && "unexpected nullptr operation");
13057     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
13058     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
13059     // are compared, the result is true of the operator is <=, >= or ==, and
13060     // false otherwise.
13061     return Success(CmpResult::Equal, E);
13062   }
13063 
13064   return DoAfter();
13065 }
13066 
13067 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
13068   if (!CheckLiteralType(Info, E))
13069     return false;
13070 
13071   auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
13072     ComparisonCategoryResult CCR;
13073     switch (CR) {
13074     case CmpResult::Unequal:
13075       llvm_unreachable("should never produce Unequal for three-way comparison");
13076     case CmpResult::Less:
13077       CCR = ComparisonCategoryResult::Less;
13078       break;
13079     case CmpResult::Equal:
13080       CCR = ComparisonCategoryResult::Equal;
13081       break;
13082     case CmpResult::Greater:
13083       CCR = ComparisonCategoryResult::Greater;
13084       break;
13085     case CmpResult::Unordered:
13086       CCR = ComparisonCategoryResult::Unordered;
13087       break;
13088     }
13089     // Evaluation succeeded. Lookup the information for the comparison category
13090     // type and fetch the VarDecl for the result.
13091     const ComparisonCategoryInfo &CmpInfo =
13092         Info.Ctx.CompCategories.getInfoForType(E->getType());
13093     const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
13094     // Check and evaluate the result as a constant expression.
13095     LValue LV;
13096     LV.set(VD);
13097     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
13098       return false;
13099     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
13100                                    ConstantExprKind::Normal);
13101   };
13102   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
13103     return ExprEvaluatorBaseTy::VisitBinCmp(E);
13104   });
13105 }
13106 
13107 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13108   // We don't support assignment in C. C++ assignments don't get here because
13109   // assignment is an lvalue in C++.
13110   if (E->isAssignmentOp()) {
13111     Error(E);
13112     if (!Info.noteFailure())
13113       return false;
13114   }
13115 
13116   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
13117     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
13118 
13119   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
13120           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
13121          "DataRecursiveIntBinOpEvaluator should have handled integral types");
13122 
13123   if (E->isComparisonOp()) {
13124     // Evaluate builtin binary comparisons by evaluating them as three-way
13125     // comparisons and then translating the result.
13126     auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
13127       assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
13128              "should only produce Unequal for equality comparisons");
13129       bool IsEqual   = CR == CmpResult::Equal,
13130            IsLess    = CR == CmpResult::Less,
13131            IsGreater = CR == CmpResult::Greater;
13132       auto Op = E->getOpcode();
13133       switch (Op) {
13134       default:
13135         llvm_unreachable("unsupported binary operator");
13136       case BO_EQ:
13137       case BO_NE:
13138         return Success(IsEqual == (Op == BO_EQ), E);
13139       case BO_LT:
13140         return Success(IsLess, E);
13141       case BO_GT:
13142         return Success(IsGreater, E);
13143       case BO_LE:
13144         return Success(IsEqual || IsLess, E);
13145       case BO_GE:
13146         return Success(IsEqual || IsGreater, E);
13147       }
13148     };
13149     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
13150       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13151     });
13152   }
13153 
13154   QualType LHSTy = E->getLHS()->getType();
13155   QualType RHSTy = E->getRHS()->getType();
13156 
13157   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
13158       E->getOpcode() == BO_Sub) {
13159     LValue LHSValue, RHSValue;
13160 
13161     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
13162     if (!LHSOK && !Info.noteFailure())
13163       return false;
13164 
13165     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13166       return false;
13167 
13168     // Reject differing bases from the normal codepath; we special-case
13169     // comparisons to null.
13170     if (!HasSameBase(LHSValue, RHSValue)) {
13171       // Handle &&A - &&B.
13172       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
13173         return Error(E);
13174       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
13175       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
13176       if (!LHSExpr || !RHSExpr)
13177         return Error(E);
13178       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
13179       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
13180       if (!LHSAddrExpr || !RHSAddrExpr)
13181         return Error(E);
13182       // Make sure both labels come from the same function.
13183       if (LHSAddrExpr->getLabel()->getDeclContext() !=
13184           RHSAddrExpr->getLabel()->getDeclContext())
13185         return Error(E);
13186       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
13187     }
13188     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
13189     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
13190 
13191     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
13192     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
13193 
13194     // C++11 [expr.add]p6:
13195     //   Unless both pointers point to elements of the same array object, or
13196     //   one past the last element of the array object, the behavior is
13197     //   undefined.
13198     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
13199         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
13200                                 RHSDesignator))
13201       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
13202 
13203     QualType Type = E->getLHS()->getType();
13204     QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
13205 
13206     CharUnits ElementSize;
13207     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
13208       return false;
13209 
13210     // As an extension, a type may have zero size (empty struct or union in
13211     // C, array of zero length). Pointer subtraction in such cases has
13212     // undefined behavior, so is not constant.
13213     if (ElementSize.isZero()) {
13214       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
13215           << ElementType;
13216       return false;
13217     }
13218 
13219     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
13220     // and produce incorrect results when it overflows. Such behavior
13221     // appears to be non-conforming, but is common, so perhaps we should
13222     // assume the standard intended for such cases to be undefined behavior
13223     // and check for them.
13224 
13225     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
13226     // overflow in the final conversion to ptrdiff_t.
13227     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
13228     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
13229     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
13230                     false);
13231     APSInt TrueResult = (LHS - RHS) / ElemSize;
13232     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
13233 
13234     if (Result.extend(65) != TrueResult &&
13235         !HandleOverflow(Info, E, TrueResult, E->getType()))
13236       return false;
13237     return Success(Result, E);
13238   }
13239 
13240   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13241 }
13242 
13243 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
13244 /// a result as the expression's type.
13245 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
13246                                     const UnaryExprOrTypeTraitExpr *E) {
13247   switch(E->getKind()) {
13248   case UETT_PreferredAlignOf:
13249   case UETT_AlignOf: {
13250     if (E->isArgumentType())
13251       return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
13252                      E);
13253     else
13254       return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
13255                      E);
13256   }
13257 
13258   case UETT_VecStep: {
13259     QualType Ty = E->getTypeOfArgument();
13260 
13261     if (Ty->isVectorType()) {
13262       unsigned n = Ty->castAs<VectorType>()->getNumElements();
13263 
13264       // The vec_step built-in functions that take a 3-component
13265       // vector return 4. (OpenCL 1.1 spec 6.11.12)
13266       if (n == 3)
13267         n = 4;
13268 
13269       return Success(n, E);
13270     } else
13271       return Success(1, E);
13272   }
13273 
13274   case UETT_SizeOf: {
13275     QualType SrcTy = E->getTypeOfArgument();
13276     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
13277     //   the result is the size of the referenced type."
13278     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
13279       SrcTy = Ref->getPointeeType();
13280 
13281     CharUnits Sizeof;
13282     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
13283       return false;
13284     return Success(Sizeof, E);
13285   }
13286   case UETT_OpenMPRequiredSimdAlign:
13287     assert(E->isArgumentType());
13288     return Success(
13289         Info.Ctx.toCharUnitsFromBits(
13290                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
13291             .getQuantity(),
13292         E);
13293   }
13294 
13295   llvm_unreachable("unknown expr/type trait");
13296 }
13297 
13298 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
13299   CharUnits Result;
13300   unsigned n = OOE->getNumComponents();
13301   if (n == 0)
13302     return Error(OOE);
13303   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
13304   for (unsigned i = 0; i != n; ++i) {
13305     OffsetOfNode ON = OOE->getComponent(i);
13306     switch (ON.getKind()) {
13307     case OffsetOfNode::Array: {
13308       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
13309       APSInt IdxResult;
13310       if (!EvaluateInteger(Idx, IdxResult, Info))
13311         return false;
13312       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
13313       if (!AT)
13314         return Error(OOE);
13315       CurrentType = AT->getElementType();
13316       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
13317       Result += IdxResult.getSExtValue() * ElementSize;
13318       break;
13319     }
13320 
13321     case OffsetOfNode::Field: {
13322       FieldDecl *MemberDecl = ON.getField();
13323       const RecordType *RT = CurrentType->getAs<RecordType>();
13324       if (!RT)
13325         return Error(OOE);
13326       RecordDecl *RD = RT->getDecl();
13327       if (RD->isInvalidDecl()) return false;
13328       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13329       unsigned i = MemberDecl->getFieldIndex();
13330       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
13331       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
13332       CurrentType = MemberDecl->getType().getNonReferenceType();
13333       break;
13334     }
13335 
13336     case OffsetOfNode::Identifier:
13337       llvm_unreachable("dependent __builtin_offsetof");
13338 
13339     case OffsetOfNode::Base: {
13340       CXXBaseSpecifier *BaseSpec = ON.getBase();
13341       if (BaseSpec->isVirtual())
13342         return Error(OOE);
13343 
13344       // Find the layout of the class whose base we are looking into.
13345       const RecordType *RT = CurrentType->getAs<RecordType>();
13346       if (!RT)
13347         return Error(OOE);
13348       RecordDecl *RD = RT->getDecl();
13349       if (RD->isInvalidDecl()) return false;
13350       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13351 
13352       // Find the base class itself.
13353       CurrentType = BaseSpec->getType();
13354       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
13355       if (!BaseRT)
13356         return Error(OOE);
13357 
13358       // Add the offset to the base.
13359       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
13360       break;
13361     }
13362     }
13363   }
13364   return Success(Result, OOE);
13365 }
13366 
13367 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13368   switch (E->getOpcode()) {
13369   default:
13370     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
13371     // See C99 6.6p3.
13372     return Error(E);
13373   case UO_Extension:
13374     // FIXME: Should extension allow i-c-e extension expressions in its scope?
13375     // If so, we could clear the diagnostic ID.
13376     return Visit(E->getSubExpr());
13377   case UO_Plus:
13378     // The result is just the value.
13379     return Visit(E->getSubExpr());
13380   case UO_Minus: {
13381     if (!Visit(E->getSubExpr()))
13382       return false;
13383     if (!Result.isInt()) return Error(E);
13384     const APSInt &Value = Result.getInt();
13385     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
13386         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
13387                         E->getType()))
13388       return false;
13389     return Success(-Value, E);
13390   }
13391   case UO_Not: {
13392     if (!Visit(E->getSubExpr()))
13393       return false;
13394     if (!Result.isInt()) return Error(E);
13395     return Success(~Result.getInt(), E);
13396   }
13397   case UO_LNot: {
13398     bool bres;
13399     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13400       return false;
13401     return Success(!bres, E);
13402   }
13403   }
13404 }
13405 
13406 /// HandleCast - This is used to evaluate implicit or explicit casts where the
13407 /// result type is integer.
13408 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
13409   const Expr *SubExpr = E->getSubExpr();
13410   QualType DestType = E->getType();
13411   QualType SrcType = SubExpr->getType();
13412 
13413   switch (E->getCastKind()) {
13414   case CK_BaseToDerived:
13415   case CK_DerivedToBase:
13416   case CK_UncheckedDerivedToBase:
13417   case CK_Dynamic:
13418   case CK_ToUnion:
13419   case CK_ArrayToPointerDecay:
13420   case CK_FunctionToPointerDecay:
13421   case CK_NullToPointer:
13422   case CK_NullToMemberPointer:
13423   case CK_BaseToDerivedMemberPointer:
13424   case CK_DerivedToBaseMemberPointer:
13425   case CK_ReinterpretMemberPointer:
13426   case CK_ConstructorConversion:
13427   case CK_IntegralToPointer:
13428   case CK_ToVoid:
13429   case CK_VectorSplat:
13430   case CK_IntegralToFloating:
13431   case CK_FloatingCast:
13432   case CK_CPointerToObjCPointerCast:
13433   case CK_BlockPointerToObjCPointerCast:
13434   case CK_AnyPointerToBlockPointerCast:
13435   case CK_ObjCObjectLValueCast:
13436   case CK_FloatingRealToComplex:
13437   case CK_FloatingComplexToReal:
13438   case CK_FloatingComplexCast:
13439   case CK_FloatingComplexToIntegralComplex:
13440   case CK_IntegralRealToComplex:
13441   case CK_IntegralComplexCast:
13442   case CK_IntegralComplexToFloatingComplex:
13443   case CK_BuiltinFnToFnPtr:
13444   case CK_ZeroToOCLOpaqueType:
13445   case CK_NonAtomicToAtomic:
13446   case CK_AddressSpaceConversion:
13447   case CK_IntToOCLSampler:
13448   case CK_FloatingToFixedPoint:
13449   case CK_FixedPointToFloating:
13450   case CK_FixedPointCast:
13451   case CK_IntegralToFixedPoint:
13452   case CK_MatrixCast:
13453     llvm_unreachable("invalid cast kind for integral value");
13454 
13455   case CK_BitCast:
13456   case CK_Dependent:
13457   case CK_LValueBitCast:
13458   case CK_ARCProduceObject:
13459   case CK_ARCConsumeObject:
13460   case CK_ARCReclaimReturnedObject:
13461   case CK_ARCExtendBlockObject:
13462   case CK_CopyAndAutoreleaseBlockObject:
13463     return Error(E);
13464 
13465   case CK_UserDefinedConversion:
13466   case CK_LValueToRValue:
13467   case CK_AtomicToNonAtomic:
13468   case CK_NoOp:
13469   case CK_LValueToRValueBitCast:
13470     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13471 
13472   case CK_MemberPointerToBoolean:
13473   case CK_PointerToBoolean:
13474   case CK_IntegralToBoolean:
13475   case CK_FloatingToBoolean:
13476   case CK_BooleanToSignedIntegral:
13477   case CK_FloatingComplexToBoolean:
13478   case CK_IntegralComplexToBoolean: {
13479     bool BoolResult;
13480     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
13481       return false;
13482     uint64_t IntResult = BoolResult;
13483     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
13484       IntResult = (uint64_t)-1;
13485     return Success(IntResult, E);
13486   }
13487 
13488   case CK_FixedPointToIntegral: {
13489     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
13490     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13491       return false;
13492     bool Overflowed;
13493     llvm::APSInt Result = Src.convertToInt(
13494         Info.Ctx.getIntWidth(DestType),
13495         DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
13496     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
13497       return false;
13498     return Success(Result, E);
13499   }
13500 
13501   case CK_FixedPointToBoolean: {
13502     // Unsigned padding does not affect this.
13503     APValue Val;
13504     if (!Evaluate(Val, Info, SubExpr))
13505       return false;
13506     return Success(Val.getFixedPoint().getBoolValue(), E);
13507   }
13508 
13509   case CK_IntegralCast: {
13510     if (!Visit(SubExpr))
13511       return false;
13512 
13513     if (!Result.isInt()) {
13514       // Allow casts of address-of-label differences if they are no-ops
13515       // or narrowing.  (The narrowing case isn't actually guaranteed to
13516       // be constant-evaluatable except in some narrow cases which are hard
13517       // to detect here.  We let it through on the assumption the user knows
13518       // what they are doing.)
13519       if (Result.isAddrLabelDiff())
13520         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
13521       // Only allow casts of lvalues if they are lossless.
13522       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
13523     }
13524 
13525     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
13526                                       Result.getInt()), E);
13527   }
13528 
13529   case CK_PointerToIntegral: {
13530     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
13531 
13532     LValue LV;
13533     if (!EvaluatePointer(SubExpr, LV, Info))
13534       return false;
13535 
13536     if (LV.getLValueBase()) {
13537       // Only allow based lvalue casts if they are lossless.
13538       // FIXME: Allow a larger integer size than the pointer size, and allow
13539       // narrowing back down to pointer width in subsequent integral casts.
13540       // FIXME: Check integer type's active bits, not its type size.
13541       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
13542         return Error(E);
13543 
13544       LV.Designator.setInvalid();
13545       LV.moveInto(Result);
13546       return true;
13547     }
13548 
13549     APSInt AsInt;
13550     APValue V;
13551     LV.moveInto(V);
13552     if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
13553       llvm_unreachable("Can't cast this!");
13554 
13555     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
13556   }
13557 
13558   case CK_IntegralComplexToReal: {
13559     ComplexValue C;
13560     if (!EvaluateComplex(SubExpr, C, Info))
13561       return false;
13562     return Success(C.getComplexIntReal(), E);
13563   }
13564 
13565   case CK_FloatingToIntegral: {
13566     APFloat F(0.0);
13567     if (!EvaluateFloat(SubExpr, F, Info))
13568       return false;
13569 
13570     APSInt Value;
13571     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
13572       return false;
13573     return Success(Value, E);
13574   }
13575   }
13576 
13577   llvm_unreachable("unknown cast resulting in integral value");
13578 }
13579 
13580 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13581   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13582     ComplexValue LV;
13583     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13584       return false;
13585     if (!LV.isComplexInt())
13586       return Error(E);
13587     return Success(LV.getComplexIntReal(), E);
13588   }
13589 
13590   return Visit(E->getSubExpr());
13591 }
13592 
13593 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13594   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
13595     ComplexValue LV;
13596     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13597       return false;
13598     if (!LV.isComplexInt())
13599       return Error(E);
13600     return Success(LV.getComplexIntImag(), E);
13601   }
13602 
13603   VisitIgnoredValue(E->getSubExpr());
13604   return Success(0, E);
13605 }
13606 
13607 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
13608   return Success(E->getPackLength(), E);
13609 }
13610 
13611 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
13612   return Success(E->getValue(), E);
13613 }
13614 
13615 bool IntExprEvaluator::VisitConceptSpecializationExpr(
13616        const ConceptSpecializationExpr *E) {
13617   return Success(E->isSatisfied(), E);
13618 }
13619 
13620 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
13621   return Success(E->isSatisfied(), E);
13622 }
13623 
13624 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13625   switch (E->getOpcode()) {
13626     default:
13627       // Invalid unary operators
13628       return Error(E);
13629     case UO_Plus:
13630       // The result is just the value.
13631       return Visit(E->getSubExpr());
13632     case UO_Minus: {
13633       if (!Visit(E->getSubExpr())) return false;
13634       if (!Result.isFixedPoint())
13635         return Error(E);
13636       bool Overflowed;
13637       APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
13638       if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
13639         return false;
13640       return Success(Negated, E);
13641     }
13642     case UO_LNot: {
13643       bool bres;
13644       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13645         return false;
13646       return Success(!bres, E);
13647     }
13648   }
13649 }
13650 
13651 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
13652   const Expr *SubExpr = E->getSubExpr();
13653   QualType DestType = E->getType();
13654   assert(DestType->isFixedPointType() &&
13655          "Expected destination type to be a fixed point type");
13656   auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
13657 
13658   switch (E->getCastKind()) {
13659   case CK_FixedPointCast: {
13660     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13661     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13662       return false;
13663     bool Overflowed;
13664     APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
13665     if (Overflowed) {
13666       if (Info.checkingForUndefinedBehavior())
13667         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13668                                          diag::warn_fixedpoint_constant_overflow)
13669           << Result.toString() << E->getType();
13670       if (!HandleOverflow(Info, E, Result, E->getType()))
13671         return false;
13672     }
13673     return Success(Result, E);
13674   }
13675   case CK_IntegralToFixedPoint: {
13676     APSInt Src;
13677     if (!EvaluateInteger(SubExpr, Src, Info))
13678       return false;
13679 
13680     bool Overflowed;
13681     APFixedPoint IntResult = APFixedPoint::getFromIntValue(
13682         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13683 
13684     if (Overflowed) {
13685       if (Info.checkingForUndefinedBehavior())
13686         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13687                                          diag::warn_fixedpoint_constant_overflow)
13688           << IntResult.toString() << E->getType();
13689       if (!HandleOverflow(Info, E, IntResult, E->getType()))
13690         return false;
13691     }
13692 
13693     return Success(IntResult, E);
13694   }
13695   case CK_FloatingToFixedPoint: {
13696     APFloat Src(0.0);
13697     if (!EvaluateFloat(SubExpr, Src, Info))
13698       return false;
13699 
13700     bool Overflowed;
13701     APFixedPoint Result = APFixedPoint::getFromFloatValue(
13702         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13703 
13704     if (Overflowed) {
13705       if (Info.checkingForUndefinedBehavior())
13706         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13707                                          diag::warn_fixedpoint_constant_overflow)
13708           << Result.toString() << E->getType();
13709       if (!HandleOverflow(Info, E, Result, E->getType()))
13710         return false;
13711     }
13712 
13713     return Success(Result, E);
13714   }
13715   case CK_NoOp:
13716   case CK_LValueToRValue:
13717     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13718   default:
13719     return Error(E);
13720   }
13721 }
13722 
13723 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13724   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13725     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13726 
13727   const Expr *LHS = E->getLHS();
13728   const Expr *RHS = E->getRHS();
13729   FixedPointSemantics ResultFXSema =
13730       Info.Ctx.getFixedPointSemantics(E->getType());
13731 
13732   APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
13733   if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
13734     return false;
13735   APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
13736   if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
13737     return false;
13738 
13739   bool OpOverflow = false, ConversionOverflow = false;
13740   APFixedPoint Result(LHSFX.getSemantics());
13741   switch (E->getOpcode()) {
13742   case BO_Add: {
13743     Result = LHSFX.add(RHSFX, &OpOverflow)
13744                   .convert(ResultFXSema, &ConversionOverflow);
13745     break;
13746   }
13747   case BO_Sub: {
13748     Result = LHSFX.sub(RHSFX, &OpOverflow)
13749                   .convert(ResultFXSema, &ConversionOverflow);
13750     break;
13751   }
13752   case BO_Mul: {
13753     Result = LHSFX.mul(RHSFX, &OpOverflow)
13754                   .convert(ResultFXSema, &ConversionOverflow);
13755     break;
13756   }
13757   case BO_Div: {
13758     if (RHSFX.getValue() == 0) {
13759       Info.FFDiag(E, diag::note_expr_divide_by_zero);
13760       return false;
13761     }
13762     Result = LHSFX.div(RHSFX, &OpOverflow)
13763                   .convert(ResultFXSema, &ConversionOverflow);
13764     break;
13765   }
13766   case BO_Shl:
13767   case BO_Shr: {
13768     FixedPointSemantics LHSSema = LHSFX.getSemantics();
13769     llvm::APSInt RHSVal = RHSFX.getValue();
13770 
13771     unsigned ShiftBW =
13772         LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
13773     unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
13774     // Embedded-C 4.1.6.2.2:
13775     //   The right operand must be nonnegative and less than the total number
13776     //   of (nonpadding) bits of the fixed-point operand ...
13777     if (RHSVal.isNegative())
13778       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
13779     else if (Amt != RHSVal)
13780       Info.CCEDiag(E, diag::note_constexpr_large_shift)
13781           << RHSVal << E->getType() << ShiftBW;
13782 
13783     if (E->getOpcode() == BO_Shl)
13784       Result = LHSFX.shl(Amt, &OpOverflow);
13785     else
13786       Result = LHSFX.shr(Amt, &OpOverflow);
13787     break;
13788   }
13789   default:
13790     return false;
13791   }
13792   if (OpOverflow || ConversionOverflow) {
13793     if (Info.checkingForUndefinedBehavior())
13794       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13795                                        diag::warn_fixedpoint_constant_overflow)
13796         << Result.toString() << E->getType();
13797     if (!HandleOverflow(Info, E, Result, E->getType()))
13798       return false;
13799   }
13800   return Success(Result, E);
13801 }
13802 
13803 //===----------------------------------------------------------------------===//
13804 // Float Evaluation
13805 //===----------------------------------------------------------------------===//
13806 
13807 namespace {
13808 class FloatExprEvaluator
13809   : public ExprEvaluatorBase<FloatExprEvaluator> {
13810   APFloat &Result;
13811 public:
13812   FloatExprEvaluator(EvalInfo &info, APFloat &result)
13813     : ExprEvaluatorBaseTy(info), Result(result) {}
13814 
13815   bool Success(const APValue &V, const Expr *e) {
13816     Result = V.getFloat();
13817     return true;
13818   }
13819 
13820   bool ZeroInitialization(const Expr *E) {
13821     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
13822     return true;
13823   }
13824 
13825   bool VisitCallExpr(const CallExpr *E);
13826 
13827   bool VisitUnaryOperator(const UnaryOperator *E);
13828   bool VisitBinaryOperator(const BinaryOperator *E);
13829   bool VisitFloatingLiteral(const FloatingLiteral *E);
13830   bool VisitCastExpr(const CastExpr *E);
13831 
13832   bool VisitUnaryReal(const UnaryOperator *E);
13833   bool VisitUnaryImag(const UnaryOperator *E);
13834 
13835   // FIXME: Missing: array subscript of vector, member of vector
13836 };
13837 } // end anonymous namespace
13838 
13839 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
13840   assert(!E->isValueDependent());
13841   assert(E->isPRValue() && E->getType()->isRealFloatingType());
13842   return FloatExprEvaluator(Info, Result).Visit(E);
13843 }
13844 
13845 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
13846                                   QualType ResultTy,
13847                                   const Expr *Arg,
13848                                   bool SNaN,
13849                                   llvm::APFloat &Result) {
13850   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
13851   if (!S) return false;
13852 
13853   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
13854 
13855   llvm::APInt fill;
13856 
13857   // Treat empty strings as if they were zero.
13858   if (S->getString().empty())
13859     fill = llvm::APInt(32, 0);
13860   else if (S->getString().getAsInteger(0, fill))
13861     return false;
13862 
13863   if (Context.getTargetInfo().isNan2008()) {
13864     if (SNaN)
13865       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13866     else
13867       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13868   } else {
13869     // Prior to IEEE 754-2008, architectures were allowed to choose whether
13870     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
13871     // a different encoding to what became a standard in 2008, and for pre-
13872     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
13873     // sNaN. This is now known as "legacy NaN" encoding.
13874     if (SNaN)
13875       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13876     else
13877       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13878   }
13879 
13880   return true;
13881 }
13882 
13883 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
13884   switch (E->getBuiltinCallee()) {
13885   default:
13886     return ExprEvaluatorBaseTy::VisitCallExpr(E);
13887 
13888   case Builtin::BI__builtin_huge_val:
13889   case Builtin::BI__builtin_huge_valf:
13890   case Builtin::BI__builtin_huge_vall:
13891   case Builtin::BI__builtin_huge_valf16:
13892   case Builtin::BI__builtin_huge_valf128:
13893   case Builtin::BI__builtin_inf:
13894   case Builtin::BI__builtin_inff:
13895   case Builtin::BI__builtin_infl:
13896   case Builtin::BI__builtin_inff16:
13897   case Builtin::BI__builtin_inff128: {
13898     const llvm::fltSemantics &Sem =
13899       Info.Ctx.getFloatTypeSemantics(E->getType());
13900     Result = llvm::APFloat::getInf(Sem);
13901     return true;
13902   }
13903 
13904   case Builtin::BI__builtin_nans:
13905   case Builtin::BI__builtin_nansf:
13906   case Builtin::BI__builtin_nansl:
13907   case Builtin::BI__builtin_nansf16:
13908   case Builtin::BI__builtin_nansf128:
13909     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13910                                true, Result))
13911       return Error(E);
13912     return true;
13913 
13914   case Builtin::BI__builtin_nan:
13915   case Builtin::BI__builtin_nanf:
13916   case Builtin::BI__builtin_nanl:
13917   case Builtin::BI__builtin_nanf16:
13918   case Builtin::BI__builtin_nanf128:
13919     // If this is __builtin_nan() turn this into a nan, otherwise we
13920     // can't constant fold it.
13921     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13922                                false, Result))
13923       return Error(E);
13924     return true;
13925 
13926   case Builtin::BI__builtin_fabs:
13927   case Builtin::BI__builtin_fabsf:
13928   case Builtin::BI__builtin_fabsl:
13929   case Builtin::BI__builtin_fabsf128:
13930     // The C standard says "fabs raises no floating-point exceptions,
13931     // even if x is a signaling NaN. The returned value is independent of
13932     // the current rounding direction mode."  Therefore constant folding can
13933     // proceed without regard to the floating point settings.
13934     // Reference, WG14 N2478 F.10.4.3
13935     if (!EvaluateFloat(E->getArg(0), Result, Info))
13936       return false;
13937 
13938     if (Result.isNegative())
13939       Result.changeSign();
13940     return true;
13941 
13942   case Builtin::BI__arithmetic_fence:
13943     return EvaluateFloat(E->getArg(0), Result, Info);
13944 
13945   // FIXME: Builtin::BI__builtin_powi
13946   // FIXME: Builtin::BI__builtin_powif
13947   // FIXME: Builtin::BI__builtin_powil
13948 
13949   case Builtin::BI__builtin_copysign:
13950   case Builtin::BI__builtin_copysignf:
13951   case Builtin::BI__builtin_copysignl:
13952   case Builtin::BI__builtin_copysignf128: {
13953     APFloat RHS(0.);
13954     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
13955         !EvaluateFloat(E->getArg(1), RHS, Info))
13956       return false;
13957     Result.copySign(RHS);
13958     return true;
13959   }
13960   }
13961 }
13962 
13963 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13964   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13965     ComplexValue CV;
13966     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13967       return false;
13968     Result = CV.FloatReal;
13969     return true;
13970   }
13971 
13972   return Visit(E->getSubExpr());
13973 }
13974 
13975 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13976   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13977     ComplexValue CV;
13978     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13979       return false;
13980     Result = CV.FloatImag;
13981     return true;
13982   }
13983 
13984   VisitIgnoredValue(E->getSubExpr());
13985   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
13986   Result = llvm::APFloat::getZero(Sem);
13987   return true;
13988 }
13989 
13990 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13991   switch (E->getOpcode()) {
13992   default: return Error(E);
13993   case UO_Plus:
13994     return EvaluateFloat(E->getSubExpr(), Result, Info);
13995   case UO_Minus:
13996     // In C standard, WG14 N2478 F.3 p4
13997     // "the unary - raises no floating point exceptions,
13998     // even if the operand is signalling."
13999     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
14000       return false;
14001     Result.changeSign();
14002     return true;
14003   }
14004 }
14005 
14006 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14007   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14008     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14009 
14010   APFloat RHS(0.0);
14011   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
14012   if (!LHSOK && !Info.noteFailure())
14013     return false;
14014   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
14015          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
14016 }
14017 
14018 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
14019   Result = E->getValue();
14020   return true;
14021 }
14022 
14023 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
14024   const Expr* SubExpr = E->getSubExpr();
14025 
14026   switch (E->getCastKind()) {
14027   default:
14028     return ExprEvaluatorBaseTy::VisitCastExpr(E);
14029 
14030   case CK_IntegralToFloating: {
14031     APSInt IntResult;
14032     const FPOptions FPO = E->getFPFeaturesInEffect(
14033                                   Info.Ctx.getLangOpts());
14034     return EvaluateInteger(SubExpr, IntResult, Info) &&
14035            HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
14036                                 IntResult, E->getType(), Result);
14037   }
14038 
14039   case CK_FixedPointToFloating: {
14040     APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
14041     if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
14042       return false;
14043     Result =
14044         FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
14045     return true;
14046   }
14047 
14048   case CK_FloatingCast: {
14049     if (!Visit(SubExpr))
14050       return false;
14051     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
14052                                   Result);
14053   }
14054 
14055   case CK_FloatingComplexToReal: {
14056     ComplexValue V;
14057     if (!EvaluateComplex(SubExpr, V, Info))
14058       return false;
14059     Result = V.getComplexFloatReal();
14060     return true;
14061   }
14062   }
14063 }
14064 
14065 //===----------------------------------------------------------------------===//
14066 // Complex Evaluation (for float and integer)
14067 //===----------------------------------------------------------------------===//
14068 
14069 namespace {
14070 class ComplexExprEvaluator
14071   : public ExprEvaluatorBase<ComplexExprEvaluator> {
14072   ComplexValue &Result;
14073 
14074 public:
14075   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
14076     : ExprEvaluatorBaseTy(info), Result(Result) {}
14077 
14078   bool Success(const APValue &V, const Expr *e) {
14079     Result.setFrom(V);
14080     return true;
14081   }
14082 
14083   bool ZeroInitialization(const Expr *E);
14084 
14085   //===--------------------------------------------------------------------===//
14086   //                            Visitor Methods
14087   //===--------------------------------------------------------------------===//
14088 
14089   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
14090   bool VisitCastExpr(const CastExpr *E);
14091   bool VisitBinaryOperator(const BinaryOperator *E);
14092   bool VisitUnaryOperator(const UnaryOperator *E);
14093   bool VisitInitListExpr(const InitListExpr *E);
14094   bool VisitCallExpr(const CallExpr *E);
14095 };
14096 } // end anonymous namespace
14097 
14098 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
14099                             EvalInfo &Info) {
14100   assert(!E->isValueDependent());
14101   assert(E->isPRValue() && E->getType()->isAnyComplexType());
14102   return ComplexExprEvaluator(Info, Result).Visit(E);
14103 }
14104 
14105 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
14106   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
14107   if (ElemTy->isRealFloatingType()) {
14108     Result.makeComplexFloat();
14109     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
14110     Result.FloatReal = Zero;
14111     Result.FloatImag = Zero;
14112   } else {
14113     Result.makeComplexInt();
14114     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
14115     Result.IntReal = Zero;
14116     Result.IntImag = Zero;
14117   }
14118   return true;
14119 }
14120 
14121 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
14122   const Expr* SubExpr = E->getSubExpr();
14123 
14124   if (SubExpr->getType()->isRealFloatingType()) {
14125     Result.makeComplexFloat();
14126     APFloat &Imag = Result.FloatImag;
14127     if (!EvaluateFloat(SubExpr, Imag, Info))
14128       return false;
14129 
14130     Result.FloatReal = APFloat(Imag.getSemantics());
14131     return true;
14132   } else {
14133     assert(SubExpr->getType()->isIntegerType() &&
14134            "Unexpected imaginary literal.");
14135 
14136     Result.makeComplexInt();
14137     APSInt &Imag = Result.IntImag;
14138     if (!EvaluateInteger(SubExpr, Imag, Info))
14139       return false;
14140 
14141     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
14142     return true;
14143   }
14144 }
14145 
14146 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
14147 
14148   switch (E->getCastKind()) {
14149   case CK_BitCast:
14150   case CK_BaseToDerived:
14151   case CK_DerivedToBase:
14152   case CK_UncheckedDerivedToBase:
14153   case CK_Dynamic:
14154   case CK_ToUnion:
14155   case CK_ArrayToPointerDecay:
14156   case CK_FunctionToPointerDecay:
14157   case CK_NullToPointer:
14158   case CK_NullToMemberPointer:
14159   case CK_BaseToDerivedMemberPointer:
14160   case CK_DerivedToBaseMemberPointer:
14161   case CK_MemberPointerToBoolean:
14162   case CK_ReinterpretMemberPointer:
14163   case CK_ConstructorConversion:
14164   case CK_IntegralToPointer:
14165   case CK_PointerToIntegral:
14166   case CK_PointerToBoolean:
14167   case CK_ToVoid:
14168   case CK_VectorSplat:
14169   case CK_IntegralCast:
14170   case CK_BooleanToSignedIntegral:
14171   case CK_IntegralToBoolean:
14172   case CK_IntegralToFloating:
14173   case CK_FloatingToIntegral:
14174   case CK_FloatingToBoolean:
14175   case CK_FloatingCast:
14176   case CK_CPointerToObjCPointerCast:
14177   case CK_BlockPointerToObjCPointerCast:
14178   case CK_AnyPointerToBlockPointerCast:
14179   case CK_ObjCObjectLValueCast:
14180   case CK_FloatingComplexToReal:
14181   case CK_FloatingComplexToBoolean:
14182   case CK_IntegralComplexToReal:
14183   case CK_IntegralComplexToBoolean:
14184   case CK_ARCProduceObject:
14185   case CK_ARCConsumeObject:
14186   case CK_ARCReclaimReturnedObject:
14187   case CK_ARCExtendBlockObject:
14188   case CK_CopyAndAutoreleaseBlockObject:
14189   case CK_BuiltinFnToFnPtr:
14190   case CK_ZeroToOCLOpaqueType:
14191   case CK_NonAtomicToAtomic:
14192   case CK_AddressSpaceConversion:
14193   case CK_IntToOCLSampler:
14194   case CK_FloatingToFixedPoint:
14195   case CK_FixedPointToFloating:
14196   case CK_FixedPointCast:
14197   case CK_FixedPointToBoolean:
14198   case CK_FixedPointToIntegral:
14199   case CK_IntegralToFixedPoint:
14200   case CK_MatrixCast:
14201     llvm_unreachable("invalid cast kind for complex value");
14202 
14203   case CK_LValueToRValue:
14204   case CK_AtomicToNonAtomic:
14205   case CK_NoOp:
14206   case CK_LValueToRValueBitCast:
14207     return ExprEvaluatorBaseTy::VisitCastExpr(E);
14208 
14209   case CK_Dependent:
14210   case CK_LValueBitCast:
14211   case CK_UserDefinedConversion:
14212     return Error(E);
14213 
14214   case CK_FloatingRealToComplex: {
14215     APFloat &Real = Result.FloatReal;
14216     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
14217       return false;
14218 
14219     Result.makeComplexFloat();
14220     Result.FloatImag = APFloat(Real.getSemantics());
14221     return true;
14222   }
14223 
14224   case CK_FloatingComplexCast: {
14225     if (!Visit(E->getSubExpr()))
14226       return false;
14227 
14228     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14229     QualType From
14230       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14231 
14232     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
14233            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
14234   }
14235 
14236   case CK_FloatingComplexToIntegralComplex: {
14237     if (!Visit(E->getSubExpr()))
14238       return false;
14239 
14240     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14241     QualType From
14242       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14243     Result.makeComplexInt();
14244     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
14245                                 To, Result.IntReal) &&
14246            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
14247                                 To, Result.IntImag);
14248   }
14249 
14250   case CK_IntegralRealToComplex: {
14251     APSInt &Real = Result.IntReal;
14252     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
14253       return false;
14254 
14255     Result.makeComplexInt();
14256     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
14257     return true;
14258   }
14259 
14260   case CK_IntegralComplexCast: {
14261     if (!Visit(E->getSubExpr()))
14262       return false;
14263 
14264     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14265     QualType From
14266       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14267 
14268     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
14269     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
14270     return true;
14271   }
14272 
14273   case CK_IntegralComplexToFloatingComplex: {
14274     if (!Visit(E->getSubExpr()))
14275       return false;
14276 
14277     const FPOptions FPO = E->getFPFeaturesInEffect(
14278                                   Info.Ctx.getLangOpts());
14279     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14280     QualType From
14281       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14282     Result.makeComplexFloat();
14283     return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
14284                                 To, Result.FloatReal) &&
14285            HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
14286                                 To, Result.FloatImag);
14287   }
14288   }
14289 
14290   llvm_unreachable("unknown cast resulting in complex value");
14291 }
14292 
14293 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14294   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14295     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14296 
14297   // Track whether the LHS or RHS is real at the type system level. When this is
14298   // the case we can simplify our evaluation strategy.
14299   bool LHSReal = false, RHSReal = false;
14300 
14301   bool LHSOK;
14302   if (E->getLHS()->getType()->isRealFloatingType()) {
14303     LHSReal = true;
14304     APFloat &Real = Result.FloatReal;
14305     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
14306     if (LHSOK) {
14307       Result.makeComplexFloat();
14308       Result.FloatImag = APFloat(Real.getSemantics());
14309     }
14310   } else {
14311     LHSOK = Visit(E->getLHS());
14312   }
14313   if (!LHSOK && !Info.noteFailure())
14314     return false;
14315 
14316   ComplexValue RHS;
14317   if (E->getRHS()->getType()->isRealFloatingType()) {
14318     RHSReal = true;
14319     APFloat &Real = RHS.FloatReal;
14320     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
14321       return false;
14322     RHS.makeComplexFloat();
14323     RHS.FloatImag = APFloat(Real.getSemantics());
14324   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
14325     return false;
14326 
14327   assert(!(LHSReal && RHSReal) &&
14328          "Cannot have both operands of a complex operation be real.");
14329   switch (E->getOpcode()) {
14330   default: return Error(E);
14331   case BO_Add:
14332     if (Result.isComplexFloat()) {
14333       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
14334                                        APFloat::rmNearestTiesToEven);
14335       if (LHSReal)
14336         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14337       else if (!RHSReal)
14338         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
14339                                          APFloat::rmNearestTiesToEven);
14340     } else {
14341       Result.getComplexIntReal() += RHS.getComplexIntReal();
14342       Result.getComplexIntImag() += RHS.getComplexIntImag();
14343     }
14344     break;
14345   case BO_Sub:
14346     if (Result.isComplexFloat()) {
14347       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
14348                                             APFloat::rmNearestTiesToEven);
14349       if (LHSReal) {
14350         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14351         Result.getComplexFloatImag().changeSign();
14352       } else if (!RHSReal) {
14353         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
14354                                               APFloat::rmNearestTiesToEven);
14355       }
14356     } else {
14357       Result.getComplexIntReal() -= RHS.getComplexIntReal();
14358       Result.getComplexIntImag() -= RHS.getComplexIntImag();
14359     }
14360     break;
14361   case BO_Mul:
14362     if (Result.isComplexFloat()) {
14363       // This is an implementation of complex multiplication according to the
14364       // constraints laid out in C11 Annex G. The implementation uses the
14365       // following naming scheme:
14366       //   (a + ib) * (c + id)
14367       ComplexValue LHS = Result;
14368       APFloat &A = LHS.getComplexFloatReal();
14369       APFloat &B = LHS.getComplexFloatImag();
14370       APFloat &C = RHS.getComplexFloatReal();
14371       APFloat &D = RHS.getComplexFloatImag();
14372       APFloat &ResR = Result.getComplexFloatReal();
14373       APFloat &ResI = Result.getComplexFloatImag();
14374       if (LHSReal) {
14375         assert(!RHSReal && "Cannot have two real operands for a complex op!");
14376         ResR = A * C;
14377         ResI = A * D;
14378       } else if (RHSReal) {
14379         ResR = C * A;
14380         ResI = C * B;
14381       } else {
14382         // In the fully general case, we need to handle NaNs and infinities
14383         // robustly.
14384         APFloat AC = A * C;
14385         APFloat BD = B * D;
14386         APFloat AD = A * D;
14387         APFloat BC = B * C;
14388         ResR = AC - BD;
14389         ResI = AD + BC;
14390         if (ResR.isNaN() && ResI.isNaN()) {
14391           bool Recalc = false;
14392           if (A.isInfinity() || B.isInfinity()) {
14393             A = APFloat::copySign(
14394                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14395             B = APFloat::copySign(
14396                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14397             if (C.isNaN())
14398               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14399             if (D.isNaN())
14400               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14401             Recalc = true;
14402           }
14403           if (C.isInfinity() || D.isInfinity()) {
14404             C = APFloat::copySign(
14405                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14406             D = APFloat::copySign(
14407                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14408             if (A.isNaN())
14409               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14410             if (B.isNaN())
14411               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14412             Recalc = true;
14413           }
14414           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
14415                           AD.isInfinity() || BC.isInfinity())) {
14416             if (A.isNaN())
14417               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14418             if (B.isNaN())
14419               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14420             if (C.isNaN())
14421               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14422             if (D.isNaN())
14423               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14424             Recalc = true;
14425           }
14426           if (Recalc) {
14427             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
14428             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
14429           }
14430         }
14431       }
14432     } else {
14433       ComplexValue LHS = Result;
14434       Result.getComplexIntReal() =
14435         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
14436          LHS.getComplexIntImag() * RHS.getComplexIntImag());
14437       Result.getComplexIntImag() =
14438         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
14439          LHS.getComplexIntImag() * RHS.getComplexIntReal());
14440     }
14441     break;
14442   case BO_Div:
14443     if (Result.isComplexFloat()) {
14444       // This is an implementation of complex division according to the
14445       // constraints laid out in C11 Annex G. The implementation uses the
14446       // following naming scheme:
14447       //   (a + ib) / (c + id)
14448       ComplexValue LHS = Result;
14449       APFloat &A = LHS.getComplexFloatReal();
14450       APFloat &B = LHS.getComplexFloatImag();
14451       APFloat &C = RHS.getComplexFloatReal();
14452       APFloat &D = RHS.getComplexFloatImag();
14453       APFloat &ResR = Result.getComplexFloatReal();
14454       APFloat &ResI = Result.getComplexFloatImag();
14455       if (RHSReal) {
14456         ResR = A / C;
14457         ResI = B / C;
14458       } else {
14459         if (LHSReal) {
14460           // No real optimizations we can do here, stub out with zero.
14461           B = APFloat::getZero(A.getSemantics());
14462         }
14463         int DenomLogB = 0;
14464         APFloat MaxCD = maxnum(abs(C), abs(D));
14465         if (MaxCD.isFinite()) {
14466           DenomLogB = ilogb(MaxCD);
14467           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
14468           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
14469         }
14470         APFloat Denom = C * C + D * D;
14471         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
14472                       APFloat::rmNearestTiesToEven);
14473         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
14474                       APFloat::rmNearestTiesToEven);
14475         if (ResR.isNaN() && ResI.isNaN()) {
14476           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
14477             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
14478             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
14479           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
14480                      D.isFinite()) {
14481             A = APFloat::copySign(
14482                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14483             B = APFloat::copySign(
14484                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14485             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
14486             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
14487           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
14488             C = APFloat::copySign(
14489                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14490             D = APFloat::copySign(
14491                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14492             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
14493             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
14494           }
14495         }
14496       }
14497     } else {
14498       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
14499         return Error(E, diag::note_expr_divide_by_zero);
14500 
14501       ComplexValue LHS = Result;
14502       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
14503         RHS.getComplexIntImag() * RHS.getComplexIntImag();
14504       Result.getComplexIntReal() =
14505         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
14506          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
14507       Result.getComplexIntImag() =
14508         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
14509          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
14510     }
14511     break;
14512   }
14513 
14514   return true;
14515 }
14516 
14517 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14518   // Get the operand value into 'Result'.
14519   if (!Visit(E->getSubExpr()))
14520     return false;
14521 
14522   switch (E->getOpcode()) {
14523   default:
14524     return Error(E);
14525   case UO_Extension:
14526     return true;
14527   case UO_Plus:
14528     // The result is always just the subexpr.
14529     return true;
14530   case UO_Minus:
14531     if (Result.isComplexFloat()) {
14532       Result.getComplexFloatReal().changeSign();
14533       Result.getComplexFloatImag().changeSign();
14534     }
14535     else {
14536       Result.getComplexIntReal() = -Result.getComplexIntReal();
14537       Result.getComplexIntImag() = -Result.getComplexIntImag();
14538     }
14539     return true;
14540   case UO_Not:
14541     if (Result.isComplexFloat())
14542       Result.getComplexFloatImag().changeSign();
14543     else
14544       Result.getComplexIntImag() = -Result.getComplexIntImag();
14545     return true;
14546   }
14547 }
14548 
14549 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
14550   if (E->getNumInits() == 2) {
14551     if (E->getType()->isComplexType()) {
14552       Result.makeComplexFloat();
14553       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
14554         return false;
14555       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
14556         return false;
14557     } else {
14558       Result.makeComplexInt();
14559       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
14560         return false;
14561       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
14562         return false;
14563     }
14564     return true;
14565   }
14566   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
14567 }
14568 
14569 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
14570   switch (E->getBuiltinCallee()) {
14571   case Builtin::BI__builtin_complex:
14572     Result.makeComplexFloat();
14573     if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
14574       return false;
14575     if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
14576       return false;
14577     return true;
14578 
14579   default:
14580     break;
14581   }
14582 
14583   return ExprEvaluatorBaseTy::VisitCallExpr(E);
14584 }
14585 
14586 //===----------------------------------------------------------------------===//
14587 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
14588 // implicit conversion.
14589 //===----------------------------------------------------------------------===//
14590 
14591 namespace {
14592 class AtomicExprEvaluator :
14593     public ExprEvaluatorBase<AtomicExprEvaluator> {
14594   const LValue *This;
14595   APValue &Result;
14596 public:
14597   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
14598       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
14599 
14600   bool Success(const APValue &V, const Expr *E) {
14601     Result = V;
14602     return true;
14603   }
14604 
14605   bool ZeroInitialization(const Expr *E) {
14606     ImplicitValueInitExpr VIE(
14607         E->getType()->castAs<AtomicType>()->getValueType());
14608     // For atomic-qualified class (and array) types in C++, initialize the
14609     // _Atomic-wrapped subobject directly, in-place.
14610     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
14611                 : Evaluate(Result, Info, &VIE);
14612   }
14613 
14614   bool VisitCastExpr(const CastExpr *E) {
14615     switch (E->getCastKind()) {
14616     default:
14617       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14618     case CK_NonAtomicToAtomic:
14619       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
14620                   : Evaluate(Result, Info, E->getSubExpr());
14621     }
14622   }
14623 };
14624 } // end anonymous namespace
14625 
14626 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
14627                            EvalInfo &Info) {
14628   assert(!E->isValueDependent());
14629   assert(E->isPRValue() && E->getType()->isAtomicType());
14630   return AtomicExprEvaluator(Info, This, Result).Visit(E);
14631 }
14632 
14633 //===----------------------------------------------------------------------===//
14634 // Void expression evaluation, primarily for a cast to void on the LHS of a
14635 // comma operator
14636 //===----------------------------------------------------------------------===//
14637 
14638 namespace {
14639 class VoidExprEvaluator
14640   : public ExprEvaluatorBase<VoidExprEvaluator> {
14641 public:
14642   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
14643 
14644   bool Success(const APValue &V, const Expr *e) { return true; }
14645 
14646   bool ZeroInitialization(const Expr *E) { return true; }
14647 
14648   bool VisitCastExpr(const CastExpr *E) {
14649     switch (E->getCastKind()) {
14650     default:
14651       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14652     case CK_ToVoid:
14653       VisitIgnoredValue(E->getSubExpr());
14654       return true;
14655     }
14656   }
14657 
14658   bool VisitCallExpr(const CallExpr *E) {
14659     switch (E->getBuiltinCallee()) {
14660     case Builtin::BI__assume:
14661     case Builtin::BI__builtin_assume:
14662       // The argument is not evaluated!
14663       return true;
14664 
14665     case Builtin::BI__builtin_operator_delete:
14666       return HandleOperatorDeleteCall(Info, E);
14667 
14668     default:
14669       break;
14670     }
14671 
14672     return ExprEvaluatorBaseTy::VisitCallExpr(E);
14673   }
14674 
14675   bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
14676 };
14677 } // end anonymous namespace
14678 
14679 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
14680   // We cannot speculatively evaluate a delete expression.
14681   if (Info.SpeculativeEvaluationDepth)
14682     return false;
14683 
14684   FunctionDecl *OperatorDelete = E->getOperatorDelete();
14685   if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
14686     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14687         << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
14688     return false;
14689   }
14690 
14691   const Expr *Arg = E->getArgument();
14692 
14693   LValue Pointer;
14694   if (!EvaluatePointer(Arg, Pointer, Info))
14695     return false;
14696   if (Pointer.Designator.Invalid)
14697     return false;
14698 
14699   // Deleting a null pointer has no effect.
14700   if (Pointer.isNullPointer()) {
14701     // This is the only case where we need to produce an extension warning:
14702     // the only other way we can succeed is if we find a dynamic allocation,
14703     // and we will have warned when we allocated it in that case.
14704     if (!Info.getLangOpts().CPlusPlus20)
14705       Info.CCEDiag(E, diag::note_constexpr_new);
14706     return true;
14707   }
14708 
14709   Optional<DynAlloc *> Alloc = CheckDeleteKind(
14710       Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
14711   if (!Alloc)
14712     return false;
14713   QualType AllocType = Pointer.Base.getDynamicAllocType();
14714 
14715   // For the non-array case, the designator must be empty if the static type
14716   // does not have a virtual destructor.
14717   if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
14718       !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
14719     Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
14720         << Arg->getType()->getPointeeType() << AllocType;
14721     return false;
14722   }
14723 
14724   // For a class type with a virtual destructor, the selected operator delete
14725   // is the one looked up when building the destructor.
14726   if (!E->isArrayForm() && !E->isGlobalDelete()) {
14727     const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
14728     if (VirtualDelete &&
14729         !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
14730       Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14731           << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
14732       return false;
14733     }
14734   }
14735 
14736   if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
14737                          (*Alloc)->Value, AllocType))
14738     return false;
14739 
14740   if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
14741     // The element was already erased. This means the destructor call also
14742     // deleted the object.
14743     // FIXME: This probably results in undefined behavior before we get this
14744     // far, and should be diagnosed elsewhere first.
14745     Info.FFDiag(E, diag::note_constexpr_double_delete);
14746     return false;
14747   }
14748 
14749   return true;
14750 }
14751 
14752 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
14753   assert(!E->isValueDependent());
14754   assert(E->isPRValue() && E->getType()->isVoidType());
14755   return VoidExprEvaluator(Info).Visit(E);
14756 }
14757 
14758 //===----------------------------------------------------------------------===//
14759 // Top level Expr::EvaluateAsRValue method.
14760 //===----------------------------------------------------------------------===//
14761 
14762 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
14763   assert(!E->isValueDependent());
14764   // In C, function designators are not lvalues, but we evaluate them as if they
14765   // are.
14766   QualType T = E->getType();
14767   if (E->isGLValue() || T->isFunctionType()) {
14768     LValue LV;
14769     if (!EvaluateLValue(E, LV, Info))
14770       return false;
14771     LV.moveInto(Result);
14772   } else if (T->isVectorType()) {
14773     if (!EvaluateVector(E, Result, Info))
14774       return false;
14775   } else if (T->isIntegralOrEnumerationType()) {
14776     if (!IntExprEvaluator(Info, Result).Visit(E))
14777       return false;
14778   } else if (T->hasPointerRepresentation()) {
14779     LValue LV;
14780     if (!EvaluatePointer(E, LV, Info))
14781       return false;
14782     LV.moveInto(Result);
14783   } else if (T->isRealFloatingType()) {
14784     llvm::APFloat F(0.0);
14785     if (!EvaluateFloat(E, F, Info))
14786       return false;
14787     Result = APValue(F);
14788   } else if (T->isAnyComplexType()) {
14789     ComplexValue C;
14790     if (!EvaluateComplex(E, C, Info))
14791       return false;
14792     C.moveInto(Result);
14793   } else if (T->isFixedPointType()) {
14794     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
14795   } else if (T->isMemberPointerType()) {
14796     MemberPtr P;
14797     if (!EvaluateMemberPointer(E, P, Info))
14798       return false;
14799     P.moveInto(Result);
14800     return true;
14801   } else if (T->isArrayType()) {
14802     LValue LV;
14803     APValue &Value =
14804         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14805     if (!EvaluateArray(E, LV, Value, Info))
14806       return false;
14807     Result = Value;
14808   } else if (T->isRecordType()) {
14809     LValue LV;
14810     APValue &Value =
14811         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14812     if (!EvaluateRecord(E, LV, Value, Info))
14813       return false;
14814     Result = Value;
14815   } else if (T->isVoidType()) {
14816     if (!Info.getLangOpts().CPlusPlus11)
14817       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
14818         << E->getType();
14819     if (!EvaluateVoid(E, Info))
14820       return false;
14821   } else if (T->isAtomicType()) {
14822     QualType Unqual = T.getAtomicUnqualifiedType();
14823     if (Unqual->isArrayType() || Unqual->isRecordType()) {
14824       LValue LV;
14825       APValue &Value = Info.CurrentCall->createTemporary(
14826           E, Unqual, ScopeKind::FullExpression, LV);
14827       if (!EvaluateAtomic(E, &LV, Value, Info))
14828         return false;
14829     } else {
14830       if (!EvaluateAtomic(E, nullptr, Result, Info))
14831         return false;
14832     }
14833   } else if (Info.getLangOpts().CPlusPlus11) {
14834     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
14835     return false;
14836   } else {
14837     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
14838     return false;
14839   }
14840 
14841   return true;
14842 }
14843 
14844 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
14845 /// cases, the in-place evaluation is essential, since later initializers for
14846 /// an object can indirectly refer to subobjects which were initialized earlier.
14847 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
14848                             const Expr *E, bool AllowNonLiteralTypes) {
14849   assert(!E->isValueDependent());
14850 
14851   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
14852     return false;
14853 
14854   if (E->isPRValue()) {
14855     // Evaluate arrays and record types in-place, so that later initializers can
14856     // refer to earlier-initialized members of the object.
14857     QualType T = E->getType();
14858     if (T->isArrayType())
14859       return EvaluateArray(E, This, Result, Info);
14860     else if (T->isRecordType())
14861       return EvaluateRecord(E, This, Result, Info);
14862     else if (T->isAtomicType()) {
14863       QualType Unqual = T.getAtomicUnqualifiedType();
14864       if (Unqual->isArrayType() || Unqual->isRecordType())
14865         return EvaluateAtomic(E, &This, Result, Info);
14866     }
14867   }
14868 
14869   // For any other type, in-place evaluation is unimportant.
14870   return Evaluate(Result, Info, E);
14871 }
14872 
14873 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
14874 /// lvalue-to-rvalue cast if it is an lvalue.
14875 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
14876   assert(!E->isValueDependent());
14877   if (Info.EnableNewConstInterp) {
14878     if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
14879       return false;
14880   } else {
14881     if (E->getType().isNull())
14882       return false;
14883 
14884     if (!CheckLiteralType(Info, E))
14885       return false;
14886 
14887     if (!::Evaluate(Result, Info, E))
14888       return false;
14889 
14890     if (E->isGLValue()) {
14891       LValue LV;
14892       LV.setFrom(Info.Ctx, Result);
14893       if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
14894         return false;
14895     }
14896   }
14897 
14898   // Check this core constant expression is a constant expression.
14899   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
14900                                  ConstantExprKind::Normal) &&
14901          CheckMemoryLeaks(Info);
14902 }
14903 
14904 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
14905                                  const ASTContext &Ctx, bool &IsConst) {
14906   // Fast-path evaluations of integer literals, since we sometimes see files
14907   // containing vast quantities of these.
14908   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
14909     Result.Val = APValue(APSInt(L->getValue(),
14910                                 L->getType()->isUnsignedIntegerType()));
14911     IsConst = true;
14912     return true;
14913   }
14914 
14915   // This case should be rare, but we need to check it before we check on
14916   // the type below.
14917   if (Exp->getType().isNull()) {
14918     IsConst = false;
14919     return true;
14920   }
14921 
14922   // FIXME: Evaluating values of large array and record types can cause
14923   // performance problems. Only do so in C++11 for now.
14924   if (Exp->isPRValue() &&
14925       (Exp->getType()->isArrayType() || Exp->getType()->isRecordType()) &&
14926       !Ctx.getLangOpts().CPlusPlus11) {
14927     IsConst = false;
14928     return true;
14929   }
14930   return false;
14931 }
14932 
14933 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
14934                                       Expr::SideEffectsKind SEK) {
14935   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
14936          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
14937 }
14938 
14939 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
14940                              const ASTContext &Ctx, EvalInfo &Info) {
14941   assert(!E->isValueDependent());
14942   bool IsConst;
14943   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
14944     return IsConst;
14945 
14946   return EvaluateAsRValue(Info, E, Result.Val);
14947 }
14948 
14949 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
14950                           const ASTContext &Ctx,
14951                           Expr::SideEffectsKind AllowSideEffects,
14952                           EvalInfo &Info) {
14953   assert(!E->isValueDependent());
14954   if (!E->getType()->isIntegralOrEnumerationType())
14955     return false;
14956 
14957   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
14958       !ExprResult.Val.isInt() ||
14959       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14960     return false;
14961 
14962   return true;
14963 }
14964 
14965 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
14966                                  const ASTContext &Ctx,
14967                                  Expr::SideEffectsKind AllowSideEffects,
14968                                  EvalInfo &Info) {
14969   assert(!E->isValueDependent());
14970   if (!E->getType()->isFixedPointType())
14971     return false;
14972 
14973   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
14974     return false;
14975 
14976   if (!ExprResult.Val.isFixedPoint() ||
14977       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14978     return false;
14979 
14980   return true;
14981 }
14982 
14983 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
14984 /// any crazy technique (that has nothing to do with language standards) that
14985 /// we want to.  If this function returns true, it returns the folded constant
14986 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
14987 /// will be applied to the result.
14988 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
14989                             bool InConstantContext) const {
14990   assert(!isValueDependent() &&
14991          "Expression evaluator can't be called on a dependent expression.");
14992   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14993   Info.InConstantContext = InConstantContext;
14994   return ::EvaluateAsRValue(this, Result, Ctx, Info);
14995 }
14996 
14997 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
14998                                       bool InConstantContext) const {
14999   assert(!isValueDependent() &&
15000          "Expression evaluator can't be called on a dependent expression.");
15001   EvalResult Scratch;
15002   return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
15003          HandleConversionToBool(Scratch.Val, Result);
15004 }
15005 
15006 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
15007                          SideEffectsKind AllowSideEffects,
15008                          bool InConstantContext) const {
15009   assert(!isValueDependent() &&
15010          "Expression evaluator can't be called on a dependent expression.");
15011   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
15012   Info.InConstantContext = InConstantContext;
15013   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
15014 }
15015 
15016 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
15017                                 SideEffectsKind AllowSideEffects,
15018                                 bool InConstantContext) const {
15019   assert(!isValueDependent() &&
15020          "Expression evaluator can't be called on a dependent expression.");
15021   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
15022   Info.InConstantContext = InConstantContext;
15023   return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
15024 }
15025 
15026 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
15027                            SideEffectsKind AllowSideEffects,
15028                            bool InConstantContext) const {
15029   assert(!isValueDependent() &&
15030          "Expression evaluator can't be called on a dependent expression.");
15031 
15032   if (!getType()->isRealFloatingType())
15033     return false;
15034 
15035   EvalResult ExprResult;
15036   if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
15037       !ExprResult.Val.isFloat() ||
15038       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
15039     return false;
15040 
15041   Result = ExprResult.Val.getFloat();
15042   return true;
15043 }
15044 
15045 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
15046                             bool InConstantContext) const {
15047   assert(!isValueDependent() &&
15048          "Expression evaluator can't be called on a dependent expression.");
15049 
15050   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
15051   Info.InConstantContext = InConstantContext;
15052   LValue LV;
15053   CheckedTemporaries CheckedTemps;
15054   if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
15055       Result.HasSideEffects ||
15056       !CheckLValueConstantExpression(Info, getExprLoc(),
15057                                      Ctx.getLValueReferenceType(getType()), LV,
15058                                      ConstantExprKind::Normal, CheckedTemps))
15059     return false;
15060 
15061   LV.moveInto(Result.Val);
15062   return true;
15063 }
15064 
15065 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base,
15066                                 APValue DestroyedValue, QualType Type,
15067                                 SourceLocation Loc, Expr::EvalStatus &EStatus,
15068                                 bool IsConstantDestruction) {
15069   EvalInfo Info(Ctx, EStatus,
15070                 IsConstantDestruction ? EvalInfo::EM_ConstantExpression
15071                                       : EvalInfo::EM_ConstantFold);
15072   Info.setEvaluatingDecl(Base, DestroyedValue,
15073                          EvalInfo::EvaluatingDeclKind::Dtor);
15074   Info.InConstantContext = IsConstantDestruction;
15075 
15076   LValue LVal;
15077   LVal.set(Base);
15078 
15079   if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
15080       EStatus.HasSideEffects)
15081     return false;
15082 
15083   if (!Info.discardCleanups())
15084     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15085 
15086   return true;
15087 }
15088 
15089 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx,
15090                                   ConstantExprKind Kind) const {
15091   assert(!isValueDependent() &&
15092          "Expression evaluator can't be called on a dependent expression.");
15093 
15094   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
15095   EvalInfo Info(Ctx, Result, EM);
15096   Info.InConstantContext = true;
15097 
15098   // The type of the object we're initializing is 'const T' for a class NTTP.
15099   QualType T = getType();
15100   if (Kind == ConstantExprKind::ClassTemplateArgument)
15101     T.addConst();
15102 
15103   // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
15104   // represent the result of the evaluation. CheckConstantExpression ensures
15105   // this doesn't escape.
15106   MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
15107   APValue::LValueBase Base(&BaseMTE);
15108 
15109   Info.setEvaluatingDecl(Base, Result.Val);
15110   LValue LVal;
15111   LVal.set(Base);
15112 
15113   if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || Result.HasSideEffects)
15114     return false;
15115 
15116   if (!Info.discardCleanups())
15117     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15118 
15119   if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
15120                                Result.Val, Kind))
15121     return false;
15122   if (!CheckMemoryLeaks(Info))
15123     return false;
15124 
15125   // If this is a class template argument, it's required to have constant
15126   // destruction too.
15127   if (Kind == ConstantExprKind::ClassTemplateArgument &&
15128       (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result,
15129                             true) ||
15130        Result.HasSideEffects)) {
15131     // FIXME: Prefix a note to indicate that the problem is lack of constant
15132     // destruction.
15133     return false;
15134   }
15135 
15136   return true;
15137 }
15138 
15139 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
15140                                  const VarDecl *VD,
15141                             SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
15142   assert(!isValueDependent() &&
15143          "Expression evaluator can't be called on a dependent expression.");
15144 
15145   // FIXME: Evaluating initializers for large array and record types can cause
15146   // performance problems. Only do so in C++11 for now.
15147   if (isPRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
15148       !Ctx.getLangOpts().CPlusPlus11)
15149     return false;
15150 
15151   Expr::EvalStatus EStatus;
15152   EStatus.Diag = &Notes;
15153 
15154   EvalInfo Info(Ctx, EStatus, VD->isConstexpr()
15155                                       ? EvalInfo::EM_ConstantExpression
15156                                       : EvalInfo::EM_ConstantFold);
15157   Info.setEvaluatingDecl(VD, Value);
15158   Info.InConstantContext = true;
15159 
15160   SourceLocation DeclLoc = VD->getLocation();
15161   QualType DeclTy = VD->getType();
15162 
15163   if (Info.EnableNewConstInterp) {
15164     auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
15165     if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
15166       return false;
15167   } else {
15168     LValue LVal;
15169     LVal.set(VD);
15170 
15171     if (!EvaluateInPlace(Value, Info, LVal, this,
15172                          /*AllowNonLiteralTypes=*/true) ||
15173         EStatus.HasSideEffects)
15174       return false;
15175 
15176     // At this point, any lifetime-extended temporaries are completely
15177     // initialized.
15178     Info.performLifetimeExtension();
15179 
15180     if (!Info.discardCleanups())
15181       llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15182   }
15183   return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
15184                                  ConstantExprKind::Normal) &&
15185          CheckMemoryLeaks(Info);
15186 }
15187 
15188 bool VarDecl::evaluateDestruction(
15189     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
15190   Expr::EvalStatus EStatus;
15191   EStatus.Diag = &Notes;
15192 
15193   // Only treat the destruction as constant destruction if we formally have
15194   // constant initialization (or are usable in a constant expression).
15195   bool IsConstantDestruction = hasConstantInitialization();
15196 
15197   // Make a copy of the value for the destructor to mutate, if we know it.
15198   // Otherwise, treat the value as default-initialized; if the destructor works
15199   // anyway, then the destruction is constant (and must be essentially empty).
15200   APValue DestroyedValue;
15201   if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
15202     DestroyedValue = *getEvaluatedValue();
15203   else if (!getDefaultInitValue(getType(), DestroyedValue))
15204     return false;
15205 
15206   if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
15207                            getType(), getLocation(), EStatus,
15208                            IsConstantDestruction) ||
15209       EStatus.HasSideEffects)
15210     return false;
15211 
15212   ensureEvaluatedStmt()->HasConstantDestruction = true;
15213   return true;
15214 }
15215 
15216 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
15217 /// constant folded, but discard the result.
15218 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
15219   assert(!isValueDependent() &&
15220          "Expression evaluator can't be called on a dependent expression.");
15221 
15222   EvalResult Result;
15223   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
15224          !hasUnacceptableSideEffect(Result, SEK);
15225 }
15226 
15227 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
15228                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
15229   assert(!isValueDependent() &&
15230          "Expression evaluator can't be called on a dependent expression.");
15231 
15232   EvalResult EVResult;
15233   EVResult.Diag = Diag;
15234   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15235   Info.InConstantContext = true;
15236 
15237   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
15238   (void)Result;
15239   assert(Result && "Could not evaluate expression");
15240   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
15241 
15242   return EVResult.Val.getInt();
15243 }
15244 
15245 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
15246     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
15247   assert(!isValueDependent() &&
15248          "Expression evaluator can't be called on a dependent expression.");
15249 
15250   EvalResult EVResult;
15251   EVResult.Diag = Diag;
15252   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15253   Info.InConstantContext = true;
15254   Info.CheckingForUndefinedBehavior = true;
15255 
15256   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
15257   (void)Result;
15258   assert(Result && "Could not evaluate expression");
15259   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
15260 
15261   return EVResult.Val.getInt();
15262 }
15263 
15264 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
15265   assert(!isValueDependent() &&
15266          "Expression evaluator can't be called on a dependent expression.");
15267 
15268   bool IsConst;
15269   EvalResult EVResult;
15270   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
15271     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15272     Info.CheckingForUndefinedBehavior = true;
15273     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
15274   }
15275 }
15276 
15277 bool Expr::EvalResult::isGlobalLValue() const {
15278   assert(Val.isLValue());
15279   return IsGlobalLValue(Val.getLValueBase());
15280 }
15281 
15282 /// isIntegerConstantExpr - this recursive routine will test if an expression is
15283 /// an integer constant expression.
15284 
15285 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
15286 /// comma, etc
15287 
15288 // CheckICE - This function does the fundamental ICE checking: the returned
15289 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
15290 // and a (possibly null) SourceLocation indicating the location of the problem.
15291 //
15292 // Note that to reduce code duplication, this helper does no evaluation
15293 // itself; the caller checks whether the expression is evaluatable, and
15294 // in the rare cases where CheckICE actually cares about the evaluated
15295 // value, it calls into Evaluate.
15296 
15297 namespace {
15298 
15299 enum ICEKind {
15300   /// This expression is an ICE.
15301   IK_ICE,
15302   /// This expression is not an ICE, but if it isn't evaluated, it's
15303   /// a legal subexpression for an ICE. This return value is used to handle
15304   /// the comma operator in C99 mode, and non-constant subexpressions.
15305   IK_ICEIfUnevaluated,
15306   /// This expression is not an ICE, and is not a legal subexpression for one.
15307   IK_NotICE
15308 };
15309 
15310 struct ICEDiag {
15311   ICEKind Kind;
15312   SourceLocation Loc;
15313 
15314   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
15315 };
15316 
15317 }
15318 
15319 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
15320 
15321 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
15322 
15323 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
15324   Expr::EvalResult EVResult;
15325   Expr::EvalStatus Status;
15326   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15327 
15328   Info.InConstantContext = true;
15329   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
15330       !EVResult.Val.isInt())
15331     return ICEDiag(IK_NotICE, E->getBeginLoc());
15332 
15333   return NoDiag();
15334 }
15335 
15336 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
15337   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
15338   if (!E->getType()->isIntegralOrEnumerationType())
15339     return ICEDiag(IK_NotICE, E->getBeginLoc());
15340 
15341   switch (E->getStmtClass()) {
15342 #define ABSTRACT_STMT(Node)
15343 #define STMT(Node, Base) case Expr::Node##Class:
15344 #define EXPR(Node, Base)
15345 #include "clang/AST/StmtNodes.inc"
15346   case Expr::PredefinedExprClass:
15347   case Expr::FloatingLiteralClass:
15348   case Expr::ImaginaryLiteralClass:
15349   case Expr::StringLiteralClass:
15350   case Expr::ArraySubscriptExprClass:
15351   case Expr::MatrixSubscriptExprClass:
15352   case Expr::OMPArraySectionExprClass:
15353   case Expr::OMPArrayShapingExprClass:
15354   case Expr::OMPIteratorExprClass:
15355   case Expr::MemberExprClass:
15356   case Expr::CompoundAssignOperatorClass:
15357   case Expr::CompoundLiteralExprClass:
15358   case Expr::ExtVectorElementExprClass:
15359   case Expr::DesignatedInitExprClass:
15360   case Expr::ArrayInitLoopExprClass:
15361   case Expr::ArrayInitIndexExprClass:
15362   case Expr::NoInitExprClass:
15363   case Expr::DesignatedInitUpdateExprClass:
15364   case Expr::ImplicitValueInitExprClass:
15365   case Expr::ParenListExprClass:
15366   case Expr::VAArgExprClass:
15367   case Expr::AddrLabelExprClass:
15368   case Expr::StmtExprClass:
15369   case Expr::CXXMemberCallExprClass:
15370   case Expr::CUDAKernelCallExprClass:
15371   case Expr::CXXAddrspaceCastExprClass:
15372   case Expr::CXXDynamicCastExprClass:
15373   case Expr::CXXTypeidExprClass:
15374   case Expr::CXXUuidofExprClass:
15375   case Expr::MSPropertyRefExprClass:
15376   case Expr::MSPropertySubscriptExprClass:
15377   case Expr::CXXNullPtrLiteralExprClass:
15378   case Expr::UserDefinedLiteralClass:
15379   case Expr::CXXThisExprClass:
15380   case Expr::CXXThrowExprClass:
15381   case Expr::CXXNewExprClass:
15382   case Expr::CXXDeleteExprClass:
15383   case Expr::CXXPseudoDestructorExprClass:
15384   case Expr::UnresolvedLookupExprClass:
15385   case Expr::TypoExprClass:
15386   case Expr::RecoveryExprClass:
15387   case Expr::DependentScopeDeclRefExprClass:
15388   case Expr::CXXConstructExprClass:
15389   case Expr::CXXInheritedCtorInitExprClass:
15390   case Expr::CXXStdInitializerListExprClass:
15391   case Expr::CXXBindTemporaryExprClass:
15392   case Expr::ExprWithCleanupsClass:
15393   case Expr::CXXTemporaryObjectExprClass:
15394   case Expr::CXXUnresolvedConstructExprClass:
15395   case Expr::CXXDependentScopeMemberExprClass:
15396   case Expr::UnresolvedMemberExprClass:
15397   case Expr::ObjCStringLiteralClass:
15398   case Expr::ObjCBoxedExprClass:
15399   case Expr::ObjCArrayLiteralClass:
15400   case Expr::ObjCDictionaryLiteralClass:
15401   case Expr::ObjCEncodeExprClass:
15402   case Expr::ObjCMessageExprClass:
15403   case Expr::ObjCSelectorExprClass:
15404   case Expr::ObjCProtocolExprClass:
15405   case Expr::ObjCIvarRefExprClass:
15406   case Expr::ObjCPropertyRefExprClass:
15407   case Expr::ObjCSubscriptRefExprClass:
15408   case Expr::ObjCIsaExprClass:
15409   case Expr::ObjCAvailabilityCheckExprClass:
15410   case Expr::ShuffleVectorExprClass:
15411   case Expr::ConvertVectorExprClass:
15412   case Expr::BlockExprClass:
15413   case Expr::NoStmtClass:
15414   case Expr::OpaqueValueExprClass:
15415   case Expr::PackExpansionExprClass:
15416   case Expr::SubstNonTypeTemplateParmPackExprClass:
15417   case Expr::FunctionParmPackExprClass:
15418   case Expr::AsTypeExprClass:
15419   case Expr::ObjCIndirectCopyRestoreExprClass:
15420   case Expr::MaterializeTemporaryExprClass:
15421   case Expr::PseudoObjectExprClass:
15422   case Expr::AtomicExprClass:
15423   case Expr::LambdaExprClass:
15424   case Expr::CXXFoldExprClass:
15425   case Expr::CoawaitExprClass:
15426   case Expr::DependentCoawaitExprClass:
15427   case Expr::CoyieldExprClass:
15428   case Expr::SYCLUniqueStableNameExprClass:
15429     return ICEDiag(IK_NotICE, E->getBeginLoc());
15430 
15431   case Expr::InitListExprClass: {
15432     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
15433     // form "T x = { a };" is equivalent to "T x = a;".
15434     // Unless we're initializing a reference, T is a scalar as it is known to be
15435     // of integral or enumeration type.
15436     if (E->isPRValue())
15437       if (cast<InitListExpr>(E)->getNumInits() == 1)
15438         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
15439     return ICEDiag(IK_NotICE, E->getBeginLoc());
15440   }
15441 
15442   case Expr::SizeOfPackExprClass:
15443   case Expr::GNUNullExprClass:
15444   case Expr::SourceLocExprClass:
15445     return NoDiag();
15446 
15447   case Expr::SubstNonTypeTemplateParmExprClass:
15448     return
15449       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
15450 
15451   case Expr::ConstantExprClass:
15452     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
15453 
15454   case Expr::ParenExprClass:
15455     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
15456   case Expr::GenericSelectionExprClass:
15457     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
15458   case Expr::IntegerLiteralClass:
15459   case Expr::FixedPointLiteralClass:
15460   case Expr::CharacterLiteralClass:
15461   case Expr::ObjCBoolLiteralExprClass:
15462   case Expr::CXXBoolLiteralExprClass:
15463   case Expr::CXXScalarValueInitExprClass:
15464   case Expr::TypeTraitExprClass:
15465   case Expr::ConceptSpecializationExprClass:
15466   case Expr::RequiresExprClass:
15467   case Expr::ArrayTypeTraitExprClass:
15468   case Expr::ExpressionTraitExprClass:
15469   case Expr::CXXNoexceptExprClass:
15470     return NoDiag();
15471   case Expr::CallExprClass:
15472   case Expr::CXXOperatorCallExprClass: {
15473     // C99 6.6/3 allows function calls within unevaluated subexpressions of
15474     // constant expressions, but they can never be ICEs because an ICE cannot
15475     // contain an operand of (pointer to) function type.
15476     const CallExpr *CE = cast<CallExpr>(E);
15477     if (CE->getBuiltinCallee())
15478       return CheckEvalInICE(E, Ctx);
15479     return ICEDiag(IK_NotICE, E->getBeginLoc());
15480   }
15481   case Expr::CXXRewrittenBinaryOperatorClass:
15482     return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
15483                     Ctx);
15484   case Expr::DeclRefExprClass: {
15485     const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
15486     if (isa<EnumConstantDecl>(D))
15487       return NoDiag();
15488 
15489     // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
15490     // integer variables in constant expressions:
15491     //
15492     // C++ 7.1.5.1p2
15493     //   A variable of non-volatile const-qualified integral or enumeration
15494     //   type initialized by an ICE can be used in ICEs.
15495     //
15496     // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
15497     // that mode, use of reference variables should not be allowed.
15498     const VarDecl *VD = dyn_cast<VarDecl>(D);
15499     if (VD && VD->isUsableInConstantExpressions(Ctx) &&
15500         !VD->getType()->isReferenceType())
15501       return NoDiag();
15502 
15503     return ICEDiag(IK_NotICE, E->getBeginLoc());
15504   }
15505   case Expr::UnaryOperatorClass: {
15506     const UnaryOperator *Exp = cast<UnaryOperator>(E);
15507     switch (Exp->getOpcode()) {
15508     case UO_PostInc:
15509     case UO_PostDec:
15510     case UO_PreInc:
15511     case UO_PreDec:
15512     case UO_AddrOf:
15513     case UO_Deref:
15514     case UO_Coawait:
15515       // C99 6.6/3 allows increment and decrement within unevaluated
15516       // subexpressions of constant expressions, but they can never be ICEs
15517       // because an ICE cannot contain an lvalue operand.
15518       return ICEDiag(IK_NotICE, E->getBeginLoc());
15519     case UO_Extension:
15520     case UO_LNot:
15521     case UO_Plus:
15522     case UO_Minus:
15523     case UO_Not:
15524     case UO_Real:
15525     case UO_Imag:
15526       return CheckICE(Exp->getSubExpr(), Ctx);
15527     }
15528     llvm_unreachable("invalid unary operator class");
15529   }
15530   case Expr::OffsetOfExprClass: {
15531     // Note that per C99, offsetof must be an ICE. And AFAIK, using
15532     // EvaluateAsRValue matches the proposed gcc behavior for cases like
15533     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
15534     // compliance: we should warn earlier for offsetof expressions with
15535     // array subscripts that aren't ICEs, and if the array subscripts
15536     // are ICEs, the value of the offsetof must be an integer constant.
15537     return CheckEvalInICE(E, Ctx);
15538   }
15539   case Expr::UnaryExprOrTypeTraitExprClass: {
15540     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
15541     if ((Exp->getKind() ==  UETT_SizeOf) &&
15542         Exp->getTypeOfArgument()->isVariableArrayType())
15543       return ICEDiag(IK_NotICE, E->getBeginLoc());
15544     return NoDiag();
15545   }
15546   case Expr::BinaryOperatorClass: {
15547     const BinaryOperator *Exp = cast<BinaryOperator>(E);
15548     switch (Exp->getOpcode()) {
15549     case BO_PtrMemD:
15550     case BO_PtrMemI:
15551     case BO_Assign:
15552     case BO_MulAssign:
15553     case BO_DivAssign:
15554     case BO_RemAssign:
15555     case BO_AddAssign:
15556     case BO_SubAssign:
15557     case BO_ShlAssign:
15558     case BO_ShrAssign:
15559     case BO_AndAssign:
15560     case BO_XorAssign:
15561     case BO_OrAssign:
15562       // C99 6.6/3 allows assignments within unevaluated subexpressions of
15563       // constant expressions, but they can never be ICEs because an ICE cannot
15564       // contain an lvalue operand.
15565       return ICEDiag(IK_NotICE, E->getBeginLoc());
15566 
15567     case BO_Mul:
15568     case BO_Div:
15569     case BO_Rem:
15570     case BO_Add:
15571     case BO_Sub:
15572     case BO_Shl:
15573     case BO_Shr:
15574     case BO_LT:
15575     case BO_GT:
15576     case BO_LE:
15577     case BO_GE:
15578     case BO_EQ:
15579     case BO_NE:
15580     case BO_And:
15581     case BO_Xor:
15582     case BO_Or:
15583     case BO_Comma:
15584     case BO_Cmp: {
15585       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15586       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15587       if (Exp->getOpcode() == BO_Div ||
15588           Exp->getOpcode() == BO_Rem) {
15589         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
15590         // we don't evaluate one.
15591         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
15592           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
15593           if (REval == 0)
15594             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15595           if (REval.isSigned() && REval.isAllOnes()) {
15596             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
15597             if (LEval.isMinSignedValue())
15598               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15599           }
15600         }
15601       }
15602       if (Exp->getOpcode() == BO_Comma) {
15603         if (Ctx.getLangOpts().C99) {
15604           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
15605           // if it isn't evaluated.
15606           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
15607             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15608         } else {
15609           // In both C89 and C++, commas in ICEs are illegal.
15610           return ICEDiag(IK_NotICE, E->getBeginLoc());
15611         }
15612       }
15613       return Worst(LHSResult, RHSResult);
15614     }
15615     case BO_LAnd:
15616     case BO_LOr: {
15617       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15618       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15619       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
15620         // Rare case where the RHS has a comma "side-effect"; we need
15621         // to actually check the condition to see whether the side
15622         // with the comma is evaluated.
15623         if ((Exp->getOpcode() == BO_LAnd) !=
15624             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
15625           return RHSResult;
15626         return NoDiag();
15627       }
15628 
15629       return Worst(LHSResult, RHSResult);
15630     }
15631     }
15632     llvm_unreachable("invalid binary operator kind");
15633   }
15634   case Expr::ImplicitCastExprClass:
15635   case Expr::CStyleCastExprClass:
15636   case Expr::CXXFunctionalCastExprClass:
15637   case Expr::CXXStaticCastExprClass:
15638   case Expr::CXXReinterpretCastExprClass:
15639   case Expr::CXXConstCastExprClass:
15640   case Expr::ObjCBridgedCastExprClass: {
15641     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
15642     if (isa<ExplicitCastExpr>(E)) {
15643       if (const FloatingLiteral *FL
15644             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
15645         unsigned DestWidth = Ctx.getIntWidth(E->getType());
15646         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
15647         APSInt IgnoredVal(DestWidth, !DestSigned);
15648         bool Ignored;
15649         // If the value does not fit in the destination type, the behavior is
15650         // undefined, so we are not required to treat it as a constant
15651         // expression.
15652         if (FL->getValue().convertToInteger(IgnoredVal,
15653                                             llvm::APFloat::rmTowardZero,
15654                                             &Ignored) & APFloat::opInvalidOp)
15655           return ICEDiag(IK_NotICE, E->getBeginLoc());
15656         return NoDiag();
15657       }
15658     }
15659     switch (cast<CastExpr>(E)->getCastKind()) {
15660     case CK_LValueToRValue:
15661     case CK_AtomicToNonAtomic:
15662     case CK_NonAtomicToAtomic:
15663     case CK_NoOp:
15664     case CK_IntegralToBoolean:
15665     case CK_IntegralCast:
15666       return CheckICE(SubExpr, Ctx);
15667     default:
15668       return ICEDiag(IK_NotICE, E->getBeginLoc());
15669     }
15670   }
15671   case Expr::BinaryConditionalOperatorClass: {
15672     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
15673     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
15674     if (CommonResult.Kind == IK_NotICE) return CommonResult;
15675     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15676     if (FalseResult.Kind == IK_NotICE) return FalseResult;
15677     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
15678     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
15679         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
15680     return FalseResult;
15681   }
15682   case Expr::ConditionalOperatorClass: {
15683     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
15684     // If the condition (ignoring parens) is a __builtin_constant_p call,
15685     // then only the true side is actually considered in an integer constant
15686     // expression, and it is fully evaluated.  This is an important GNU
15687     // extension.  See GCC PR38377 for discussion.
15688     if (const CallExpr *CallCE
15689         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
15690       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
15691         return CheckEvalInICE(E, Ctx);
15692     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
15693     if (CondResult.Kind == IK_NotICE)
15694       return CondResult;
15695 
15696     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
15697     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15698 
15699     if (TrueResult.Kind == IK_NotICE)
15700       return TrueResult;
15701     if (FalseResult.Kind == IK_NotICE)
15702       return FalseResult;
15703     if (CondResult.Kind == IK_ICEIfUnevaluated)
15704       return CondResult;
15705     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
15706       return NoDiag();
15707     // Rare case where the diagnostics depend on which side is evaluated
15708     // Note that if we get here, CondResult is 0, and at least one of
15709     // TrueResult and FalseResult is non-zero.
15710     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
15711       return FalseResult;
15712     return TrueResult;
15713   }
15714   case Expr::CXXDefaultArgExprClass:
15715     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
15716   case Expr::CXXDefaultInitExprClass:
15717     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
15718   case Expr::ChooseExprClass: {
15719     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
15720   }
15721   case Expr::BuiltinBitCastExprClass: {
15722     if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
15723       return ICEDiag(IK_NotICE, E->getBeginLoc());
15724     return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
15725   }
15726   }
15727 
15728   llvm_unreachable("Invalid StmtClass!");
15729 }
15730 
15731 /// Evaluate an expression as a C++11 integral constant expression.
15732 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
15733                                                     const Expr *E,
15734                                                     llvm::APSInt *Value,
15735                                                     SourceLocation *Loc) {
15736   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15737     if (Loc) *Loc = E->getExprLoc();
15738     return false;
15739   }
15740 
15741   APValue Result;
15742   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
15743     return false;
15744 
15745   if (!Result.isInt()) {
15746     if (Loc) *Loc = E->getExprLoc();
15747     return false;
15748   }
15749 
15750   if (Value) *Value = Result.getInt();
15751   return true;
15752 }
15753 
15754 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
15755                                  SourceLocation *Loc) const {
15756   assert(!isValueDependent() &&
15757          "Expression evaluator can't be called on a dependent expression.");
15758 
15759   if (Ctx.getLangOpts().CPlusPlus11)
15760     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
15761 
15762   ICEDiag D = CheckICE(this, Ctx);
15763   if (D.Kind != IK_ICE) {
15764     if (Loc) *Loc = D.Loc;
15765     return false;
15766   }
15767   return true;
15768 }
15769 
15770 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx,
15771                                                     SourceLocation *Loc,
15772                                                     bool isEvaluated) const {
15773   if (isValueDependent()) {
15774     // Expression evaluator can't succeed on a dependent expression.
15775     return None;
15776   }
15777 
15778   APSInt Value;
15779 
15780   if (Ctx.getLangOpts().CPlusPlus11) {
15781     if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc))
15782       return Value;
15783     return None;
15784   }
15785 
15786   if (!isIntegerConstantExpr(Ctx, Loc))
15787     return None;
15788 
15789   // The only possible side-effects here are due to UB discovered in the
15790   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
15791   // required to treat the expression as an ICE, so we produce the folded
15792   // value.
15793   EvalResult ExprResult;
15794   Expr::EvalStatus Status;
15795   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
15796   Info.InConstantContext = true;
15797 
15798   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
15799     llvm_unreachable("ICE cannot be evaluated!");
15800 
15801   return ExprResult.Val.getInt();
15802 }
15803 
15804 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
15805   assert(!isValueDependent() &&
15806          "Expression evaluator can't be called on a dependent expression.");
15807 
15808   return CheckICE(this, Ctx).Kind == IK_ICE;
15809 }
15810 
15811 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
15812                                SourceLocation *Loc) const {
15813   assert(!isValueDependent() &&
15814          "Expression evaluator can't be called on a dependent expression.");
15815 
15816   // We support this checking in C++98 mode in order to diagnose compatibility
15817   // issues.
15818   assert(Ctx.getLangOpts().CPlusPlus);
15819 
15820   // Build evaluation settings.
15821   Expr::EvalStatus Status;
15822   SmallVector<PartialDiagnosticAt, 8> Diags;
15823   Status.Diag = &Diags;
15824   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15825 
15826   APValue Scratch;
15827   bool IsConstExpr =
15828       ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
15829       // FIXME: We don't produce a diagnostic for this, but the callers that
15830       // call us on arbitrary full-expressions should generally not care.
15831       Info.discardCleanups() && !Status.HasSideEffects;
15832 
15833   if (!Diags.empty()) {
15834     IsConstExpr = false;
15835     if (Loc) *Loc = Diags[0].first;
15836   } else if (!IsConstExpr) {
15837     // FIXME: This shouldn't happen.
15838     if (Loc) *Loc = getExprLoc();
15839   }
15840 
15841   return IsConstExpr;
15842 }
15843 
15844 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
15845                                     const FunctionDecl *Callee,
15846                                     ArrayRef<const Expr*> Args,
15847                                     const Expr *This) const {
15848   assert(!isValueDependent() &&
15849          "Expression evaluator can't be called on a dependent expression.");
15850 
15851   Expr::EvalStatus Status;
15852   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
15853   Info.InConstantContext = true;
15854 
15855   LValue ThisVal;
15856   const LValue *ThisPtr = nullptr;
15857   if (This) {
15858 #ifndef NDEBUG
15859     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
15860     assert(MD && "Don't provide `this` for non-methods.");
15861     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
15862 #endif
15863     if (!This->isValueDependent() &&
15864         EvaluateObjectArgument(Info, This, ThisVal) &&
15865         !Info.EvalStatus.HasSideEffects)
15866       ThisPtr = &ThisVal;
15867 
15868     // Ignore any side-effects from a failed evaluation. This is safe because
15869     // they can't interfere with any other argument evaluation.
15870     Info.EvalStatus.HasSideEffects = false;
15871   }
15872 
15873   CallRef Call = Info.CurrentCall->createCall(Callee);
15874   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
15875        I != E; ++I) {
15876     unsigned Idx = I - Args.begin();
15877     if (Idx >= Callee->getNumParams())
15878       break;
15879     const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
15880     if ((*I)->isValueDependent() ||
15881         !EvaluateCallArg(PVD, *I, Call, Info) ||
15882         Info.EvalStatus.HasSideEffects) {
15883       // If evaluation fails, throw away the argument entirely.
15884       if (APValue *Slot = Info.getParamSlot(Call, PVD))
15885         *Slot = APValue();
15886     }
15887 
15888     // Ignore any side-effects from a failed evaluation. This is safe because
15889     // they can't interfere with any other argument evaluation.
15890     Info.EvalStatus.HasSideEffects = false;
15891   }
15892 
15893   // Parameter cleanups happen in the caller and are not part of this
15894   // evaluation.
15895   Info.discardCleanups();
15896   Info.EvalStatus.HasSideEffects = false;
15897 
15898   // Build fake call to Callee.
15899   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call);
15900   // FIXME: Missing ExprWithCleanups in enable_if conditions?
15901   FullExpressionRAII Scope(Info);
15902   return Evaluate(Value, Info, this) && Scope.destroy() &&
15903          !Info.EvalStatus.HasSideEffects;
15904 }
15905 
15906 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
15907                                    SmallVectorImpl<
15908                                      PartialDiagnosticAt> &Diags) {
15909   // FIXME: It would be useful to check constexpr function templates, but at the
15910   // moment the constant expression evaluator cannot cope with the non-rigorous
15911   // ASTs which we build for dependent expressions.
15912   if (FD->isDependentContext())
15913     return true;
15914 
15915   Expr::EvalStatus Status;
15916   Status.Diag = &Diags;
15917 
15918   EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
15919   Info.InConstantContext = true;
15920   Info.CheckingPotentialConstantExpression = true;
15921 
15922   // The constexpr VM attempts to compile all methods to bytecode here.
15923   if (Info.EnableNewConstInterp) {
15924     Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
15925     return Diags.empty();
15926   }
15927 
15928   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
15929   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
15930 
15931   // Fabricate an arbitrary expression on the stack and pretend that it
15932   // is a temporary being used as the 'this' pointer.
15933   LValue This;
15934   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
15935   This.set({&VIE, Info.CurrentCall->Index});
15936 
15937   ArrayRef<const Expr*> Args;
15938 
15939   APValue Scratch;
15940   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
15941     // Evaluate the call as a constant initializer, to allow the construction
15942     // of objects of non-literal types.
15943     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
15944     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
15945   } else {
15946     SourceLocation Loc = FD->getLocation();
15947     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
15948                        Args, CallRef(), FD->getBody(), Info, Scratch, nullptr);
15949   }
15950 
15951   return Diags.empty();
15952 }
15953 
15954 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
15955                                               const FunctionDecl *FD,
15956                                               SmallVectorImpl<
15957                                                 PartialDiagnosticAt> &Diags) {
15958   assert(!E->isValueDependent() &&
15959          "Expression evaluator can't be called on a dependent expression.");
15960 
15961   Expr::EvalStatus Status;
15962   Status.Diag = &Diags;
15963 
15964   EvalInfo Info(FD->getASTContext(), Status,
15965                 EvalInfo::EM_ConstantExpressionUnevaluated);
15966   Info.InConstantContext = true;
15967   Info.CheckingPotentialConstantExpression = true;
15968 
15969   // Fabricate a call stack frame to give the arguments a plausible cover story.
15970   CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef());
15971 
15972   APValue ResultScratch;
15973   Evaluate(ResultScratch, Info, E);
15974   return Diags.empty();
15975 }
15976 
15977 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
15978                                  unsigned Type) const {
15979   if (!getType()->isPointerType())
15980     return false;
15981 
15982   Expr::EvalStatus Status;
15983   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
15984   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
15985 }
15986 
15987 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
15988                                   EvalInfo &Info) {
15989   if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
15990     return false;
15991 
15992   LValue String;
15993 
15994   if (!EvaluatePointer(E, String, Info))
15995     return false;
15996 
15997   QualType CharTy = E->getType()->getPointeeType();
15998 
15999   // Fast path: if it's a string literal, search the string value.
16000   if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
16001           String.getLValueBase().dyn_cast<const Expr *>())) {
16002     StringRef Str = S->getBytes();
16003     int64_t Off = String.Offset.getQuantity();
16004     if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
16005         S->getCharByteWidth() == 1 &&
16006         // FIXME: Add fast-path for wchar_t too.
16007         Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
16008       Str = Str.substr(Off);
16009 
16010       StringRef::size_type Pos = Str.find(0);
16011       if (Pos != StringRef::npos)
16012         Str = Str.substr(0, Pos);
16013 
16014       Result = Str.size();
16015       return true;
16016     }
16017 
16018     // Fall through to slow path.
16019   }
16020 
16021   // Slow path: scan the bytes of the string looking for the terminating 0.
16022   for (uint64_t Strlen = 0; /**/; ++Strlen) {
16023     APValue Char;
16024     if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
16025         !Char.isInt())
16026       return false;
16027     if (!Char.getInt()) {
16028       Result = Strlen;
16029       return true;
16030     }
16031     if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
16032       return false;
16033   }
16034 }
16035 
16036 bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
16037   Expr::EvalStatus Status;
16038   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
16039   return EvaluateBuiltinStrLen(this, Result, Info);
16040 }
16041