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/SmallBitVector.h"
56 #include "llvm/Support/Debug.h"
57 #include "llvm/Support/SaveAndRestore.h"
58 #include "llvm/Support/TimeProfiler.h"
59 #include "llvm/Support/raw_ostream.h"
60 #include <cstring>
61 #include <functional>
62 #include <optional>
63 
64 #define DEBUG_TYPE "exprconstant"
65 
66 using namespace clang;
67 using llvm::APFixedPoint;
68 using llvm::APInt;
69 using llvm::APSInt;
70 using llvm::APFloat;
71 using llvm::FixedPointSemantics;
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 ValueDecl *, 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       return nullptr;
596     }
597 
598     // Return the current temporary for Key in the map.
599     APValue *getCurrentTemporary(const void *Key) {
600       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
601       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
602         return &std::prev(UB)->second;
603       return nullptr;
604     }
605 
606     // Return the version number of the current temporary for Key.
607     unsigned getCurrentTemporaryVersion(const void *Key) const {
608       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
609       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
610         return std::prev(UB)->first.second;
611       return 0;
612     }
613 
614     /// Allocate storage for an object of type T in this stack frame.
615     /// Populates LV with a handle to the created object. Key identifies
616     /// the temporary within the stack frame, and must not be reused without
617     /// bumping the temporary version number.
618     template<typename KeyT>
619     APValue &createTemporary(const KeyT *Key, QualType T,
620                              ScopeKind Scope, LValue &LV);
621 
622     /// Allocate storage for a parameter of a function call made in this frame.
623     APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
624 
625     void describe(llvm::raw_ostream &OS) override;
626 
627     Frame *getCaller() const override { return Caller; }
628     SourceLocation getCallLocation() const override { return CallLoc; }
629     const FunctionDecl *getCallee() const override { return Callee; }
630 
631     bool isStdFunction() const {
632       for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
633         if (DC->isStdNamespace())
634           return true;
635       return false;
636     }
637 
638   private:
639     APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
640                          ScopeKind Scope);
641   };
642 
643   /// Temporarily override 'this'.
644   class ThisOverrideRAII {
645   public:
646     ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
647         : Frame(Frame), OldThis(Frame.This) {
648       if (Enable)
649         Frame.This = NewThis;
650     }
651     ~ThisOverrideRAII() {
652       Frame.This = OldThis;
653     }
654   private:
655     CallStackFrame &Frame;
656     const LValue *OldThis;
657   };
658 
659   // A shorthand time trace scope struct, prints source range, for example
660   // {"name":"EvaluateAsRValue","args":{"detail":"<test.cc:8:21, col:25>"}}}
661   class ExprTimeTraceScope {
662   public:
663     ExprTimeTraceScope(const Expr *E, const ASTContext &Ctx, StringRef Name)
664         : TimeScope(Name, [E, &Ctx] {
665             return E->getSourceRange().printToString(Ctx.getSourceManager());
666           }) {}
667 
668   private:
669     llvm::TimeTraceScope TimeScope;
670   };
671 }
672 
673 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
674                               const LValue &This, QualType ThisType);
675 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
676                               APValue::LValueBase LVBase, APValue &Value,
677                               QualType T);
678 
679 namespace {
680   /// A cleanup, and a flag indicating whether it is lifetime-extended.
681   class Cleanup {
682     llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
683     APValue::LValueBase Base;
684     QualType T;
685 
686   public:
687     Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
688             ScopeKind Scope)
689         : Value(Val, Scope), Base(Base), T(T) {}
690 
691     /// Determine whether this cleanup should be performed at the end of the
692     /// given kind of scope.
693     bool isDestroyedAtEndOf(ScopeKind K) const {
694       return (int)Value.getInt() >= (int)K;
695     }
696     bool endLifetime(EvalInfo &Info, bool RunDestructors) {
697       if (RunDestructors) {
698         SourceLocation Loc;
699         if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
700           Loc = VD->getLocation();
701         else if (const Expr *E = Base.dyn_cast<const Expr*>())
702           Loc = E->getExprLoc();
703         return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
704       }
705       *Value.getPointer() = APValue();
706       return true;
707     }
708 
709     bool hasSideEffect() {
710       return T.isDestructedType();
711     }
712   };
713 
714   /// A reference to an object whose construction we are currently evaluating.
715   struct ObjectUnderConstruction {
716     APValue::LValueBase Base;
717     ArrayRef<APValue::LValuePathEntry> Path;
718     friend bool operator==(const ObjectUnderConstruction &LHS,
719                            const ObjectUnderConstruction &RHS) {
720       return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
721     }
722     friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
723       return llvm::hash_combine(Obj.Base, Obj.Path);
724     }
725   };
726   enum class ConstructionPhase {
727     None,
728     Bases,
729     AfterBases,
730     AfterFields,
731     Destroying,
732     DestroyingBases
733   };
734 }
735 
736 namespace llvm {
737 template<> struct DenseMapInfo<ObjectUnderConstruction> {
738   using Base = DenseMapInfo<APValue::LValueBase>;
739   static ObjectUnderConstruction getEmptyKey() {
740     return {Base::getEmptyKey(), {}}; }
741   static ObjectUnderConstruction getTombstoneKey() {
742     return {Base::getTombstoneKey(), {}};
743   }
744   static unsigned getHashValue(const ObjectUnderConstruction &Object) {
745     return hash_value(Object);
746   }
747   static bool isEqual(const ObjectUnderConstruction &LHS,
748                       const ObjectUnderConstruction &RHS) {
749     return LHS == RHS;
750   }
751 };
752 }
753 
754 namespace {
755   /// A dynamically-allocated heap object.
756   struct DynAlloc {
757     /// The value of this heap-allocated object.
758     APValue Value;
759     /// The allocating expression; used for diagnostics. Either a CXXNewExpr
760     /// or a CallExpr (the latter is for direct calls to operator new inside
761     /// std::allocator<T>::allocate).
762     const Expr *AllocExpr = nullptr;
763 
764     enum Kind {
765       New,
766       ArrayNew,
767       StdAllocator
768     };
769 
770     /// Get the kind of the allocation. This must match between allocation
771     /// and deallocation.
772     Kind getKind() const {
773       if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
774         return NE->isArray() ? ArrayNew : New;
775       assert(isa<CallExpr>(AllocExpr));
776       return StdAllocator;
777     }
778   };
779 
780   struct DynAllocOrder {
781     bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
782       return L.getIndex() < R.getIndex();
783     }
784   };
785 
786   /// EvalInfo - This is a private struct used by the evaluator to capture
787   /// information about a subexpression as it is folded.  It retains information
788   /// about the AST context, but also maintains information about the folded
789   /// expression.
790   ///
791   /// If an expression could be evaluated, it is still possible it is not a C
792   /// "integer constant expression" or constant expression.  If not, this struct
793   /// captures information about how and why not.
794   ///
795   /// One bit of information passed *into* the request for constant folding
796   /// indicates whether the subexpression is "evaluated" or not according to C
797   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
798   /// evaluate the expression regardless of what the RHS is, but C only allows
799   /// certain things in certain situations.
800   class EvalInfo : public interp::State {
801   public:
802     ASTContext &Ctx;
803 
804     /// EvalStatus - Contains information about the evaluation.
805     Expr::EvalStatus &EvalStatus;
806 
807     /// CurrentCall - The top of the constexpr call stack.
808     CallStackFrame *CurrentCall;
809 
810     /// CallStackDepth - The number of calls in the call stack right now.
811     unsigned CallStackDepth;
812 
813     /// NextCallIndex - The next call index to assign.
814     unsigned NextCallIndex;
815 
816     /// StepsLeft - The remaining number of evaluation steps we're permitted
817     /// to perform. This is essentially a limit for the number of statements
818     /// we will evaluate.
819     unsigned StepsLeft;
820 
821     /// Enable the experimental new constant interpreter. If an expression is
822     /// not supported by the interpreter, an error is triggered.
823     bool EnableNewConstInterp;
824 
825     /// BottomFrame - The frame in which evaluation started. This must be
826     /// initialized after CurrentCall and CallStackDepth.
827     CallStackFrame BottomFrame;
828 
829     /// A stack of values whose lifetimes end at the end of some surrounding
830     /// evaluation frame.
831     llvm::SmallVector<Cleanup, 16> CleanupStack;
832 
833     /// EvaluatingDecl - This is the declaration whose initializer is being
834     /// evaluated, if any.
835     APValue::LValueBase EvaluatingDecl;
836 
837     enum class EvaluatingDeclKind {
838       None,
839       /// We're evaluating the construction of EvaluatingDecl.
840       Ctor,
841       /// We're evaluating the destruction of EvaluatingDecl.
842       Dtor,
843     };
844     EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
845 
846     /// EvaluatingDeclValue - This is the value being constructed for the
847     /// declaration whose initializer is being evaluated, if any.
848     APValue *EvaluatingDeclValue;
849 
850     /// Set of objects that are currently being constructed.
851     llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
852         ObjectsUnderConstruction;
853 
854     /// Current heap allocations, along with the location where each was
855     /// allocated. We use std::map here because we need stable addresses
856     /// for the stored APValues.
857     std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
858 
859     /// The number of heap allocations performed so far in this evaluation.
860     unsigned NumHeapAllocs = 0;
861 
862     struct EvaluatingConstructorRAII {
863       EvalInfo &EI;
864       ObjectUnderConstruction Object;
865       bool DidInsert;
866       EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
867                                 bool HasBases)
868           : EI(EI), Object(Object) {
869         DidInsert =
870             EI.ObjectsUnderConstruction
871                 .insert({Object, HasBases ? ConstructionPhase::Bases
872                                           : ConstructionPhase::AfterBases})
873                 .second;
874       }
875       void finishedConstructingBases() {
876         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
877       }
878       void finishedConstructingFields() {
879         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
880       }
881       ~EvaluatingConstructorRAII() {
882         if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
883       }
884     };
885 
886     struct EvaluatingDestructorRAII {
887       EvalInfo &EI;
888       ObjectUnderConstruction Object;
889       bool DidInsert;
890       EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
891           : EI(EI), Object(Object) {
892         DidInsert = EI.ObjectsUnderConstruction
893                         .insert({Object, ConstructionPhase::Destroying})
894                         .second;
895       }
896       void startedDestroyingBases() {
897         EI.ObjectsUnderConstruction[Object] =
898             ConstructionPhase::DestroyingBases;
899       }
900       ~EvaluatingDestructorRAII() {
901         if (DidInsert)
902           EI.ObjectsUnderConstruction.erase(Object);
903       }
904     };
905 
906     ConstructionPhase
907     isEvaluatingCtorDtor(APValue::LValueBase Base,
908                          ArrayRef<APValue::LValuePathEntry> Path) {
909       return ObjectsUnderConstruction.lookup({Base, Path});
910     }
911 
912     /// If we're currently speculatively evaluating, the outermost call stack
913     /// depth at which we can mutate state, otherwise 0.
914     unsigned SpeculativeEvaluationDepth = 0;
915 
916     /// The current array initialization index, if we're performing array
917     /// initialization.
918     uint64_t ArrayInitIndex = -1;
919 
920     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
921     /// notes attached to it will also be stored, otherwise they will not be.
922     bool HasActiveDiagnostic;
923 
924     /// Have we emitted a diagnostic explaining why we couldn't constant
925     /// fold (not just why it's not strictly a constant expression)?
926     bool HasFoldFailureDiagnostic;
927 
928     /// Whether we're checking that an expression is a potential constant
929     /// expression. If so, do not fail on constructs that could become constant
930     /// later on (such as a use of an undefined global).
931     bool CheckingPotentialConstantExpression = false;
932 
933     /// Whether we're checking for an expression that has undefined behavior.
934     /// If so, we will produce warnings if we encounter an operation that is
935     /// always undefined.
936     ///
937     /// Note that we still need to evaluate the expression normally when this
938     /// is set; this is used when evaluating ICEs in C.
939     bool CheckingForUndefinedBehavior = false;
940 
941     enum EvaluationMode {
942       /// Evaluate as a constant expression. Stop if we find that the expression
943       /// is not a constant expression.
944       EM_ConstantExpression,
945 
946       /// Evaluate as a constant expression. Stop if we find that the expression
947       /// is not a constant expression. Some expressions can be retried in the
948       /// optimizer if we don't constant fold them here, but in an unevaluated
949       /// context we try to fold them immediately since the optimizer never
950       /// gets a chance to look at it.
951       EM_ConstantExpressionUnevaluated,
952 
953       /// Fold the expression to a constant. Stop if we hit a side-effect that
954       /// we can't model.
955       EM_ConstantFold,
956 
957       /// Evaluate in any way we know how. Don't worry about side-effects that
958       /// can't be modeled.
959       EM_IgnoreSideEffects,
960     } EvalMode;
961 
962     /// Are we checking whether the expression is a potential constant
963     /// expression?
964     bool checkingPotentialConstantExpression() const override  {
965       return CheckingPotentialConstantExpression;
966     }
967 
968     /// Are we checking an expression for overflow?
969     // FIXME: We should check for any kind of undefined or suspicious behavior
970     // in such constructs, not just overflow.
971     bool checkingForUndefinedBehavior() const override {
972       return CheckingForUndefinedBehavior;
973     }
974 
975     EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
976         : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
977           CallStackDepth(0), NextCallIndex(1),
978           StepsLeft(C.getLangOpts().ConstexprStepLimit),
979           EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
980           BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()),
981           EvaluatingDecl((const ValueDecl *)nullptr),
982           EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
983           HasFoldFailureDiagnostic(false), EvalMode(Mode) {}
984 
985     ~EvalInfo() {
986       discardCleanups();
987     }
988 
989     ASTContext &getCtx() const override { return Ctx; }
990 
991     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
992                            EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
993       EvaluatingDecl = Base;
994       IsEvaluatingDecl = EDK;
995       EvaluatingDeclValue = &Value;
996     }
997 
998     bool CheckCallLimit(SourceLocation Loc) {
999       // Don't perform any constexpr calls (other than the call we're checking)
1000       // when checking a potential constant expression.
1001       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
1002         return false;
1003       if (NextCallIndex == 0) {
1004         // NextCallIndex has wrapped around.
1005         FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
1006         return false;
1007       }
1008       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
1009         return true;
1010       FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
1011         << getLangOpts().ConstexprCallDepth;
1012       return false;
1013     }
1014 
1015     std::pair<CallStackFrame *, unsigned>
1016     getCallFrameAndDepth(unsigned CallIndex) {
1017       assert(CallIndex && "no call index in getCallFrameAndDepth");
1018       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1019       // be null in this loop.
1020       unsigned Depth = CallStackDepth;
1021       CallStackFrame *Frame = CurrentCall;
1022       while (Frame->Index > CallIndex) {
1023         Frame = Frame->Caller;
1024         --Depth;
1025       }
1026       if (Frame->Index == CallIndex)
1027         return {Frame, Depth};
1028       return {nullptr, 0};
1029     }
1030 
1031     bool nextStep(const Stmt *S) {
1032       if (!StepsLeft) {
1033         FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1034         return false;
1035       }
1036       --StepsLeft;
1037       return true;
1038     }
1039 
1040     APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1041 
1042     std::optional<DynAlloc *> lookupDynamicAlloc(DynamicAllocLValue DA) {
1043       std::optional<DynAlloc *> Result;
1044       auto It = HeapAllocs.find(DA);
1045       if (It != HeapAllocs.end())
1046         Result = &It->second;
1047       return Result;
1048     }
1049 
1050     /// Get the allocated storage for the given parameter of the given call.
1051     APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1052       CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1053       return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1054                    : nullptr;
1055     }
1056 
1057     /// Information about a stack frame for std::allocator<T>::[de]allocate.
1058     struct StdAllocatorCaller {
1059       unsigned FrameIndex;
1060       QualType ElemType;
1061       explicit operator bool() const { return FrameIndex != 0; };
1062     };
1063 
1064     StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1065       for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1066            Call = Call->Caller) {
1067         const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1068         if (!MD)
1069           continue;
1070         const IdentifierInfo *FnII = MD->getIdentifier();
1071         if (!FnII || !FnII->isStr(FnName))
1072           continue;
1073 
1074         const auto *CTSD =
1075             dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1076         if (!CTSD)
1077           continue;
1078 
1079         const IdentifierInfo *ClassII = CTSD->getIdentifier();
1080         const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1081         if (CTSD->isInStdNamespace() && ClassII &&
1082             ClassII->isStr("allocator") && TAL.size() >= 1 &&
1083             TAL[0].getKind() == TemplateArgument::Type)
1084           return {Call->Index, TAL[0].getAsType()};
1085       }
1086 
1087       return {};
1088     }
1089 
1090     void performLifetimeExtension() {
1091       // Disable the cleanups for lifetime-extended temporaries.
1092       llvm::erase_if(CleanupStack, [](Cleanup &C) {
1093         return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1094       });
1095     }
1096 
1097     /// Throw away any remaining cleanups at the end of evaluation. If any
1098     /// cleanups would have had a side-effect, note that as an unmodeled
1099     /// side-effect and return false. Otherwise, return true.
1100     bool discardCleanups() {
1101       for (Cleanup &C : CleanupStack) {
1102         if (C.hasSideEffect() && !noteSideEffect()) {
1103           CleanupStack.clear();
1104           return false;
1105         }
1106       }
1107       CleanupStack.clear();
1108       return true;
1109     }
1110 
1111   private:
1112     interp::Frame *getCurrentFrame() override { return CurrentCall; }
1113     const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1114 
1115     bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1116     void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1117 
1118     void setFoldFailureDiagnostic(bool Flag) override {
1119       HasFoldFailureDiagnostic = Flag;
1120     }
1121 
1122     Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1123 
1124     // If we have a prior diagnostic, it will be noting that the expression
1125     // isn't a constant expression. This diagnostic is more important,
1126     // unless we require this evaluation to produce a constant expression.
1127     //
1128     // FIXME: We might want to show both diagnostics to the user in
1129     // EM_ConstantFold mode.
1130     bool hasPriorDiagnostic() override {
1131       if (!EvalStatus.Diag->empty()) {
1132         switch (EvalMode) {
1133         case EM_ConstantFold:
1134         case EM_IgnoreSideEffects:
1135           if (!HasFoldFailureDiagnostic)
1136             break;
1137           // We've already failed to fold something. Keep that diagnostic.
1138           [[fallthrough]];
1139         case EM_ConstantExpression:
1140         case EM_ConstantExpressionUnevaluated:
1141           setActiveDiagnostic(false);
1142           return true;
1143         }
1144       }
1145       return false;
1146     }
1147 
1148     unsigned getCallStackDepth() override { return CallStackDepth; }
1149 
1150   public:
1151     /// Should we continue evaluation after encountering a side-effect that we
1152     /// couldn't model?
1153     bool keepEvaluatingAfterSideEffect() {
1154       switch (EvalMode) {
1155       case EM_IgnoreSideEffects:
1156         return true;
1157 
1158       case EM_ConstantExpression:
1159       case EM_ConstantExpressionUnevaluated:
1160       case EM_ConstantFold:
1161         // By default, assume any side effect might be valid in some other
1162         // evaluation of this expression from a different context.
1163         return checkingPotentialConstantExpression() ||
1164                checkingForUndefinedBehavior();
1165       }
1166       llvm_unreachable("Missed EvalMode case");
1167     }
1168 
1169     /// Note that we have had a side-effect, and determine whether we should
1170     /// keep evaluating.
1171     bool noteSideEffect() {
1172       EvalStatus.HasSideEffects = true;
1173       return keepEvaluatingAfterSideEffect();
1174     }
1175 
1176     /// Should we continue evaluation after encountering undefined behavior?
1177     bool keepEvaluatingAfterUndefinedBehavior() {
1178       switch (EvalMode) {
1179       case EM_IgnoreSideEffects:
1180       case EM_ConstantFold:
1181         return true;
1182 
1183       case EM_ConstantExpression:
1184       case EM_ConstantExpressionUnevaluated:
1185         return checkingForUndefinedBehavior();
1186       }
1187       llvm_unreachable("Missed EvalMode case");
1188     }
1189 
1190     /// Note that we hit something that was technically undefined behavior, but
1191     /// that we can evaluate past it (such as signed overflow or floating-point
1192     /// division by zero.)
1193     bool noteUndefinedBehavior() override {
1194       EvalStatus.HasUndefinedBehavior = true;
1195       return keepEvaluatingAfterUndefinedBehavior();
1196     }
1197 
1198     /// Should we continue evaluation as much as possible after encountering a
1199     /// construct which can't be reduced to a value?
1200     bool keepEvaluatingAfterFailure() const override {
1201       if (!StepsLeft)
1202         return false;
1203 
1204       switch (EvalMode) {
1205       case EM_ConstantExpression:
1206       case EM_ConstantExpressionUnevaluated:
1207       case EM_ConstantFold:
1208       case EM_IgnoreSideEffects:
1209         return checkingPotentialConstantExpression() ||
1210                checkingForUndefinedBehavior();
1211       }
1212       llvm_unreachable("Missed EvalMode case");
1213     }
1214 
1215     /// Notes that we failed to evaluate an expression that other expressions
1216     /// directly depend on, and determine if we should keep evaluating. This
1217     /// should only be called if we actually intend to keep evaluating.
1218     ///
1219     /// Call noteSideEffect() instead if we may be able to ignore the value that
1220     /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1221     ///
1222     /// (Foo(), 1)      // use noteSideEffect
1223     /// (Foo() || true) // use noteSideEffect
1224     /// Foo() + 1       // use noteFailure
1225     [[nodiscard]] bool noteFailure() {
1226       // Failure when evaluating some expression often means there is some
1227       // subexpression whose evaluation was skipped. Therefore, (because we
1228       // don't track whether we skipped an expression when unwinding after an
1229       // evaluation failure) every evaluation failure that bubbles up from a
1230       // subexpression implies that a side-effect has potentially happened. We
1231       // skip setting the HasSideEffects flag to true until we decide to
1232       // continue evaluating after that point, which happens here.
1233       bool KeepGoing = keepEvaluatingAfterFailure();
1234       EvalStatus.HasSideEffects |= KeepGoing;
1235       return KeepGoing;
1236     }
1237 
1238     class ArrayInitLoopIndex {
1239       EvalInfo &Info;
1240       uint64_t OuterIndex;
1241 
1242     public:
1243       ArrayInitLoopIndex(EvalInfo &Info)
1244           : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1245         Info.ArrayInitIndex = 0;
1246       }
1247       ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1248 
1249       operator uint64_t&() { return Info.ArrayInitIndex; }
1250     };
1251   };
1252 
1253   /// Object used to treat all foldable expressions as constant expressions.
1254   struct FoldConstant {
1255     EvalInfo &Info;
1256     bool Enabled;
1257     bool HadNoPriorDiags;
1258     EvalInfo::EvaluationMode OldMode;
1259 
1260     explicit FoldConstant(EvalInfo &Info, bool Enabled)
1261       : Info(Info),
1262         Enabled(Enabled),
1263         HadNoPriorDiags(Info.EvalStatus.Diag &&
1264                         Info.EvalStatus.Diag->empty() &&
1265                         !Info.EvalStatus.HasSideEffects),
1266         OldMode(Info.EvalMode) {
1267       if (Enabled)
1268         Info.EvalMode = EvalInfo::EM_ConstantFold;
1269     }
1270     void keepDiagnostics() { Enabled = false; }
1271     ~FoldConstant() {
1272       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1273           !Info.EvalStatus.HasSideEffects)
1274         Info.EvalStatus.Diag->clear();
1275       Info.EvalMode = OldMode;
1276     }
1277   };
1278 
1279   /// RAII object used to set the current evaluation mode to ignore
1280   /// side-effects.
1281   struct IgnoreSideEffectsRAII {
1282     EvalInfo &Info;
1283     EvalInfo::EvaluationMode OldMode;
1284     explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1285         : Info(Info), OldMode(Info.EvalMode) {
1286       Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1287     }
1288 
1289     ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1290   };
1291 
1292   /// RAII object used to optionally suppress diagnostics and side-effects from
1293   /// a speculative evaluation.
1294   class SpeculativeEvaluationRAII {
1295     EvalInfo *Info = nullptr;
1296     Expr::EvalStatus OldStatus;
1297     unsigned OldSpeculativeEvaluationDepth;
1298 
1299     void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1300       Info = Other.Info;
1301       OldStatus = Other.OldStatus;
1302       OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1303       Other.Info = nullptr;
1304     }
1305 
1306     void maybeRestoreState() {
1307       if (!Info)
1308         return;
1309 
1310       Info->EvalStatus = OldStatus;
1311       Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1312     }
1313 
1314   public:
1315     SpeculativeEvaluationRAII() = default;
1316 
1317     SpeculativeEvaluationRAII(
1318         EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1319         : Info(&Info), OldStatus(Info.EvalStatus),
1320           OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1321       Info.EvalStatus.Diag = NewDiag;
1322       Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1323     }
1324 
1325     SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1326     SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1327       moveFromAndCancel(std::move(Other));
1328     }
1329 
1330     SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1331       maybeRestoreState();
1332       moveFromAndCancel(std::move(Other));
1333       return *this;
1334     }
1335 
1336     ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1337   };
1338 
1339   /// RAII object wrapping a full-expression or block scope, and handling
1340   /// the ending of the lifetime of temporaries created within it.
1341   template<ScopeKind Kind>
1342   class ScopeRAII {
1343     EvalInfo &Info;
1344     unsigned OldStackSize;
1345   public:
1346     ScopeRAII(EvalInfo &Info)
1347         : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1348       // Push a new temporary version. This is needed to distinguish between
1349       // temporaries created in different iterations of a loop.
1350       Info.CurrentCall->pushTempVersion();
1351     }
1352     bool destroy(bool RunDestructors = true) {
1353       bool OK = cleanup(Info, RunDestructors, OldStackSize);
1354       OldStackSize = -1U;
1355       return OK;
1356     }
1357     ~ScopeRAII() {
1358       if (OldStackSize != -1U)
1359         destroy(false);
1360       // Body moved to a static method to encourage the compiler to inline away
1361       // instances of this class.
1362       Info.CurrentCall->popTempVersion();
1363     }
1364   private:
1365     static bool cleanup(EvalInfo &Info, bool RunDestructors,
1366                         unsigned OldStackSize) {
1367       assert(OldStackSize <= Info.CleanupStack.size() &&
1368              "running cleanups out of order?");
1369 
1370       // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1371       // for a full-expression scope.
1372       bool Success = true;
1373       for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1374         if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1375           if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1376             Success = false;
1377             break;
1378           }
1379         }
1380       }
1381 
1382       // Compact any retained cleanups.
1383       auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1384       if (Kind != ScopeKind::Block)
1385         NewEnd =
1386             std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1387               return C.isDestroyedAtEndOf(Kind);
1388             });
1389       Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1390       return Success;
1391     }
1392   };
1393   typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1394   typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1395   typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1396 }
1397 
1398 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1399                                          CheckSubobjectKind CSK) {
1400   if (Invalid)
1401     return false;
1402   if (isOnePastTheEnd()) {
1403     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1404       << CSK;
1405     setInvalid();
1406     return false;
1407   }
1408   // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1409   // must actually be at least one array element; even a VLA cannot have a
1410   // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1411   return true;
1412 }
1413 
1414 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1415                                                                 const Expr *E) {
1416   Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1417   // Do not set the designator as invalid: we can represent this situation,
1418   // and correct handling of __builtin_object_size requires us to do so.
1419 }
1420 
1421 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1422                                                     const Expr *E,
1423                                                     const APSInt &N) {
1424   // If we're complaining, we must be able to statically determine the size of
1425   // the most derived array.
1426   if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1427     Info.CCEDiag(E, diag::note_constexpr_array_index)
1428       << N << /*array*/ 0
1429       << static_cast<unsigned>(getMostDerivedArraySize());
1430   else
1431     Info.CCEDiag(E, diag::note_constexpr_array_index)
1432       << N << /*non-array*/ 1;
1433   setInvalid();
1434 }
1435 
1436 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1437                                const FunctionDecl *Callee, const LValue *This,
1438                                CallRef Call)
1439     : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1440       Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1441   Info.CurrentCall = this;
1442   ++Info.CallStackDepth;
1443 }
1444 
1445 CallStackFrame::~CallStackFrame() {
1446   assert(Info.CurrentCall == this && "calls retired out of order");
1447   --Info.CallStackDepth;
1448   Info.CurrentCall = Caller;
1449 }
1450 
1451 static bool isRead(AccessKinds AK) {
1452   return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1453 }
1454 
1455 static bool isModification(AccessKinds AK) {
1456   switch (AK) {
1457   case AK_Read:
1458   case AK_ReadObjectRepresentation:
1459   case AK_MemberCall:
1460   case AK_DynamicCast:
1461   case AK_TypeId:
1462     return false;
1463   case AK_Assign:
1464   case AK_Increment:
1465   case AK_Decrement:
1466   case AK_Construct:
1467   case AK_Destroy:
1468     return true;
1469   }
1470   llvm_unreachable("unknown access kind");
1471 }
1472 
1473 static bool isAnyAccess(AccessKinds AK) {
1474   return isRead(AK) || isModification(AK);
1475 }
1476 
1477 /// Is this an access per the C++ definition?
1478 static bool isFormalAccess(AccessKinds AK) {
1479   return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
1480 }
1481 
1482 /// Is this kind of axcess valid on an indeterminate object value?
1483 static bool isValidIndeterminateAccess(AccessKinds AK) {
1484   switch (AK) {
1485   case AK_Read:
1486   case AK_Increment:
1487   case AK_Decrement:
1488     // These need the object's value.
1489     return false;
1490 
1491   case AK_ReadObjectRepresentation:
1492   case AK_Assign:
1493   case AK_Construct:
1494   case AK_Destroy:
1495     // Construction and destruction don't need the value.
1496     return true;
1497 
1498   case AK_MemberCall:
1499   case AK_DynamicCast:
1500   case AK_TypeId:
1501     // These aren't really meaningful on scalars.
1502     return true;
1503   }
1504   llvm_unreachable("unknown access kind");
1505 }
1506 
1507 namespace {
1508   struct ComplexValue {
1509   private:
1510     bool IsInt;
1511 
1512   public:
1513     APSInt IntReal, IntImag;
1514     APFloat FloatReal, FloatImag;
1515 
1516     ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1517 
1518     void makeComplexFloat() { IsInt = false; }
1519     bool isComplexFloat() const { return !IsInt; }
1520     APFloat &getComplexFloatReal() { return FloatReal; }
1521     APFloat &getComplexFloatImag() { return FloatImag; }
1522 
1523     void makeComplexInt() { IsInt = true; }
1524     bool isComplexInt() const { return IsInt; }
1525     APSInt &getComplexIntReal() { return IntReal; }
1526     APSInt &getComplexIntImag() { return IntImag; }
1527 
1528     void moveInto(APValue &v) const {
1529       if (isComplexFloat())
1530         v = APValue(FloatReal, FloatImag);
1531       else
1532         v = APValue(IntReal, IntImag);
1533     }
1534     void setFrom(const APValue &v) {
1535       assert(v.isComplexFloat() || v.isComplexInt());
1536       if (v.isComplexFloat()) {
1537         makeComplexFloat();
1538         FloatReal = v.getComplexFloatReal();
1539         FloatImag = v.getComplexFloatImag();
1540       } else {
1541         makeComplexInt();
1542         IntReal = v.getComplexIntReal();
1543         IntImag = v.getComplexIntImag();
1544       }
1545     }
1546   };
1547 
1548   struct LValue {
1549     APValue::LValueBase Base;
1550     CharUnits Offset;
1551     SubobjectDesignator Designator;
1552     bool IsNullPtr : 1;
1553     bool InvalidBase : 1;
1554 
1555     const APValue::LValueBase getLValueBase() const { return Base; }
1556     CharUnits &getLValueOffset() { return Offset; }
1557     const CharUnits &getLValueOffset() const { return Offset; }
1558     SubobjectDesignator &getLValueDesignator() { return Designator; }
1559     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1560     bool isNullPointer() const { return IsNullPtr;}
1561 
1562     unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1563     unsigned getLValueVersion() const { return Base.getVersion(); }
1564 
1565     void moveInto(APValue &V) const {
1566       if (Designator.Invalid)
1567         V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1568       else {
1569         assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1570         V = APValue(Base, Offset, Designator.Entries,
1571                     Designator.IsOnePastTheEnd, IsNullPtr);
1572       }
1573     }
1574     void setFrom(ASTContext &Ctx, const APValue &V) {
1575       assert(V.isLValue() && "Setting LValue from a non-LValue?");
1576       Base = V.getLValueBase();
1577       Offset = V.getLValueOffset();
1578       InvalidBase = false;
1579       Designator = SubobjectDesignator(Ctx, V);
1580       IsNullPtr = V.isNullPointer();
1581     }
1582 
1583     void set(APValue::LValueBase B, bool BInvalid = false) {
1584 #ifndef NDEBUG
1585       // We only allow a few types of invalid bases. Enforce that here.
1586       if (BInvalid) {
1587         const auto *E = B.get<const Expr *>();
1588         assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1589                "Unexpected type of invalid base");
1590       }
1591 #endif
1592 
1593       Base = B;
1594       Offset = CharUnits::fromQuantity(0);
1595       InvalidBase = BInvalid;
1596       Designator = SubobjectDesignator(getType(B));
1597       IsNullPtr = false;
1598     }
1599 
1600     void setNull(ASTContext &Ctx, QualType PointerTy) {
1601       Base = (const ValueDecl *)nullptr;
1602       Offset =
1603           CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
1604       InvalidBase = false;
1605       Designator = SubobjectDesignator(PointerTy->getPointeeType());
1606       IsNullPtr = true;
1607     }
1608 
1609     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1610       set(B, true);
1611     }
1612 
1613     std::string toString(ASTContext &Ctx, QualType T) const {
1614       APValue Printable;
1615       moveInto(Printable);
1616       return Printable.getAsString(Ctx, T);
1617     }
1618 
1619   private:
1620     // Check that this LValue is not based on a null pointer. If it is, produce
1621     // a diagnostic and mark the designator as invalid.
1622     template <typename GenDiagType>
1623     bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1624       if (Designator.Invalid)
1625         return false;
1626       if (IsNullPtr) {
1627         GenDiag();
1628         Designator.setInvalid();
1629         return false;
1630       }
1631       return true;
1632     }
1633 
1634   public:
1635     bool checkNullPointer(EvalInfo &Info, const Expr *E,
1636                           CheckSubobjectKind CSK) {
1637       return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1638         Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1639       });
1640     }
1641 
1642     bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1643                                        AccessKinds AK) {
1644       return checkNullPointerDiagnosingWith([&Info, E, AK] {
1645         Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1646       });
1647     }
1648 
1649     // Check this LValue refers to an object. If not, set the designator to be
1650     // invalid and emit a diagnostic.
1651     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1652       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1653              Designator.checkSubobject(Info, E, CSK);
1654     }
1655 
1656     void addDecl(EvalInfo &Info, const Expr *E,
1657                  const Decl *D, bool Virtual = false) {
1658       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1659         Designator.addDeclUnchecked(D, Virtual);
1660     }
1661     void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1662       if (!Designator.Entries.empty()) {
1663         Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1664         Designator.setInvalid();
1665         return;
1666       }
1667       if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1668         assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1669         Designator.FirstEntryIsAnUnsizedArray = true;
1670         Designator.addUnsizedArrayUnchecked(ElemTy);
1671       }
1672     }
1673     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1674       if (checkSubobject(Info, E, CSK_ArrayToPointer))
1675         Designator.addArrayUnchecked(CAT);
1676     }
1677     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1678       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1679         Designator.addComplexUnchecked(EltTy, Imag);
1680     }
1681     void clearIsNullPointer() {
1682       IsNullPtr = false;
1683     }
1684     void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1685                               const APSInt &Index, CharUnits ElementSize) {
1686       // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1687       // but we're not required to diagnose it and it's valid in C++.)
1688       if (!Index)
1689         return;
1690 
1691       // Compute the new offset in the appropriate width, wrapping at 64 bits.
1692       // FIXME: When compiling for a 32-bit target, we should use 32-bit
1693       // offsets.
1694       uint64_t Offset64 = Offset.getQuantity();
1695       uint64_t ElemSize64 = ElementSize.getQuantity();
1696       uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1697       Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1698 
1699       if (checkNullPointer(Info, E, CSK_ArrayIndex))
1700         Designator.adjustIndex(Info, E, Index);
1701       clearIsNullPointer();
1702     }
1703     void adjustOffset(CharUnits N) {
1704       Offset += N;
1705       if (N.getQuantity())
1706         clearIsNullPointer();
1707     }
1708   };
1709 
1710   struct MemberPtr {
1711     MemberPtr() {}
1712     explicit MemberPtr(const ValueDecl *Decl)
1713         : DeclAndIsDerivedMember(Decl, false) {}
1714 
1715     /// The member or (direct or indirect) field referred to by this member
1716     /// pointer, or 0 if this is a null member pointer.
1717     const ValueDecl *getDecl() const {
1718       return DeclAndIsDerivedMember.getPointer();
1719     }
1720     /// Is this actually a member of some type derived from the relevant class?
1721     bool isDerivedMember() const {
1722       return DeclAndIsDerivedMember.getInt();
1723     }
1724     /// Get the class which the declaration actually lives in.
1725     const CXXRecordDecl *getContainingRecord() const {
1726       return cast<CXXRecordDecl>(
1727           DeclAndIsDerivedMember.getPointer()->getDeclContext());
1728     }
1729 
1730     void moveInto(APValue &V) const {
1731       V = APValue(getDecl(), isDerivedMember(), Path);
1732     }
1733     void setFrom(const APValue &V) {
1734       assert(V.isMemberPointer());
1735       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1736       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1737       Path.clear();
1738       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1739       Path.insert(Path.end(), P.begin(), P.end());
1740     }
1741 
1742     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1743     /// whether the member is a member of some class derived from the class type
1744     /// of the member pointer.
1745     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1746     /// Path - The path of base/derived classes from the member declaration's
1747     /// class (exclusive) to the class type of the member pointer (inclusive).
1748     SmallVector<const CXXRecordDecl*, 4> Path;
1749 
1750     /// Perform a cast towards the class of the Decl (either up or down the
1751     /// hierarchy).
1752     bool castBack(const CXXRecordDecl *Class) {
1753       assert(!Path.empty());
1754       const CXXRecordDecl *Expected;
1755       if (Path.size() >= 2)
1756         Expected = Path[Path.size() - 2];
1757       else
1758         Expected = getContainingRecord();
1759       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1760         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1761         // if B does not contain the original member and is not a base or
1762         // derived class of the class containing the original member, the result
1763         // of the cast is undefined.
1764         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1765         // (D::*). We consider that to be a language defect.
1766         return false;
1767       }
1768       Path.pop_back();
1769       return true;
1770     }
1771     /// Perform a base-to-derived member pointer cast.
1772     bool castToDerived(const CXXRecordDecl *Derived) {
1773       if (!getDecl())
1774         return true;
1775       if (!isDerivedMember()) {
1776         Path.push_back(Derived);
1777         return true;
1778       }
1779       if (!castBack(Derived))
1780         return false;
1781       if (Path.empty())
1782         DeclAndIsDerivedMember.setInt(false);
1783       return true;
1784     }
1785     /// Perform a derived-to-base member pointer cast.
1786     bool castToBase(const CXXRecordDecl *Base) {
1787       if (!getDecl())
1788         return true;
1789       if (Path.empty())
1790         DeclAndIsDerivedMember.setInt(true);
1791       if (isDerivedMember()) {
1792         Path.push_back(Base);
1793         return true;
1794       }
1795       return castBack(Base);
1796     }
1797   };
1798 
1799   /// Compare two member pointers, which are assumed to be of the same type.
1800   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1801     if (!LHS.getDecl() || !RHS.getDecl())
1802       return !LHS.getDecl() && !RHS.getDecl();
1803     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1804       return false;
1805     return LHS.Path == RHS.Path;
1806   }
1807 }
1808 
1809 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1810 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1811                             const LValue &This, const Expr *E,
1812                             bool AllowNonLiteralTypes = false);
1813 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1814                            bool InvalidBaseOK = false);
1815 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1816                             bool InvalidBaseOK = false);
1817 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1818                                   EvalInfo &Info);
1819 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1820 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1821 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1822                                     EvalInfo &Info);
1823 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1824 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1825 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1826                            EvalInfo &Info);
1827 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1828 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
1829                                   EvalInfo &Info);
1830 
1831 /// Evaluate an integer or fixed point expression into an APResult.
1832 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1833                                         EvalInfo &Info);
1834 
1835 /// Evaluate only a fixed point expression into an APResult.
1836 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1837                                EvalInfo &Info);
1838 
1839 //===----------------------------------------------------------------------===//
1840 // Misc utilities
1841 //===----------------------------------------------------------------------===//
1842 
1843 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1844 /// preserving its value (by extending by up to one bit as needed).
1845 static void negateAsSigned(APSInt &Int) {
1846   if (Int.isUnsigned() || Int.isMinSignedValue()) {
1847     Int = Int.extend(Int.getBitWidth() + 1);
1848     Int.setIsSigned(true);
1849   }
1850   Int = -Int;
1851 }
1852 
1853 template<typename KeyT>
1854 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1855                                          ScopeKind Scope, LValue &LV) {
1856   unsigned Version = getTempVersion();
1857   APValue::LValueBase Base(Key, Index, Version);
1858   LV.set(Base);
1859   return createLocal(Base, Key, T, Scope);
1860 }
1861 
1862 /// Allocate storage for a parameter of a function call made in this frame.
1863 APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1864                                      LValue &LV) {
1865   assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1866   APValue::LValueBase Base(PVD, Index, Args.Version);
1867   LV.set(Base);
1868   // We always destroy parameters at the end of the call, even if we'd allow
1869   // them to live to the end of the full-expression at runtime, in order to
1870   // give portable results and match other compilers.
1871   return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1872 }
1873 
1874 APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1875                                      QualType T, ScopeKind Scope) {
1876   assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1877   unsigned Version = Base.getVersion();
1878   APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1879   assert(Result.isAbsent() && "local created multiple times");
1880 
1881   // If we're creating a local immediately in the operand of a speculative
1882   // evaluation, don't register a cleanup to be run outside the speculative
1883   // evaluation context, since we won't actually be able to initialize this
1884   // object.
1885   if (Index <= Info.SpeculativeEvaluationDepth) {
1886     if (T.isDestructedType())
1887       Info.noteSideEffect();
1888   } else {
1889     Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1890   }
1891   return Result;
1892 }
1893 
1894 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1895   if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1896     FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1897     return nullptr;
1898   }
1899 
1900   DynamicAllocLValue DA(NumHeapAllocs++);
1901   LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1902   auto Result = HeapAllocs.emplace(std::piecewise_construct,
1903                                    std::forward_as_tuple(DA), std::tuple<>());
1904   assert(Result.second && "reused a heap alloc index?");
1905   Result.first->second.AllocExpr = E;
1906   return &Result.first->second.Value;
1907 }
1908 
1909 /// Produce a string describing the given constexpr call.
1910 void CallStackFrame::describe(raw_ostream &Out) {
1911   unsigned ArgIndex = 0;
1912   bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1913                       !isa<CXXConstructorDecl>(Callee) &&
1914                       cast<CXXMethodDecl>(Callee)->isInstance();
1915 
1916   if (!IsMemberCall)
1917     Out << *Callee << '(';
1918 
1919   if (This && IsMemberCall) {
1920     APValue Val;
1921     This->moveInto(Val);
1922     Val.printPretty(Out, Info.Ctx,
1923                     This->Designator.MostDerivedType);
1924     // FIXME: Add parens around Val if needed.
1925     Out << "->" << *Callee << '(';
1926     IsMemberCall = false;
1927   }
1928 
1929   for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1930        E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
1931     if (ArgIndex > (unsigned)IsMemberCall)
1932       Out << ", ";
1933 
1934     const ParmVarDecl *Param = *I;
1935     APValue *V = Info.getParamSlot(Arguments, Param);
1936     if (V)
1937       V->printPretty(Out, Info.Ctx, Param->getType());
1938     else
1939       Out << "<...>";
1940 
1941     if (ArgIndex == 0 && IsMemberCall)
1942       Out << "->" << *Callee << '(';
1943   }
1944 
1945   Out << ')';
1946 }
1947 
1948 /// Evaluate an expression to see if it had side-effects, and discard its
1949 /// result.
1950 /// \return \c true if the caller should keep evaluating.
1951 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1952   assert(!E->isValueDependent());
1953   APValue Scratch;
1954   if (!Evaluate(Scratch, Info, E))
1955     // We don't need the value, but we might have skipped a side effect here.
1956     return Info.noteSideEffect();
1957   return true;
1958 }
1959 
1960 /// Should this call expression be treated as a no-op?
1961 static bool IsNoOpCall(const CallExpr *E) {
1962   unsigned Builtin = E->getBuiltinCallee();
1963   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1964           Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
1965           Builtin == Builtin::BI__builtin_function_start);
1966 }
1967 
1968 static bool IsGlobalLValue(APValue::LValueBase B) {
1969   // C++11 [expr.const]p3 An address constant expression is a prvalue core
1970   // constant expression of pointer type that evaluates to...
1971 
1972   // ... a null pointer value, or a prvalue core constant expression of type
1973   // std::nullptr_t.
1974   if (!B) return true;
1975 
1976   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1977     // ... the address of an object with static storage duration,
1978     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1979       return VD->hasGlobalStorage();
1980     if (isa<TemplateParamObjectDecl>(D))
1981       return true;
1982     // ... the address of a function,
1983     // ... the address of a GUID [MS extension],
1984     // ... the address of an unnamed global constant
1985     return isa<FunctionDecl, MSGuidDecl, UnnamedGlobalConstantDecl>(D);
1986   }
1987 
1988   if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
1989     return true;
1990 
1991   const Expr *E = B.get<const Expr*>();
1992   switch (E->getStmtClass()) {
1993   default:
1994     return false;
1995   case Expr::CompoundLiteralExprClass: {
1996     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1997     return CLE->isFileScope() && CLE->isLValue();
1998   }
1999   case Expr::MaterializeTemporaryExprClass:
2000     // A materialized temporary might have been lifetime-extended to static
2001     // storage duration.
2002     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
2003   // A string literal has static storage duration.
2004   case Expr::StringLiteralClass:
2005   case Expr::PredefinedExprClass:
2006   case Expr::ObjCStringLiteralClass:
2007   case Expr::ObjCEncodeExprClass:
2008     return true;
2009   case Expr::ObjCBoxedExprClass:
2010     return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2011   case Expr::CallExprClass:
2012     return IsNoOpCall(cast<CallExpr>(E));
2013   // For GCC compatibility, &&label has static storage duration.
2014   case Expr::AddrLabelExprClass:
2015     return true;
2016   // A Block literal expression may be used as the initialization value for
2017   // Block variables at global or local static scope.
2018   case Expr::BlockExprClass:
2019     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2020   // The APValue generated from a __builtin_source_location will be emitted as a
2021   // literal.
2022   case Expr::SourceLocExprClass:
2023     return true;
2024   case Expr::ImplicitValueInitExprClass:
2025     // FIXME:
2026     // We can never form an lvalue with an implicit value initialization as its
2027     // base through expression evaluation, so these only appear in one case: the
2028     // implicit variable declaration we invent when checking whether a constexpr
2029     // constructor can produce a constant expression. We must assume that such
2030     // an expression might be a global lvalue.
2031     return true;
2032   }
2033 }
2034 
2035 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2036   return LVal.Base.dyn_cast<const ValueDecl*>();
2037 }
2038 
2039 static bool IsLiteralLValue(const LValue &Value) {
2040   if (Value.getLValueCallIndex())
2041     return false;
2042   const Expr *E = Value.Base.dyn_cast<const Expr*>();
2043   return E && !isa<MaterializeTemporaryExpr>(E);
2044 }
2045 
2046 static bool IsWeakLValue(const LValue &Value) {
2047   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2048   return Decl && Decl->isWeak();
2049 }
2050 
2051 static bool isZeroSized(const LValue &Value) {
2052   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2053   if (Decl && isa<VarDecl>(Decl)) {
2054     QualType Ty = Decl->getType();
2055     if (Ty->isArrayType())
2056       return Ty->isIncompleteType() ||
2057              Decl->getASTContext().getTypeSize(Ty) == 0;
2058   }
2059   return false;
2060 }
2061 
2062 static bool HasSameBase(const LValue &A, const LValue &B) {
2063   if (!A.getLValueBase())
2064     return !B.getLValueBase();
2065   if (!B.getLValueBase())
2066     return false;
2067 
2068   if (A.getLValueBase().getOpaqueValue() !=
2069       B.getLValueBase().getOpaqueValue())
2070     return false;
2071 
2072   return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2073          A.getLValueVersion() == B.getLValueVersion();
2074 }
2075 
2076 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2077   assert(Base && "no location for a null lvalue");
2078   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2079 
2080   // For a parameter, find the corresponding call stack frame (if it still
2081   // exists), and point at the parameter of the function definition we actually
2082   // invoked.
2083   if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2084     unsigned Idx = PVD->getFunctionScopeIndex();
2085     for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2086       if (F->Arguments.CallIndex == Base.getCallIndex() &&
2087           F->Arguments.Version == Base.getVersion() && F->Callee &&
2088           Idx < F->Callee->getNumParams()) {
2089         VD = F->Callee->getParamDecl(Idx);
2090         break;
2091       }
2092     }
2093   }
2094 
2095   if (VD)
2096     Info.Note(VD->getLocation(), diag::note_declared_at);
2097   else if (const Expr *E = Base.dyn_cast<const Expr*>())
2098     Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2099   else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2100     // FIXME: Produce a note for dangling pointers too.
2101     if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA))
2102       Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2103                 diag::note_constexpr_dynamic_alloc_here);
2104   }
2105   // We have no information to show for a typeid(T) object.
2106 }
2107 
2108 enum class CheckEvaluationResultKind {
2109   ConstantExpression,
2110   FullyInitialized,
2111 };
2112 
2113 /// Materialized temporaries that we've already checked to determine if they're
2114 /// initializsed by a constant expression.
2115 using CheckedTemporaries =
2116     llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
2117 
2118 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2119                                   EvalInfo &Info, SourceLocation DiagLoc,
2120                                   QualType Type, const APValue &Value,
2121                                   ConstantExprKind Kind,
2122                                   SourceLocation SubobjectLoc,
2123                                   CheckedTemporaries &CheckedTemps);
2124 
2125 /// Check that this reference or pointer core constant expression is a valid
2126 /// value for an address or reference constant expression. Return true if we
2127 /// can fold this expression, whether or not it's a constant expression.
2128 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2129                                           QualType Type, const LValue &LVal,
2130                                           ConstantExprKind Kind,
2131                                           CheckedTemporaries &CheckedTemps) {
2132   bool IsReferenceType = Type->isReferenceType();
2133 
2134   APValue::LValueBase Base = LVal.getLValueBase();
2135   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2136 
2137   const Expr *BaseE = Base.dyn_cast<const Expr *>();
2138   const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2139 
2140   // Additional restrictions apply in a template argument. We only enforce the
2141   // C++20 restrictions here; additional syntactic and semantic restrictions
2142   // are applied elsewhere.
2143   if (isTemplateArgument(Kind)) {
2144     int InvalidBaseKind = -1;
2145     StringRef Ident;
2146     if (Base.is<TypeInfoLValue>())
2147       InvalidBaseKind = 0;
2148     else if (isa_and_nonnull<StringLiteral>(BaseE))
2149       InvalidBaseKind = 1;
2150     else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2151              isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2152       InvalidBaseKind = 2;
2153     else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2154       InvalidBaseKind = 3;
2155       Ident = PE->getIdentKindName();
2156     }
2157 
2158     if (InvalidBaseKind != -1) {
2159       Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2160           << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2161           << Ident;
2162       return false;
2163     }
2164   }
2165 
2166   if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD)) {
2167     if (FD->isConsteval()) {
2168       Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2169           << !Type->isAnyPointerType();
2170       Info.Note(FD->getLocation(), diag::note_declared_at);
2171       return false;
2172     }
2173   }
2174 
2175   // Check that the object is a global. Note that the fake 'this' object we
2176   // manufacture when checking potential constant expressions is conservatively
2177   // assumed to be global here.
2178   if (!IsGlobalLValue(Base)) {
2179     if (Info.getLangOpts().CPlusPlus11) {
2180       Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2181           << IsReferenceType << !Designator.Entries.empty() << !!BaseVD
2182           << BaseVD;
2183       auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD);
2184       if (VarD && VarD->isConstexpr()) {
2185         // Non-static local constexpr variables have unintuitive semantics:
2186         //   constexpr int a = 1;
2187         //   constexpr const int *p = &a;
2188         // ... is invalid because the address of 'a' is not constant. Suggest
2189         // adding a 'static' in this case.
2190         Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2191             << VarD
2192             << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2193       } else {
2194         NoteLValueLocation(Info, Base);
2195       }
2196     } else {
2197       Info.FFDiag(Loc);
2198     }
2199     // Don't allow references to temporaries to escape.
2200     return false;
2201   }
2202   assert((Info.checkingPotentialConstantExpression() ||
2203           LVal.getLValueCallIndex() == 0) &&
2204          "have call index for global lvalue");
2205 
2206   if (Base.is<DynamicAllocLValue>()) {
2207     Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2208         << IsReferenceType << !Designator.Entries.empty();
2209     NoteLValueLocation(Info, Base);
2210     return false;
2211   }
2212 
2213   if (BaseVD) {
2214     if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2215       // Check if this is a thread-local variable.
2216       if (Var->getTLSKind())
2217         // FIXME: Diagnostic!
2218         return false;
2219 
2220       // A dllimport variable never acts like a constant, unless we're
2221       // evaluating a value for use only in name mangling.
2222       if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2223         // FIXME: Diagnostic!
2224         return false;
2225 
2226       // In CUDA/HIP device compilation, only device side variables have
2227       // constant addresses.
2228       if (Info.getCtx().getLangOpts().CUDA &&
2229           Info.getCtx().getLangOpts().CUDAIsDevice &&
2230           Info.getCtx().CUDAConstantEvalCtx.NoWrongSidedVars) {
2231         if ((!Var->hasAttr<CUDADeviceAttr>() &&
2232              !Var->hasAttr<CUDAConstantAttr>() &&
2233              !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2234              !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
2235             Var->hasAttr<HIPManagedAttr>())
2236           return false;
2237       }
2238     }
2239     if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2240       // __declspec(dllimport) must be handled very carefully:
2241       // We must never initialize an expression with the thunk in C++.
2242       // Doing otherwise would allow the same id-expression to yield
2243       // different addresses for the same function in different translation
2244       // units.  However, this means that we must dynamically initialize the
2245       // expression with the contents of the import address table at runtime.
2246       //
2247       // The C language has no notion of ODR; furthermore, it has no notion of
2248       // dynamic initialization.  This means that we are permitted to
2249       // perform initialization with the address of the thunk.
2250       if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2251           FD->hasAttr<DLLImportAttr>())
2252         // FIXME: Diagnostic!
2253         return false;
2254     }
2255   } else if (const auto *MTE =
2256                  dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2257     if (CheckedTemps.insert(MTE).second) {
2258       QualType TempType = getType(Base);
2259       if (TempType.isDestructedType()) {
2260         Info.FFDiag(MTE->getExprLoc(),
2261                     diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2262             << TempType;
2263         return false;
2264       }
2265 
2266       APValue *V = MTE->getOrCreateValue(false);
2267       assert(V && "evasluation result refers to uninitialised temporary");
2268       if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2269                                  Info, MTE->getExprLoc(), TempType, *V,
2270                                  Kind, SourceLocation(), CheckedTemps))
2271         return false;
2272     }
2273   }
2274 
2275   // Allow address constant expressions to be past-the-end pointers. This is
2276   // an extension: the standard requires them to point to an object.
2277   if (!IsReferenceType)
2278     return true;
2279 
2280   // A reference constant expression must refer to an object.
2281   if (!Base) {
2282     // FIXME: diagnostic
2283     Info.CCEDiag(Loc);
2284     return true;
2285   }
2286 
2287   // Does this refer one past the end of some object?
2288   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2289     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2290       << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2291     NoteLValueLocation(Info, Base);
2292   }
2293 
2294   return true;
2295 }
2296 
2297 /// Member pointers are constant expressions unless they point to a
2298 /// non-virtual dllimport member function.
2299 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2300                                                  SourceLocation Loc,
2301                                                  QualType Type,
2302                                                  const APValue &Value,
2303                                                  ConstantExprKind Kind) {
2304   const ValueDecl *Member = Value.getMemberPointerDecl();
2305   const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2306   if (!FD)
2307     return true;
2308   if (FD->isConsteval()) {
2309     Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2310     Info.Note(FD->getLocation(), diag::note_declared_at);
2311     return false;
2312   }
2313   return isForManglingOnly(Kind) || FD->isVirtual() ||
2314          !FD->hasAttr<DLLImportAttr>();
2315 }
2316 
2317 /// Check that this core constant expression is of literal type, and if not,
2318 /// produce an appropriate diagnostic.
2319 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2320                              const LValue *This = nullptr) {
2321   if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2322     return true;
2323 
2324   // C++1y: A constant initializer for an object o [...] may also invoke
2325   // constexpr constructors for o and its subobjects even if those objects
2326   // are of non-literal class types.
2327   //
2328   // C++11 missed this detail for aggregates, so classes like this:
2329   //   struct foo_t { union { int i; volatile int j; } u; };
2330   // are not (obviously) initializable like so:
2331   //   __attribute__((__require_constant_initialization__))
2332   //   static const foo_t x = {{0}};
2333   // because "i" is a subobject with non-literal initialization (due to the
2334   // volatile member of the union). See:
2335   //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2336   // Therefore, we use the C++1y behavior.
2337   if (This && Info.EvaluatingDecl == This->getLValueBase())
2338     return true;
2339 
2340   // Prvalue constant expressions must be of literal types.
2341   if (Info.getLangOpts().CPlusPlus11)
2342     Info.FFDiag(E, diag::note_constexpr_nonliteral)
2343       << E->getType();
2344   else
2345     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2346   return false;
2347 }
2348 
2349 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2350                                   EvalInfo &Info, SourceLocation DiagLoc,
2351                                   QualType Type, const APValue &Value,
2352                                   ConstantExprKind Kind,
2353                                   SourceLocation SubobjectLoc,
2354                                   CheckedTemporaries &CheckedTemps) {
2355   if (!Value.hasValue()) {
2356     Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2357       << true << Type;
2358     if (SubobjectLoc.isValid())
2359       Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2360     return false;
2361   }
2362 
2363   // We allow _Atomic(T) to be initialized from anything that T can be
2364   // initialized from.
2365   if (const AtomicType *AT = Type->getAs<AtomicType>())
2366     Type = AT->getValueType();
2367 
2368   // Core issue 1454: For a literal constant expression of array or class type,
2369   // each subobject of its value shall have been initialized by a constant
2370   // expression.
2371   if (Value.isArray()) {
2372     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2373     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2374       if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2375                                  Value.getArrayInitializedElt(I), Kind,
2376                                  SubobjectLoc, CheckedTemps))
2377         return false;
2378     }
2379     if (!Value.hasArrayFiller())
2380       return true;
2381     return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2382                                  Value.getArrayFiller(), Kind, SubobjectLoc,
2383                                  CheckedTemps);
2384   }
2385   if (Value.isUnion() && Value.getUnionField()) {
2386     return CheckEvaluationResult(
2387         CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2388         Value.getUnionValue(), Kind, Value.getUnionField()->getLocation(),
2389         CheckedTemps);
2390   }
2391   if (Value.isStruct()) {
2392     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2393     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2394       unsigned BaseIndex = 0;
2395       for (const CXXBaseSpecifier &BS : CD->bases()) {
2396         if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2397                                    Value.getStructBase(BaseIndex), Kind,
2398                                    BS.getBeginLoc(), CheckedTemps))
2399           return false;
2400         ++BaseIndex;
2401       }
2402     }
2403     for (const auto *I : RD->fields()) {
2404       if (I->isUnnamedBitfield())
2405         continue;
2406 
2407       if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2408                                  Value.getStructField(I->getFieldIndex()),
2409                                  Kind, I->getLocation(), CheckedTemps))
2410         return false;
2411     }
2412   }
2413 
2414   if (Value.isLValue() &&
2415       CERK == CheckEvaluationResultKind::ConstantExpression) {
2416     LValue LVal;
2417     LVal.setFrom(Info.Ctx, Value);
2418     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2419                                          CheckedTemps);
2420   }
2421 
2422   if (Value.isMemberPointer() &&
2423       CERK == CheckEvaluationResultKind::ConstantExpression)
2424     return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2425 
2426   // Everything else is fine.
2427   return true;
2428 }
2429 
2430 /// Check that this core constant expression value is a valid value for a
2431 /// constant expression. If not, report an appropriate diagnostic. Does not
2432 /// check that the expression is of literal type.
2433 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2434                                     QualType Type, const APValue &Value,
2435                                     ConstantExprKind Kind) {
2436   // Nothing to check for a constant expression of type 'cv void'.
2437   if (Type->isVoidType())
2438     return true;
2439 
2440   CheckedTemporaries CheckedTemps;
2441   return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2442                                Info, DiagLoc, Type, Value, Kind,
2443                                SourceLocation(), CheckedTemps);
2444 }
2445 
2446 /// Check that this evaluated value is fully-initialized and can be loaded by
2447 /// an lvalue-to-rvalue conversion.
2448 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2449                                   QualType Type, const APValue &Value) {
2450   CheckedTemporaries CheckedTemps;
2451   return CheckEvaluationResult(
2452       CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2453       ConstantExprKind::Normal, SourceLocation(), CheckedTemps);
2454 }
2455 
2456 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2457 /// "the allocated storage is deallocated within the evaluation".
2458 static bool CheckMemoryLeaks(EvalInfo &Info) {
2459   if (!Info.HeapAllocs.empty()) {
2460     // We can still fold to a constant despite a compile-time memory leak,
2461     // so long as the heap allocation isn't referenced in the result (we check
2462     // that in CheckConstantExpression).
2463     Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2464                  diag::note_constexpr_memory_leak)
2465         << unsigned(Info.HeapAllocs.size() - 1);
2466   }
2467   return true;
2468 }
2469 
2470 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2471   // A null base expression indicates a null pointer.  These are always
2472   // evaluatable, and they are false unless the offset is zero.
2473   if (!Value.getLValueBase()) {
2474     // TODO: Should a non-null pointer with an offset of zero evaluate to true?
2475     Result = !Value.getLValueOffset().isZero();
2476     return true;
2477   }
2478 
2479   // We have a non-null base.  These are generally known to be true, but if it's
2480   // a weak declaration it can be null at runtime.
2481   Result = true;
2482   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2483   return !Decl || !Decl->isWeak();
2484 }
2485 
2486 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2487   // TODO: This function should produce notes if it fails.
2488   switch (Val.getKind()) {
2489   case APValue::None:
2490   case APValue::Indeterminate:
2491     return false;
2492   case APValue::Int:
2493     Result = Val.getInt().getBoolValue();
2494     return true;
2495   case APValue::FixedPoint:
2496     Result = Val.getFixedPoint().getBoolValue();
2497     return true;
2498   case APValue::Float:
2499     Result = !Val.getFloat().isZero();
2500     return true;
2501   case APValue::ComplexInt:
2502     Result = Val.getComplexIntReal().getBoolValue() ||
2503              Val.getComplexIntImag().getBoolValue();
2504     return true;
2505   case APValue::ComplexFloat:
2506     Result = !Val.getComplexFloatReal().isZero() ||
2507              !Val.getComplexFloatImag().isZero();
2508     return true;
2509   case APValue::LValue:
2510     return EvalPointerValueAsBool(Val, Result);
2511   case APValue::MemberPointer:
2512     if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) {
2513       return false;
2514     }
2515     Result = Val.getMemberPointerDecl();
2516     return true;
2517   case APValue::Vector:
2518   case APValue::Array:
2519   case APValue::Struct:
2520   case APValue::Union:
2521   case APValue::AddrLabelDiff:
2522     return false;
2523   }
2524 
2525   llvm_unreachable("unknown APValue kind");
2526 }
2527 
2528 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2529                                        EvalInfo &Info) {
2530   assert(!E->isValueDependent());
2531   assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2532   APValue Val;
2533   if (!Evaluate(Val, Info, E))
2534     return false;
2535   return HandleConversionToBool(Val, Result);
2536 }
2537 
2538 template<typename T>
2539 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2540                            const T &SrcValue, QualType DestType) {
2541   Info.CCEDiag(E, diag::note_constexpr_overflow)
2542     << SrcValue << DestType;
2543   return Info.noteUndefinedBehavior();
2544 }
2545 
2546 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2547                                  QualType SrcType, const APFloat &Value,
2548                                  QualType DestType, APSInt &Result) {
2549   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2550   // Determine whether we are converting to unsigned or signed.
2551   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2552 
2553   Result = APSInt(DestWidth, !DestSigned);
2554   bool ignored;
2555   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2556       & APFloat::opInvalidOp)
2557     return HandleOverflow(Info, E, Value, DestType);
2558   return true;
2559 }
2560 
2561 /// Get rounding mode to use in evaluation of the specified expression.
2562 ///
2563 /// If rounding mode is unknown at compile time, still try to evaluate the
2564 /// expression. If the result is exact, it does not depend on rounding mode.
2565 /// So return "tonearest" mode instead of "dynamic".
2566 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
2567   llvm::RoundingMode RM =
2568       E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2569   if (RM == llvm::RoundingMode::Dynamic)
2570     RM = llvm::RoundingMode::NearestTiesToEven;
2571   return RM;
2572 }
2573 
2574 /// Check if the given evaluation result is allowed for constant evaluation.
2575 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2576                                      APFloat::opStatus St) {
2577   // In a constant context, assume that any dynamic rounding mode or FP
2578   // exception state matches the default floating-point environment.
2579   if (Info.InConstantContext)
2580     return true;
2581 
2582   FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2583   if ((St & APFloat::opInexact) &&
2584       FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2585     // Inexact result means that it depends on rounding mode. If the requested
2586     // mode is dynamic, the evaluation cannot be made in compile time.
2587     Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2588     return false;
2589   }
2590 
2591   if ((St != APFloat::opOK) &&
2592       (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2593        FPO.getExceptionMode() != LangOptions::FPE_Ignore ||
2594        FPO.getAllowFEnvAccess())) {
2595     Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2596     return false;
2597   }
2598 
2599   if ((St & APFloat::opStatus::opInvalidOp) &&
2600       FPO.getExceptionMode() != LangOptions::FPE_Ignore) {
2601     // There is no usefully definable result.
2602     Info.FFDiag(E);
2603     return false;
2604   }
2605 
2606   // FIXME: if:
2607   // - evaluation triggered other FP exception, and
2608   // - exception mode is not "ignore", and
2609   // - the expression being evaluated is not a part of global variable
2610   //   initializer,
2611   // the evaluation probably need to be rejected.
2612   return true;
2613 }
2614 
2615 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2616                                    QualType SrcType, QualType DestType,
2617                                    APFloat &Result) {
2618   assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E));
2619   llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2620   APFloat::opStatus St;
2621   APFloat Value = Result;
2622   bool ignored;
2623   St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2624   return checkFloatingPointResult(Info, E, St);
2625 }
2626 
2627 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2628                                  QualType DestType, QualType SrcType,
2629                                  const APSInt &Value) {
2630   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2631   // Figure out if this is a truncate, extend or noop cast.
2632   // If the input is signed, do a sign extend, noop, or truncate.
2633   APSInt Result = Value.extOrTrunc(DestWidth);
2634   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2635   if (DestType->isBooleanType())
2636     Result = Value.getBoolValue();
2637   return Result;
2638 }
2639 
2640 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2641                                  const FPOptions FPO,
2642                                  QualType SrcType, const APSInt &Value,
2643                                  QualType DestType, APFloat &Result) {
2644   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2645   llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2646   APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), RM);
2647   return checkFloatingPointResult(Info, E, St);
2648 }
2649 
2650 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2651                                   APValue &Value, const FieldDecl *FD) {
2652   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2653 
2654   if (!Value.isInt()) {
2655     // Trying to store a pointer-cast-to-integer into a bitfield.
2656     // FIXME: In this case, we should provide the diagnostic for casting
2657     // a pointer to an integer.
2658     assert(Value.isLValue() && "integral value neither int nor lvalue?");
2659     Info.FFDiag(E);
2660     return false;
2661   }
2662 
2663   APSInt &Int = Value.getInt();
2664   unsigned OldBitWidth = Int.getBitWidth();
2665   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2666   if (NewBitWidth < OldBitWidth)
2667     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2668   return true;
2669 }
2670 
2671 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2672                                   llvm::APInt &Res) {
2673   APValue SVal;
2674   if (!Evaluate(SVal, Info, E))
2675     return false;
2676   if (SVal.isInt()) {
2677     Res = SVal.getInt();
2678     return true;
2679   }
2680   if (SVal.isFloat()) {
2681     Res = SVal.getFloat().bitcastToAPInt();
2682     return true;
2683   }
2684   if (SVal.isVector()) {
2685     QualType VecTy = E->getType();
2686     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2687     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2688     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2689     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2690     Res = llvm::APInt::getZero(VecSize);
2691     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2692       APValue &Elt = SVal.getVectorElt(i);
2693       llvm::APInt EltAsInt;
2694       if (Elt.isInt()) {
2695         EltAsInt = Elt.getInt();
2696       } else if (Elt.isFloat()) {
2697         EltAsInt = Elt.getFloat().bitcastToAPInt();
2698       } else {
2699         // Don't try to handle vectors of anything other than int or float
2700         // (not sure if it's possible to hit this case).
2701         Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2702         return false;
2703       }
2704       unsigned BaseEltSize = EltAsInt.getBitWidth();
2705       if (BigEndian)
2706         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2707       else
2708         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2709     }
2710     return true;
2711   }
2712   // Give up if the input isn't an int, float, or vector.  For example, we
2713   // reject "(v4i16)(intptr_t)&a".
2714   Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2715   return false;
2716 }
2717 
2718 /// Perform the given integer operation, which is known to need at most BitWidth
2719 /// bits, and check for overflow in the original type (if that type was not an
2720 /// unsigned type).
2721 template<typename Operation>
2722 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2723                                  const APSInt &LHS, const APSInt &RHS,
2724                                  unsigned BitWidth, Operation Op,
2725                                  APSInt &Result) {
2726   if (LHS.isUnsigned()) {
2727     Result = Op(LHS, RHS);
2728     return true;
2729   }
2730 
2731   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2732   Result = Value.trunc(LHS.getBitWidth());
2733   if (Result.extend(BitWidth) != Value) {
2734     if (Info.checkingForUndefinedBehavior())
2735       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2736                                        diag::warn_integer_constant_overflow)
2737           << toString(Result, 10) << E->getType();
2738     return HandleOverflow(Info, E, Value, E->getType());
2739   }
2740   return true;
2741 }
2742 
2743 /// Perform the given binary integer operation.
2744 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2745                               BinaryOperatorKind Opcode, APSInt RHS,
2746                               APSInt &Result) {
2747   bool HandleOverflowResult = true;
2748   switch (Opcode) {
2749   default:
2750     Info.FFDiag(E);
2751     return false;
2752   case BO_Mul:
2753     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2754                                 std::multiplies<APSInt>(), Result);
2755   case BO_Add:
2756     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2757                                 std::plus<APSInt>(), Result);
2758   case BO_Sub:
2759     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2760                                 std::minus<APSInt>(), Result);
2761   case BO_And: Result = LHS & RHS; return true;
2762   case BO_Xor: Result = LHS ^ RHS; return true;
2763   case BO_Or:  Result = LHS | RHS; return true;
2764   case BO_Div:
2765   case BO_Rem:
2766     if (RHS == 0) {
2767       Info.FFDiag(E, diag::note_expr_divide_by_zero);
2768       return false;
2769     }
2770     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2771     // this operation and gives the two's complement result.
2772     if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2773         LHS.isMinSignedValue())
2774       HandleOverflowResult = HandleOverflow(
2775           Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
2776     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2777     return HandleOverflowResult;
2778   case BO_Shl: {
2779     if (Info.getLangOpts().OpenCL)
2780       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2781       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2782                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2783                     RHS.isUnsigned());
2784     else if (RHS.isSigned() && RHS.isNegative()) {
2785       // During constant-folding, a negative shift is an opposite shift. Such
2786       // a shift is not a constant expression.
2787       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2788       RHS = -RHS;
2789       goto shift_right;
2790     }
2791   shift_left:
2792     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2793     // the shifted type.
2794     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2795     if (SA != RHS) {
2796       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2797         << RHS << E->getType() << LHS.getBitWidth();
2798     } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2799       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2800       // operand, and must not overflow the corresponding unsigned type.
2801       // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2802       // E1 x 2^E2 module 2^N.
2803       if (LHS.isNegative())
2804         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2805       else if (LHS.countLeadingZeros() < SA)
2806         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2807     }
2808     Result = LHS << SA;
2809     return true;
2810   }
2811   case BO_Shr: {
2812     if (Info.getLangOpts().OpenCL)
2813       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2814       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2815                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2816                     RHS.isUnsigned());
2817     else if (RHS.isSigned() && RHS.isNegative()) {
2818       // During constant-folding, a negative shift is an opposite shift. Such a
2819       // shift is not a constant expression.
2820       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2821       RHS = -RHS;
2822       goto shift_left;
2823     }
2824   shift_right:
2825     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2826     // shifted type.
2827     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2828     if (SA != RHS)
2829       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2830         << RHS << E->getType() << LHS.getBitWidth();
2831     Result = LHS >> SA;
2832     return true;
2833   }
2834 
2835   case BO_LT: Result = LHS < RHS; return true;
2836   case BO_GT: Result = LHS > RHS; return true;
2837   case BO_LE: Result = LHS <= RHS; return true;
2838   case BO_GE: Result = LHS >= RHS; return true;
2839   case BO_EQ: Result = LHS == RHS; return true;
2840   case BO_NE: Result = LHS != RHS; return true;
2841   case BO_Cmp:
2842     llvm_unreachable("BO_Cmp should be handled elsewhere");
2843   }
2844 }
2845 
2846 /// Perform the given binary floating-point operation, in-place, on LHS.
2847 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2848                                   APFloat &LHS, BinaryOperatorKind Opcode,
2849                                   const APFloat &RHS) {
2850   llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2851   APFloat::opStatus St;
2852   switch (Opcode) {
2853   default:
2854     Info.FFDiag(E);
2855     return false;
2856   case BO_Mul:
2857     St = LHS.multiply(RHS, RM);
2858     break;
2859   case BO_Add:
2860     St = LHS.add(RHS, RM);
2861     break;
2862   case BO_Sub:
2863     St = LHS.subtract(RHS, RM);
2864     break;
2865   case BO_Div:
2866     // [expr.mul]p4:
2867     //   If the second operand of / or % is zero the behavior is undefined.
2868     if (RHS.isZero())
2869       Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2870     St = LHS.divide(RHS, RM);
2871     break;
2872   }
2873 
2874   // [expr.pre]p4:
2875   //   If during the evaluation of an expression, the result is not
2876   //   mathematically defined [...], the behavior is undefined.
2877   // FIXME: C++ rules require us to not conform to IEEE 754 here.
2878   if (LHS.isNaN()) {
2879     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2880     return Info.noteUndefinedBehavior();
2881   }
2882 
2883   return checkFloatingPointResult(Info, E, St);
2884 }
2885 
2886 static bool handleLogicalOpForVector(const APInt &LHSValue,
2887                                      BinaryOperatorKind Opcode,
2888                                      const APInt &RHSValue, APInt &Result) {
2889   bool LHS = (LHSValue != 0);
2890   bool RHS = (RHSValue != 0);
2891 
2892   if (Opcode == BO_LAnd)
2893     Result = LHS && RHS;
2894   else
2895     Result = LHS || RHS;
2896   return true;
2897 }
2898 static bool handleLogicalOpForVector(const APFloat &LHSValue,
2899                                      BinaryOperatorKind Opcode,
2900                                      const APFloat &RHSValue, APInt &Result) {
2901   bool LHS = !LHSValue.isZero();
2902   bool RHS = !RHSValue.isZero();
2903 
2904   if (Opcode == BO_LAnd)
2905     Result = LHS && RHS;
2906   else
2907     Result = LHS || RHS;
2908   return true;
2909 }
2910 
2911 static bool handleLogicalOpForVector(const APValue &LHSValue,
2912                                      BinaryOperatorKind Opcode,
2913                                      const APValue &RHSValue, APInt &Result) {
2914   // The result is always an int type, however operands match the first.
2915   if (LHSValue.getKind() == APValue::Int)
2916     return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2917                                     RHSValue.getInt(), Result);
2918   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2919   return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2920                                   RHSValue.getFloat(), Result);
2921 }
2922 
2923 template <typename APTy>
2924 static bool
2925 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
2926                                const APTy &RHSValue, APInt &Result) {
2927   switch (Opcode) {
2928   default:
2929     llvm_unreachable("unsupported binary operator");
2930   case BO_EQ:
2931     Result = (LHSValue == RHSValue);
2932     break;
2933   case BO_NE:
2934     Result = (LHSValue != RHSValue);
2935     break;
2936   case BO_LT:
2937     Result = (LHSValue < RHSValue);
2938     break;
2939   case BO_GT:
2940     Result = (LHSValue > RHSValue);
2941     break;
2942   case BO_LE:
2943     Result = (LHSValue <= RHSValue);
2944     break;
2945   case BO_GE:
2946     Result = (LHSValue >= RHSValue);
2947     break;
2948   }
2949 
2950   // The boolean operations on these vector types use an instruction that
2951   // results in a mask of '-1' for the 'truth' value.  Ensure that we negate 1
2952   // to -1 to make sure that we produce the correct value.
2953   Result.negate();
2954 
2955   return true;
2956 }
2957 
2958 static bool handleCompareOpForVector(const APValue &LHSValue,
2959                                      BinaryOperatorKind Opcode,
2960                                      const APValue &RHSValue, APInt &Result) {
2961   // The result is always an int type, however operands match the first.
2962   if (LHSValue.getKind() == APValue::Int)
2963     return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
2964                                           RHSValue.getInt(), Result);
2965   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2966   return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
2967                                         RHSValue.getFloat(), Result);
2968 }
2969 
2970 // Perform binary operations for vector types, in place on the LHS.
2971 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
2972                                     BinaryOperatorKind Opcode,
2973                                     APValue &LHSValue,
2974                                     const APValue &RHSValue) {
2975   assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
2976          "Operation not supported on vector types");
2977 
2978   const auto *VT = E->getType()->castAs<VectorType>();
2979   unsigned NumElements = VT->getNumElements();
2980   QualType EltTy = VT->getElementType();
2981 
2982   // In the cases (typically C as I've observed) where we aren't evaluating
2983   // constexpr but are checking for cases where the LHS isn't yet evaluatable,
2984   // just give up.
2985   if (!LHSValue.isVector()) {
2986     assert(LHSValue.isLValue() &&
2987            "A vector result that isn't a vector OR uncalculated LValue");
2988     Info.FFDiag(E);
2989     return false;
2990   }
2991 
2992   assert(LHSValue.getVectorLength() == NumElements &&
2993          RHSValue.getVectorLength() == NumElements && "Different vector sizes");
2994 
2995   SmallVector<APValue, 4> ResultElements;
2996 
2997   for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
2998     APValue LHSElt = LHSValue.getVectorElt(EltNum);
2999     APValue RHSElt = RHSValue.getVectorElt(EltNum);
3000 
3001     if (EltTy->isIntegerType()) {
3002       APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3003                        EltTy->isUnsignedIntegerType()};
3004       bool Success = true;
3005 
3006       if (BinaryOperator::isLogicalOp(Opcode))
3007         Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3008       else if (BinaryOperator::isComparisonOp(Opcode))
3009         Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3010       else
3011         Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3012                                     RHSElt.getInt(), EltResult);
3013 
3014       if (!Success) {
3015         Info.FFDiag(E);
3016         return false;
3017       }
3018       ResultElements.emplace_back(EltResult);
3019 
3020     } else if (EltTy->isFloatingType()) {
3021       assert(LHSElt.getKind() == APValue::Float &&
3022              RHSElt.getKind() == APValue::Float &&
3023              "Mismatched LHS/RHS/Result Type");
3024       APFloat LHSFloat = LHSElt.getFloat();
3025 
3026       if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3027                                  RHSElt.getFloat())) {
3028         Info.FFDiag(E);
3029         return false;
3030       }
3031 
3032       ResultElements.emplace_back(LHSFloat);
3033     }
3034   }
3035 
3036   LHSValue = APValue(ResultElements.data(), ResultElements.size());
3037   return true;
3038 }
3039 
3040 /// Cast an lvalue referring to a base subobject to a derived class, by
3041 /// truncating the lvalue's path to the given length.
3042 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3043                                const RecordDecl *TruncatedType,
3044                                unsigned TruncatedElements) {
3045   SubobjectDesignator &D = Result.Designator;
3046 
3047   // Check we actually point to a derived class object.
3048   if (TruncatedElements == D.Entries.size())
3049     return true;
3050   assert(TruncatedElements >= D.MostDerivedPathLength &&
3051          "not casting to a derived class");
3052   if (!Result.checkSubobject(Info, E, CSK_Derived))
3053     return false;
3054 
3055   // Truncate the path to the subobject, and remove any derived-to-base offsets.
3056   const RecordDecl *RD = TruncatedType;
3057   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3058     if (RD->isInvalidDecl()) return false;
3059     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3060     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3061     if (isVirtualBaseClass(D.Entries[I]))
3062       Result.Offset -= Layout.getVBaseClassOffset(Base);
3063     else
3064       Result.Offset -= Layout.getBaseClassOffset(Base);
3065     RD = Base;
3066   }
3067   D.Entries.resize(TruncatedElements);
3068   return true;
3069 }
3070 
3071 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3072                                    const CXXRecordDecl *Derived,
3073                                    const CXXRecordDecl *Base,
3074                                    const ASTRecordLayout *RL = nullptr) {
3075   if (!RL) {
3076     if (Derived->isInvalidDecl()) return false;
3077     RL = &Info.Ctx.getASTRecordLayout(Derived);
3078   }
3079 
3080   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3081   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3082   return true;
3083 }
3084 
3085 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3086                              const CXXRecordDecl *DerivedDecl,
3087                              const CXXBaseSpecifier *Base) {
3088   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3089 
3090   if (!Base->isVirtual())
3091     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3092 
3093   SubobjectDesignator &D = Obj.Designator;
3094   if (D.Invalid)
3095     return false;
3096 
3097   // Extract most-derived object and corresponding type.
3098   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3099   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3100     return false;
3101 
3102   // Find the virtual base class.
3103   if (DerivedDecl->isInvalidDecl()) return false;
3104   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3105   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3106   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3107   return true;
3108 }
3109 
3110 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3111                                  QualType Type, LValue &Result) {
3112   for (CastExpr::path_const_iterator PathI = E->path_begin(),
3113                                      PathE = E->path_end();
3114        PathI != PathE; ++PathI) {
3115     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3116                           *PathI))
3117       return false;
3118     Type = (*PathI)->getType();
3119   }
3120   return true;
3121 }
3122 
3123 /// Cast an lvalue referring to a derived class to a known base subobject.
3124 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3125                             const CXXRecordDecl *DerivedRD,
3126                             const CXXRecordDecl *BaseRD) {
3127   CXXBasePaths Paths(/*FindAmbiguities=*/false,
3128                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
3129   if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3130     llvm_unreachable("Class must be derived from the passed in base class!");
3131 
3132   for (CXXBasePathElement &Elem : Paths.front())
3133     if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3134       return false;
3135   return true;
3136 }
3137 
3138 /// Update LVal to refer to the given field, which must be a member of the type
3139 /// currently described by LVal.
3140 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3141                                const FieldDecl *FD,
3142                                const ASTRecordLayout *RL = nullptr) {
3143   if (!RL) {
3144     if (FD->getParent()->isInvalidDecl()) return false;
3145     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3146   }
3147 
3148   unsigned I = FD->getFieldIndex();
3149   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3150   LVal.addDecl(Info, E, FD);
3151   return true;
3152 }
3153 
3154 /// Update LVal to refer to the given indirect field.
3155 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3156                                        LValue &LVal,
3157                                        const IndirectFieldDecl *IFD) {
3158   for (const auto *C : IFD->chain())
3159     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3160       return false;
3161   return true;
3162 }
3163 
3164 /// Get the size of the given type in char units.
3165 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
3166                          QualType Type, CharUnits &Size) {
3167   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3168   // extension.
3169   if (Type->isVoidType() || Type->isFunctionType()) {
3170     Size = CharUnits::One();
3171     return true;
3172   }
3173 
3174   if (Type->isDependentType()) {
3175     Info.FFDiag(Loc);
3176     return false;
3177   }
3178 
3179   if (!Type->isConstantSizeType()) {
3180     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3181     // FIXME: Better diagnostic.
3182     Info.FFDiag(Loc);
3183     return false;
3184   }
3185 
3186   Size = Info.Ctx.getTypeSizeInChars(Type);
3187   return true;
3188 }
3189 
3190 /// Update a pointer value to model pointer arithmetic.
3191 /// \param Info - Information about the ongoing evaluation.
3192 /// \param E - The expression being evaluated, for diagnostic purposes.
3193 /// \param LVal - The pointer value to be updated.
3194 /// \param EltTy - The pointee type represented by LVal.
3195 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3196 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3197                                         LValue &LVal, QualType EltTy,
3198                                         APSInt Adjustment) {
3199   CharUnits SizeOfPointee;
3200   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3201     return false;
3202 
3203   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3204   return true;
3205 }
3206 
3207 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3208                                         LValue &LVal, QualType EltTy,
3209                                         int64_t Adjustment) {
3210   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3211                                      APSInt::get(Adjustment));
3212 }
3213 
3214 /// Update an lvalue to refer to a component of a complex number.
3215 /// \param Info - Information about the ongoing evaluation.
3216 /// \param LVal - The lvalue to be updated.
3217 /// \param EltTy - The complex number's component type.
3218 /// \param Imag - False for the real component, true for the imaginary.
3219 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3220                                        LValue &LVal, QualType EltTy,
3221                                        bool Imag) {
3222   if (Imag) {
3223     CharUnits SizeOfComponent;
3224     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3225       return false;
3226     LVal.Offset += SizeOfComponent;
3227   }
3228   LVal.addComplex(Info, E, EltTy, Imag);
3229   return true;
3230 }
3231 
3232 /// Try to evaluate the initializer for a variable declaration.
3233 ///
3234 /// \param Info   Information about the ongoing evaluation.
3235 /// \param E      An expression to be used when printing diagnostics.
3236 /// \param VD     The variable whose initializer should be obtained.
3237 /// \param Version The version of the variable within the frame.
3238 /// \param Frame  The frame in which the variable was created. Must be null
3239 ///               if this variable is not local to the evaluation.
3240 /// \param Result Filled in with a pointer to the value of the variable.
3241 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3242                                 const VarDecl *VD, CallStackFrame *Frame,
3243                                 unsigned Version, APValue *&Result) {
3244   APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3245 
3246   // If this is a local variable, dig out its value.
3247   if (Frame) {
3248     Result = Frame->getTemporary(VD, Version);
3249     if (Result)
3250       return true;
3251 
3252     if (!isa<ParmVarDecl>(VD)) {
3253       // Assume variables referenced within a lambda's call operator that were
3254       // not declared within the call operator are captures and during checking
3255       // of a potential constant expression, assume they are unknown constant
3256       // expressions.
3257       assert(isLambdaCallOperator(Frame->Callee) &&
3258              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3259              "missing value for local variable");
3260       if (Info.checkingPotentialConstantExpression())
3261         return false;
3262       // FIXME: This diagnostic is bogus; we do support captures. Is this code
3263       // still reachable at all?
3264       Info.FFDiag(E->getBeginLoc(),
3265                   diag::note_unimplemented_constexpr_lambda_feature_ast)
3266           << "captures not currently allowed";
3267       return false;
3268     }
3269   }
3270 
3271   // If we're currently evaluating the initializer of this declaration, use that
3272   // in-flight value.
3273   if (Info.EvaluatingDecl == Base) {
3274     Result = Info.EvaluatingDeclValue;
3275     return true;
3276   }
3277 
3278   if (isa<ParmVarDecl>(VD)) {
3279     // Assume parameters of a potential constant expression are usable in
3280     // constant expressions.
3281     if (!Info.checkingPotentialConstantExpression() ||
3282         !Info.CurrentCall->Callee ||
3283         !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3284       if (Info.getLangOpts().CPlusPlus11) {
3285         Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3286             << VD;
3287         NoteLValueLocation(Info, Base);
3288       } else {
3289         Info.FFDiag(E);
3290       }
3291     }
3292     return false;
3293   }
3294 
3295   // Dig out the initializer, and use the declaration which it's attached to.
3296   // FIXME: We should eventually check whether the variable has a reachable
3297   // initializing declaration.
3298   const Expr *Init = VD->getAnyInitializer(VD);
3299   if (!Init) {
3300     // Don't diagnose during potential constant expression checking; an
3301     // initializer might be added later.
3302     if (!Info.checkingPotentialConstantExpression()) {
3303       Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3304         << VD;
3305       NoteLValueLocation(Info, Base);
3306     }
3307     return false;
3308   }
3309 
3310   if (Init->isValueDependent()) {
3311     // The DeclRefExpr is not value-dependent, but the variable it refers to
3312     // has a value-dependent initializer. This should only happen in
3313     // constant-folding cases, where the variable is not actually of a suitable
3314     // type for use in a constant expression (otherwise the DeclRefExpr would
3315     // have been value-dependent too), so diagnose that.
3316     assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3317     if (!Info.checkingPotentialConstantExpression()) {
3318       Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3319                          ? diag::note_constexpr_ltor_non_constexpr
3320                          : diag::note_constexpr_ltor_non_integral, 1)
3321           << VD << VD->getType();
3322       NoteLValueLocation(Info, Base);
3323     }
3324     return false;
3325   }
3326 
3327   // Check that we can fold the initializer. In C++, we will have already done
3328   // this in the cases where it matters for conformance.
3329   SmallVector<PartialDiagnosticAt, 8> Notes;
3330   if (!VD->evaluateValue(Notes)) {
3331     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
3332               Notes.size() + 1) << VD;
3333     NoteLValueLocation(Info, Base);
3334     Info.addNotes(Notes);
3335     return false;
3336   }
3337 
3338   // Check that the variable is actually usable in constant expressions. For a
3339   // const integral variable or a reference, we might have a non-constant
3340   // initializer that we can nonetheless evaluate the initializer for. Such
3341   // variables are not usable in constant expressions. In C++98, the
3342   // initializer also syntactically needs to be an ICE.
3343   //
3344   // FIXME: We don't diagnose cases that aren't potentially usable in constant
3345   // expressions here; doing so would regress diagnostics for things like
3346   // reading from a volatile constexpr variable.
3347   if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3348        VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||
3349       ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3350        !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3351     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3352     NoteLValueLocation(Info, Base);
3353   }
3354 
3355   // Never use the initializer of a weak variable, not even for constant
3356   // folding. We can't be sure that this is the definition that will be used.
3357   if (VD->isWeak()) {
3358     Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3359     NoteLValueLocation(Info, Base);
3360     return false;
3361   }
3362 
3363   Result = VD->getEvaluatedValue();
3364   return true;
3365 }
3366 
3367 /// Get the base index of the given base class within an APValue representing
3368 /// the given derived class.
3369 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3370                              const CXXRecordDecl *Base) {
3371   Base = Base->getCanonicalDecl();
3372   unsigned Index = 0;
3373   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3374          E = Derived->bases_end(); I != E; ++I, ++Index) {
3375     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3376       return Index;
3377   }
3378 
3379   llvm_unreachable("base class missing from derived class's bases list");
3380 }
3381 
3382 /// Extract the value of a character from a string literal.
3383 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3384                                             uint64_t Index) {
3385   assert(!isa<SourceLocExpr>(Lit) &&
3386          "SourceLocExpr should have already been converted to a StringLiteral");
3387 
3388   // FIXME: Support MakeStringConstant
3389   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3390     std::string Str;
3391     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3392     assert(Index <= Str.size() && "Index too large");
3393     return APSInt::getUnsigned(Str.c_str()[Index]);
3394   }
3395 
3396   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3397     Lit = PE->getFunctionName();
3398   const StringLiteral *S = cast<StringLiteral>(Lit);
3399   const ConstantArrayType *CAT =
3400       Info.Ctx.getAsConstantArrayType(S->getType());
3401   assert(CAT && "string literal isn't an array");
3402   QualType CharType = CAT->getElementType();
3403   assert(CharType->isIntegerType() && "unexpected character type");
3404 
3405   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3406                CharType->isUnsignedIntegerType());
3407   if (Index < S->getLength())
3408     Value = S->getCodeUnit(Index);
3409   return Value;
3410 }
3411 
3412 // Expand a string literal into an array of characters.
3413 //
3414 // FIXME: This is inefficient; we should probably introduce something similar
3415 // to the LLVM ConstantDataArray to make this cheaper.
3416 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3417                                 APValue &Result,
3418                                 QualType AllocType = QualType()) {
3419   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3420       AllocType.isNull() ? S->getType() : AllocType);
3421   assert(CAT && "string literal isn't an array");
3422   QualType CharType = CAT->getElementType();
3423   assert(CharType->isIntegerType() && "unexpected character type");
3424 
3425   unsigned Elts = CAT->getSize().getZExtValue();
3426   Result = APValue(APValue::UninitArray(),
3427                    std::min(S->getLength(), Elts), Elts);
3428   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3429                CharType->isUnsignedIntegerType());
3430   if (Result.hasArrayFiller())
3431     Result.getArrayFiller() = APValue(Value);
3432   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3433     Value = S->getCodeUnit(I);
3434     Result.getArrayInitializedElt(I) = APValue(Value);
3435   }
3436 }
3437 
3438 // Expand an array so that it has more than Index filled elements.
3439 static void expandArray(APValue &Array, unsigned Index) {
3440   unsigned Size = Array.getArraySize();
3441   assert(Index < Size);
3442 
3443   // Always at least double the number of elements for which we store a value.
3444   unsigned OldElts = Array.getArrayInitializedElts();
3445   unsigned NewElts = std::max(Index+1, OldElts * 2);
3446   NewElts = std::min(Size, std::max(NewElts, 8u));
3447 
3448   // Copy the data across.
3449   APValue NewValue(APValue::UninitArray(), NewElts, Size);
3450   for (unsigned I = 0; I != OldElts; ++I)
3451     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3452   for (unsigned I = OldElts; I != NewElts; ++I)
3453     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3454   if (NewValue.hasArrayFiller())
3455     NewValue.getArrayFiller() = Array.getArrayFiller();
3456   Array.swap(NewValue);
3457 }
3458 
3459 /// Determine whether a type would actually be read by an lvalue-to-rvalue
3460 /// conversion. If it's of class type, we may assume that the copy operation
3461 /// is trivial. Note that this is never true for a union type with fields
3462 /// (because the copy always "reads" the active member) and always true for
3463 /// a non-class type.
3464 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3465 static bool isReadByLvalueToRvalueConversion(QualType T) {
3466   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3467   return !RD || isReadByLvalueToRvalueConversion(RD);
3468 }
3469 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3470   // FIXME: A trivial copy of a union copies the object representation, even if
3471   // the union is empty.
3472   if (RD->isUnion())
3473     return !RD->field_empty();
3474   if (RD->isEmpty())
3475     return false;
3476 
3477   for (auto *Field : RD->fields())
3478     if (!Field->isUnnamedBitfield() &&
3479         isReadByLvalueToRvalueConversion(Field->getType()))
3480       return true;
3481 
3482   for (auto &BaseSpec : RD->bases())
3483     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3484       return true;
3485 
3486   return false;
3487 }
3488 
3489 /// Diagnose an attempt to read from any unreadable field within the specified
3490 /// type, which might be a class type.
3491 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3492                                   QualType T) {
3493   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3494   if (!RD)
3495     return false;
3496 
3497   if (!RD->hasMutableFields())
3498     return false;
3499 
3500   for (auto *Field : RD->fields()) {
3501     // If we're actually going to read this field in some way, then it can't
3502     // be mutable. If we're in a union, then assigning to a mutable field
3503     // (even an empty one) can change the active member, so that's not OK.
3504     // FIXME: Add core issue number for the union case.
3505     if (Field->isMutable() &&
3506         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3507       Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3508       Info.Note(Field->getLocation(), diag::note_declared_at);
3509       return true;
3510     }
3511 
3512     if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3513       return true;
3514   }
3515 
3516   for (auto &BaseSpec : RD->bases())
3517     if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3518       return true;
3519 
3520   // All mutable fields were empty, and thus not actually read.
3521   return false;
3522 }
3523 
3524 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3525                                         APValue::LValueBase Base,
3526                                         bool MutableSubobject = false) {
3527   // A temporary or transient heap allocation we created.
3528   if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3529     return true;
3530 
3531   switch (Info.IsEvaluatingDecl) {
3532   case EvalInfo::EvaluatingDeclKind::None:
3533     return false;
3534 
3535   case EvalInfo::EvaluatingDeclKind::Ctor:
3536     // The variable whose initializer we're evaluating.
3537     if (Info.EvaluatingDecl == Base)
3538       return true;
3539 
3540     // A temporary lifetime-extended by the variable whose initializer we're
3541     // evaluating.
3542     if (auto *BaseE = Base.dyn_cast<const Expr *>())
3543       if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3544         return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3545     return false;
3546 
3547   case EvalInfo::EvaluatingDeclKind::Dtor:
3548     // C++2a [expr.const]p6:
3549     //   [during constant destruction] the lifetime of a and its non-mutable
3550     //   subobjects (but not its mutable subobjects) [are] considered to start
3551     //   within e.
3552     if (MutableSubobject || Base != Info.EvaluatingDecl)
3553       return false;
3554     // FIXME: We can meaningfully extend this to cover non-const objects, but
3555     // we will need special handling: we should be able to access only
3556     // subobjects of such objects that are themselves declared const.
3557     QualType T = getType(Base);
3558     return T.isConstQualified() || T->isReferenceType();
3559   }
3560 
3561   llvm_unreachable("unknown evaluating decl kind");
3562 }
3563 
3564 namespace {
3565 /// A handle to a complete object (an object that is not a subobject of
3566 /// another object).
3567 struct CompleteObject {
3568   /// The identity of the object.
3569   APValue::LValueBase Base;
3570   /// The value of the complete object.
3571   APValue *Value;
3572   /// The type of the complete object.
3573   QualType Type;
3574 
3575   CompleteObject() : Value(nullptr) {}
3576   CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3577       : Base(Base), Value(Value), Type(Type) {}
3578 
3579   bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3580     // If this isn't a "real" access (eg, if it's just accessing the type
3581     // info), allow it. We assume the type doesn't change dynamically for
3582     // subobjects of constexpr objects (even though we'd hit UB here if it
3583     // did). FIXME: Is this right?
3584     if (!isAnyAccess(AK))
3585       return true;
3586 
3587     // In C++14 onwards, it is permitted to read a mutable member whose
3588     // lifetime began within the evaluation.
3589     // FIXME: Should we also allow this in C++11?
3590     if (!Info.getLangOpts().CPlusPlus14)
3591       return false;
3592     return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3593   }
3594 
3595   explicit operator bool() const { return !Type.isNull(); }
3596 };
3597 } // end anonymous namespace
3598 
3599 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3600                                  bool IsMutable = false) {
3601   // C++ [basic.type.qualifier]p1:
3602   // - A const object is an object of type const T or a non-mutable subobject
3603   //   of a const object.
3604   if (ObjType.isConstQualified() && !IsMutable)
3605     SubobjType.addConst();
3606   // - A volatile object is an object of type const T or a subobject of a
3607   //   volatile object.
3608   if (ObjType.isVolatileQualified())
3609     SubobjType.addVolatile();
3610   return SubobjType;
3611 }
3612 
3613 /// Find the designated sub-object of an rvalue.
3614 template<typename SubobjectHandler>
3615 typename SubobjectHandler::result_type
3616 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3617               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3618   if (Sub.Invalid)
3619     // A diagnostic will have already been produced.
3620     return handler.failed();
3621   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3622     if (Info.getLangOpts().CPlusPlus11)
3623       Info.FFDiag(E, Sub.isOnePastTheEnd()
3624                          ? diag::note_constexpr_access_past_end
3625                          : diag::note_constexpr_access_unsized_array)
3626           << handler.AccessKind;
3627     else
3628       Info.FFDiag(E);
3629     return handler.failed();
3630   }
3631 
3632   APValue *O = Obj.Value;
3633   QualType ObjType = Obj.Type;
3634   const FieldDecl *LastField = nullptr;
3635   const FieldDecl *VolatileField = nullptr;
3636 
3637   // Walk the designator's path to find the subobject.
3638   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3639     // Reading an indeterminate value is undefined, but assigning over one is OK.
3640     if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3641         (O->isIndeterminate() &&
3642          !isValidIndeterminateAccess(handler.AccessKind))) {
3643       if (!Info.checkingPotentialConstantExpression())
3644         Info.FFDiag(E, diag::note_constexpr_access_uninit)
3645             << handler.AccessKind << O->isIndeterminate();
3646       return handler.failed();
3647     }
3648 
3649     // C++ [class.ctor]p5, C++ [class.dtor]p5:
3650     //    const and volatile semantics are not applied on an object under
3651     //    {con,de}struction.
3652     if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3653         ObjType->isRecordType() &&
3654         Info.isEvaluatingCtorDtor(
3655             Obj.Base,
3656             llvm::ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
3657             ConstructionPhase::None) {
3658       ObjType = Info.Ctx.getCanonicalType(ObjType);
3659       ObjType.removeLocalConst();
3660       ObjType.removeLocalVolatile();
3661     }
3662 
3663     // If this is our last pass, check that the final object type is OK.
3664     if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3665       // Accesses to volatile objects are prohibited.
3666       if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3667         if (Info.getLangOpts().CPlusPlus) {
3668           int DiagKind;
3669           SourceLocation Loc;
3670           const NamedDecl *Decl = nullptr;
3671           if (VolatileField) {
3672             DiagKind = 2;
3673             Loc = VolatileField->getLocation();
3674             Decl = VolatileField;
3675           } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3676             DiagKind = 1;
3677             Loc = VD->getLocation();
3678             Decl = VD;
3679           } else {
3680             DiagKind = 0;
3681             if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3682               Loc = E->getExprLoc();
3683           }
3684           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3685               << handler.AccessKind << DiagKind << Decl;
3686           Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3687         } else {
3688           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3689         }
3690         return handler.failed();
3691       }
3692 
3693       // If we are reading an object of class type, there may still be more
3694       // things we need to check: if there are any mutable subobjects, we
3695       // cannot perform this read. (This only happens when performing a trivial
3696       // copy or assignment.)
3697       if (ObjType->isRecordType() &&
3698           !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3699           diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3700         return handler.failed();
3701     }
3702 
3703     if (I == N) {
3704       if (!handler.found(*O, ObjType))
3705         return false;
3706 
3707       // If we modified a bit-field, truncate it to the right width.
3708       if (isModification(handler.AccessKind) &&
3709           LastField && LastField->isBitField() &&
3710           !truncateBitfieldValue(Info, E, *O, LastField))
3711         return false;
3712 
3713       return true;
3714     }
3715 
3716     LastField = nullptr;
3717     if (ObjType->isArrayType()) {
3718       // Next subobject is an array element.
3719       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3720       assert(CAT && "vla in literal type?");
3721       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3722       if (CAT->getSize().ule(Index)) {
3723         // Note, it should not be possible to form a pointer with a valid
3724         // designator which points more than one past the end of the array.
3725         if (Info.getLangOpts().CPlusPlus11)
3726           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3727             << handler.AccessKind;
3728         else
3729           Info.FFDiag(E);
3730         return handler.failed();
3731       }
3732 
3733       ObjType = CAT->getElementType();
3734 
3735       if (O->getArrayInitializedElts() > Index)
3736         O = &O->getArrayInitializedElt(Index);
3737       else if (!isRead(handler.AccessKind)) {
3738         expandArray(*O, Index);
3739         O = &O->getArrayInitializedElt(Index);
3740       } else
3741         O = &O->getArrayFiller();
3742     } else if (ObjType->isAnyComplexType()) {
3743       // Next subobject is a complex number.
3744       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3745       if (Index > 1) {
3746         if (Info.getLangOpts().CPlusPlus11)
3747           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3748             << handler.AccessKind;
3749         else
3750           Info.FFDiag(E);
3751         return handler.failed();
3752       }
3753 
3754       ObjType = getSubobjectType(
3755           ObjType, ObjType->castAs<ComplexType>()->getElementType());
3756 
3757       assert(I == N - 1 && "extracting subobject of scalar?");
3758       if (O->isComplexInt()) {
3759         return handler.found(Index ? O->getComplexIntImag()
3760                                    : O->getComplexIntReal(), ObjType);
3761       } else {
3762         assert(O->isComplexFloat());
3763         return handler.found(Index ? O->getComplexFloatImag()
3764                                    : O->getComplexFloatReal(), ObjType);
3765       }
3766     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3767       if (Field->isMutable() &&
3768           !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3769         Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3770           << handler.AccessKind << Field;
3771         Info.Note(Field->getLocation(), diag::note_declared_at);
3772         return handler.failed();
3773       }
3774 
3775       // Next subobject is a class, struct or union field.
3776       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3777       if (RD->isUnion()) {
3778         const FieldDecl *UnionField = O->getUnionField();
3779         if (!UnionField ||
3780             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3781           if (I == N - 1 && handler.AccessKind == AK_Construct) {
3782             // Placement new onto an inactive union member makes it active.
3783             O->setUnion(Field, APValue());
3784           } else {
3785             // FIXME: If O->getUnionValue() is absent, report that there's no
3786             // active union member rather than reporting the prior active union
3787             // member. We'll need to fix nullptr_t to not use APValue() as its
3788             // representation first.
3789             Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3790                 << handler.AccessKind << Field << !UnionField << UnionField;
3791             return handler.failed();
3792           }
3793         }
3794         O = &O->getUnionValue();
3795       } else
3796         O = &O->getStructField(Field->getFieldIndex());
3797 
3798       ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3799       LastField = Field;
3800       if (Field->getType().isVolatileQualified())
3801         VolatileField = Field;
3802     } else {
3803       // Next subobject is a base class.
3804       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3805       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3806       O = &O->getStructBase(getBaseIndex(Derived, Base));
3807 
3808       ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3809     }
3810   }
3811 }
3812 
3813 namespace {
3814 struct ExtractSubobjectHandler {
3815   EvalInfo &Info;
3816   const Expr *E;
3817   APValue &Result;
3818   const AccessKinds AccessKind;
3819 
3820   typedef bool result_type;
3821   bool failed() { return false; }
3822   bool found(APValue &Subobj, QualType SubobjType) {
3823     Result = Subobj;
3824     if (AccessKind == AK_ReadObjectRepresentation)
3825       return true;
3826     return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3827   }
3828   bool found(APSInt &Value, QualType SubobjType) {
3829     Result = APValue(Value);
3830     return true;
3831   }
3832   bool found(APFloat &Value, QualType SubobjType) {
3833     Result = APValue(Value);
3834     return true;
3835   }
3836 };
3837 } // end anonymous namespace
3838 
3839 /// Extract the designated sub-object of an rvalue.
3840 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3841                              const CompleteObject &Obj,
3842                              const SubobjectDesignator &Sub, APValue &Result,
3843                              AccessKinds AK = AK_Read) {
3844   assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3845   ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3846   return findSubobject(Info, E, Obj, Sub, Handler);
3847 }
3848 
3849 namespace {
3850 struct ModifySubobjectHandler {
3851   EvalInfo &Info;
3852   APValue &NewVal;
3853   const Expr *E;
3854 
3855   typedef bool result_type;
3856   static const AccessKinds AccessKind = AK_Assign;
3857 
3858   bool checkConst(QualType QT) {
3859     // Assigning to a const object has undefined behavior.
3860     if (QT.isConstQualified()) {
3861       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3862       return false;
3863     }
3864     return true;
3865   }
3866 
3867   bool failed() { return false; }
3868   bool found(APValue &Subobj, QualType SubobjType) {
3869     if (!checkConst(SubobjType))
3870       return false;
3871     // We've been given ownership of NewVal, so just swap it in.
3872     Subobj.swap(NewVal);
3873     return true;
3874   }
3875   bool found(APSInt &Value, QualType SubobjType) {
3876     if (!checkConst(SubobjType))
3877       return false;
3878     if (!NewVal.isInt()) {
3879       // Maybe trying to write a cast pointer value into a complex?
3880       Info.FFDiag(E);
3881       return false;
3882     }
3883     Value = NewVal.getInt();
3884     return true;
3885   }
3886   bool found(APFloat &Value, QualType SubobjType) {
3887     if (!checkConst(SubobjType))
3888       return false;
3889     Value = NewVal.getFloat();
3890     return true;
3891   }
3892 };
3893 } // end anonymous namespace
3894 
3895 const AccessKinds ModifySubobjectHandler::AccessKind;
3896 
3897 /// Update the designated sub-object of an rvalue to the given value.
3898 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3899                             const CompleteObject &Obj,
3900                             const SubobjectDesignator &Sub,
3901                             APValue &NewVal) {
3902   ModifySubobjectHandler Handler = { Info, NewVal, E };
3903   return findSubobject(Info, E, Obj, Sub, Handler);
3904 }
3905 
3906 /// Find the position where two subobject designators diverge, or equivalently
3907 /// the length of the common initial subsequence.
3908 static unsigned FindDesignatorMismatch(QualType ObjType,
3909                                        const SubobjectDesignator &A,
3910                                        const SubobjectDesignator &B,
3911                                        bool &WasArrayIndex) {
3912   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3913   for (/**/; I != N; ++I) {
3914     if (!ObjType.isNull() &&
3915         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3916       // Next subobject is an array element.
3917       if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3918         WasArrayIndex = true;
3919         return I;
3920       }
3921       if (ObjType->isAnyComplexType())
3922         ObjType = ObjType->castAs<ComplexType>()->getElementType();
3923       else
3924         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3925     } else {
3926       if (A.Entries[I].getAsBaseOrMember() !=
3927           B.Entries[I].getAsBaseOrMember()) {
3928         WasArrayIndex = false;
3929         return I;
3930       }
3931       if (const FieldDecl *FD = getAsField(A.Entries[I]))
3932         // Next subobject is a field.
3933         ObjType = FD->getType();
3934       else
3935         // Next subobject is a base class.
3936         ObjType = QualType();
3937     }
3938   }
3939   WasArrayIndex = false;
3940   return I;
3941 }
3942 
3943 /// Determine whether the given subobject designators refer to elements of the
3944 /// same array object.
3945 static bool AreElementsOfSameArray(QualType ObjType,
3946                                    const SubobjectDesignator &A,
3947                                    const SubobjectDesignator &B) {
3948   if (A.Entries.size() != B.Entries.size())
3949     return false;
3950 
3951   bool IsArray = A.MostDerivedIsArrayElement;
3952   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3953     // A is a subobject of the array element.
3954     return false;
3955 
3956   // If A (and B) designates an array element, the last entry will be the array
3957   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3958   // of length 1' case, and the entire path must match.
3959   bool WasArrayIndex;
3960   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3961   return CommonLength >= A.Entries.size() - IsArray;
3962 }
3963 
3964 /// Find the complete object to which an LValue refers.
3965 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3966                                          AccessKinds AK, const LValue &LVal,
3967                                          QualType LValType) {
3968   if (LVal.InvalidBase) {
3969     Info.FFDiag(E);
3970     return CompleteObject();
3971   }
3972 
3973   if (!LVal.Base) {
3974     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3975     return CompleteObject();
3976   }
3977 
3978   CallStackFrame *Frame = nullptr;
3979   unsigned Depth = 0;
3980   if (LVal.getLValueCallIndex()) {
3981     std::tie(Frame, Depth) =
3982         Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3983     if (!Frame) {
3984       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3985         << AK << LVal.Base.is<const ValueDecl*>();
3986       NoteLValueLocation(Info, LVal.Base);
3987       return CompleteObject();
3988     }
3989   }
3990 
3991   bool IsAccess = isAnyAccess(AK);
3992 
3993   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3994   // is not a constant expression (even if the object is non-volatile). We also
3995   // apply this rule to C++98, in order to conform to the expected 'volatile'
3996   // semantics.
3997   if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
3998     if (Info.getLangOpts().CPlusPlus)
3999       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
4000         << AK << LValType;
4001     else
4002       Info.FFDiag(E);
4003     return CompleteObject();
4004   }
4005 
4006   // Compute value storage location and type of base object.
4007   APValue *BaseVal = nullptr;
4008   QualType BaseType = getType(LVal.Base);
4009 
4010   if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4011       lifetimeStartedInEvaluation(Info, LVal.Base)) {
4012     // This is the object whose initializer we're evaluating, so its lifetime
4013     // started in the current evaluation.
4014     BaseVal = Info.EvaluatingDeclValue;
4015   } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4016     // Allow reading from a GUID declaration.
4017     if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4018       if (isModification(AK)) {
4019         // All the remaining cases do not permit modification of the object.
4020         Info.FFDiag(E, diag::note_constexpr_modify_global);
4021         return CompleteObject();
4022       }
4023       APValue &V = GD->getAsAPValue();
4024       if (V.isAbsent()) {
4025         Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4026             << GD->getType();
4027         return CompleteObject();
4028       }
4029       return CompleteObject(LVal.Base, &V, GD->getType());
4030     }
4031 
4032     // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4033     if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4034       if (isModification(AK)) {
4035         Info.FFDiag(E, diag::note_constexpr_modify_global);
4036         return CompleteObject();
4037       }
4038       return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4039                             GCD->getType());
4040     }
4041 
4042     // Allow reading from template parameter objects.
4043     if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4044       if (isModification(AK)) {
4045         Info.FFDiag(E, diag::note_constexpr_modify_global);
4046         return CompleteObject();
4047       }
4048       return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4049                             TPO->getType());
4050     }
4051 
4052     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4053     // In C++11, constexpr, non-volatile variables initialized with constant
4054     // expressions are constant expressions too. Inside constexpr functions,
4055     // parameters are constant expressions even if they're non-const.
4056     // In C++1y, objects local to a constant expression (those with a Frame) are
4057     // both readable and writable inside constant expressions.
4058     // In C, such things can also be folded, although they are not ICEs.
4059     const VarDecl *VD = dyn_cast<VarDecl>(D);
4060     if (VD) {
4061       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4062         VD = VDef;
4063     }
4064     if (!VD || VD->isInvalidDecl()) {
4065       Info.FFDiag(E);
4066       return CompleteObject();
4067     }
4068 
4069     bool IsConstant = BaseType.isConstant(Info.Ctx);
4070 
4071     // Unless we're looking at a local variable or argument in a constexpr call,
4072     // the variable we're reading must be const.
4073     if (!Frame) {
4074       if (IsAccess && isa<ParmVarDecl>(VD)) {
4075         // Access of a parameter that's not associated with a frame isn't going
4076         // to work out, but we can leave it to evaluateVarDeclInit to provide a
4077         // suitable diagnostic.
4078       } else if (Info.getLangOpts().CPlusPlus14 &&
4079                  lifetimeStartedInEvaluation(Info, LVal.Base)) {
4080         // OK, we can read and modify an object if we're in the process of
4081         // evaluating its initializer, because its lifetime began in this
4082         // evaluation.
4083       } else if (isModification(AK)) {
4084         // All the remaining cases do not permit modification of the object.
4085         Info.FFDiag(E, diag::note_constexpr_modify_global);
4086         return CompleteObject();
4087       } else if (VD->isConstexpr()) {
4088         // OK, we can read this variable.
4089       } else if (BaseType->isIntegralOrEnumerationType()) {
4090         if (!IsConstant) {
4091           if (!IsAccess)
4092             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4093           if (Info.getLangOpts().CPlusPlus) {
4094             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4095             Info.Note(VD->getLocation(), diag::note_declared_at);
4096           } else {
4097             Info.FFDiag(E);
4098           }
4099           return CompleteObject();
4100         }
4101       } else if (!IsAccess) {
4102         return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4103       } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
4104                  BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4105         // This variable might end up being constexpr. Don't diagnose it yet.
4106       } else if (IsConstant) {
4107         // Keep evaluating to see what we can do. In particular, we support
4108         // folding of const floating-point types, in order to make static const
4109         // data members of such types (supported as an extension) more useful.
4110         if (Info.getLangOpts().CPlusPlus) {
4111           Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4112                               ? diag::note_constexpr_ltor_non_constexpr
4113                               : diag::note_constexpr_ltor_non_integral, 1)
4114               << VD << BaseType;
4115           Info.Note(VD->getLocation(), diag::note_declared_at);
4116         } else {
4117           Info.CCEDiag(E);
4118         }
4119       } else {
4120         // Never allow reading a non-const value.
4121         if (Info.getLangOpts().CPlusPlus) {
4122           Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4123                              ? diag::note_constexpr_ltor_non_constexpr
4124                              : diag::note_constexpr_ltor_non_integral, 1)
4125               << VD << BaseType;
4126           Info.Note(VD->getLocation(), diag::note_declared_at);
4127         } else {
4128           Info.FFDiag(E);
4129         }
4130         return CompleteObject();
4131       }
4132     }
4133 
4134     if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
4135       return CompleteObject();
4136   } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4137     std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
4138     if (!Alloc) {
4139       Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4140       return CompleteObject();
4141     }
4142     return CompleteObject(LVal.Base, &(*Alloc)->Value,
4143                           LVal.Base.getDynamicAllocType());
4144   } else {
4145     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4146 
4147     if (!Frame) {
4148       if (const MaterializeTemporaryExpr *MTE =
4149               dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4150         assert(MTE->getStorageDuration() == SD_Static &&
4151                "should have a frame for a non-global materialized temporary");
4152 
4153         // C++20 [expr.const]p4: [DR2126]
4154         //   An object or reference is usable in constant expressions if it is
4155         //   - a temporary object of non-volatile const-qualified literal type
4156         //     whose lifetime is extended to that of a variable that is usable
4157         //     in constant expressions
4158         //
4159         // C++20 [expr.const]p5:
4160         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4161         //   - a non-volatile glvalue that refers to an object that is usable
4162         //     in constant expressions, or
4163         //   - a non-volatile glvalue of literal type that refers to a
4164         //     non-volatile object whose lifetime began within the evaluation
4165         //     of E;
4166         //
4167         // C++11 misses the 'began within the evaluation of e' check and
4168         // instead allows all temporaries, including things like:
4169         //   int &&r = 1;
4170         //   int x = ++r;
4171         //   constexpr int k = r;
4172         // Therefore we use the C++14-onwards rules in C++11 too.
4173         //
4174         // Note that temporaries whose lifetimes began while evaluating a
4175         // variable's constructor are not usable while evaluating the
4176         // corresponding destructor, not even if they're of const-qualified
4177         // types.
4178         if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4179             !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4180           if (!IsAccess)
4181             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4182           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4183           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4184           return CompleteObject();
4185         }
4186 
4187         BaseVal = MTE->getOrCreateValue(false);
4188         assert(BaseVal && "got reference to unevaluated temporary");
4189       } else {
4190         if (!IsAccess)
4191           return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4192         APValue Val;
4193         LVal.moveInto(Val);
4194         Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4195             << AK
4196             << Val.getAsString(Info.Ctx,
4197                                Info.Ctx.getLValueReferenceType(LValType));
4198         NoteLValueLocation(Info, LVal.Base);
4199         return CompleteObject();
4200       }
4201     } else {
4202       BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4203       assert(BaseVal && "missing value for temporary");
4204     }
4205   }
4206 
4207   // In C++14, we can't safely access any mutable state when we might be
4208   // evaluating after an unmodeled side effect. Parameters are modeled as state
4209   // in the caller, but aren't visible once the call returns, so they can be
4210   // modified in a speculatively-evaluated call.
4211   //
4212   // FIXME: Not all local state is mutable. Allow local constant subobjects
4213   // to be read here (but take care with 'mutable' fields).
4214   unsigned VisibleDepth = Depth;
4215   if (llvm::isa_and_nonnull<ParmVarDecl>(
4216           LVal.Base.dyn_cast<const ValueDecl *>()))
4217     ++VisibleDepth;
4218   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4219        Info.EvalStatus.HasSideEffects) ||
4220       (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4221     return CompleteObject();
4222 
4223   return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4224 }
4225 
4226 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4227 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4228 /// glvalue referred to by an entity of reference type.
4229 ///
4230 /// \param Info - Information about the ongoing evaluation.
4231 /// \param Conv - The expression for which we are performing the conversion.
4232 ///               Used for diagnostics.
4233 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4234 ///               case of a non-class type).
4235 /// \param LVal - The glvalue on which we are attempting to perform this action.
4236 /// \param RVal - The produced value will be placed here.
4237 /// \param WantObjectRepresentation - If true, we're looking for the object
4238 ///               representation rather than the value, and in particular,
4239 ///               there is no requirement that the result be fully initialized.
4240 static bool
4241 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
4242                                const LValue &LVal, APValue &RVal,
4243                                bool WantObjectRepresentation = false) {
4244   if (LVal.Designator.Invalid)
4245     return false;
4246 
4247   // Check for special cases where there is no existing APValue to look at.
4248   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4249 
4250   AccessKinds AK =
4251       WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4252 
4253   if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4254     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4255       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4256       // initializer until now for such expressions. Such an expression can't be
4257       // an ICE in C, so this only matters for fold.
4258       if (Type.isVolatileQualified()) {
4259         Info.FFDiag(Conv);
4260         return false;
4261       }
4262 
4263       APValue Lit;
4264       if (!Evaluate(Lit, Info, CLE->getInitializer()))
4265         return false;
4266 
4267       // According to GCC info page:
4268       //
4269       // 6.28 Compound Literals
4270       //
4271       // As an optimization, G++ sometimes gives array compound literals longer
4272       // lifetimes: when the array either appears outside a function or has a
4273       // const-qualified type. If foo and its initializer had elements of type
4274       // char *const rather than char *, or if foo were a global variable, the
4275       // array would have static storage duration. But it is probably safest
4276       // just to avoid the use of array compound literals in C++ code.
4277       //
4278       // Obey that rule by checking constness for converted array types.
4279 
4280       QualType CLETy = CLE->getType();
4281       if (CLETy->isArrayType() && !Type->isArrayType()) {
4282         if (!CLETy.isConstant(Info.Ctx)) {
4283           Info.FFDiag(Conv);
4284           Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4285           return false;
4286         }
4287       }
4288 
4289       CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4290       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4291     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4292       // Special-case character extraction so we don't have to construct an
4293       // APValue for the whole string.
4294       assert(LVal.Designator.Entries.size() <= 1 &&
4295              "Can only read characters from string literals");
4296       if (LVal.Designator.Entries.empty()) {
4297         // Fail for now for LValue to RValue conversion of an array.
4298         // (This shouldn't show up in C/C++, but it could be triggered by a
4299         // weird EvaluateAsRValue call from a tool.)
4300         Info.FFDiag(Conv);
4301         return false;
4302       }
4303       if (LVal.Designator.isOnePastTheEnd()) {
4304         if (Info.getLangOpts().CPlusPlus11)
4305           Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4306         else
4307           Info.FFDiag(Conv);
4308         return false;
4309       }
4310       uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4311       RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4312       return true;
4313     }
4314   }
4315 
4316   CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4317   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4318 }
4319 
4320 /// Perform an assignment of Val to LVal. Takes ownership of Val.
4321 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4322                              QualType LValType, APValue &Val) {
4323   if (LVal.Designator.Invalid)
4324     return false;
4325 
4326   if (!Info.getLangOpts().CPlusPlus14) {
4327     Info.FFDiag(E);
4328     return false;
4329   }
4330 
4331   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4332   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4333 }
4334 
4335 namespace {
4336 struct CompoundAssignSubobjectHandler {
4337   EvalInfo &Info;
4338   const CompoundAssignOperator *E;
4339   QualType PromotedLHSType;
4340   BinaryOperatorKind Opcode;
4341   const APValue &RHS;
4342 
4343   static const AccessKinds AccessKind = AK_Assign;
4344 
4345   typedef bool result_type;
4346 
4347   bool checkConst(QualType QT) {
4348     // Assigning to a const object has undefined behavior.
4349     if (QT.isConstQualified()) {
4350       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4351       return false;
4352     }
4353     return true;
4354   }
4355 
4356   bool failed() { return false; }
4357   bool found(APValue &Subobj, QualType SubobjType) {
4358     switch (Subobj.getKind()) {
4359     case APValue::Int:
4360       return found(Subobj.getInt(), SubobjType);
4361     case APValue::Float:
4362       return found(Subobj.getFloat(), SubobjType);
4363     case APValue::ComplexInt:
4364     case APValue::ComplexFloat:
4365       // FIXME: Implement complex compound assignment.
4366       Info.FFDiag(E);
4367       return false;
4368     case APValue::LValue:
4369       return foundPointer(Subobj, SubobjType);
4370     case APValue::Vector:
4371       return foundVector(Subobj, SubobjType);
4372     default:
4373       // FIXME: can this happen?
4374       Info.FFDiag(E);
4375       return false;
4376     }
4377   }
4378 
4379   bool foundVector(APValue &Value, QualType SubobjType) {
4380     if (!checkConst(SubobjType))
4381       return false;
4382 
4383     if (!SubobjType->isVectorType()) {
4384       Info.FFDiag(E);
4385       return false;
4386     }
4387     return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4388   }
4389 
4390   bool found(APSInt &Value, QualType SubobjType) {
4391     if (!checkConst(SubobjType))
4392       return false;
4393 
4394     if (!SubobjType->isIntegerType()) {
4395       // We don't support compound assignment on integer-cast-to-pointer
4396       // values.
4397       Info.FFDiag(E);
4398       return false;
4399     }
4400 
4401     if (RHS.isInt()) {
4402       APSInt LHS =
4403           HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4404       if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4405         return false;
4406       Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4407       return true;
4408     } else if (RHS.isFloat()) {
4409       const FPOptions FPO = E->getFPFeaturesInEffect(
4410                                     Info.Ctx.getLangOpts());
4411       APFloat FValue(0.0);
4412       return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4413                                   PromotedLHSType, FValue) &&
4414              handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4415              HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4416                                   Value);
4417     }
4418 
4419     Info.FFDiag(E);
4420     return false;
4421   }
4422   bool found(APFloat &Value, QualType SubobjType) {
4423     return checkConst(SubobjType) &&
4424            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4425                                   Value) &&
4426            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4427            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4428   }
4429   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4430     if (!checkConst(SubobjType))
4431       return false;
4432 
4433     QualType PointeeType;
4434     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4435       PointeeType = PT->getPointeeType();
4436 
4437     if (PointeeType.isNull() || !RHS.isInt() ||
4438         (Opcode != BO_Add && Opcode != BO_Sub)) {
4439       Info.FFDiag(E);
4440       return false;
4441     }
4442 
4443     APSInt Offset = RHS.getInt();
4444     if (Opcode == BO_Sub)
4445       negateAsSigned(Offset);
4446 
4447     LValue LVal;
4448     LVal.setFrom(Info.Ctx, Subobj);
4449     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4450       return false;
4451     LVal.moveInto(Subobj);
4452     return true;
4453   }
4454 };
4455 } // end anonymous namespace
4456 
4457 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4458 
4459 /// Perform a compound assignment of LVal <op>= RVal.
4460 static bool handleCompoundAssignment(EvalInfo &Info,
4461                                      const CompoundAssignOperator *E,
4462                                      const LValue &LVal, QualType LValType,
4463                                      QualType PromotedLValType,
4464                                      BinaryOperatorKind Opcode,
4465                                      const APValue &RVal) {
4466   if (LVal.Designator.Invalid)
4467     return false;
4468 
4469   if (!Info.getLangOpts().CPlusPlus14) {
4470     Info.FFDiag(E);
4471     return false;
4472   }
4473 
4474   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4475   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4476                                              RVal };
4477   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4478 }
4479 
4480 namespace {
4481 struct IncDecSubobjectHandler {
4482   EvalInfo &Info;
4483   const UnaryOperator *E;
4484   AccessKinds AccessKind;
4485   APValue *Old;
4486 
4487   typedef bool result_type;
4488 
4489   bool checkConst(QualType QT) {
4490     // Assigning to a const object has undefined behavior.
4491     if (QT.isConstQualified()) {
4492       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4493       return false;
4494     }
4495     return true;
4496   }
4497 
4498   bool failed() { return false; }
4499   bool found(APValue &Subobj, QualType SubobjType) {
4500     // Stash the old value. Also clear Old, so we don't clobber it later
4501     // if we're post-incrementing a complex.
4502     if (Old) {
4503       *Old = Subobj;
4504       Old = nullptr;
4505     }
4506 
4507     switch (Subobj.getKind()) {
4508     case APValue::Int:
4509       return found(Subobj.getInt(), SubobjType);
4510     case APValue::Float:
4511       return found(Subobj.getFloat(), SubobjType);
4512     case APValue::ComplexInt:
4513       return found(Subobj.getComplexIntReal(),
4514                    SubobjType->castAs<ComplexType>()->getElementType()
4515                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4516     case APValue::ComplexFloat:
4517       return found(Subobj.getComplexFloatReal(),
4518                    SubobjType->castAs<ComplexType>()->getElementType()
4519                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4520     case APValue::LValue:
4521       return foundPointer(Subobj, SubobjType);
4522     default:
4523       // FIXME: can this happen?
4524       Info.FFDiag(E);
4525       return false;
4526     }
4527   }
4528   bool found(APSInt &Value, QualType SubobjType) {
4529     if (!checkConst(SubobjType))
4530       return false;
4531 
4532     if (!SubobjType->isIntegerType()) {
4533       // We don't support increment / decrement on integer-cast-to-pointer
4534       // values.
4535       Info.FFDiag(E);
4536       return false;
4537     }
4538 
4539     if (Old) *Old = APValue(Value);
4540 
4541     // bool arithmetic promotes to int, and the conversion back to bool
4542     // doesn't reduce mod 2^n, so special-case it.
4543     if (SubobjType->isBooleanType()) {
4544       if (AccessKind == AK_Increment)
4545         Value = 1;
4546       else
4547         Value = !Value;
4548       return true;
4549     }
4550 
4551     bool WasNegative = Value.isNegative();
4552     if (AccessKind == AK_Increment) {
4553       ++Value;
4554 
4555       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4556         APSInt ActualValue(Value, /*IsUnsigned*/true);
4557         return HandleOverflow(Info, E, ActualValue, SubobjType);
4558       }
4559     } else {
4560       --Value;
4561 
4562       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4563         unsigned BitWidth = Value.getBitWidth();
4564         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4565         ActualValue.setBit(BitWidth);
4566         return HandleOverflow(Info, E, ActualValue, SubobjType);
4567       }
4568     }
4569     return true;
4570   }
4571   bool found(APFloat &Value, QualType SubobjType) {
4572     if (!checkConst(SubobjType))
4573       return false;
4574 
4575     if (Old) *Old = APValue(Value);
4576 
4577     APFloat One(Value.getSemantics(), 1);
4578     if (AccessKind == AK_Increment)
4579       Value.add(One, APFloat::rmNearestTiesToEven);
4580     else
4581       Value.subtract(One, APFloat::rmNearestTiesToEven);
4582     return true;
4583   }
4584   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4585     if (!checkConst(SubobjType))
4586       return false;
4587 
4588     QualType PointeeType;
4589     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4590       PointeeType = PT->getPointeeType();
4591     else {
4592       Info.FFDiag(E);
4593       return false;
4594     }
4595 
4596     LValue LVal;
4597     LVal.setFrom(Info.Ctx, Subobj);
4598     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4599                                      AccessKind == AK_Increment ? 1 : -1))
4600       return false;
4601     LVal.moveInto(Subobj);
4602     return true;
4603   }
4604 };
4605 } // end anonymous namespace
4606 
4607 /// Perform an increment or decrement on LVal.
4608 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4609                          QualType LValType, bool IsIncrement, APValue *Old) {
4610   if (LVal.Designator.Invalid)
4611     return false;
4612 
4613   if (!Info.getLangOpts().CPlusPlus14) {
4614     Info.FFDiag(E);
4615     return false;
4616   }
4617 
4618   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4619   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4620   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4621   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4622 }
4623 
4624 /// Build an lvalue for the object argument of a member function call.
4625 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4626                                    LValue &This) {
4627   if (Object->getType()->isPointerType() && Object->isPRValue())
4628     return EvaluatePointer(Object, This, Info);
4629 
4630   if (Object->isGLValue())
4631     return EvaluateLValue(Object, This, Info);
4632 
4633   if (Object->getType()->isLiteralType(Info.Ctx))
4634     return EvaluateTemporary(Object, This, Info);
4635 
4636   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4637   return false;
4638 }
4639 
4640 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
4641 /// lvalue referring to the result.
4642 ///
4643 /// \param Info - Information about the ongoing evaluation.
4644 /// \param LV - An lvalue referring to the base of the member pointer.
4645 /// \param RHS - The member pointer expression.
4646 /// \param IncludeMember - Specifies whether the member itself is included in
4647 ///        the resulting LValue subobject designator. This is not possible when
4648 ///        creating a bound member function.
4649 /// \return The field or method declaration to which the member pointer refers,
4650 ///         or 0 if evaluation fails.
4651 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4652                                                   QualType LVType,
4653                                                   LValue &LV,
4654                                                   const Expr *RHS,
4655                                                   bool IncludeMember = true) {
4656   MemberPtr MemPtr;
4657   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4658     return nullptr;
4659 
4660   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4661   // member value, the behavior is undefined.
4662   if (!MemPtr.getDecl()) {
4663     // FIXME: Specific diagnostic.
4664     Info.FFDiag(RHS);
4665     return nullptr;
4666   }
4667 
4668   if (MemPtr.isDerivedMember()) {
4669     // This is a member of some derived class. Truncate LV appropriately.
4670     // The end of the derived-to-base path for the base object must match the
4671     // derived-to-base path for the member pointer.
4672     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4673         LV.Designator.Entries.size()) {
4674       Info.FFDiag(RHS);
4675       return nullptr;
4676     }
4677     unsigned PathLengthToMember =
4678         LV.Designator.Entries.size() - MemPtr.Path.size();
4679     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4680       const CXXRecordDecl *LVDecl = getAsBaseClass(
4681           LV.Designator.Entries[PathLengthToMember + I]);
4682       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4683       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4684         Info.FFDiag(RHS);
4685         return nullptr;
4686       }
4687     }
4688 
4689     // Truncate the lvalue to the appropriate derived class.
4690     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4691                             PathLengthToMember))
4692       return nullptr;
4693   } else if (!MemPtr.Path.empty()) {
4694     // Extend the LValue path with the member pointer's path.
4695     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4696                                   MemPtr.Path.size() + IncludeMember);
4697 
4698     // Walk down to the appropriate base class.
4699     if (const PointerType *PT = LVType->getAs<PointerType>())
4700       LVType = PT->getPointeeType();
4701     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4702     assert(RD && "member pointer access on non-class-type expression");
4703     // The first class in the path is that of the lvalue.
4704     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4705       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4706       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4707         return nullptr;
4708       RD = Base;
4709     }
4710     // Finally cast to the class containing the member.
4711     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4712                                 MemPtr.getContainingRecord()))
4713       return nullptr;
4714   }
4715 
4716   // Add the member. Note that we cannot build bound member functions here.
4717   if (IncludeMember) {
4718     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4719       if (!HandleLValueMember(Info, RHS, LV, FD))
4720         return nullptr;
4721     } else if (const IndirectFieldDecl *IFD =
4722                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4723       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4724         return nullptr;
4725     } else {
4726       llvm_unreachable("can't construct reference to bound member function");
4727     }
4728   }
4729 
4730   return MemPtr.getDecl();
4731 }
4732 
4733 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4734                                                   const BinaryOperator *BO,
4735                                                   LValue &LV,
4736                                                   bool IncludeMember = true) {
4737   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4738 
4739   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4740     if (Info.noteFailure()) {
4741       MemberPtr MemPtr;
4742       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4743     }
4744     return nullptr;
4745   }
4746 
4747   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4748                                    BO->getRHS(), IncludeMember);
4749 }
4750 
4751 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4752 /// the provided lvalue, which currently refers to the base object.
4753 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4754                                     LValue &Result) {
4755   SubobjectDesignator &D = Result.Designator;
4756   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4757     return false;
4758 
4759   QualType TargetQT = E->getType();
4760   if (const PointerType *PT = TargetQT->getAs<PointerType>())
4761     TargetQT = PT->getPointeeType();
4762 
4763   // Check this cast lands within the final derived-to-base subobject path.
4764   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4765     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4766       << D.MostDerivedType << TargetQT;
4767     return false;
4768   }
4769 
4770   // Check the type of the final cast. We don't need to check the path,
4771   // since a cast can only be formed if the path is unique.
4772   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4773   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4774   const CXXRecordDecl *FinalType;
4775   if (NewEntriesSize == D.MostDerivedPathLength)
4776     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4777   else
4778     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4779   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4780     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4781       << D.MostDerivedType << TargetQT;
4782     return false;
4783   }
4784 
4785   // Truncate the lvalue to the appropriate derived class.
4786   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4787 }
4788 
4789 /// Get the value to use for a default-initialized object of type T.
4790 /// Return false if it encounters something invalid.
4791 static bool getDefaultInitValue(QualType T, APValue &Result) {
4792   bool Success = true;
4793   if (auto *RD = T->getAsCXXRecordDecl()) {
4794     if (RD->isInvalidDecl()) {
4795       Result = APValue();
4796       return false;
4797     }
4798     if (RD->isUnion()) {
4799       Result = APValue((const FieldDecl *)nullptr);
4800       return true;
4801     }
4802     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4803                      std::distance(RD->field_begin(), RD->field_end()));
4804 
4805     unsigned Index = 0;
4806     for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4807                                                   End = RD->bases_end();
4808          I != End; ++I, ++Index)
4809       Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index));
4810 
4811     for (const auto *I : RD->fields()) {
4812       if (I->isUnnamedBitfield())
4813         continue;
4814       Success &= getDefaultInitValue(I->getType(),
4815                                      Result.getStructField(I->getFieldIndex()));
4816     }
4817     return Success;
4818   }
4819 
4820   if (auto *AT =
4821           dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4822     Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4823     if (Result.hasArrayFiller())
4824       Success &=
4825           getDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
4826 
4827     return Success;
4828   }
4829 
4830   Result = APValue::IndeterminateValue();
4831   return true;
4832 }
4833 
4834 namespace {
4835 enum EvalStmtResult {
4836   /// Evaluation failed.
4837   ESR_Failed,
4838   /// Hit a 'return' statement.
4839   ESR_Returned,
4840   /// Evaluation succeeded.
4841   ESR_Succeeded,
4842   /// Hit a 'continue' statement.
4843   ESR_Continue,
4844   /// Hit a 'break' statement.
4845   ESR_Break,
4846   /// Still scanning for 'case' or 'default' statement.
4847   ESR_CaseNotFound
4848 };
4849 }
4850 
4851 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4852   if (VD->isInvalidDecl())
4853     return false;
4854   // We don't need to evaluate the initializer for a static local.
4855   if (!VD->hasLocalStorage())
4856     return true;
4857 
4858   LValue Result;
4859   APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
4860                                                    ScopeKind::Block, Result);
4861 
4862   const Expr *InitE = VD->getInit();
4863   if (!InitE) {
4864     if (VD->getType()->isDependentType())
4865       return Info.noteSideEffect();
4866     return getDefaultInitValue(VD->getType(), Val);
4867   }
4868   if (InitE->isValueDependent())
4869     return false;
4870 
4871   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4872     // Wipe out any partially-computed value, to allow tracking that this
4873     // evaluation failed.
4874     Val = APValue();
4875     return false;
4876   }
4877 
4878   return true;
4879 }
4880 
4881 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4882   bool OK = true;
4883 
4884   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4885     OK &= EvaluateVarDecl(Info, VD);
4886 
4887   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4888     for (auto *BD : DD->bindings())
4889       if (auto *VD = BD->getHoldingVar())
4890         OK &= EvaluateDecl(Info, VD);
4891 
4892   return OK;
4893 }
4894 
4895 static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
4896   assert(E->isValueDependent());
4897   if (Info.noteSideEffect())
4898     return true;
4899   assert(E->containsErrors() && "valid value-dependent expression should never "
4900                                 "reach invalid code path.");
4901   return false;
4902 }
4903 
4904 /// Evaluate a condition (either a variable declaration or an expression).
4905 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4906                          const Expr *Cond, bool &Result) {
4907   if (Cond->isValueDependent())
4908     return false;
4909   FullExpressionRAII Scope(Info);
4910   if (CondDecl && !EvaluateDecl(Info, CondDecl))
4911     return false;
4912   if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4913     return false;
4914   return Scope.destroy();
4915 }
4916 
4917 namespace {
4918 /// A location where the result (returned value) of evaluating a
4919 /// statement should be stored.
4920 struct StmtResult {
4921   /// The APValue that should be filled in with the returned value.
4922   APValue &Value;
4923   /// The location containing the result, if any (used to support RVO).
4924   const LValue *Slot;
4925 };
4926 
4927 struct TempVersionRAII {
4928   CallStackFrame &Frame;
4929 
4930   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4931     Frame.pushTempVersion();
4932   }
4933 
4934   ~TempVersionRAII() {
4935     Frame.popTempVersion();
4936   }
4937 };
4938 
4939 }
4940 
4941 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4942                                    const Stmt *S,
4943                                    const SwitchCase *SC = nullptr);
4944 
4945 /// Evaluate the body of a loop, and translate the result as appropriate.
4946 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4947                                        const Stmt *Body,
4948                                        const SwitchCase *Case = nullptr) {
4949   BlockScopeRAII Scope(Info);
4950 
4951   EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4952   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4953     ESR = ESR_Failed;
4954 
4955   switch (ESR) {
4956   case ESR_Break:
4957     return ESR_Succeeded;
4958   case ESR_Succeeded:
4959   case ESR_Continue:
4960     return ESR_Continue;
4961   case ESR_Failed:
4962   case ESR_Returned:
4963   case ESR_CaseNotFound:
4964     return ESR;
4965   }
4966   llvm_unreachable("Invalid EvalStmtResult!");
4967 }
4968 
4969 /// Evaluate a switch statement.
4970 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4971                                      const SwitchStmt *SS) {
4972   BlockScopeRAII Scope(Info);
4973 
4974   // Evaluate the switch condition.
4975   APSInt Value;
4976   {
4977     if (const Stmt *Init = SS->getInit()) {
4978       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4979       if (ESR != ESR_Succeeded) {
4980         if (ESR != ESR_Failed && !Scope.destroy())
4981           ESR = ESR_Failed;
4982         return ESR;
4983       }
4984     }
4985 
4986     FullExpressionRAII CondScope(Info);
4987     if (SS->getConditionVariable() &&
4988         !EvaluateDecl(Info, SS->getConditionVariable()))
4989       return ESR_Failed;
4990     if (SS->getCond()->isValueDependent()) {
4991       if (!EvaluateDependentExpr(SS->getCond(), Info))
4992         return ESR_Failed;
4993     } else {
4994       if (!EvaluateInteger(SS->getCond(), Value, Info))
4995         return ESR_Failed;
4996     }
4997     if (!CondScope.destroy())
4998       return ESR_Failed;
4999   }
5000 
5001   // Find the switch case corresponding to the value of the condition.
5002   // FIXME: Cache this lookup.
5003   const SwitchCase *Found = nullptr;
5004   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
5005        SC = SC->getNextSwitchCase()) {
5006     if (isa<DefaultStmt>(SC)) {
5007       Found = SC;
5008       continue;
5009     }
5010 
5011     const CaseStmt *CS = cast<CaseStmt>(SC);
5012     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
5013     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
5014                               : LHS;
5015     if (LHS <= Value && Value <= RHS) {
5016       Found = SC;
5017       break;
5018     }
5019   }
5020 
5021   if (!Found)
5022     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5023 
5024   // Search the switch body for the switch case and evaluate it from there.
5025   EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5026   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5027     return ESR_Failed;
5028 
5029   switch (ESR) {
5030   case ESR_Break:
5031     return ESR_Succeeded;
5032   case ESR_Succeeded:
5033   case ESR_Continue:
5034   case ESR_Failed:
5035   case ESR_Returned:
5036     return ESR;
5037   case ESR_CaseNotFound:
5038     // This can only happen if the switch case is nested within a statement
5039     // expression. We have no intention of supporting that.
5040     Info.FFDiag(Found->getBeginLoc(),
5041                 diag::note_constexpr_stmt_expr_unsupported);
5042     return ESR_Failed;
5043   }
5044   llvm_unreachable("Invalid EvalStmtResult!");
5045 }
5046 
5047 static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5048   // An expression E is a core constant expression unless the evaluation of E
5049   // would evaluate one of the following: [C++2b] - a control flow that passes
5050   // through a declaration of a variable with static or thread storage duration
5051   // unless that variable is usable in constant expressions.
5052   if (VD->isLocalVarDecl() && VD->isStaticLocal() &&
5053       !VD->isUsableInConstantExpressions(Info.Ctx)) {
5054     Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5055         << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5056     return false;
5057   }
5058   return true;
5059 }
5060 
5061 // Evaluate a statement.
5062 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5063                                    const Stmt *S, const SwitchCase *Case) {
5064   if (!Info.nextStep(S))
5065     return ESR_Failed;
5066 
5067   // If we're hunting down a 'case' or 'default' label, recurse through
5068   // substatements until we hit the label.
5069   if (Case) {
5070     switch (S->getStmtClass()) {
5071     case Stmt::CompoundStmtClass:
5072       // FIXME: Precompute which substatement of a compound statement we
5073       // would jump to, and go straight there rather than performing a
5074       // linear scan each time.
5075     case Stmt::LabelStmtClass:
5076     case Stmt::AttributedStmtClass:
5077     case Stmt::DoStmtClass:
5078       break;
5079 
5080     case Stmt::CaseStmtClass:
5081     case Stmt::DefaultStmtClass:
5082       if (Case == S)
5083         Case = nullptr;
5084       break;
5085 
5086     case Stmt::IfStmtClass: {
5087       // FIXME: Precompute which side of an 'if' we would jump to, and go
5088       // straight there rather than scanning both sides.
5089       const IfStmt *IS = cast<IfStmt>(S);
5090 
5091       // Wrap the evaluation in a block scope, in case it's a DeclStmt
5092       // preceded by our switch label.
5093       BlockScopeRAII Scope(Info);
5094 
5095       // Step into the init statement in case it brings an (uninitialized)
5096       // variable into scope.
5097       if (const Stmt *Init = IS->getInit()) {
5098         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5099         if (ESR != ESR_CaseNotFound) {
5100           assert(ESR != ESR_Succeeded);
5101           return ESR;
5102         }
5103       }
5104 
5105       // Condition variable must be initialized if it exists.
5106       // FIXME: We can skip evaluating the body if there's a condition
5107       // variable, as there can't be any case labels within it.
5108       // (The same is true for 'for' statements.)
5109 
5110       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5111       if (ESR == ESR_Failed)
5112         return ESR;
5113       if (ESR != ESR_CaseNotFound)
5114         return Scope.destroy() ? ESR : ESR_Failed;
5115       if (!IS->getElse())
5116         return ESR_CaseNotFound;
5117 
5118       ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5119       if (ESR == ESR_Failed)
5120         return ESR;
5121       if (ESR != ESR_CaseNotFound)
5122         return Scope.destroy() ? ESR : ESR_Failed;
5123       return ESR_CaseNotFound;
5124     }
5125 
5126     case Stmt::WhileStmtClass: {
5127       EvalStmtResult ESR =
5128           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5129       if (ESR != ESR_Continue)
5130         return ESR;
5131       break;
5132     }
5133 
5134     case Stmt::ForStmtClass: {
5135       const ForStmt *FS = cast<ForStmt>(S);
5136       BlockScopeRAII Scope(Info);
5137 
5138       // Step into the init statement in case it brings an (uninitialized)
5139       // variable into scope.
5140       if (const Stmt *Init = FS->getInit()) {
5141         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5142         if (ESR != ESR_CaseNotFound) {
5143           assert(ESR != ESR_Succeeded);
5144           return ESR;
5145         }
5146       }
5147 
5148       EvalStmtResult ESR =
5149           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5150       if (ESR != ESR_Continue)
5151         return ESR;
5152       if (const auto *Inc = FS->getInc()) {
5153         if (Inc->isValueDependent()) {
5154           if (!EvaluateDependentExpr(Inc, Info))
5155             return ESR_Failed;
5156         } else {
5157           FullExpressionRAII IncScope(Info);
5158           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5159             return ESR_Failed;
5160         }
5161       }
5162       break;
5163     }
5164 
5165     case Stmt::DeclStmtClass: {
5166       // Start the lifetime of any uninitialized variables we encounter. They
5167       // might be used by the selected branch of the switch.
5168       const DeclStmt *DS = cast<DeclStmt>(S);
5169       for (const auto *D : DS->decls()) {
5170         if (const auto *VD = dyn_cast<VarDecl>(D)) {
5171           if (!CheckLocalVariableDeclaration(Info, VD))
5172             return ESR_Failed;
5173           if (VD->hasLocalStorage() && !VD->getInit())
5174             if (!EvaluateVarDecl(Info, VD))
5175               return ESR_Failed;
5176           // FIXME: If the variable has initialization that can't be jumped
5177           // over, bail out of any immediately-surrounding compound-statement
5178           // too. There can't be any case labels here.
5179         }
5180       }
5181       return ESR_CaseNotFound;
5182     }
5183 
5184     default:
5185       return ESR_CaseNotFound;
5186     }
5187   }
5188 
5189   switch (S->getStmtClass()) {
5190   default:
5191     if (const Expr *E = dyn_cast<Expr>(S)) {
5192       if (E->isValueDependent()) {
5193         if (!EvaluateDependentExpr(E, Info))
5194           return ESR_Failed;
5195       } else {
5196         // Don't bother evaluating beyond an expression-statement which couldn't
5197         // be evaluated.
5198         // FIXME: Do we need the FullExpressionRAII object here?
5199         // VisitExprWithCleanups should create one when necessary.
5200         FullExpressionRAII Scope(Info);
5201         if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5202           return ESR_Failed;
5203       }
5204       return ESR_Succeeded;
5205     }
5206 
5207     Info.FFDiag(S->getBeginLoc());
5208     return ESR_Failed;
5209 
5210   case Stmt::NullStmtClass:
5211     return ESR_Succeeded;
5212 
5213   case Stmt::DeclStmtClass: {
5214     const DeclStmt *DS = cast<DeclStmt>(S);
5215     for (const auto *D : DS->decls()) {
5216       const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
5217       if (VD && !CheckLocalVariableDeclaration(Info, VD))
5218         return ESR_Failed;
5219       // Each declaration initialization is its own full-expression.
5220       FullExpressionRAII Scope(Info);
5221       if (!EvaluateDecl(Info, D) && !Info.noteFailure())
5222         return ESR_Failed;
5223       if (!Scope.destroy())
5224         return ESR_Failed;
5225     }
5226     return ESR_Succeeded;
5227   }
5228 
5229   case Stmt::ReturnStmtClass: {
5230     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5231     FullExpressionRAII Scope(Info);
5232     if (RetExpr && RetExpr->isValueDependent()) {
5233       EvaluateDependentExpr(RetExpr, Info);
5234       // We know we returned, but we don't know what the value is.
5235       return ESR_Failed;
5236     }
5237     if (RetExpr &&
5238         !(Result.Slot
5239               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5240               : Evaluate(Result.Value, Info, RetExpr)))
5241       return ESR_Failed;
5242     return Scope.destroy() ? ESR_Returned : ESR_Failed;
5243   }
5244 
5245   case Stmt::CompoundStmtClass: {
5246     BlockScopeRAII Scope(Info);
5247 
5248     const CompoundStmt *CS = cast<CompoundStmt>(S);
5249     for (const auto *BI : CS->body()) {
5250       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5251       if (ESR == ESR_Succeeded)
5252         Case = nullptr;
5253       else if (ESR != ESR_CaseNotFound) {
5254         if (ESR != ESR_Failed && !Scope.destroy())
5255           return ESR_Failed;
5256         return ESR;
5257       }
5258     }
5259     if (Case)
5260       return ESR_CaseNotFound;
5261     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5262   }
5263 
5264   case Stmt::IfStmtClass: {
5265     const IfStmt *IS = cast<IfStmt>(S);
5266 
5267     // Evaluate the condition, as either a var decl or as an expression.
5268     BlockScopeRAII Scope(Info);
5269     if (const Stmt *Init = IS->getInit()) {
5270       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5271       if (ESR != ESR_Succeeded) {
5272         if (ESR != ESR_Failed && !Scope.destroy())
5273           return ESR_Failed;
5274         return ESR;
5275       }
5276     }
5277     bool Cond;
5278     if (IS->isConsteval()) {
5279       Cond = IS->isNonNegatedConsteval();
5280       // If we are not in a constant context, if consteval should not evaluate
5281       // to true.
5282       if (!Info.InConstantContext)
5283         Cond = !Cond;
5284     } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
5285                              Cond))
5286       return ESR_Failed;
5287 
5288     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5289       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5290       if (ESR != ESR_Succeeded) {
5291         if (ESR != ESR_Failed && !Scope.destroy())
5292           return ESR_Failed;
5293         return ESR;
5294       }
5295     }
5296     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5297   }
5298 
5299   case Stmt::WhileStmtClass: {
5300     const WhileStmt *WS = cast<WhileStmt>(S);
5301     while (true) {
5302       BlockScopeRAII Scope(Info);
5303       bool Continue;
5304       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5305                         Continue))
5306         return ESR_Failed;
5307       if (!Continue)
5308         break;
5309 
5310       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5311       if (ESR != ESR_Continue) {
5312         if (ESR != ESR_Failed && !Scope.destroy())
5313           return ESR_Failed;
5314         return ESR;
5315       }
5316       if (!Scope.destroy())
5317         return ESR_Failed;
5318     }
5319     return ESR_Succeeded;
5320   }
5321 
5322   case Stmt::DoStmtClass: {
5323     const DoStmt *DS = cast<DoStmt>(S);
5324     bool Continue;
5325     do {
5326       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5327       if (ESR != ESR_Continue)
5328         return ESR;
5329       Case = nullptr;
5330 
5331       if (DS->getCond()->isValueDependent()) {
5332         EvaluateDependentExpr(DS->getCond(), Info);
5333         // Bailout as we don't know whether to keep going or terminate the loop.
5334         return ESR_Failed;
5335       }
5336       FullExpressionRAII CondScope(Info);
5337       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5338           !CondScope.destroy())
5339         return ESR_Failed;
5340     } while (Continue);
5341     return ESR_Succeeded;
5342   }
5343 
5344   case Stmt::ForStmtClass: {
5345     const ForStmt *FS = cast<ForStmt>(S);
5346     BlockScopeRAII ForScope(Info);
5347     if (FS->getInit()) {
5348       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5349       if (ESR != ESR_Succeeded) {
5350         if (ESR != ESR_Failed && !ForScope.destroy())
5351           return ESR_Failed;
5352         return ESR;
5353       }
5354     }
5355     while (true) {
5356       BlockScopeRAII IterScope(Info);
5357       bool Continue = true;
5358       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5359                                          FS->getCond(), Continue))
5360         return ESR_Failed;
5361       if (!Continue)
5362         break;
5363 
5364       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5365       if (ESR != ESR_Continue) {
5366         if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5367           return ESR_Failed;
5368         return ESR;
5369       }
5370 
5371       if (const auto *Inc = FS->getInc()) {
5372         if (Inc->isValueDependent()) {
5373           if (!EvaluateDependentExpr(Inc, Info))
5374             return ESR_Failed;
5375         } else {
5376           FullExpressionRAII IncScope(Info);
5377           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5378             return ESR_Failed;
5379         }
5380       }
5381 
5382       if (!IterScope.destroy())
5383         return ESR_Failed;
5384     }
5385     return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5386   }
5387 
5388   case Stmt::CXXForRangeStmtClass: {
5389     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5390     BlockScopeRAII Scope(Info);
5391 
5392     // Evaluate the init-statement if present.
5393     if (FS->getInit()) {
5394       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5395       if (ESR != ESR_Succeeded) {
5396         if (ESR != ESR_Failed && !Scope.destroy())
5397           return ESR_Failed;
5398         return ESR;
5399       }
5400     }
5401 
5402     // Initialize the __range variable.
5403     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5404     if (ESR != ESR_Succeeded) {
5405       if (ESR != ESR_Failed && !Scope.destroy())
5406         return ESR_Failed;
5407       return ESR;
5408     }
5409 
5410     // In error-recovery cases it's possible to get here even if we failed to
5411     // synthesize the __begin and __end variables.
5412     if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
5413       return ESR_Failed;
5414 
5415     // Create the __begin and __end iterators.
5416     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5417     if (ESR != ESR_Succeeded) {
5418       if (ESR != ESR_Failed && !Scope.destroy())
5419         return ESR_Failed;
5420       return ESR;
5421     }
5422     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5423     if (ESR != ESR_Succeeded) {
5424       if (ESR != ESR_Failed && !Scope.destroy())
5425         return ESR_Failed;
5426       return ESR;
5427     }
5428 
5429     while (true) {
5430       // Condition: __begin != __end.
5431       {
5432         if (FS->getCond()->isValueDependent()) {
5433           EvaluateDependentExpr(FS->getCond(), Info);
5434           // We don't know whether to keep going or terminate the loop.
5435           return ESR_Failed;
5436         }
5437         bool Continue = true;
5438         FullExpressionRAII CondExpr(Info);
5439         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5440           return ESR_Failed;
5441         if (!Continue)
5442           break;
5443       }
5444 
5445       // User's variable declaration, initialized by *__begin.
5446       BlockScopeRAII InnerScope(Info);
5447       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5448       if (ESR != ESR_Succeeded) {
5449         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5450           return ESR_Failed;
5451         return ESR;
5452       }
5453 
5454       // Loop body.
5455       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5456       if (ESR != ESR_Continue) {
5457         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5458           return ESR_Failed;
5459         return ESR;
5460       }
5461       if (FS->getInc()->isValueDependent()) {
5462         if (!EvaluateDependentExpr(FS->getInc(), Info))
5463           return ESR_Failed;
5464       } else {
5465         // Increment: ++__begin
5466         if (!EvaluateIgnoredValue(Info, FS->getInc()))
5467           return ESR_Failed;
5468       }
5469 
5470       if (!InnerScope.destroy())
5471         return ESR_Failed;
5472     }
5473 
5474     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5475   }
5476 
5477   case Stmt::SwitchStmtClass:
5478     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5479 
5480   case Stmt::ContinueStmtClass:
5481     return ESR_Continue;
5482 
5483   case Stmt::BreakStmtClass:
5484     return ESR_Break;
5485 
5486   case Stmt::LabelStmtClass:
5487     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5488 
5489   case Stmt::AttributedStmtClass:
5490     // As a general principle, C++11 attributes can be ignored without
5491     // any semantic impact.
5492     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
5493                         Case);
5494 
5495   case Stmt::CaseStmtClass:
5496   case Stmt::DefaultStmtClass:
5497     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5498   case Stmt::CXXTryStmtClass:
5499     // Evaluate try blocks by evaluating all sub statements.
5500     return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5501   }
5502 }
5503 
5504 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5505 /// default constructor. If so, we'll fold it whether or not it's marked as
5506 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
5507 /// so we need special handling.
5508 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5509                                            const CXXConstructorDecl *CD,
5510                                            bool IsValueInitialization) {
5511   if (!CD->isTrivial() || !CD->isDefaultConstructor())
5512     return false;
5513 
5514   // Value-initialization does not call a trivial default constructor, so such a
5515   // call is a core constant expression whether or not the constructor is
5516   // constexpr.
5517   if (!CD->isConstexpr() && !IsValueInitialization) {
5518     if (Info.getLangOpts().CPlusPlus11) {
5519       // FIXME: If DiagDecl is an implicitly-declared special member function,
5520       // we should be much more explicit about why it's not constexpr.
5521       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5522         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5523       Info.Note(CD->getLocation(), diag::note_declared_at);
5524     } else {
5525       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5526     }
5527   }
5528   return true;
5529 }
5530 
5531 /// CheckConstexprFunction - Check that a function can be called in a constant
5532 /// expression.
5533 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5534                                    const FunctionDecl *Declaration,
5535                                    const FunctionDecl *Definition,
5536                                    const Stmt *Body) {
5537   // Potential constant expressions can contain calls to declared, but not yet
5538   // defined, constexpr functions.
5539   if (Info.checkingPotentialConstantExpression() && !Definition &&
5540       Declaration->isConstexpr())
5541     return false;
5542 
5543   // Bail out if the function declaration itself is invalid.  We will
5544   // have produced a relevant diagnostic while parsing it, so just
5545   // note the problematic sub-expression.
5546   if (Declaration->isInvalidDecl()) {
5547     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5548     return false;
5549   }
5550 
5551   // DR1872: An instantiated virtual constexpr function can't be called in a
5552   // constant expression (prior to C++20). We can still constant-fold such a
5553   // call.
5554   if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5555       cast<CXXMethodDecl>(Declaration)->isVirtual())
5556     Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5557 
5558   if (Definition && Definition->isInvalidDecl()) {
5559     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5560     return false;
5561   }
5562 
5563   // Can we evaluate this function call?
5564   if (Definition && Definition->isConstexpr() && Body)
5565     return true;
5566 
5567   if (Info.getLangOpts().CPlusPlus11) {
5568     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5569 
5570     // If this function is not constexpr because it is an inherited
5571     // non-constexpr constructor, diagnose that directly.
5572     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5573     if (CD && CD->isInheritingConstructor()) {
5574       auto *Inherited = CD->getInheritedConstructor().getConstructor();
5575       if (!Inherited->isConstexpr())
5576         DiagDecl = CD = Inherited;
5577     }
5578 
5579     // FIXME: If DiagDecl is an implicitly-declared special member function
5580     // or an inheriting constructor, we should be much more explicit about why
5581     // it's not constexpr.
5582     if (CD && CD->isInheritingConstructor())
5583       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5584         << CD->getInheritedConstructor().getConstructor()->getParent();
5585     else
5586       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5587         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5588     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5589   } else {
5590     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5591   }
5592   return false;
5593 }
5594 
5595 namespace {
5596 struct CheckDynamicTypeHandler {
5597   AccessKinds AccessKind;
5598   typedef bool result_type;
5599   bool failed() { return false; }
5600   bool found(APValue &Subobj, QualType SubobjType) { return true; }
5601   bool found(APSInt &Value, QualType SubobjType) { return true; }
5602   bool found(APFloat &Value, QualType SubobjType) { return true; }
5603 };
5604 } // end anonymous namespace
5605 
5606 /// Check that we can access the notional vptr of an object / determine its
5607 /// dynamic type.
5608 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5609                              AccessKinds AK, bool Polymorphic) {
5610   if (This.Designator.Invalid)
5611     return false;
5612 
5613   CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5614 
5615   if (!Obj)
5616     return false;
5617 
5618   if (!Obj.Value) {
5619     // The object is not usable in constant expressions, so we can't inspect
5620     // its value to see if it's in-lifetime or what the active union members
5621     // are. We can still check for a one-past-the-end lvalue.
5622     if (This.Designator.isOnePastTheEnd() ||
5623         This.Designator.isMostDerivedAnUnsizedArray()) {
5624       Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5625                          ? diag::note_constexpr_access_past_end
5626                          : diag::note_constexpr_access_unsized_array)
5627           << AK;
5628       return false;
5629     } else if (Polymorphic) {
5630       // Conservatively refuse to perform a polymorphic operation if we would
5631       // not be able to read a notional 'vptr' value.
5632       APValue Val;
5633       This.moveInto(Val);
5634       QualType StarThisType =
5635           Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5636       Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5637           << AK << Val.getAsString(Info.Ctx, StarThisType);
5638       return false;
5639     }
5640     return true;
5641   }
5642 
5643   CheckDynamicTypeHandler Handler{AK};
5644   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5645 }
5646 
5647 /// Check that the pointee of the 'this' pointer in a member function call is
5648 /// either within its lifetime or in its period of construction or destruction.
5649 static bool
5650 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5651                                      const LValue &This,
5652                                      const CXXMethodDecl *NamedMember) {
5653   return checkDynamicType(
5654       Info, E, This,
5655       isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5656 }
5657 
5658 struct DynamicType {
5659   /// The dynamic class type of the object.
5660   const CXXRecordDecl *Type;
5661   /// The corresponding path length in the lvalue.
5662   unsigned PathLength;
5663 };
5664 
5665 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5666                                              unsigned PathLength) {
5667   assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5668       Designator.Entries.size() && "invalid path length");
5669   return (PathLength == Designator.MostDerivedPathLength)
5670              ? Designator.MostDerivedType->getAsCXXRecordDecl()
5671              : getAsBaseClass(Designator.Entries[PathLength - 1]);
5672 }
5673 
5674 /// Determine the dynamic type of an object.
5675 static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info,
5676                                                      const Expr *E,
5677                                                      LValue &This,
5678                                                      AccessKinds AK) {
5679   // If we don't have an lvalue denoting an object of class type, there is no
5680   // meaningful dynamic type. (We consider objects of non-class type to have no
5681   // dynamic type.)
5682   if (!checkDynamicType(Info, E, This, AK, true))
5683     return std::nullopt;
5684 
5685   // Refuse to compute a dynamic type in the presence of virtual bases. This
5686   // shouldn't happen other than in constant-folding situations, since literal
5687   // types can't have virtual bases.
5688   //
5689   // Note that consumers of DynamicType assume that the type has no virtual
5690   // bases, and will need modifications if this restriction is relaxed.
5691   const CXXRecordDecl *Class =
5692       This.Designator.MostDerivedType->getAsCXXRecordDecl();
5693   if (!Class || Class->getNumVBases()) {
5694     Info.FFDiag(E);
5695     return std::nullopt;
5696   }
5697 
5698   // FIXME: For very deep class hierarchies, it might be beneficial to use a
5699   // binary search here instead. But the overwhelmingly common case is that
5700   // we're not in the middle of a constructor, so it probably doesn't matter
5701   // in practice.
5702   ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5703   for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5704        PathLength <= Path.size(); ++PathLength) {
5705     switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5706                                       Path.slice(0, PathLength))) {
5707     case ConstructionPhase::Bases:
5708     case ConstructionPhase::DestroyingBases:
5709       // We're constructing or destroying a base class. This is not the dynamic
5710       // type.
5711       break;
5712 
5713     case ConstructionPhase::None:
5714     case ConstructionPhase::AfterBases:
5715     case ConstructionPhase::AfterFields:
5716     case ConstructionPhase::Destroying:
5717       // We've finished constructing the base classes and not yet started
5718       // destroying them again, so this is the dynamic type.
5719       return DynamicType{getBaseClassType(This.Designator, PathLength),
5720                          PathLength};
5721     }
5722   }
5723 
5724   // CWG issue 1517: we're constructing a base class of the object described by
5725   // 'This', so that object has not yet begun its period of construction and
5726   // any polymorphic operation on it results in undefined behavior.
5727   Info.FFDiag(E);
5728   return std::nullopt;
5729 }
5730 
5731 /// Perform virtual dispatch.
5732 static const CXXMethodDecl *HandleVirtualDispatch(
5733     EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5734     llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5735   std::optional<DynamicType> DynType = ComputeDynamicType(
5736       Info, E, This,
5737       isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5738   if (!DynType)
5739     return nullptr;
5740 
5741   // Find the final overrider. It must be declared in one of the classes on the
5742   // path from the dynamic type to the static type.
5743   // FIXME: If we ever allow literal types to have virtual base classes, that
5744   // won't be true.
5745   const CXXMethodDecl *Callee = Found;
5746   unsigned PathLength = DynType->PathLength;
5747   for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5748     const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5749     const CXXMethodDecl *Overrider =
5750         Found->getCorrespondingMethodDeclaredInClass(Class, false);
5751     if (Overrider) {
5752       Callee = Overrider;
5753       break;
5754     }
5755   }
5756 
5757   // C++2a [class.abstract]p6:
5758   //   the effect of making a virtual call to a pure virtual function [...] is
5759   //   undefined
5760   if (Callee->isPure()) {
5761     Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5762     Info.Note(Callee->getLocation(), diag::note_declared_at);
5763     return nullptr;
5764   }
5765 
5766   // If necessary, walk the rest of the path to determine the sequence of
5767   // covariant adjustment steps to apply.
5768   if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5769                                        Found->getReturnType())) {
5770     CovariantAdjustmentPath.push_back(Callee->getReturnType());
5771     for (unsigned CovariantPathLength = PathLength + 1;
5772          CovariantPathLength != This.Designator.Entries.size();
5773          ++CovariantPathLength) {
5774       const CXXRecordDecl *NextClass =
5775           getBaseClassType(This.Designator, CovariantPathLength);
5776       const CXXMethodDecl *Next =
5777           Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5778       if (Next && !Info.Ctx.hasSameUnqualifiedType(
5779                       Next->getReturnType(), CovariantAdjustmentPath.back()))
5780         CovariantAdjustmentPath.push_back(Next->getReturnType());
5781     }
5782     if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5783                                          CovariantAdjustmentPath.back()))
5784       CovariantAdjustmentPath.push_back(Found->getReturnType());
5785   }
5786 
5787   // Perform 'this' adjustment.
5788   if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5789     return nullptr;
5790 
5791   return Callee;
5792 }
5793 
5794 /// Perform the adjustment from a value returned by a virtual function to
5795 /// a value of the statically expected type, which may be a pointer or
5796 /// reference to a base class of the returned type.
5797 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5798                                             APValue &Result,
5799                                             ArrayRef<QualType> Path) {
5800   assert(Result.isLValue() &&
5801          "unexpected kind of APValue for covariant return");
5802   if (Result.isNullPointer())
5803     return true;
5804 
5805   LValue LVal;
5806   LVal.setFrom(Info.Ctx, Result);
5807 
5808   const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5809   for (unsigned I = 1; I != Path.size(); ++I) {
5810     const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5811     assert(OldClass && NewClass && "unexpected kind of covariant return");
5812     if (OldClass != NewClass &&
5813         !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5814       return false;
5815     OldClass = NewClass;
5816   }
5817 
5818   LVal.moveInto(Result);
5819   return true;
5820 }
5821 
5822 /// Determine whether \p Base, which is known to be a direct base class of
5823 /// \p Derived, is a public base class.
5824 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5825                               const CXXRecordDecl *Base) {
5826   for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5827     auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5828     if (BaseClass && declaresSameEntity(BaseClass, Base))
5829       return BaseSpec.getAccessSpecifier() == AS_public;
5830   }
5831   llvm_unreachable("Base is not a direct base of Derived");
5832 }
5833 
5834 /// Apply the given dynamic cast operation on the provided lvalue.
5835 ///
5836 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
5837 /// to find a suitable target subobject.
5838 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5839                               LValue &Ptr) {
5840   // We can't do anything with a non-symbolic pointer value.
5841   SubobjectDesignator &D = Ptr.Designator;
5842   if (D.Invalid)
5843     return false;
5844 
5845   // C++ [expr.dynamic.cast]p6:
5846   //   If v is a null pointer value, the result is a null pointer value.
5847   if (Ptr.isNullPointer() && !E->isGLValue())
5848     return true;
5849 
5850   // For all the other cases, we need the pointer to point to an object within
5851   // its lifetime / period of construction / destruction, and we need to know
5852   // its dynamic type.
5853   std::optional<DynamicType> DynType =
5854       ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5855   if (!DynType)
5856     return false;
5857 
5858   // C++ [expr.dynamic.cast]p7:
5859   //   If T is "pointer to cv void", then the result is a pointer to the most
5860   //   derived object
5861   if (E->getType()->isVoidPointerType())
5862     return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5863 
5864   const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5865   assert(C && "dynamic_cast target is not void pointer nor class");
5866   CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5867 
5868   auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5869     // C++ [expr.dynamic.cast]p9:
5870     if (!E->isGLValue()) {
5871       //   The value of a failed cast to pointer type is the null pointer value
5872       //   of the required result type.
5873       Ptr.setNull(Info.Ctx, E->getType());
5874       return true;
5875     }
5876 
5877     //   A failed cast to reference type throws [...] std::bad_cast.
5878     unsigned DiagKind;
5879     if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5880                    DynType->Type->isDerivedFrom(C)))
5881       DiagKind = 0;
5882     else if (!Paths || Paths->begin() == Paths->end())
5883       DiagKind = 1;
5884     else if (Paths->isAmbiguous(CQT))
5885       DiagKind = 2;
5886     else {
5887       assert(Paths->front().Access != AS_public && "why did the cast fail?");
5888       DiagKind = 3;
5889     }
5890     Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5891         << DiagKind << Ptr.Designator.getType(Info.Ctx)
5892         << Info.Ctx.getRecordType(DynType->Type)
5893         << E->getType().getUnqualifiedType();
5894     return false;
5895   };
5896 
5897   // Runtime check, phase 1:
5898   //   Walk from the base subobject towards the derived object looking for the
5899   //   target type.
5900   for (int PathLength = Ptr.Designator.Entries.size();
5901        PathLength >= (int)DynType->PathLength; --PathLength) {
5902     const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5903     if (declaresSameEntity(Class, C))
5904       return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5905     // We can only walk across public inheritance edges.
5906     if (PathLength > (int)DynType->PathLength &&
5907         !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5908                            Class))
5909       return RuntimeCheckFailed(nullptr);
5910   }
5911 
5912   // Runtime check, phase 2:
5913   //   Search the dynamic type for an unambiguous public base of type C.
5914   CXXBasePaths Paths(/*FindAmbiguities=*/true,
5915                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
5916   if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5917       Paths.front().Access == AS_public) {
5918     // Downcast to the dynamic type...
5919     if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5920       return false;
5921     // ... then upcast to the chosen base class subobject.
5922     for (CXXBasePathElement &Elem : Paths.front())
5923       if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5924         return false;
5925     return true;
5926   }
5927 
5928   // Otherwise, the runtime check fails.
5929   return RuntimeCheckFailed(&Paths);
5930 }
5931 
5932 namespace {
5933 struct StartLifetimeOfUnionMemberHandler {
5934   EvalInfo &Info;
5935   const Expr *LHSExpr;
5936   const FieldDecl *Field;
5937   bool DuringInit;
5938   bool Failed = false;
5939   static const AccessKinds AccessKind = AK_Assign;
5940 
5941   typedef bool result_type;
5942   bool failed() { return Failed; }
5943   bool found(APValue &Subobj, QualType SubobjType) {
5944     // We are supposed to perform no initialization but begin the lifetime of
5945     // the object. We interpret that as meaning to do what default
5946     // initialization of the object would do if all constructors involved were
5947     // trivial:
5948     //  * All base, non-variant member, and array element subobjects' lifetimes
5949     //    begin
5950     //  * No variant members' lifetimes begin
5951     //  * All scalar subobjects whose lifetimes begin have indeterminate values
5952     assert(SubobjType->isUnionType());
5953     if (declaresSameEntity(Subobj.getUnionField(), Field)) {
5954       // This union member is already active. If it's also in-lifetime, there's
5955       // nothing to do.
5956       if (Subobj.getUnionValue().hasValue())
5957         return true;
5958     } else if (DuringInit) {
5959       // We're currently in the process of initializing a different union
5960       // member.  If we carried on, that initialization would attempt to
5961       // store to an inactive union member, resulting in undefined behavior.
5962       Info.FFDiag(LHSExpr,
5963                   diag::note_constexpr_union_member_change_during_init);
5964       return false;
5965     }
5966     APValue Result;
5967     Failed = !getDefaultInitValue(Field->getType(), Result);
5968     Subobj.setUnion(Field, Result);
5969     return true;
5970   }
5971   bool found(APSInt &Value, QualType SubobjType) {
5972     llvm_unreachable("wrong value kind for union object");
5973   }
5974   bool found(APFloat &Value, QualType SubobjType) {
5975     llvm_unreachable("wrong value kind for union object");
5976   }
5977 };
5978 } // end anonymous namespace
5979 
5980 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5981 
5982 /// Handle a builtin simple-assignment or a call to a trivial assignment
5983 /// operator whose left-hand side might involve a union member access. If it
5984 /// does, implicitly start the lifetime of any accessed union elements per
5985 /// C++20 [class.union]5.
5986 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5987                                           const LValue &LHS) {
5988   if (LHS.InvalidBase || LHS.Designator.Invalid)
5989     return false;
5990 
5991   llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5992   // C++ [class.union]p5:
5993   //   define the set S(E) of subexpressions of E as follows:
5994   unsigned PathLength = LHS.Designator.Entries.size();
5995   for (const Expr *E = LHSExpr; E != nullptr;) {
5996     //   -- If E is of the form A.B, S(E) contains the elements of S(A)...
5997     if (auto *ME = dyn_cast<MemberExpr>(E)) {
5998       auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5999       // Note that we can't implicitly start the lifetime of a reference,
6000       // so we don't need to proceed any further if we reach one.
6001       if (!FD || FD->getType()->isReferenceType())
6002         break;
6003 
6004       //    ... and also contains A.B if B names a union member ...
6005       if (FD->getParent()->isUnion()) {
6006         //    ... of a non-class, non-array type, or of a class type with a
6007         //    trivial default constructor that is not deleted, or an array of
6008         //    such types.
6009         auto *RD =
6010             FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6011         if (!RD || RD->hasTrivialDefaultConstructor())
6012           UnionPathLengths.push_back({PathLength - 1, FD});
6013       }
6014 
6015       E = ME->getBase();
6016       --PathLength;
6017       assert(declaresSameEntity(FD,
6018                                 LHS.Designator.Entries[PathLength]
6019                                     .getAsBaseOrMember().getPointer()));
6020 
6021       //   -- If E is of the form A[B] and is interpreted as a built-in array
6022       //      subscripting operator, S(E) is [S(the array operand, if any)].
6023     } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6024       // Step over an ArrayToPointerDecay implicit cast.
6025       auto *Base = ASE->getBase()->IgnoreImplicit();
6026       if (!Base->getType()->isArrayType())
6027         break;
6028 
6029       E = Base;
6030       --PathLength;
6031 
6032     } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6033       // Step over a derived-to-base conversion.
6034       E = ICE->getSubExpr();
6035       if (ICE->getCastKind() == CK_NoOp)
6036         continue;
6037       if (ICE->getCastKind() != CK_DerivedToBase &&
6038           ICE->getCastKind() != CK_UncheckedDerivedToBase)
6039         break;
6040       // Walk path backwards as we walk up from the base to the derived class.
6041       for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
6042         --PathLength;
6043         (void)Elt;
6044         assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
6045                                   LHS.Designator.Entries[PathLength]
6046                                       .getAsBaseOrMember().getPointer()));
6047       }
6048 
6049     //   -- Otherwise, S(E) is empty.
6050     } else {
6051       break;
6052     }
6053   }
6054 
6055   // Common case: no unions' lifetimes are started.
6056   if (UnionPathLengths.empty())
6057     return true;
6058 
6059   //   if modification of X [would access an inactive union member], an object
6060   //   of the type of X is implicitly created
6061   CompleteObject Obj =
6062       findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
6063   if (!Obj)
6064     return false;
6065   for (std::pair<unsigned, const FieldDecl *> LengthAndField :
6066            llvm::reverse(UnionPathLengths)) {
6067     // Form a designator for the union object.
6068     SubobjectDesignator D = LHS.Designator;
6069     D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
6070 
6071     bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
6072                       ConstructionPhase::AfterBases;
6073     StartLifetimeOfUnionMemberHandler StartLifetime{
6074         Info, LHSExpr, LengthAndField.second, DuringInit};
6075     if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
6076       return false;
6077   }
6078 
6079   return true;
6080 }
6081 
6082 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
6083                             CallRef Call, EvalInfo &Info,
6084                             bool NonNull = false) {
6085   LValue LV;
6086   // Create the parameter slot and register its destruction. For a vararg
6087   // argument, create a temporary.
6088   // FIXME: For calling conventions that destroy parameters in the callee,
6089   // should we consider performing destruction when the function returns
6090   // instead?
6091   APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6092                    : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6093                                                        ScopeKind::Call, LV);
6094   if (!EvaluateInPlace(V, Info, LV, Arg))
6095     return false;
6096 
6097   // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6098   // undefined behavior, so is non-constant.
6099   if (NonNull && V.isLValue() && V.isNullPointer()) {
6100     Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6101     return false;
6102   }
6103 
6104   return true;
6105 }
6106 
6107 /// Evaluate the arguments to a function call.
6108 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6109                          EvalInfo &Info, const FunctionDecl *Callee,
6110                          bool RightToLeft = false) {
6111   bool Success = true;
6112   llvm::SmallBitVector ForbiddenNullArgs;
6113   if (Callee->hasAttr<NonNullAttr>()) {
6114     ForbiddenNullArgs.resize(Args.size());
6115     for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6116       if (!Attr->args_size()) {
6117         ForbiddenNullArgs.set();
6118         break;
6119       } else
6120         for (auto Idx : Attr->args()) {
6121           unsigned ASTIdx = Idx.getASTIndex();
6122           if (ASTIdx >= Args.size())
6123             continue;
6124           ForbiddenNullArgs[ASTIdx] = true;
6125         }
6126     }
6127   }
6128   for (unsigned I = 0; I < Args.size(); I++) {
6129     unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6130     const ParmVarDecl *PVD =
6131         Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6132     bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6133     if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) {
6134       // If we're checking for a potential constant expression, evaluate all
6135       // initializers even if some of them fail.
6136       if (!Info.noteFailure())
6137         return false;
6138       Success = false;
6139     }
6140   }
6141   return Success;
6142 }
6143 
6144 /// Perform a trivial copy from Param, which is the parameter of a copy or move
6145 /// constructor or assignment operator.
6146 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6147                               const Expr *E, APValue &Result,
6148                               bool CopyObjectRepresentation) {
6149   // Find the reference argument.
6150   CallStackFrame *Frame = Info.CurrentCall;
6151   APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6152   if (!RefValue) {
6153     Info.FFDiag(E);
6154     return false;
6155   }
6156 
6157   // Copy out the contents of the RHS object.
6158   LValue RefLValue;
6159   RefLValue.setFrom(Info.Ctx, *RefValue);
6160   return handleLValueToRValueConversion(
6161       Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6162       CopyObjectRepresentation);
6163 }
6164 
6165 /// Evaluate a function call.
6166 static bool HandleFunctionCall(SourceLocation CallLoc,
6167                                const FunctionDecl *Callee, const LValue *This,
6168                                ArrayRef<const Expr *> Args, CallRef Call,
6169                                const Stmt *Body, EvalInfo &Info,
6170                                APValue &Result, const LValue *ResultSlot) {
6171   if (!Info.CheckCallLimit(CallLoc))
6172     return false;
6173 
6174   CallStackFrame Frame(Info, CallLoc, Callee, This, Call);
6175 
6176   // For a trivial copy or move assignment, perform an APValue copy. This is
6177   // essential for unions, where the operations performed by the assignment
6178   // operator cannot be represented as statements.
6179   //
6180   // Skip this for non-union classes with no fields; in that case, the defaulted
6181   // copy/move does not actually read the object.
6182   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6183   if (MD && MD->isDefaulted() &&
6184       (MD->getParent()->isUnion() ||
6185        (MD->isTrivial() &&
6186         isReadByLvalueToRvalueConversion(MD->getParent())))) {
6187     assert(This &&
6188            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
6189     APValue RHSValue;
6190     if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6191                            MD->getParent()->isUnion()))
6192       return false;
6193     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
6194                           RHSValue))
6195       return false;
6196     This->moveInto(Result);
6197     return true;
6198   } else if (MD && isLambdaCallOperator(MD)) {
6199     // We're in a lambda; determine the lambda capture field maps unless we're
6200     // just constexpr checking a lambda's call operator. constexpr checking is
6201     // done before the captures have been added to the closure object (unless
6202     // we're inferring constexpr-ness), so we don't have access to them in this
6203     // case. But since we don't need the captures to constexpr check, we can
6204     // just ignore them.
6205     if (!Info.checkingPotentialConstantExpression())
6206       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6207                                         Frame.LambdaThisCaptureField);
6208   }
6209 
6210   StmtResult Ret = {Result, ResultSlot};
6211   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6212   if (ESR == ESR_Succeeded) {
6213     if (Callee->getReturnType()->isVoidType())
6214       return true;
6215     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6216   }
6217   return ESR == ESR_Returned;
6218 }
6219 
6220 /// Evaluate a constructor call.
6221 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6222                                   CallRef Call,
6223                                   const CXXConstructorDecl *Definition,
6224                                   EvalInfo &Info, APValue &Result) {
6225   SourceLocation CallLoc = E->getExprLoc();
6226   if (!Info.CheckCallLimit(CallLoc))
6227     return false;
6228 
6229   const CXXRecordDecl *RD = Definition->getParent();
6230   if (RD->getNumVBases()) {
6231     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6232     return false;
6233   }
6234 
6235   EvalInfo::EvaluatingConstructorRAII EvalObj(
6236       Info,
6237       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6238       RD->getNumBases());
6239   CallStackFrame Frame(Info, CallLoc, Definition, &This, Call);
6240 
6241   // FIXME: Creating an APValue just to hold a nonexistent return value is
6242   // wasteful.
6243   APValue RetVal;
6244   StmtResult Ret = {RetVal, nullptr};
6245 
6246   // If it's a delegating constructor, delegate.
6247   if (Definition->isDelegatingConstructor()) {
6248     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
6249     if ((*I)->getInit()->isValueDependent()) {
6250       if (!EvaluateDependentExpr((*I)->getInit(), Info))
6251         return false;
6252     } else {
6253       FullExpressionRAII InitScope(Info);
6254       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6255           !InitScope.destroy())
6256         return false;
6257     }
6258     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6259   }
6260 
6261   // For a trivial copy or move constructor, perform an APValue copy. This is
6262   // essential for unions (or classes with anonymous union members), where the
6263   // operations performed by the constructor cannot be represented by
6264   // ctor-initializers.
6265   //
6266   // Skip this for empty non-union classes; we should not perform an
6267   // lvalue-to-rvalue conversion on them because their copy constructor does not
6268   // actually read them.
6269   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6270       (Definition->getParent()->isUnion() ||
6271        (Definition->isTrivial() &&
6272         isReadByLvalueToRvalueConversion(Definition->getParent())))) {
6273     return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6274                              Definition->getParent()->isUnion());
6275   }
6276 
6277   // Reserve space for the struct members.
6278   if (!Result.hasValue()) {
6279     if (!RD->isUnion())
6280       Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6281                        std::distance(RD->field_begin(), RD->field_end()));
6282     else
6283       // A union starts with no active member.
6284       Result = APValue((const FieldDecl*)nullptr);
6285   }
6286 
6287   if (RD->isInvalidDecl()) return false;
6288   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6289 
6290   // A scope for temporaries lifetime-extended by reference members.
6291   BlockScopeRAII LifetimeExtendedScope(Info);
6292 
6293   bool Success = true;
6294   unsigned BasesSeen = 0;
6295 #ifndef NDEBUG
6296   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
6297 #endif
6298   CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
6299   auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6300     // We might be initializing the same field again if this is an indirect
6301     // field initialization.
6302     if (FieldIt == RD->field_end() ||
6303         FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6304       assert(Indirect && "fields out of order?");
6305       return;
6306     }
6307 
6308     // Default-initialize any fields with no explicit initializer.
6309     for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6310       assert(FieldIt != RD->field_end() && "missing field?");
6311       if (!FieldIt->isUnnamedBitfield())
6312         Success &= getDefaultInitValue(
6313             FieldIt->getType(),
6314             Result.getStructField(FieldIt->getFieldIndex()));
6315     }
6316     ++FieldIt;
6317   };
6318   for (const auto *I : Definition->inits()) {
6319     LValue Subobject = This;
6320     LValue SubobjectParent = This;
6321     APValue *Value = &Result;
6322 
6323     // Determine the subobject to initialize.
6324     FieldDecl *FD = nullptr;
6325     if (I->isBaseInitializer()) {
6326       QualType BaseType(I->getBaseClass(), 0);
6327 #ifndef NDEBUG
6328       // Non-virtual base classes are initialized in the order in the class
6329       // definition. We have already checked for virtual base classes.
6330       assert(!BaseIt->isVirtual() && "virtual base for literal type");
6331       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
6332              "base class initializers not in expected order");
6333       ++BaseIt;
6334 #endif
6335       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6336                                   BaseType->getAsCXXRecordDecl(), &Layout))
6337         return false;
6338       Value = &Result.getStructBase(BasesSeen++);
6339     } else if ((FD = I->getMember())) {
6340       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6341         return false;
6342       if (RD->isUnion()) {
6343         Result = APValue(FD);
6344         Value = &Result.getUnionValue();
6345       } else {
6346         SkipToField(FD, false);
6347         Value = &Result.getStructField(FD->getFieldIndex());
6348       }
6349     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6350       // Walk the indirect field decl's chain to find the object to initialize,
6351       // and make sure we've initialized every step along it.
6352       auto IndirectFieldChain = IFD->chain();
6353       for (auto *C : IndirectFieldChain) {
6354         FD = cast<FieldDecl>(C);
6355         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6356         // Switch the union field if it differs. This happens if we had
6357         // preceding zero-initialization, and we're now initializing a union
6358         // subobject other than the first.
6359         // FIXME: In this case, the values of the other subobjects are
6360         // specified, since zero-initialization sets all padding bits to zero.
6361         if (!Value->hasValue() ||
6362             (Value->isUnion() && Value->getUnionField() != FD)) {
6363           if (CD->isUnion())
6364             *Value = APValue(FD);
6365           else
6366             // FIXME: This immediately starts the lifetime of all members of
6367             // an anonymous struct. It would be preferable to strictly start
6368             // member lifetime in initialization order.
6369             Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
6370         }
6371         // Store Subobject as its parent before updating it for the last element
6372         // in the chain.
6373         if (C == IndirectFieldChain.back())
6374           SubobjectParent = Subobject;
6375         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6376           return false;
6377         if (CD->isUnion())
6378           Value = &Value->getUnionValue();
6379         else {
6380           if (C == IndirectFieldChain.front() && !RD->isUnion())
6381             SkipToField(FD, true);
6382           Value = &Value->getStructField(FD->getFieldIndex());
6383         }
6384       }
6385     } else {
6386       llvm_unreachable("unknown base initializer kind");
6387     }
6388 
6389     // Need to override This for implicit field initializers as in this case
6390     // This refers to innermost anonymous struct/union containing initializer,
6391     // not to currently constructed class.
6392     const Expr *Init = I->getInit();
6393     if (Init->isValueDependent()) {
6394       if (!EvaluateDependentExpr(Init, Info))
6395         return false;
6396     } else {
6397       ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6398                                     isa<CXXDefaultInitExpr>(Init));
6399       FullExpressionRAII InitScope(Info);
6400       if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6401           (FD && FD->isBitField() &&
6402            !truncateBitfieldValue(Info, Init, *Value, FD))) {
6403         // If we're checking for a potential constant expression, evaluate all
6404         // initializers even if some of them fail.
6405         if (!Info.noteFailure())
6406           return false;
6407         Success = false;
6408       }
6409     }
6410 
6411     // This is the point at which the dynamic type of the object becomes this
6412     // class type.
6413     if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6414       EvalObj.finishedConstructingBases();
6415   }
6416 
6417   // Default-initialize any remaining fields.
6418   if (!RD->isUnion()) {
6419     for (; FieldIt != RD->field_end(); ++FieldIt) {
6420       if (!FieldIt->isUnnamedBitfield())
6421         Success &= getDefaultInitValue(
6422             FieldIt->getType(),
6423             Result.getStructField(FieldIt->getFieldIndex()));
6424     }
6425   }
6426 
6427   EvalObj.finishedConstructingFields();
6428 
6429   return Success &&
6430          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6431          LifetimeExtendedScope.destroy();
6432 }
6433 
6434 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6435                                   ArrayRef<const Expr*> Args,
6436                                   const CXXConstructorDecl *Definition,
6437                                   EvalInfo &Info, APValue &Result) {
6438   CallScopeRAII CallScope(Info);
6439   CallRef Call = Info.CurrentCall->createCall(Definition);
6440   if (!EvaluateArgs(Args, Call, Info, Definition))
6441     return false;
6442 
6443   return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6444          CallScope.destroy();
6445 }
6446 
6447 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
6448                                   const LValue &This, APValue &Value,
6449                                   QualType T) {
6450   // Objects can only be destroyed while they're within their lifetimes.
6451   // FIXME: We have no representation for whether an object of type nullptr_t
6452   // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6453   // as indeterminate instead?
6454   if (Value.isAbsent() && !T->isNullPtrType()) {
6455     APValue Printable;
6456     This.moveInto(Printable);
6457     Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
6458       << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6459     return false;
6460   }
6461 
6462   // Invent an expression for location purposes.
6463   // FIXME: We shouldn't need to do this.
6464   OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_PRValue);
6465 
6466   // For arrays, destroy elements right-to-left.
6467   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6468     uint64_t Size = CAT->getSize().getZExtValue();
6469     QualType ElemT = CAT->getElementType();
6470 
6471     LValue ElemLV = This;
6472     ElemLV.addArray(Info, &LocE, CAT);
6473     if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6474       return false;
6475 
6476     // Ensure that we have actual array elements available to destroy; the
6477     // destructors might mutate the value, so we can't run them on the array
6478     // filler.
6479     if (Size && Size > Value.getArrayInitializedElts())
6480       expandArray(Value, Value.getArraySize() - 1);
6481 
6482     for (; Size != 0; --Size) {
6483       APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6484       if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6485           !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
6486         return false;
6487     }
6488 
6489     // End the lifetime of this array now.
6490     Value = APValue();
6491     return true;
6492   }
6493 
6494   const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6495   if (!RD) {
6496     if (T.isDestructedType()) {
6497       Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
6498       return false;
6499     }
6500 
6501     Value = APValue();
6502     return true;
6503   }
6504 
6505   if (RD->getNumVBases()) {
6506     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6507     return false;
6508   }
6509 
6510   const CXXDestructorDecl *DD = RD->getDestructor();
6511   if (!DD && !RD->hasTrivialDestructor()) {
6512     Info.FFDiag(CallLoc);
6513     return false;
6514   }
6515 
6516   if (!DD || DD->isTrivial() ||
6517       (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6518     // A trivial destructor just ends the lifetime of the object. Check for
6519     // this case before checking for a body, because we might not bother
6520     // building a body for a trivial destructor. Note that it doesn't matter
6521     // whether the destructor is constexpr in this case; all trivial
6522     // destructors are constexpr.
6523     //
6524     // If an anonymous union would be destroyed, some enclosing destructor must
6525     // have been explicitly defined, and the anonymous union destruction should
6526     // have no effect.
6527     Value = APValue();
6528     return true;
6529   }
6530 
6531   if (!Info.CheckCallLimit(CallLoc))
6532     return false;
6533 
6534   const FunctionDecl *Definition = nullptr;
6535   const Stmt *Body = DD->getBody(Definition);
6536 
6537   if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
6538     return false;
6539 
6540   CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef());
6541 
6542   // We're now in the period of destruction of this object.
6543   unsigned BasesLeft = RD->getNumBases();
6544   EvalInfo::EvaluatingDestructorRAII EvalObj(
6545       Info,
6546       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6547   if (!EvalObj.DidInsert) {
6548     // C++2a [class.dtor]p19:
6549     //   the behavior is undefined if the destructor is invoked for an object
6550     //   whose lifetime has ended
6551     // (Note that formally the lifetime ends when the period of destruction
6552     // begins, even though certain uses of the object remain valid until the
6553     // period of destruction ends.)
6554     Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
6555     return false;
6556   }
6557 
6558   // FIXME: Creating an APValue just to hold a nonexistent return value is
6559   // wasteful.
6560   APValue RetVal;
6561   StmtResult Ret = {RetVal, nullptr};
6562   if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6563     return false;
6564 
6565   // A union destructor does not implicitly destroy its members.
6566   if (RD->isUnion())
6567     return true;
6568 
6569   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6570 
6571   // We don't have a good way to iterate fields in reverse, so collect all the
6572   // fields first and then walk them backwards.
6573   SmallVector<FieldDecl*, 16> Fields(RD->fields());
6574   for (const FieldDecl *FD : llvm::reverse(Fields)) {
6575     if (FD->isUnnamedBitfield())
6576       continue;
6577 
6578     LValue Subobject = This;
6579     if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6580       return false;
6581 
6582     APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6583     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6584                                FD->getType()))
6585       return false;
6586   }
6587 
6588   if (BasesLeft != 0)
6589     EvalObj.startedDestroyingBases();
6590 
6591   // Destroy base classes in reverse order.
6592   for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6593     --BasesLeft;
6594 
6595     QualType BaseType = Base.getType();
6596     LValue Subobject = This;
6597     if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
6598                                 BaseType->getAsCXXRecordDecl(), &Layout))
6599       return false;
6600 
6601     APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
6602     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6603                                BaseType))
6604       return false;
6605   }
6606   assert(BasesLeft == 0 && "NumBases was wrong?");
6607 
6608   // The period of destruction ends now. The object is gone.
6609   Value = APValue();
6610   return true;
6611 }
6612 
6613 namespace {
6614 struct DestroyObjectHandler {
6615   EvalInfo &Info;
6616   const Expr *E;
6617   const LValue &This;
6618   const AccessKinds AccessKind;
6619 
6620   typedef bool result_type;
6621   bool failed() { return false; }
6622   bool found(APValue &Subobj, QualType SubobjType) {
6623     return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
6624                                  SubobjType);
6625   }
6626   bool found(APSInt &Value, QualType SubobjType) {
6627     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6628     return false;
6629   }
6630   bool found(APFloat &Value, QualType SubobjType) {
6631     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6632     return false;
6633   }
6634 };
6635 }
6636 
6637 /// Perform a destructor or pseudo-destructor call on the given object, which
6638 /// might in general not be a complete object.
6639 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6640                               const LValue &This, QualType ThisType) {
6641   CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6642   DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6643   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6644 }
6645 
6646 /// Destroy and end the lifetime of the given complete object.
6647 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6648                               APValue::LValueBase LVBase, APValue &Value,
6649                               QualType T) {
6650   // If we've had an unmodeled side-effect, we can't rely on mutable state
6651   // (such as the object we're about to destroy) being correct.
6652   if (Info.EvalStatus.HasSideEffects)
6653     return false;
6654 
6655   LValue LV;
6656   LV.set({LVBase});
6657   return HandleDestructionImpl(Info, Loc, LV, Value, T);
6658 }
6659 
6660 /// Perform a call to 'perator new' or to `__builtin_operator_new'.
6661 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6662                                   LValue &Result) {
6663   if (Info.checkingPotentialConstantExpression() ||
6664       Info.SpeculativeEvaluationDepth)
6665     return false;
6666 
6667   // This is permitted only within a call to std::allocator<T>::allocate.
6668   auto Caller = Info.getStdAllocatorCaller("allocate");
6669   if (!Caller) {
6670     Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
6671                                      ? diag::note_constexpr_new_untyped
6672                                      : diag::note_constexpr_new);
6673     return false;
6674   }
6675 
6676   QualType ElemType = Caller.ElemType;
6677   if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6678     Info.FFDiag(E->getExprLoc(),
6679                 diag::note_constexpr_new_not_complete_object_type)
6680         << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6681     return false;
6682   }
6683 
6684   APSInt ByteSize;
6685   if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6686     return false;
6687   bool IsNothrow = false;
6688   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6689     EvaluateIgnoredValue(Info, E->getArg(I));
6690     IsNothrow |= E->getType()->isNothrowT();
6691   }
6692 
6693   CharUnits ElemSize;
6694   if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6695     return false;
6696   APInt Size, Remainder;
6697   APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6698   APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6699   if (Remainder != 0) {
6700     // This likely indicates a bug in the implementation of 'std::allocator'.
6701     Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6702         << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6703     return false;
6704   }
6705 
6706   if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
6707     if (IsNothrow) {
6708       Result.setNull(Info.Ctx, E->getType());
6709       return true;
6710     }
6711 
6712     Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
6713     return false;
6714   }
6715 
6716   QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
6717                                                      ArrayType::Normal, 0);
6718   APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6719   *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6720   Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6721   return true;
6722 }
6723 
6724 static bool hasVirtualDestructor(QualType T) {
6725   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6726     if (CXXDestructorDecl *DD = RD->getDestructor())
6727       return DD->isVirtual();
6728   return false;
6729 }
6730 
6731 static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6732   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6733     if (CXXDestructorDecl *DD = RD->getDestructor())
6734       return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6735   return nullptr;
6736 }
6737 
6738 /// Check that the given object is a suitable pointer to a heap allocation that
6739 /// still exists and is of the right kind for the purpose of a deletion.
6740 ///
6741 /// On success, returns the heap allocation to deallocate. On failure, produces
6742 /// a diagnostic and returns std::nullopt.
6743 static std::optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6744                                                  const LValue &Pointer,
6745                                                  DynAlloc::Kind DeallocKind) {
6746   auto PointerAsString = [&] {
6747     return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6748   };
6749 
6750   DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6751   if (!DA) {
6752     Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6753         << PointerAsString();
6754     if (Pointer.Base)
6755       NoteLValueLocation(Info, Pointer.Base);
6756     return std::nullopt;
6757   }
6758 
6759   std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6760   if (!Alloc) {
6761     Info.FFDiag(E, diag::note_constexpr_double_delete);
6762     return std::nullopt;
6763   }
6764 
6765   QualType AllocType = Pointer.Base.getDynamicAllocType();
6766   if (DeallocKind != (*Alloc)->getKind()) {
6767     Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6768         << DeallocKind << (*Alloc)->getKind() << AllocType;
6769     NoteLValueLocation(Info, Pointer.Base);
6770     return std::nullopt;
6771   }
6772 
6773   bool Subobject = false;
6774   if (DeallocKind == DynAlloc::New) {
6775     Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6776                 Pointer.Designator.isOnePastTheEnd();
6777   } else {
6778     Subobject = Pointer.Designator.Entries.size() != 1 ||
6779                 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6780   }
6781   if (Subobject) {
6782     Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6783         << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6784     return std::nullopt;
6785   }
6786 
6787   return Alloc;
6788 }
6789 
6790 // Perform a call to 'operator delete' or '__builtin_operator_delete'.
6791 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6792   if (Info.checkingPotentialConstantExpression() ||
6793       Info.SpeculativeEvaluationDepth)
6794     return false;
6795 
6796   // This is permitted only within a call to std::allocator<T>::deallocate.
6797   if (!Info.getStdAllocatorCaller("deallocate")) {
6798     Info.FFDiag(E->getExprLoc());
6799     return true;
6800   }
6801 
6802   LValue Pointer;
6803   if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6804     return false;
6805   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6806     EvaluateIgnoredValue(Info, E->getArg(I));
6807 
6808   if (Pointer.Designator.Invalid)
6809     return false;
6810 
6811   // Deleting a null pointer would have no effect, but it's not permitted by
6812   // std::allocator<T>::deallocate's contract.
6813   if (Pointer.isNullPointer()) {
6814     Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
6815     return true;
6816   }
6817 
6818   if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6819     return false;
6820 
6821   Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6822   return true;
6823 }
6824 
6825 //===----------------------------------------------------------------------===//
6826 // Generic Evaluation
6827 //===----------------------------------------------------------------------===//
6828 namespace {
6829 
6830 class BitCastBuffer {
6831   // FIXME: We're going to need bit-level granularity when we support
6832   // bit-fields.
6833   // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6834   // we don't support a host or target where that is the case. Still, we should
6835   // use a more generic type in case we ever do.
6836   SmallVector<std::optional<unsigned char>, 32> Bytes;
6837 
6838   static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6839                 "Need at least 8 bit unsigned char");
6840 
6841   bool TargetIsLittleEndian;
6842 
6843 public:
6844   BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6845       : Bytes(Width.getQuantity()),
6846         TargetIsLittleEndian(TargetIsLittleEndian) {}
6847 
6848   [[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width,
6849                                 SmallVectorImpl<unsigned char> &Output) const {
6850     for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6851       // If a byte of an integer is uninitialized, then the whole integer is
6852       // uninitialized.
6853       if (!Bytes[I.getQuantity()])
6854         return false;
6855       Output.push_back(*Bytes[I.getQuantity()]);
6856     }
6857     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6858       std::reverse(Output.begin(), Output.end());
6859     return true;
6860   }
6861 
6862   void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6863     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6864       std::reverse(Input.begin(), Input.end());
6865 
6866     size_t Index = 0;
6867     for (unsigned char Byte : Input) {
6868       assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
6869       Bytes[Offset.getQuantity() + Index] = Byte;
6870       ++Index;
6871     }
6872   }
6873 
6874   size_t size() { return Bytes.size(); }
6875 };
6876 
6877 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6878 /// target would represent the value at runtime.
6879 class APValueToBufferConverter {
6880   EvalInfo &Info;
6881   BitCastBuffer Buffer;
6882   const CastExpr *BCE;
6883 
6884   APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6885                            const CastExpr *BCE)
6886       : Info(Info),
6887         Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6888         BCE(BCE) {}
6889 
6890   bool visit(const APValue &Val, QualType Ty) {
6891     return visit(Val, Ty, CharUnits::fromQuantity(0));
6892   }
6893 
6894   // Write out Val with type Ty into Buffer starting at Offset.
6895   bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6896     assert((size_t)Offset.getQuantity() <= Buffer.size());
6897 
6898     // As a special case, nullptr_t has an indeterminate value.
6899     if (Ty->isNullPtrType())
6900       return true;
6901 
6902     // Dig through Src to find the byte at SrcOffset.
6903     switch (Val.getKind()) {
6904     case APValue::Indeterminate:
6905     case APValue::None:
6906       return true;
6907 
6908     case APValue::Int:
6909       return visitInt(Val.getInt(), Ty, Offset);
6910     case APValue::Float:
6911       return visitFloat(Val.getFloat(), Ty, Offset);
6912     case APValue::Array:
6913       return visitArray(Val, Ty, Offset);
6914     case APValue::Struct:
6915       return visitRecord(Val, Ty, Offset);
6916 
6917     case APValue::ComplexInt:
6918     case APValue::ComplexFloat:
6919     case APValue::Vector:
6920     case APValue::FixedPoint:
6921       // FIXME: We should support these.
6922 
6923     case APValue::Union:
6924     case APValue::MemberPointer:
6925     case APValue::AddrLabelDiff: {
6926       Info.FFDiag(BCE->getBeginLoc(),
6927                   diag::note_constexpr_bit_cast_unsupported_type)
6928           << Ty;
6929       return false;
6930     }
6931 
6932     case APValue::LValue:
6933       llvm_unreachable("LValue subobject in bit_cast?");
6934     }
6935     llvm_unreachable("Unhandled APValue::ValueKind");
6936   }
6937 
6938   bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
6939     const RecordDecl *RD = Ty->getAsRecordDecl();
6940     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6941 
6942     // Visit the base classes.
6943     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6944       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6945         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6946         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6947 
6948         if (!visitRecord(Val.getStructBase(I), BS.getType(),
6949                          Layout.getBaseClassOffset(BaseDecl) + Offset))
6950           return false;
6951       }
6952     }
6953 
6954     // Visit the fields.
6955     unsigned FieldIdx = 0;
6956     for (FieldDecl *FD : RD->fields()) {
6957       if (FD->isBitField()) {
6958         Info.FFDiag(BCE->getBeginLoc(),
6959                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6960         return false;
6961       }
6962 
6963       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6964 
6965       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
6966              "only bit-fields can have sub-char alignment");
6967       CharUnits FieldOffset =
6968           Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
6969       QualType FieldTy = FD->getType();
6970       if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
6971         return false;
6972       ++FieldIdx;
6973     }
6974 
6975     return true;
6976   }
6977 
6978   bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
6979     const auto *CAT =
6980         dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
6981     if (!CAT)
6982       return false;
6983 
6984     CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
6985     unsigned NumInitializedElts = Val.getArrayInitializedElts();
6986     unsigned ArraySize = Val.getArraySize();
6987     // First, initialize the initialized elements.
6988     for (unsigned I = 0; I != NumInitializedElts; ++I) {
6989       const APValue &SubObj = Val.getArrayInitializedElt(I);
6990       if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
6991         return false;
6992     }
6993 
6994     // Next, initialize the rest of the array using the filler.
6995     if (Val.hasArrayFiller()) {
6996       const APValue &Filler = Val.getArrayFiller();
6997       for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
6998         if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
6999           return false;
7000       }
7001     }
7002 
7003     return true;
7004   }
7005 
7006   bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
7007     APSInt AdjustedVal = Val;
7008     unsigned Width = AdjustedVal.getBitWidth();
7009     if (Ty->isBooleanType()) {
7010       Width = Info.Ctx.getTypeSize(Ty);
7011       AdjustedVal = AdjustedVal.extend(Width);
7012     }
7013 
7014     SmallVector<unsigned char, 8> Bytes(Width / 8);
7015     llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
7016     Buffer.writeObject(Offset, Bytes);
7017     return true;
7018   }
7019 
7020   bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
7021     APSInt AsInt(Val.bitcastToAPInt());
7022     return visitInt(AsInt, Ty, Offset);
7023   }
7024 
7025 public:
7026   static std::optional<BitCastBuffer>
7027   convert(EvalInfo &Info, const APValue &Src, const CastExpr *BCE) {
7028     CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
7029     APValueToBufferConverter Converter(Info, DstSize, BCE);
7030     if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
7031       return std::nullopt;
7032     return Converter.Buffer;
7033   }
7034 };
7035 
7036 /// Write an BitCastBuffer into an APValue.
7037 class BufferToAPValueConverter {
7038   EvalInfo &Info;
7039   const BitCastBuffer &Buffer;
7040   const CastExpr *BCE;
7041 
7042   BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
7043                            const CastExpr *BCE)
7044       : Info(Info), Buffer(Buffer), BCE(BCE) {}
7045 
7046   // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
7047   // with an invalid type, so anything left is a deficiency on our part (FIXME).
7048   // Ideally this will be unreachable.
7049   std::nullopt_t unsupportedType(QualType Ty) {
7050     Info.FFDiag(BCE->getBeginLoc(),
7051                 diag::note_constexpr_bit_cast_unsupported_type)
7052         << Ty;
7053     return std::nullopt;
7054   }
7055 
7056   std::nullopt_t unrepresentableValue(QualType Ty, const APSInt &Val) {
7057     Info.FFDiag(BCE->getBeginLoc(),
7058                 diag::note_constexpr_bit_cast_unrepresentable_value)
7059         << Ty << toString(Val, /*Radix=*/10);
7060     return std::nullopt;
7061   }
7062 
7063   std::optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
7064                                const EnumType *EnumSugar = nullptr) {
7065     if (T->isNullPtrType()) {
7066       uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
7067       return APValue((Expr *)nullptr,
7068                      /*Offset=*/CharUnits::fromQuantity(NullValue),
7069                      APValue::NoLValuePath{}, /*IsNullPtr=*/true);
7070     }
7071 
7072     CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
7073 
7074     // Work around floating point types that contain unused padding bytes. This
7075     // is really just `long double` on x86, which is the only fundamental type
7076     // with padding bytes.
7077     if (T->isRealFloatingType()) {
7078       const llvm::fltSemantics &Semantics =
7079           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7080       unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
7081       assert(NumBits % 8 == 0);
7082       CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
7083       if (NumBytes != SizeOf)
7084         SizeOf = NumBytes;
7085     }
7086 
7087     SmallVector<uint8_t, 8> Bytes;
7088     if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
7089       // If this is std::byte or unsigned char, then its okay to store an
7090       // indeterminate value.
7091       bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
7092       bool IsUChar =
7093           !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
7094                          T->isSpecificBuiltinType(BuiltinType::Char_U));
7095       if (!IsStdByte && !IsUChar) {
7096         QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
7097         Info.FFDiag(BCE->getExprLoc(),
7098                     diag::note_constexpr_bit_cast_indet_dest)
7099             << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
7100         return std::nullopt;
7101       }
7102 
7103       return APValue::IndeterminateValue();
7104     }
7105 
7106     APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
7107     llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
7108 
7109     if (T->isIntegralOrEnumerationType()) {
7110       Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7111 
7112       unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
7113       if (IntWidth != Val.getBitWidth()) {
7114         APSInt Truncated = Val.trunc(IntWidth);
7115         if (Truncated.extend(Val.getBitWidth()) != Val)
7116           return unrepresentableValue(QualType(T, 0), Val);
7117         Val = Truncated;
7118       }
7119 
7120       return APValue(Val);
7121     }
7122 
7123     if (T->isRealFloatingType()) {
7124       const llvm::fltSemantics &Semantics =
7125           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7126       return APValue(APFloat(Semantics, Val));
7127     }
7128 
7129     return unsupportedType(QualType(T, 0));
7130   }
7131 
7132   std::optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7133     const RecordDecl *RD = RTy->getAsRecordDecl();
7134     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7135 
7136     unsigned NumBases = 0;
7137     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7138       NumBases = CXXRD->getNumBases();
7139 
7140     APValue ResultVal(APValue::UninitStruct(), NumBases,
7141                       std::distance(RD->field_begin(), RD->field_end()));
7142 
7143     // Visit the base classes.
7144     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7145       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7146         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7147         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7148         if (BaseDecl->isEmpty() ||
7149             Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
7150           continue;
7151 
7152         std::optional<APValue> SubObj = visitType(
7153             BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7154         if (!SubObj)
7155           return std::nullopt;
7156         ResultVal.getStructBase(I) = *SubObj;
7157       }
7158     }
7159 
7160     // Visit the fields.
7161     unsigned FieldIdx = 0;
7162     for (FieldDecl *FD : RD->fields()) {
7163       // FIXME: We don't currently support bit-fields. A lot of the logic for
7164       // this is in CodeGen, so we need to factor it around.
7165       if (FD->isBitField()) {
7166         Info.FFDiag(BCE->getBeginLoc(),
7167                     diag::note_constexpr_bit_cast_unsupported_bitfield);
7168         return std::nullopt;
7169       }
7170 
7171       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7172       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
7173 
7174       CharUnits FieldOffset =
7175           CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7176           Offset;
7177       QualType FieldTy = FD->getType();
7178       std::optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7179       if (!SubObj)
7180         return std::nullopt;
7181       ResultVal.getStructField(FieldIdx) = *SubObj;
7182       ++FieldIdx;
7183     }
7184 
7185     return ResultVal;
7186   }
7187 
7188   std::optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7189     QualType RepresentationType = Ty->getDecl()->getIntegerType();
7190     assert(!RepresentationType.isNull() &&
7191            "enum forward decl should be caught by Sema");
7192     const auto *AsBuiltin =
7193         RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7194     // Recurse into the underlying type. Treat std::byte transparently as
7195     // unsigned char.
7196     return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7197   }
7198 
7199   std::optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7200     size_t Size = Ty->getSize().getLimitedValue();
7201     CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7202 
7203     APValue ArrayValue(APValue::UninitArray(), Size, Size);
7204     for (size_t I = 0; I != Size; ++I) {
7205       std::optional<APValue> ElementValue =
7206           visitType(Ty->getElementType(), Offset + I * ElementWidth);
7207       if (!ElementValue)
7208         return std::nullopt;
7209       ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7210     }
7211 
7212     return ArrayValue;
7213   }
7214 
7215   std::optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7216     return unsupportedType(QualType(Ty, 0));
7217   }
7218 
7219   std::optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7220     QualType Can = Ty.getCanonicalType();
7221 
7222     switch (Can->getTypeClass()) {
7223 #define TYPE(Class, Base)                                                      \
7224   case Type::Class:                                                            \
7225     return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7226 #define ABSTRACT_TYPE(Class, Base)
7227 #define NON_CANONICAL_TYPE(Class, Base)                                        \
7228   case Type::Class:                                                            \
7229     llvm_unreachable("non-canonical type should be impossible!");
7230 #define DEPENDENT_TYPE(Class, Base)                                            \
7231   case Type::Class:                                                            \
7232     llvm_unreachable(                                                          \
7233         "dependent types aren't supported in the constant evaluator!");
7234 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)                            \
7235   case Type::Class:                                                            \
7236     llvm_unreachable("either dependent or not canonical!");
7237 #include "clang/AST/TypeNodes.inc"
7238     }
7239     llvm_unreachable("Unhandled Type::TypeClass");
7240   }
7241 
7242 public:
7243   // Pull out a full value of type DstType.
7244   static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7245                                         const CastExpr *BCE) {
7246     BufferToAPValueConverter Converter(Info, Buffer, BCE);
7247     return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7248   }
7249 };
7250 
7251 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7252                                                  QualType Ty, EvalInfo *Info,
7253                                                  const ASTContext &Ctx,
7254                                                  bool CheckingDest) {
7255   Ty = Ty.getCanonicalType();
7256 
7257   auto diag = [&](int Reason) {
7258     if (Info)
7259       Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7260           << CheckingDest << (Reason == 4) << Reason;
7261     return false;
7262   };
7263   auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7264     if (Info)
7265       Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7266           << NoteTy << Construct << Ty;
7267     return false;
7268   };
7269 
7270   if (Ty->isUnionType())
7271     return diag(0);
7272   if (Ty->isPointerType())
7273     return diag(1);
7274   if (Ty->isMemberPointerType())
7275     return diag(2);
7276   if (Ty.isVolatileQualified())
7277     return diag(3);
7278 
7279   if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7280     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7281       for (CXXBaseSpecifier &BS : CXXRD->bases())
7282         if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7283                                                   CheckingDest))
7284           return note(1, BS.getType(), BS.getBeginLoc());
7285     }
7286     for (FieldDecl *FD : Record->fields()) {
7287       if (FD->getType()->isReferenceType())
7288         return diag(4);
7289       if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7290                                                 CheckingDest))
7291         return note(0, FD->getType(), FD->getBeginLoc());
7292     }
7293   }
7294 
7295   if (Ty->isArrayType() &&
7296       !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7297                                             Info, Ctx, CheckingDest))
7298     return false;
7299 
7300   return true;
7301 }
7302 
7303 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
7304                                              const ASTContext &Ctx,
7305                                              const CastExpr *BCE) {
7306   bool DestOK = checkBitCastConstexprEligibilityType(
7307       BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
7308   bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
7309                                 BCE->getBeginLoc(),
7310                                 BCE->getSubExpr()->getType(), Info, Ctx, false);
7311   return SourceOK;
7312 }
7313 
7314 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7315                                         APValue &SourceValue,
7316                                         const CastExpr *BCE) {
7317   assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7318          "no host or target supports non 8-bit chars");
7319   assert(SourceValue.isLValue() &&
7320          "LValueToRValueBitcast requires an lvalue operand!");
7321 
7322   if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
7323     return false;
7324 
7325   LValue SourceLValue;
7326   APValue SourceRValue;
7327   SourceLValue.setFrom(Info.Ctx, SourceValue);
7328   if (!handleLValueToRValueConversion(
7329           Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
7330           SourceRValue, /*WantObjectRepresentation=*/true))
7331     return false;
7332 
7333   // Read out SourceValue into a char buffer.
7334   std::optional<BitCastBuffer> Buffer =
7335       APValueToBufferConverter::convert(Info, SourceRValue, BCE);
7336   if (!Buffer)
7337     return false;
7338 
7339   // Write out the buffer into a new APValue.
7340   std::optional<APValue> MaybeDestValue =
7341       BufferToAPValueConverter::convert(Info, *Buffer, BCE);
7342   if (!MaybeDestValue)
7343     return false;
7344 
7345   DestValue = std::move(*MaybeDestValue);
7346   return true;
7347 }
7348 
7349 template <class Derived>
7350 class ExprEvaluatorBase
7351   : public ConstStmtVisitor<Derived, bool> {
7352 private:
7353   Derived &getDerived() { return static_cast<Derived&>(*this); }
7354   bool DerivedSuccess(const APValue &V, const Expr *E) {
7355     return getDerived().Success(V, E);
7356   }
7357   bool DerivedZeroInitialization(const Expr *E) {
7358     return getDerived().ZeroInitialization(E);
7359   }
7360 
7361   // Check whether a conditional operator with a non-constant condition is a
7362   // potential constant expression. If neither arm is a potential constant
7363   // expression, then the conditional operator is not either.
7364   template<typename ConditionalOperator>
7365   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7366     assert(Info.checkingPotentialConstantExpression());
7367 
7368     // Speculatively evaluate both arms.
7369     SmallVector<PartialDiagnosticAt, 8> Diag;
7370     {
7371       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7372       StmtVisitorTy::Visit(E->getFalseExpr());
7373       if (Diag.empty())
7374         return;
7375     }
7376 
7377     {
7378       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7379       Diag.clear();
7380       StmtVisitorTy::Visit(E->getTrueExpr());
7381       if (Diag.empty())
7382         return;
7383     }
7384 
7385     Error(E, diag::note_constexpr_conditional_never_const);
7386   }
7387 
7388 
7389   template<typename ConditionalOperator>
7390   bool HandleConditionalOperator(const ConditionalOperator *E) {
7391     bool BoolResult;
7392     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7393       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7394         CheckPotentialConstantConditional(E);
7395         return false;
7396       }
7397       if (Info.noteFailure()) {
7398         StmtVisitorTy::Visit(E->getTrueExpr());
7399         StmtVisitorTy::Visit(E->getFalseExpr());
7400       }
7401       return false;
7402     }
7403 
7404     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
7405     return StmtVisitorTy::Visit(EvalExpr);
7406   }
7407 
7408 protected:
7409   EvalInfo &Info;
7410   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
7411   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
7412 
7413   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7414     return Info.CCEDiag(E, D);
7415   }
7416 
7417   bool ZeroInitialization(const Expr *E) { return Error(E); }
7418 
7419   bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
7420     unsigned BuiltinOp = E->getBuiltinCallee();
7421     return BuiltinOp != 0 &&
7422            Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp);
7423   }
7424 
7425 public:
7426   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
7427 
7428   EvalInfo &getEvalInfo() { return Info; }
7429 
7430   /// Report an evaluation error. This should only be called when an error is
7431   /// first discovered. When propagating an error, just return false.
7432   bool Error(const Expr *E, diag::kind D) {
7433     Info.FFDiag(E, D);
7434     return false;
7435   }
7436   bool Error(const Expr *E) {
7437     return Error(E, diag::note_invalid_subexpr_in_const_expr);
7438   }
7439 
7440   bool VisitStmt(const Stmt *) {
7441     llvm_unreachable("Expression evaluator should not be called on stmts");
7442   }
7443   bool VisitExpr(const Expr *E) {
7444     return Error(E);
7445   }
7446 
7447   bool VisitConstantExpr(const ConstantExpr *E) {
7448     if (E->hasAPValueResult())
7449       return DerivedSuccess(E->getAPValueResult(), E);
7450 
7451     return StmtVisitorTy::Visit(E->getSubExpr());
7452   }
7453 
7454   bool VisitParenExpr(const ParenExpr *E)
7455     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7456   bool VisitUnaryExtension(const UnaryOperator *E)
7457     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7458   bool VisitUnaryPlus(const UnaryOperator *E)
7459     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7460   bool VisitChooseExpr(const ChooseExpr *E)
7461     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
7462   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
7463     { return StmtVisitorTy::Visit(E->getResultExpr()); }
7464   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
7465     { return StmtVisitorTy::Visit(E->getReplacement()); }
7466   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7467     TempVersionRAII RAII(*Info.CurrentCall);
7468     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7469     return StmtVisitorTy::Visit(E->getExpr());
7470   }
7471   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7472     TempVersionRAII RAII(*Info.CurrentCall);
7473     // The initializer may not have been parsed yet, or might be erroneous.
7474     if (!E->getExpr())
7475       return Error(E);
7476     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7477     return StmtVisitorTy::Visit(E->getExpr());
7478   }
7479 
7480   bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7481     FullExpressionRAII Scope(Info);
7482     return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
7483   }
7484 
7485   // Temporaries are registered when created, so we don't care about
7486   // CXXBindTemporaryExpr.
7487   bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7488     return StmtVisitorTy::Visit(E->getSubExpr());
7489   }
7490 
7491   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7492     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7493     return static_cast<Derived*>(this)->VisitCastExpr(E);
7494   }
7495   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7496     if (!Info.Ctx.getLangOpts().CPlusPlus20)
7497       CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
7498     return static_cast<Derived*>(this)->VisitCastExpr(E);
7499   }
7500   bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7501     return static_cast<Derived*>(this)->VisitCastExpr(E);
7502   }
7503 
7504   bool VisitBinaryOperator(const BinaryOperator *E) {
7505     switch (E->getOpcode()) {
7506     default:
7507       return Error(E);
7508 
7509     case BO_Comma:
7510       VisitIgnoredValue(E->getLHS());
7511       return StmtVisitorTy::Visit(E->getRHS());
7512 
7513     case BO_PtrMemD:
7514     case BO_PtrMemI: {
7515       LValue Obj;
7516       if (!HandleMemberPointerAccess(Info, E, Obj))
7517         return false;
7518       APValue Result;
7519       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7520         return false;
7521       return DerivedSuccess(Result, E);
7522     }
7523     }
7524   }
7525 
7526   bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
7527     return StmtVisitorTy::Visit(E->getSemanticForm());
7528   }
7529 
7530   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7531     // Evaluate and cache the common expression. We treat it as a temporary,
7532     // even though it's not quite the same thing.
7533     LValue CommonLV;
7534     if (!Evaluate(Info.CurrentCall->createTemporary(
7535                       E->getOpaqueValue(),
7536                       getStorageType(Info.Ctx, E->getOpaqueValue()),
7537                       ScopeKind::FullExpression, CommonLV),
7538                   Info, E->getCommon()))
7539       return false;
7540 
7541     return HandleConditionalOperator(E);
7542   }
7543 
7544   bool VisitConditionalOperator(const ConditionalOperator *E) {
7545     bool IsBcpCall = false;
7546     // If the condition (ignoring parens) is a __builtin_constant_p call,
7547     // the result is a constant expression if it can be folded without
7548     // side-effects. This is an important GNU extension. See GCC PR38377
7549     // for discussion.
7550     if (const CallExpr *CallCE =
7551           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7552       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7553         IsBcpCall = true;
7554 
7555     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7556     // constant expression; we can't check whether it's potentially foldable.
7557     // FIXME: We should instead treat __builtin_constant_p as non-constant if
7558     // it would return 'false' in this mode.
7559     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
7560       return false;
7561 
7562     FoldConstant Fold(Info, IsBcpCall);
7563     if (!HandleConditionalOperator(E)) {
7564       Fold.keepDiagnostics();
7565       return false;
7566     }
7567 
7568     return true;
7569   }
7570 
7571   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7572     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
7573       return DerivedSuccess(*Value, E);
7574 
7575     const Expr *Source = E->getSourceExpr();
7576     if (!Source)
7577       return Error(E);
7578     if (Source == E) {
7579       assert(0 && "OpaqueValueExpr recursively refers to itself");
7580       return Error(E);
7581     }
7582     return StmtVisitorTy::Visit(Source);
7583   }
7584 
7585   bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7586     for (const Expr *SemE : E->semantics()) {
7587       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7588         // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7589         // result expression: there could be two different LValues that would
7590         // refer to the same object in that case, and we can't model that.
7591         if (SemE == E->getResultExpr())
7592           return Error(E);
7593 
7594         // Unique OVEs get evaluated if and when we encounter them when
7595         // emitting the rest of the semantic form, rather than eagerly.
7596         if (OVE->isUnique())
7597           continue;
7598 
7599         LValue LV;
7600         if (!Evaluate(Info.CurrentCall->createTemporary(
7601                           OVE, getStorageType(Info.Ctx, OVE),
7602                           ScopeKind::FullExpression, LV),
7603                       Info, OVE->getSourceExpr()))
7604           return false;
7605       } else if (SemE == E->getResultExpr()) {
7606         if (!StmtVisitorTy::Visit(SemE))
7607           return false;
7608       } else {
7609         if (!EvaluateIgnoredValue(Info, SemE))
7610           return false;
7611       }
7612     }
7613     return true;
7614   }
7615 
7616   bool VisitCallExpr(const CallExpr *E) {
7617     APValue Result;
7618     if (!handleCallExpr(E, Result, nullptr))
7619       return false;
7620     return DerivedSuccess(Result, E);
7621   }
7622 
7623   bool handleCallExpr(const CallExpr *E, APValue &Result,
7624                      const LValue *ResultSlot) {
7625     CallScopeRAII CallScope(Info);
7626 
7627     const Expr *Callee = E->getCallee()->IgnoreParens();
7628     QualType CalleeType = Callee->getType();
7629 
7630     const FunctionDecl *FD = nullptr;
7631     LValue *This = nullptr, ThisVal;
7632     auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
7633     bool HasQualifier = false;
7634 
7635     CallRef Call;
7636 
7637     // Extract function decl and 'this' pointer from the callee.
7638     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7639       const CXXMethodDecl *Member = nullptr;
7640       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7641         // Explicit bound member calls, such as x.f() or p->g();
7642         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7643           return false;
7644         Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7645         if (!Member)
7646           return Error(Callee);
7647         This = &ThisVal;
7648         HasQualifier = ME->hasQualifier();
7649       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
7650         // Indirect bound member calls ('.*' or '->*').
7651         const ValueDecl *D =
7652             HandleMemberPointerAccess(Info, BE, ThisVal, false);
7653         if (!D)
7654           return false;
7655         Member = dyn_cast<CXXMethodDecl>(D);
7656         if (!Member)
7657           return Error(Callee);
7658         This = &ThisVal;
7659       } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7660         if (!Info.getLangOpts().CPlusPlus20)
7661           Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7662         return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7663                HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7664       } else
7665         return Error(Callee);
7666       FD = Member;
7667     } else if (CalleeType->isFunctionPointerType()) {
7668       LValue CalleeLV;
7669       if (!EvaluatePointer(Callee, CalleeLV, Info))
7670         return false;
7671 
7672       if (!CalleeLV.getLValueOffset().isZero())
7673         return Error(Callee);
7674       FD = dyn_cast_or_null<FunctionDecl>(
7675           CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
7676       if (!FD)
7677         return Error(Callee);
7678       // Don't call function pointers which have been cast to some other type.
7679       // Per DR (no number yet), the caller and callee can differ in noexcept.
7680       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7681         CalleeType->getPointeeType(), FD->getType())) {
7682         return Error(E);
7683       }
7684 
7685       // For an (overloaded) assignment expression, evaluate the RHS before the
7686       // LHS.
7687       auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
7688       if (OCE && OCE->isAssignmentOp()) {
7689         assert(Args.size() == 2 && "wrong number of arguments in assignment");
7690         Call = Info.CurrentCall->createCall(FD);
7691         if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call,
7692                           Info, FD, /*RightToLeft=*/true))
7693           return false;
7694       }
7695 
7696       // Overloaded operator calls to member functions are represented as normal
7697       // calls with '*this' as the first argument.
7698       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7699       if (MD && !MD->isStatic()) {
7700         // FIXME: When selecting an implicit conversion for an overloaded
7701         // operator delete, we sometimes try to evaluate calls to conversion
7702         // operators without a 'this' parameter!
7703         if (Args.empty())
7704           return Error(E);
7705 
7706         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7707           return false;
7708         This = &ThisVal;
7709 
7710         // If this is syntactically a simple assignment using a trivial
7711         // assignment operator, start the lifetimes of union members as needed,
7712         // per C++20 [class.union]5.
7713         if (Info.getLangOpts().CPlusPlus20 && OCE &&
7714             OCE->getOperator() == OO_Equal && MD->isTrivial() &&
7715             !HandleUnionActiveMemberChange(Info, Args[0], ThisVal))
7716           return false;
7717 
7718         Args = Args.slice(1);
7719       } else if (MD && MD->isLambdaStaticInvoker()) {
7720         // Map the static invoker for the lambda back to the call operator.
7721         // Conveniently, we don't have to slice out the 'this' argument (as is
7722         // being done for the non-static case), since a static member function
7723         // doesn't have an implicit argument passed in.
7724         const CXXRecordDecl *ClosureClass = MD->getParent();
7725         assert(
7726             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7727             "Number of captures must be zero for conversion to function-ptr");
7728 
7729         const CXXMethodDecl *LambdaCallOp =
7730             ClosureClass->getLambdaCallOperator();
7731 
7732         // Set 'FD', the function that will be called below, to the call
7733         // operator.  If the closure object represents a generic lambda, find
7734         // the corresponding specialization of the call operator.
7735 
7736         if (ClosureClass->isGenericLambda()) {
7737           assert(MD->isFunctionTemplateSpecialization() &&
7738                  "A generic lambda's static-invoker function must be a "
7739                  "template specialization");
7740           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7741           FunctionTemplateDecl *CallOpTemplate =
7742               LambdaCallOp->getDescribedFunctionTemplate();
7743           void *InsertPos = nullptr;
7744           FunctionDecl *CorrespondingCallOpSpecialization =
7745               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7746           assert(CorrespondingCallOpSpecialization &&
7747                  "We must always have a function call operator specialization "
7748                  "that corresponds to our static invoker specialization");
7749           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7750         } else
7751           FD = LambdaCallOp;
7752       } else if (FD->isReplaceableGlobalAllocationFunction()) {
7753         if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7754             FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7755           LValue Ptr;
7756           if (!HandleOperatorNewCall(Info, E, Ptr))
7757             return false;
7758           Ptr.moveInto(Result);
7759           return CallScope.destroy();
7760         } else {
7761           return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
7762         }
7763       }
7764     } else
7765       return Error(E);
7766 
7767     // Evaluate the arguments now if we've not already done so.
7768     if (!Call) {
7769       Call = Info.CurrentCall->createCall(FD);
7770       if (!EvaluateArgs(Args, Call, Info, FD))
7771         return false;
7772     }
7773 
7774     SmallVector<QualType, 4> CovariantAdjustmentPath;
7775     if (This) {
7776       auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7777       if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
7778         // Perform virtual dispatch, if necessary.
7779         FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
7780                                    CovariantAdjustmentPath);
7781         if (!FD)
7782           return false;
7783       } else {
7784         // Check that the 'this' pointer points to an object of the right type.
7785         // FIXME: If this is an assignment operator call, we may need to change
7786         // the active union member before we check this.
7787         if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
7788           return false;
7789       }
7790     }
7791 
7792     // Destructor calls are different enough that they have their own codepath.
7793     if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
7794       assert(This && "no 'this' pointer for destructor call");
7795       return HandleDestruction(Info, E, *This,
7796                                Info.Ctx.getRecordType(DD->getParent())) &&
7797              CallScope.destroy();
7798     }
7799 
7800     const FunctionDecl *Definition = nullptr;
7801     Stmt *Body = FD->getBody(Definition);
7802 
7803     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
7804         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call,
7805                             Body, Info, Result, ResultSlot))
7806       return false;
7807 
7808     if (!CovariantAdjustmentPath.empty() &&
7809         !HandleCovariantReturnAdjustment(Info, E, Result,
7810                                          CovariantAdjustmentPath))
7811       return false;
7812 
7813     return CallScope.destroy();
7814   }
7815 
7816   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7817     return StmtVisitorTy::Visit(E->getInitializer());
7818   }
7819   bool VisitInitListExpr(const InitListExpr *E) {
7820     if (E->getNumInits() == 0)
7821       return DerivedZeroInitialization(E);
7822     if (E->getNumInits() == 1)
7823       return StmtVisitorTy::Visit(E->getInit(0));
7824     return Error(E);
7825   }
7826   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
7827     return DerivedZeroInitialization(E);
7828   }
7829   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
7830     return DerivedZeroInitialization(E);
7831   }
7832   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
7833     return DerivedZeroInitialization(E);
7834   }
7835 
7836   /// A member expression where the object is a prvalue is itself a prvalue.
7837   bool VisitMemberExpr(const MemberExpr *E) {
7838     assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
7839            "missing temporary materialization conversion");
7840     assert(!E->isArrow() && "missing call to bound member function?");
7841 
7842     APValue Val;
7843     if (!Evaluate(Val, Info, E->getBase()))
7844       return false;
7845 
7846     QualType BaseTy = E->getBase()->getType();
7847 
7848     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
7849     if (!FD) return Error(E);
7850     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
7851     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7852            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7853 
7854     // Note: there is no lvalue base here. But this case should only ever
7855     // happen in C or in C++98, where we cannot be evaluating a constexpr
7856     // constructor, which is the only case the base matters.
7857     CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
7858     SubobjectDesignator Designator(BaseTy);
7859     Designator.addDeclUnchecked(FD);
7860 
7861     APValue Result;
7862     return extractSubobject(Info, E, Obj, Designator, Result) &&
7863            DerivedSuccess(Result, E);
7864   }
7865 
7866   bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
7867     APValue Val;
7868     if (!Evaluate(Val, Info, E->getBase()))
7869       return false;
7870 
7871     if (Val.isVector()) {
7872       SmallVector<uint32_t, 4> Indices;
7873       E->getEncodedElementAccess(Indices);
7874       if (Indices.size() == 1) {
7875         // Return scalar.
7876         return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
7877       } else {
7878         // Construct new APValue vector.
7879         SmallVector<APValue, 4> Elts;
7880         for (unsigned I = 0; I < Indices.size(); ++I) {
7881           Elts.push_back(Val.getVectorElt(Indices[I]));
7882         }
7883         APValue VecResult(Elts.data(), Indices.size());
7884         return DerivedSuccess(VecResult, E);
7885       }
7886     }
7887 
7888     return false;
7889   }
7890 
7891   bool VisitCastExpr(const CastExpr *E) {
7892     switch (E->getCastKind()) {
7893     default:
7894       break;
7895 
7896     case CK_AtomicToNonAtomic: {
7897       APValue AtomicVal;
7898       // This does not need to be done in place even for class/array types:
7899       // atomic-to-non-atomic conversion implies copying the object
7900       // representation.
7901       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
7902         return false;
7903       return DerivedSuccess(AtomicVal, E);
7904     }
7905 
7906     case CK_NoOp:
7907     case CK_UserDefinedConversion:
7908       return StmtVisitorTy::Visit(E->getSubExpr());
7909 
7910     case CK_LValueToRValue: {
7911       LValue LVal;
7912       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
7913         return false;
7914       APValue RVal;
7915       // Note, we use the subexpression's type in order to retain cv-qualifiers.
7916       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7917                                           LVal, RVal))
7918         return false;
7919       return DerivedSuccess(RVal, E);
7920     }
7921     case CK_LValueToRValueBitCast: {
7922       APValue DestValue, SourceValue;
7923       if (!Evaluate(SourceValue, Info, E->getSubExpr()))
7924         return false;
7925       if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
7926         return false;
7927       return DerivedSuccess(DestValue, E);
7928     }
7929 
7930     case CK_AddressSpaceConversion: {
7931       APValue Value;
7932       if (!Evaluate(Value, Info, E->getSubExpr()))
7933         return false;
7934       return DerivedSuccess(Value, E);
7935     }
7936     }
7937 
7938     return Error(E);
7939   }
7940 
7941   bool VisitUnaryPostInc(const UnaryOperator *UO) {
7942     return VisitUnaryPostIncDec(UO);
7943   }
7944   bool VisitUnaryPostDec(const UnaryOperator *UO) {
7945     return VisitUnaryPostIncDec(UO);
7946   }
7947   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
7948     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7949       return Error(UO);
7950 
7951     LValue LVal;
7952     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
7953       return false;
7954     APValue RVal;
7955     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
7956                       UO->isIncrementOp(), &RVal))
7957       return false;
7958     return DerivedSuccess(RVal, UO);
7959   }
7960 
7961   bool VisitStmtExpr(const StmtExpr *E) {
7962     // We will have checked the full-expressions inside the statement expression
7963     // when they were completed, and don't need to check them again now.
7964     llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
7965                                           false);
7966 
7967     const CompoundStmt *CS = E->getSubStmt();
7968     if (CS->body_empty())
7969       return true;
7970 
7971     BlockScopeRAII Scope(Info);
7972     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
7973                                            BE = CS->body_end();
7974          /**/; ++BI) {
7975       if (BI + 1 == BE) {
7976         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
7977         if (!FinalExpr) {
7978           Info.FFDiag((*BI)->getBeginLoc(),
7979                       diag::note_constexpr_stmt_expr_unsupported);
7980           return false;
7981         }
7982         return this->Visit(FinalExpr) && Scope.destroy();
7983       }
7984 
7985       APValue ReturnValue;
7986       StmtResult Result = { ReturnValue, nullptr };
7987       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
7988       if (ESR != ESR_Succeeded) {
7989         // FIXME: If the statement-expression terminated due to 'return',
7990         // 'break', or 'continue', it would be nice to propagate that to
7991         // the outer statement evaluation rather than bailing out.
7992         if (ESR != ESR_Failed)
7993           Info.FFDiag((*BI)->getBeginLoc(),
7994                       diag::note_constexpr_stmt_expr_unsupported);
7995         return false;
7996       }
7997     }
7998 
7999     llvm_unreachable("Return from function from the loop above.");
8000   }
8001 
8002   /// Visit a value which is evaluated, but whose value is ignored.
8003   void VisitIgnoredValue(const Expr *E) {
8004     EvaluateIgnoredValue(Info, E);
8005   }
8006 
8007   /// Potentially visit a MemberExpr's base expression.
8008   void VisitIgnoredBaseExpression(const Expr *E) {
8009     // While MSVC doesn't evaluate the base expression, it does diagnose the
8010     // presence of side-effecting behavior.
8011     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
8012       return;
8013     VisitIgnoredValue(E);
8014   }
8015 };
8016 
8017 } // namespace
8018 
8019 //===----------------------------------------------------------------------===//
8020 // Common base class for lvalue and temporary evaluation.
8021 //===----------------------------------------------------------------------===//
8022 namespace {
8023 template<class Derived>
8024 class LValueExprEvaluatorBase
8025   : public ExprEvaluatorBase<Derived> {
8026 protected:
8027   LValue &Result;
8028   bool InvalidBaseOK;
8029   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
8030   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
8031 
8032   bool Success(APValue::LValueBase B) {
8033     Result.set(B);
8034     return true;
8035   }
8036 
8037   bool evaluatePointer(const Expr *E, LValue &Result) {
8038     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
8039   }
8040 
8041 public:
8042   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
8043       : ExprEvaluatorBaseTy(Info), Result(Result),
8044         InvalidBaseOK(InvalidBaseOK) {}
8045 
8046   bool Success(const APValue &V, const Expr *E) {
8047     Result.setFrom(this->Info.Ctx, V);
8048     return true;
8049   }
8050 
8051   bool VisitMemberExpr(const MemberExpr *E) {
8052     // Handle non-static data members.
8053     QualType BaseTy;
8054     bool EvalOK;
8055     if (E->isArrow()) {
8056       EvalOK = evaluatePointer(E->getBase(), Result);
8057       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
8058     } else if (E->getBase()->isPRValue()) {
8059       assert(E->getBase()->getType()->isRecordType());
8060       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
8061       BaseTy = E->getBase()->getType();
8062     } else {
8063       EvalOK = this->Visit(E->getBase());
8064       BaseTy = E->getBase()->getType();
8065     }
8066     if (!EvalOK) {
8067       if (!InvalidBaseOK)
8068         return false;
8069       Result.setInvalid(E);
8070       return true;
8071     }
8072 
8073     const ValueDecl *MD = E->getMemberDecl();
8074     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
8075       assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8076              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8077       (void)BaseTy;
8078       if (!HandleLValueMember(this->Info, E, Result, FD))
8079         return false;
8080     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
8081       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
8082         return false;
8083     } else
8084       return this->Error(E);
8085 
8086     if (MD->getType()->isReferenceType()) {
8087       APValue RefValue;
8088       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
8089                                           RefValue))
8090         return false;
8091       return Success(RefValue, E);
8092     }
8093     return true;
8094   }
8095 
8096   bool VisitBinaryOperator(const BinaryOperator *E) {
8097     switch (E->getOpcode()) {
8098     default:
8099       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8100 
8101     case BO_PtrMemD:
8102     case BO_PtrMemI:
8103       return HandleMemberPointerAccess(this->Info, E, Result);
8104     }
8105   }
8106 
8107   bool VisitCastExpr(const CastExpr *E) {
8108     switch (E->getCastKind()) {
8109     default:
8110       return ExprEvaluatorBaseTy::VisitCastExpr(E);
8111 
8112     case CK_DerivedToBase:
8113     case CK_UncheckedDerivedToBase:
8114       if (!this->Visit(E->getSubExpr()))
8115         return false;
8116 
8117       // Now figure out the necessary offset to add to the base LV to get from
8118       // the derived class to the base class.
8119       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8120                                   Result);
8121     }
8122   }
8123 };
8124 }
8125 
8126 //===----------------------------------------------------------------------===//
8127 // LValue Evaluation
8128 //
8129 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8130 // function designators (in C), decl references to void objects (in C), and
8131 // temporaries (if building with -Wno-address-of-temporary).
8132 //
8133 // LValue evaluation produces values comprising a base expression of one of the
8134 // following types:
8135 // - Declarations
8136 //  * VarDecl
8137 //  * FunctionDecl
8138 // - Literals
8139 //  * CompoundLiteralExpr in C (and in global scope in C++)
8140 //  * StringLiteral
8141 //  * PredefinedExpr
8142 //  * ObjCStringLiteralExpr
8143 //  * ObjCEncodeExpr
8144 //  * AddrLabelExpr
8145 //  * BlockExpr
8146 //  * CallExpr for a MakeStringConstant builtin
8147 // - typeid(T) expressions, as TypeInfoLValues
8148 // - Locals and temporaries
8149 //  * MaterializeTemporaryExpr
8150 //  * Any Expr, with a CallIndex indicating the function in which the temporary
8151 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
8152 //    from the AST (FIXME).
8153 //  * A MaterializeTemporaryExpr that has static storage duration, with no
8154 //    CallIndex, for a lifetime-extended temporary.
8155 //  * The ConstantExpr that is currently being evaluated during evaluation of an
8156 //    immediate invocation.
8157 // plus an offset in bytes.
8158 //===----------------------------------------------------------------------===//
8159 namespace {
8160 class LValueExprEvaluator
8161   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8162 public:
8163   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8164     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8165 
8166   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8167   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8168 
8169   bool VisitCallExpr(const CallExpr *E);
8170   bool VisitDeclRefExpr(const DeclRefExpr *E);
8171   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8172   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8173   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8174   bool VisitMemberExpr(const MemberExpr *E);
8175   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
8176   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8177   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8178   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8179   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8180   bool VisitUnaryDeref(const UnaryOperator *E);
8181   bool VisitUnaryReal(const UnaryOperator *E);
8182   bool VisitUnaryImag(const UnaryOperator *E);
8183   bool VisitUnaryPreInc(const UnaryOperator *UO) {
8184     return VisitUnaryPreIncDec(UO);
8185   }
8186   bool VisitUnaryPreDec(const UnaryOperator *UO) {
8187     return VisitUnaryPreIncDec(UO);
8188   }
8189   bool VisitBinAssign(const BinaryOperator *BO);
8190   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8191 
8192   bool VisitCastExpr(const CastExpr *E) {
8193     switch (E->getCastKind()) {
8194     default:
8195       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8196 
8197     case CK_LValueBitCast:
8198       this->CCEDiag(E, diag::note_constexpr_invalid_cast)
8199           << 2 << Info.Ctx.getLangOpts().CPlusPlus;
8200       if (!Visit(E->getSubExpr()))
8201         return false;
8202       Result.Designator.setInvalid();
8203       return true;
8204 
8205     case CK_BaseToDerived:
8206       if (!Visit(E->getSubExpr()))
8207         return false;
8208       return HandleBaseToDerivedCast(Info, E, Result);
8209 
8210     case CK_Dynamic:
8211       if (!Visit(E->getSubExpr()))
8212         return false;
8213       return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8214     }
8215   }
8216 };
8217 } // end anonymous namespace
8218 
8219 /// Evaluate an expression as an lvalue. This can be legitimately called on
8220 /// expressions which are not glvalues, in three cases:
8221 ///  * function designators in C, and
8222 ///  * "extern void" objects
8223 ///  * @selector() expressions in Objective-C
8224 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
8225                            bool InvalidBaseOK) {
8226   assert(!E->isValueDependent());
8227   assert(E->isGLValue() || E->getType()->isFunctionType() ||
8228          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E->IgnoreParens()));
8229   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8230 }
8231 
8232 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
8233   const NamedDecl *D = E->getDecl();
8234   if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl,
8235           UnnamedGlobalConstantDecl>(D))
8236     return Success(cast<ValueDecl>(D));
8237   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
8238     return VisitVarDecl(E, VD);
8239   if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
8240     return Visit(BD->getBinding());
8241   return Error(E);
8242 }
8243 
8244 
8245 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
8246 
8247   // If we are within a lambda's call operator, check whether the 'VD' referred
8248   // to within 'E' actually represents a lambda-capture that maps to a
8249   // data-member/field within the closure object, and if so, evaluate to the
8250   // field or what the field refers to.
8251   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
8252       isa<DeclRefExpr>(E) &&
8253       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
8254     // We don't always have a complete capture-map when checking or inferring if
8255     // the function call operator meets the requirements of a constexpr function
8256     // - but we don't need to evaluate the captures to determine constexprness
8257     // (dcl.constexpr C++17).
8258     if (Info.checkingPotentialConstantExpression())
8259       return false;
8260 
8261     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
8262       // Start with 'Result' referring to the complete closure object...
8263       Result = *Info.CurrentCall->This;
8264       // ... then update it to refer to the field of the closure object
8265       // that represents the capture.
8266       if (!HandleLValueMember(Info, E, Result, FD))
8267         return false;
8268       // And if the field is of reference type, update 'Result' to refer to what
8269       // the field refers to.
8270       if (FD->getType()->isReferenceType()) {
8271         APValue RVal;
8272         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
8273                                             RVal))
8274           return false;
8275         Result.setFrom(Info.Ctx, RVal);
8276       }
8277       return true;
8278     }
8279   }
8280 
8281   CallStackFrame *Frame = nullptr;
8282   unsigned Version = 0;
8283   if (VD->hasLocalStorage()) {
8284     // Only if a local variable was declared in the function currently being
8285     // evaluated, do we expect to be able to find its value in the current
8286     // frame. (Otherwise it was likely declared in an enclosing context and
8287     // could either have a valid evaluatable value (for e.g. a constexpr
8288     // variable) or be ill-formed (and trigger an appropriate evaluation
8289     // diagnostic)).
8290     CallStackFrame *CurrFrame = Info.CurrentCall;
8291     if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
8292       // Function parameters are stored in some caller's frame. (Usually the
8293       // immediate caller, but for an inherited constructor they may be more
8294       // distant.)
8295       if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
8296         if (CurrFrame->Arguments) {
8297           VD = CurrFrame->Arguments.getOrigParam(PVD);
8298           Frame =
8299               Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
8300           Version = CurrFrame->Arguments.Version;
8301         }
8302       } else {
8303         Frame = CurrFrame;
8304         Version = CurrFrame->getCurrentTemporaryVersion(VD);
8305       }
8306     }
8307   }
8308 
8309   if (!VD->getType()->isReferenceType()) {
8310     if (Frame) {
8311       Result.set({VD, Frame->Index, Version});
8312       return true;
8313     }
8314     return Success(VD);
8315   }
8316 
8317   if (!Info.getLangOpts().CPlusPlus11) {
8318     Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
8319         << VD << VD->getType();
8320     Info.Note(VD->getLocation(), diag::note_declared_at);
8321   }
8322 
8323   APValue *V;
8324   if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
8325     return false;
8326   if (!V->hasValue()) {
8327     // FIXME: Is it possible for V to be indeterminate here? If so, we should
8328     // adjust the diagnostic to say that.
8329     if (!Info.checkingPotentialConstantExpression())
8330       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
8331     return false;
8332   }
8333   return Success(*V, E);
8334 }
8335 
8336 bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {
8337   if (!IsConstantEvaluatedBuiltinCall(E))
8338     return ExprEvaluatorBaseTy::VisitCallExpr(E);
8339 
8340   switch (E->getBuiltinCallee()) {
8341   default:
8342     return false;
8343   case Builtin::BIas_const:
8344   case Builtin::BIforward:
8345   case Builtin::BImove:
8346   case Builtin::BImove_if_noexcept:
8347     if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())
8348       return Visit(E->getArg(0));
8349     break;
8350   }
8351 
8352   return ExprEvaluatorBaseTy::VisitCallExpr(E);
8353 }
8354 
8355 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
8356     const MaterializeTemporaryExpr *E) {
8357   // Walk through the expression to find the materialized temporary itself.
8358   SmallVector<const Expr *, 2> CommaLHSs;
8359   SmallVector<SubobjectAdjustment, 2> Adjustments;
8360   const Expr *Inner =
8361       E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
8362 
8363   // If we passed any comma operators, evaluate their LHSs.
8364   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
8365     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
8366       return false;
8367 
8368   // A materialized temporary with static storage duration can appear within the
8369   // result of a constant expression evaluation, so we need to preserve its
8370   // value for use outside this evaluation.
8371   APValue *Value;
8372   if (E->getStorageDuration() == SD_Static) {
8373     // FIXME: What about SD_Thread?
8374     Value = E->getOrCreateValue(true);
8375     *Value = APValue();
8376     Result.set(E);
8377   } else {
8378     Value = &Info.CurrentCall->createTemporary(
8379         E, E->getType(),
8380         E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
8381                                                      : ScopeKind::Block,
8382         Result);
8383   }
8384 
8385   QualType Type = Inner->getType();
8386 
8387   // Materialize the temporary itself.
8388   if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
8389     *Value = APValue();
8390     return false;
8391   }
8392 
8393   // Adjust our lvalue to refer to the desired subobject.
8394   for (unsigned I = Adjustments.size(); I != 0; /**/) {
8395     --I;
8396     switch (Adjustments[I].Kind) {
8397     case SubobjectAdjustment::DerivedToBaseAdjustment:
8398       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
8399                                 Type, Result))
8400         return false;
8401       Type = Adjustments[I].DerivedToBase.BasePath->getType();
8402       break;
8403 
8404     case SubobjectAdjustment::FieldAdjustment:
8405       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
8406         return false;
8407       Type = Adjustments[I].Field->getType();
8408       break;
8409 
8410     case SubobjectAdjustment::MemberPointerAdjustment:
8411       if (!HandleMemberPointerAccess(this->Info, Type, Result,
8412                                      Adjustments[I].Ptr.RHS))
8413         return false;
8414       Type = Adjustments[I].Ptr.MPT->getPointeeType();
8415       break;
8416     }
8417   }
8418 
8419   return true;
8420 }
8421 
8422 bool
8423 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8424   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
8425          "lvalue compound literal in c++?");
8426   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
8427   // only see this when folding in C, so there's no standard to follow here.
8428   return Success(E);
8429 }
8430 
8431 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
8432   TypeInfoLValue TypeInfo;
8433 
8434   if (!E->isPotentiallyEvaluated()) {
8435     if (E->isTypeOperand())
8436       TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
8437     else
8438       TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
8439   } else {
8440     if (!Info.Ctx.getLangOpts().CPlusPlus20) {
8441       Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
8442         << E->getExprOperand()->getType()
8443         << E->getExprOperand()->getSourceRange();
8444     }
8445 
8446     if (!Visit(E->getExprOperand()))
8447       return false;
8448 
8449     std::optional<DynamicType> DynType =
8450         ComputeDynamicType(Info, E, Result, AK_TypeId);
8451     if (!DynType)
8452       return false;
8453 
8454     TypeInfo =
8455         TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
8456   }
8457 
8458   return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
8459 }
8460 
8461 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
8462   return Success(E->getGuidDecl());
8463 }
8464 
8465 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
8466   // Handle static data members.
8467   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
8468     VisitIgnoredBaseExpression(E->getBase());
8469     return VisitVarDecl(E, VD);
8470   }
8471 
8472   // Handle static member functions.
8473   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
8474     if (MD->isStatic()) {
8475       VisitIgnoredBaseExpression(E->getBase());
8476       return Success(MD);
8477     }
8478   }
8479 
8480   // Handle non-static data members.
8481   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
8482 }
8483 
8484 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
8485   // FIXME: Deal with vectors as array subscript bases.
8486   if (E->getBase()->getType()->isVectorType() ||
8487       E->getBase()->getType()->isVLSTBuiltinType())
8488     return Error(E);
8489 
8490   APSInt Index;
8491   bool Success = true;
8492 
8493   // C++17's rules require us to evaluate the LHS first, regardless of which
8494   // side is the base.
8495   for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
8496     if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
8497                                 : !EvaluateInteger(SubExpr, Index, Info)) {
8498       if (!Info.noteFailure())
8499         return false;
8500       Success = false;
8501     }
8502   }
8503 
8504   return Success &&
8505          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
8506 }
8507 
8508 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
8509   return evaluatePointer(E->getSubExpr(), Result);
8510 }
8511 
8512 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8513   if (!Visit(E->getSubExpr()))
8514     return false;
8515   // __real is a no-op on scalar lvalues.
8516   if (E->getSubExpr()->getType()->isAnyComplexType())
8517     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
8518   return true;
8519 }
8520 
8521 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8522   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
8523          "lvalue __imag__ on scalar?");
8524   if (!Visit(E->getSubExpr()))
8525     return false;
8526   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
8527   return true;
8528 }
8529 
8530 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
8531   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8532     return Error(UO);
8533 
8534   if (!this->Visit(UO->getSubExpr()))
8535     return false;
8536 
8537   return handleIncDec(
8538       this->Info, UO, Result, UO->getSubExpr()->getType(),
8539       UO->isIncrementOp(), nullptr);
8540 }
8541 
8542 bool LValueExprEvaluator::VisitCompoundAssignOperator(
8543     const CompoundAssignOperator *CAO) {
8544   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8545     return Error(CAO);
8546 
8547   bool Success = true;
8548 
8549   // C++17 onwards require that we evaluate the RHS first.
8550   APValue RHS;
8551   if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
8552     if (!Info.noteFailure())
8553       return false;
8554     Success = false;
8555   }
8556 
8557   // The overall lvalue result is the result of evaluating the LHS.
8558   if (!this->Visit(CAO->getLHS()) || !Success)
8559     return false;
8560 
8561   return handleCompoundAssignment(
8562       this->Info, CAO,
8563       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
8564       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
8565 }
8566 
8567 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
8568   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8569     return Error(E);
8570 
8571   bool Success = true;
8572 
8573   // C++17 onwards require that we evaluate the RHS first.
8574   APValue NewVal;
8575   if (!Evaluate(NewVal, this->Info, E->getRHS())) {
8576     if (!Info.noteFailure())
8577       return false;
8578     Success = false;
8579   }
8580 
8581   if (!this->Visit(E->getLHS()) || !Success)
8582     return false;
8583 
8584   if (Info.getLangOpts().CPlusPlus20 &&
8585       !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
8586     return false;
8587 
8588   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
8589                           NewVal);
8590 }
8591 
8592 //===----------------------------------------------------------------------===//
8593 // Pointer Evaluation
8594 //===----------------------------------------------------------------------===//
8595 
8596 /// Attempts to compute the number of bytes available at the pointer
8597 /// returned by a function with the alloc_size attribute. Returns true if we
8598 /// were successful. Places an unsigned number into `Result`.
8599 ///
8600 /// This expects the given CallExpr to be a call to a function with an
8601 /// alloc_size attribute.
8602 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8603                                             const CallExpr *Call,
8604                                             llvm::APInt &Result) {
8605   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
8606 
8607   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
8608   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
8609   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
8610   if (Call->getNumArgs() <= SizeArgNo)
8611     return false;
8612 
8613   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
8614     Expr::EvalResult ExprResult;
8615     if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
8616       return false;
8617     Into = ExprResult.Val.getInt();
8618     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
8619       return false;
8620     Into = Into.zext(BitsInSizeT);
8621     return true;
8622   };
8623 
8624   APSInt SizeOfElem;
8625   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
8626     return false;
8627 
8628   if (!AllocSize->getNumElemsParam().isValid()) {
8629     Result = std::move(SizeOfElem);
8630     return true;
8631   }
8632 
8633   APSInt NumberOfElems;
8634   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
8635   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
8636     return false;
8637 
8638   bool Overflow;
8639   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
8640   if (Overflow)
8641     return false;
8642 
8643   Result = std::move(BytesAvailable);
8644   return true;
8645 }
8646 
8647 /// Convenience function. LVal's base must be a call to an alloc_size
8648 /// function.
8649 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8650                                             const LValue &LVal,
8651                                             llvm::APInt &Result) {
8652   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8653          "Can't get the size of a non alloc_size function");
8654   const auto *Base = LVal.getLValueBase().get<const Expr *>();
8655   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
8656   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
8657 }
8658 
8659 /// Attempts to evaluate the given LValueBase as the result of a call to
8660 /// a function with the alloc_size attribute. If it was possible to do so, this
8661 /// function will return true, make Result's Base point to said function call,
8662 /// and mark Result's Base as invalid.
8663 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
8664                                       LValue &Result) {
8665   if (Base.isNull())
8666     return false;
8667 
8668   // Because we do no form of static analysis, we only support const variables.
8669   //
8670   // Additionally, we can't support parameters, nor can we support static
8671   // variables (in the latter case, use-before-assign isn't UB; in the former,
8672   // we have no clue what they'll be assigned to).
8673   const auto *VD =
8674       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
8675   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
8676     return false;
8677 
8678   const Expr *Init = VD->getAnyInitializer();
8679   if (!Init || Init->getType().isNull())
8680     return false;
8681 
8682   const Expr *E = Init->IgnoreParens();
8683   if (!tryUnwrapAllocSizeCall(E))
8684     return false;
8685 
8686   // Store E instead of E unwrapped so that the type of the LValue's base is
8687   // what the user wanted.
8688   Result.setInvalid(E);
8689 
8690   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
8691   Result.addUnsizedArray(Info, E, Pointee);
8692   return true;
8693 }
8694 
8695 namespace {
8696 class PointerExprEvaluator
8697   : public ExprEvaluatorBase<PointerExprEvaluator> {
8698   LValue &Result;
8699   bool InvalidBaseOK;
8700 
8701   bool Success(const Expr *E) {
8702     Result.set(E);
8703     return true;
8704   }
8705 
8706   bool evaluateLValue(const Expr *E, LValue &Result) {
8707     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
8708   }
8709 
8710   bool evaluatePointer(const Expr *E, LValue &Result) {
8711     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
8712   }
8713 
8714   bool visitNonBuiltinCallExpr(const CallExpr *E);
8715 public:
8716 
8717   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
8718       : ExprEvaluatorBaseTy(info), Result(Result),
8719         InvalidBaseOK(InvalidBaseOK) {}
8720 
8721   bool Success(const APValue &V, const Expr *E) {
8722     Result.setFrom(Info.Ctx, V);
8723     return true;
8724   }
8725   bool ZeroInitialization(const Expr *E) {
8726     Result.setNull(Info.Ctx, E->getType());
8727     return true;
8728   }
8729 
8730   bool VisitBinaryOperator(const BinaryOperator *E);
8731   bool VisitCastExpr(const CastExpr* E);
8732   bool VisitUnaryAddrOf(const UnaryOperator *E);
8733   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
8734       { return Success(E); }
8735   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
8736     if (E->isExpressibleAsConstantInitializer())
8737       return Success(E);
8738     if (Info.noteFailure())
8739       EvaluateIgnoredValue(Info, E->getSubExpr());
8740     return Error(E);
8741   }
8742   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
8743       { return Success(E); }
8744   bool VisitCallExpr(const CallExpr *E);
8745   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
8746   bool VisitBlockExpr(const BlockExpr *E) {
8747     if (!E->getBlockDecl()->hasCaptures())
8748       return Success(E);
8749     return Error(E);
8750   }
8751   bool VisitCXXThisExpr(const CXXThisExpr *E) {
8752     // Can't look at 'this' when checking a potential constant expression.
8753     if (Info.checkingPotentialConstantExpression())
8754       return false;
8755     if (!Info.CurrentCall->This) {
8756       if (Info.getLangOpts().CPlusPlus11)
8757         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
8758       else
8759         Info.FFDiag(E);
8760       return false;
8761     }
8762     Result = *Info.CurrentCall->This;
8763     // If we are inside a lambda's call operator, the 'this' expression refers
8764     // to the enclosing '*this' object (either by value or reference) which is
8765     // either copied into the closure object's field that represents the '*this'
8766     // or refers to '*this'.
8767     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
8768       // Ensure we actually have captured 'this'. (an error will have
8769       // been previously reported if not).
8770       if (!Info.CurrentCall->LambdaThisCaptureField)
8771         return false;
8772 
8773       // Update 'Result' to refer to the data member/field of the closure object
8774       // that represents the '*this' capture.
8775       if (!HandleLValueMember(Info, E, Result,
8776                              Info.CurrentCall->LambdaThisCaptureField))
8777         return false;
8778       // If we captured '*this' by reference, replace the field with its referent.
8779       if (Info.CurrentCall->LambdaThisCaptureField->getType()
8780               ->isPointerType()) {
8781         APValue RVal;
8782         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
8783                                             RVal))
8784           return false;
8785 
8786         Result.setFrom(Info.Ctx, RVal);
8787       }
8788     }
8789     return true;
8790   }
8791 
8792   bool VisitCXXNewExpr(const CXXNewExpr *E);
8793 
8794   bool VisitSourceLocExpr(const SourceLocExpr *E) {
8795     assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
8796     APValue LValResult = E->EvaluateInContext(
8797         Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8798     Result.setFrom(Info.Ctx, LValResult);
8799     return true;
8800   }
8801 
8802   bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
8803     std::string ResultStr = E->ComputeName(Info.Ctx);
8804 
8805     QualType CharTy = Info.Ctx.CharTy.withConst();
8806     APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
8807                ResultStr.size() + 1);
8808     QualType ArrayTy = Info.Ctx.getConstantArrayType(CharTy, Size, nullptr,
8809                                                      ArrayType::Normal, 0);
8810 
8811     StringLiteral *SL =
8812         StringLiteral::Create(Info.Ctx, ResultStr, StringLiteral::Ordinary,
8813                               /*Pascal*/ false, ArrayTy, E->getLocation());
8814 
8815     evaluateLValue(SL, Result);
8816     Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
8817     return true;
8818   }
8819 
8820   // FIXME: Missing: @protocol, @selector
8821 };
8822 } // end anonymous namespace
8823 
8824 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
8825                             bool InvalidBaseOK) {
8826   assert(!E->isValueDependent());
8827   assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
8828   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8829 }
8830 
8831 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8832   if (E->getOpcode() != BO_Add &&
8833       E->getOpcode() != BO_Sub)
8834     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8835 
8836   const Expr *PExp = E->getLHS();
8837   const Expr *IExp = E->getRHS();
8838   if (IExp->getType()->isPointerType())
8839     std::swap(PExp, IExp);
8840 
8841   bool EvalPtrOK = evaluatePointer(PExp, Result);
8842   if (!EvalPtrOK && !Info.noteFailure())
8843     return false;
8844 
8845   llvm::APSInt Offset;
8846   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
8847     return false;
8848 
8849   if (E->getOpcode() == BO_Sub)
8850     negateAsSigned(Offset);
8851 
8852   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
8853   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
8854 }
8855 
8856 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8857   return evaluateLValue(E->getSubExpr(), Result);
8858 }
8859 
8860 // Is the provided decl 'std::source_location::current'?
8861 static bool IsDeclSourceLocationCurrent(const FunctionDecl *FD) {
8862   if (!FD)
8863     return false;
8864   const IdentifierInfo *FnII = FD->getIdentifier();
8865   if (!FnII || !FnII->isStr("current"))
8866     return false;
8867 
8868   const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
8869   if (!RD)
8870     return false;
8871 
8872   const IdentifierInfo *ClassII = RD->getIdentifier();
8873   return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
8874 }
8875 
8876 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8877   const Expr *SubExpr = E->getSubExpr();
8878 
8879   switch (E->getCastKind()) {
8880   default:
8881     break;
8882   case CK_BitCast:
8883   case CK_CPointerToObjCPointerCast:
8884   case CK_BlockPointerToObjCPointerCast:
8885   case CK_AnyPointerToBlockPointerCast:
8886   case CK_AddressSpaceConversion:
8887     if (!Visit(SubExpr))
8888       return false;
8889     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
8890     // permitted in constant expressions in C++11. Bitcasts from cv void* are
8891     // also static_casts, but we disallow them as a resolution to DR1312.
8892     if (!E->getType()->isVoidPointerType()) {
8893       // In some circumstances, we permit casting from void* to cv1 T*, when the
8894       // actual pointee object is actually a cv2 T.
8895       bool VoidPtrCastMaybeOK =
8896           !Result.InvalidBase && !Result.Designator.Invalid &&
8897           !Result.IsNullPtr &&
8898           Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
8899                                           E->getType()->getPointeeType());
8900       // 1. We'll allow it in std::allocator::allocate, and anything which that
8901       //    calls.
8902       // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
8903       //    <source_location> header. Fixed in GCC 12 and later (2022-04-??).
8904       //    We'll allow it in the body of std::source_location::current.  GCC's
8905       //    implementation had a parameter of type `void*`, and casts from
8906       //    that back to `const __impl*` in its body.
8907       if (VoidPtrCastMaybeOK &&
8908           (Info.getStdAllocatorCaller("allocate") ||
8909            IsDeclSourceLocationCurrent(Info.CurrentCall->Callee))) {
8910         // Permitted.
8911       } else {
8912         Result.Designator.setInvalid();
8913         if (SubExpr->getType()->isVoidPointerType())
8914           CCEDiag(E, diag::note_constexpr_invalid_cast)
8915               << 3 << SubExpr->getType();
8916         else
8917           CCEDiag(E, diag::note_constexpr_invalid_cast)
8918               << 2 << Info.Ctx.getLangOpts().CPlusPlus;
8919       }
8920     }
8921     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
8922       ZeroInitialization(E);
8923     return true;
8924 
8925   case CK_DerivedToBase:
8926   case CK_UncheckedDerivedToBase:
8927     if (!evaluatePointer(E->getSubExpr(), Result))
8928       return false;
8929     if (!Result.Base && Result.Offset.isZero())
8930       return true;
8931 
8932     // Now figure out the necessary offset to add to the base LV to get from
8933     // the derived class to the base class.
8934     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
8935                                   castAs<PointerType>()->getPointeeType(),
8936                                 Result);
8937 
8938   case CK_BaseToDerived:
8939     if (!Visit(E->getSubExpr()))
8940       return false;
8941     if (!Result.Base && Result.Offset.isZero())
8942       return true;
8943     return HandleBaseToDerivedCast(Info, E, Result);
8944 
8945   case CK_Dynamic:
8946     if (!Visit(E->getSubExpr()))
8947       return false;
8948     return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8949 
8950   case CK_NullToPointer:
8951     VisitIgnoredValue(E->getSubExpr());
8952     return ZeroInitialization(E);
8953 
8954   case CK_IntegralToPointer: {
8955     CCEDiag(E, diag::note_constexpr_invalid_cast)
8956         << 2 << Info.Ctx.getLangOpts().CPlusPlus;
8957 
8958     APValue Value;
8959     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
8960       break;
8961 
8962     if (Value.isInt()) {
8963       unsigned Size = Info.Ctx.getTypeSize(E->getType());
8964       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
8965       Result.Base = (Expr*)nullptr;
8966       Result.InvalidBase = false;
8967       Result.Offset = CharUnits::fromQuantity(N);
8968       Result.Designator.setInvalid();
8969       Result.IsNullPtr = false;
8970       return true;
8971     } else {
8972       // Cast is of an lvalue, no need to change value.
8973       Result.setFrom(Info.Ctx, Value);
8974       return true;
8975     }
8976   }
8977 
8978   case CK_ArrayToPointerDecay: {
8979     if (SubExpr->isGLValue()) {
8980       if (!evaluateLValue(SubExpr, Result))
8981         return false;
8982     } else {
8983       APValue &Value = Info.CurrentCall->createTemporary(
8984           SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
8985       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
8986         return false;
8987     }
8988     // The result is a pointer to the first element of the array.
8989     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
8990     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
8991       Result.addArray(Info, E, CAT);
8992     else
8993       Result.addUnsizedArray(Info, E, AT->getElementType());
8994     return true;
8995   }
8996 
8997   case CK_FunctionToPointerDecay:
8998     return evaluateLValue(SubExpr, Result);
8999 
9000   case CK_LValueToRValue: {
9001     LValue LVal;
9002     if (!evaluateLValue(E->getSubExpr(), LVal))
9003       return false;
9004 
9005     APValue RVal;
9006     // Note, we use the subexpression's type in order to retain cv-qualifiers.
9007     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
9008                                         LVal, RVal))
9009       return InvalidBaseOK &&
9010              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
9011     return Success(RVal, E);
9012   }
9013   }
9014 
9015   return ExprEvaluatorBaseTy::VisitCastExpr(E);
9016 }
9017 
9018 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
9019                                 UnaryExprOrTypeTrait ExprKind) {
9020   // C++ [expr.alignof]p3:
9021   //     When alignof is applied to a reference type, the result is the
9022   //     alignment of the referenced type.
9023   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
9024     T = Ref->getPointeeType();
9025 
9026   if (T.getQualifiers().hasUnaligned())
9027     return CharUnits::One();
9028 
9029   const bool AlignOfReturnsPreferred =
9030       Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
9031 
9032   // __alignof is defined to return the preferred alignment.
9033   // Before 8, clang returned the preferred alignment for alignof and _Alignof
9034   // as well.
9035   if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
9036     return Info.Ctx.toCharUnitsFromBits(
9037       Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
9038   // alignof and _Alignof are defined to return the ABI alignment.
9039   else if (ExprKind == UETT_AlignOf)
9040     return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
9041   else
9042     llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
9043 }
9044 
9045 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
9046                                 UnaryExprOrTypeTrait ExprKind) {
9047   E = E->IgnoreParens();
9048 
9049   // The kinds of expressions that we have special-case logic here for
9050   // should be kept up to date with the special checks for those
9051   // expressions in Sema.
9052 
9053   // alignof decl is always accepted, even if it doesn't make sense: we default
9054   // to 1 in those cases.
9055   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9056     return Info.Ctx.getDeclAlign(DRE->getDecl(),
9057                                  /*RefAsPointee*/true);
9058 
9059   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
9060     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
9061                                  /*RefAsPointee*/true);
9062 
9063   return GetAlignOfType(Info, E->getType(), ExprKind);
9064 }
9065 
9066 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
9067   if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
9068     return Info.Ctx.getDeclAlign(VD);
9069   if (const auto *E = Value.Base.dyn_cast<const Expr *>())
9070     return GetAlignOfExpr(Info, E, UETT_AlignOf);
9071   return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
9072 }
9073 
9074 /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
9075 /// __builtin_is_aligned and __builtin_assume_aligned.
9076 static bool getAlignmentArgument(const Expr *E, QualType ForType,
9077                                  EvalInfo &Info, APSInt &Alignment) {
9078   if (!EvaluateInteger(E, Alignment, Info))
9079     return false;
9080   if (Alignment < 0 || !Alignment.isPowerOf2()) {
9081     Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
9082     return false;
9083   }
9084   unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
9085   APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
9086   if (APSInt::compareValues(Alignment, MaxValue) > 0) {
9087     Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
9088         << MaxValue << ForType << Alignment;
9089     return false;
9090   }
9091   // Ensure both alignment and source value have the same bit width so that we
9092   // don't assert when computing the resulting value.
9093   APSInt ExtAlignment =
9094       APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
9095   assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
9096          "Alignment should not be changed by ext/trunc");
9097   Alignment = ExtAlignment;
9098   assert(Alignment.getBitWidth() == SrcWidth);
9099   return true;
9100 }
9101 
9102 // To be clear: this happily visits unsupported builtins. Better name welcomed.
9103 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
9104   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
9105     return true;
9106 
9107   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
9108     return false;
9109 
9110   Result.setInvalid(E);
9111   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
9112   Result.addUnsizedArray(Info, E, PointeeTy);
9113   return true;
9114 }
9115 
9116 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
9117   if (!IsConstantEvaluatedBuiltinCall(E))
9118     return visitNonBuiltinCallExpr(E);
9119   return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
9120 }
9121 
9122 // Determine if T is a character type for which we guarantee that
9123 // sizeof(T) == 1.
9124 static bool isOneByteCharacterType(QualType T) {
9125   return T->isCharType() || T->isChar8Type();
9126 }
9127 
9128 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
9129                                                 unsigned BuiltinOp) {
9130   if (IsNoOpCall(E))
9131     return Success(E);
9132 
9133   switch (BuiltinOp) {
9134   case Builtin::BIaddressof:
9135   case Builtin::BI__addressof:
9136   case Builtin::BI__builtin_addressof:
9137     return evaluateLValue(E->getArg(0), Result);
9138   case Builtin::BI__builtin_assume_aligned: {
9139     // We need to be very careful here because: if the pointer does not have the
9140     // asserted alignment, then the behavior is undefined, and undefined
9141     // behavior is non-constant.
9142     if (!evaluatePointer(E->getArg(0), Result))
9143       return false;
9144 
9145     LValue OffsetResult(Result);
9146     APSInt Alignment;
9147     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9148                               Alignment))
9149       return false;
9150     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
9151 
9152     if (E->getNumArgs() > 2) {
9153       APSInt Offset;
9154       if (!EvaluateInteger(E->getArg(2), Offset, Info))
9155         return false;
9156 
9157       int64_t AdditionalOffset = -Offset.getZExtValue();
9158       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
9159     }
9160 
9161     // If there is a base object, then it must have the correct alignment.
9162     if (OffsetResult.Base) {
9163       CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
9164 
9165       if (BaseAlignment < Align) {
9166         Result.Designator.setInvalid();
9167         // FIXME: Add support to Diagnostic for long / long long.
9168         CCEDiag(E->getArg(0),
9169                 diag::note_constexpr_baa_insufficient_alignment) << 0
9170           << (unsigned)BaseAlignment.getQuantity()
9171           << (unsigned)Align.getQuantity();
9172         return false;
9173       }
9174     }
9175 
9176     // The offset must also have the correct alignment.
9177     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
9178       Result.Designator.setInvalid();
9179 
9180       (OffsetResult.Base
9181            ? CCEDiag(E->getArg(0),
9182                      diag::note_constexpr_baa_insufficient_alignment) << 1
9183            : CCEDiag(E->getArg(0),
9184                      diag::note_constexpr_baa_value_insufficient_alignment))
9185         << (int)OffsetResult.Offset.getQuantity()
9186         << (unsigned)Align.getQuantity();
9187       return false;
9188     }
9189 
9190     return true;
9191   }
9192   case Builtin::BI__builtin_align_up:
9193   case Builtin::BI__builtin_align_down: {
9194     if (!evaluatePointer(E->getArg(0), Result))
9195       return false;
9196     APSInt Alignment;
9197     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9198                               Alignment))
9199       return false;
9200     CharUnits BaseAlignment = getBaseAlignment(Info, Result);
9201     CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
9202     // For align_up/align_down, we can return the same value if the alignment
9203     // is known to be greater or equal to the requested value.
9204     if (PtrAlign.getQuantity() >= Alignment)
9205       return true;
9206 
9207     // The alignment could be greater than the minimum at run-time, so we cannot
9208     // infer much about the resulting pointer value. One case is possible:
9209     // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
9210     // can infer the correct index if the requested alignment is smaller than
9211     // the base alignment so we can perform the computation on the offset.
9212     if (BaseAlignment.getQuantity() >= Alignment) {
9213       assert(Alignment.getBitWidth() <= 64 &&
9214              "Cannot handle > 64-bit address-space");
9215       uint64_t Alignment64 = Alignment.getZExtValue();
9216       CharUnits NewOffset = CharUnits::fromQuantity(
9217           BuiltinOp == Builtin::BI__builtin_align_down
9218               ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
9219               : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
9220       Result.adjustOffset(NewOffset - Result.Offset);
9221       // TODO: diagnose out-of-bounds values/only allow for arrays?
9222       return true;
9223     }
9224     // Otherwise, we cannot constant-evaluate the result.
9225     Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
9226         << Alignment;
9227     return false;
9228   }
9229   case Builtin::BI__builtin_operator_new:
9230     return HandleOperatorNewCall(Info, E, Result);
9231   case Builtin::BI__builtin_launder:
9232     return evaluatePointer(E->getArg(0), Result);
9233   case Builtin::BIstrchr:
9234   case Builtin::BIwcschr:
9235   case Builtin::BImemchr:
9236   case Builtin::BIwmemchr:
9237     if (Info.getLangOpts().CPlusPlus11)
9238       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9239           << /*isConstexpr*/ 0 << /*isConstructor*/ 0
9240           << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
9241     else
9242       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9243     [[fallthrough]];
9244   case Builtin::BI__builtin_strchr:
9245   case Builtin::BI__builtin_wcschr:
9246   case Builtin::BI__builtin_memchr:
9247   case Builtin::BI__builtin_char_memchr:
9248   case Builtin::BI__builtin_wmemchr: {
9249     if (!Visit(E->getArg(0)))
9250       return false;
9251     APSInt Desired;
9252     if (!EvaluateInteger(E->getArg(1), Desired, Info))
9253       return false;
9254     uint64_t MaxLength = uint64_t(-1);
9255     if (BuiltinOp != Builtin::BIstrchr &&
9256         BuiltinOp != Builtin::BIwcschr &&
9257         BuiltinOp != Builtin::BI__builtin_strchr &&
9258         BuiltinOp != Builtin::BI__builtin_wcschr) {
9259       APSInt N;
9260       if (!EvaluateInteger(E->getArg(2), N, Info))
9261         return false;
9262       MaxLength = N.getExtValue();
9263     }
9264     // We cannot find the value if there are no candidates to match against.
9265     if (MaxLength == 0u)
9266       return ZeroInitialization(E);
9267     if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9268         Result.Designator.Invalid)
9269       return false;
9270     QualType CharTy = Result.Designator.getType(Info.Ctx);
9271     bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
9272                      BuiltinOp == Builtin::BI__builtin_memchr;
9273     assert(IsRawByte ||
9274            Info.Ctx.hasSameUnqualifiedType(
9275                CharTy, E->getArg(0)->getType()->getPointeeType()));
9276     // Pointers to const void may point to objects of incomplete type.
9277     if (IsRawByte && CharTy->isIncompleteType()) {
9278       Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
9279       return false;
9280     }
9281     // Give up on byte-oriented matching against multibyte elements.
9282     // FIXME: We can compare the bytes in the correct order.
9283     if (IsRawByte && !isOneByteCharacterType(CharTy)) {
9284       Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
9285           << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str()
9286           << CharTy;
9287       return false;
9288     }
9289     // Figure out what value we're actually looking for (after converting to
9290     // the corresponding unsigned type if necessary).
9291     uint64_t DesiredVal;
9292     bool StopAtNull = false;
9293     switch (BuiltinOp) {
9294     case Builtin::BIstrchr:
9295     case Builtin::BI__builtin_strchr:
9296       // strchr compares directly to the passed integer, and therefore
9297       // always fails if given an int that is not a char.
9298       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
9299                                                   E->getArg(1)->getType(),
9300                                                   Desired),
9301                                Desired))
9302         return ZeroInitialization(E);
9303       StopAtNull = true;
9304       [[fallthrough]];
9305     case Builtin::BImemchr:
9306     case Builtin::BI__builtin_memchr:
9307     case Builtin::BI__builtin_char_memchr:
9308       // memchr compares by converting both sides to unsigned char. That's also
9309       // correct for strchr if we get this far (to cope with plain char being
9310       // unsigned in the strchr case).
9311       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
9312       break;
9313 
9314     case Builtin::BIwcschr:
9315     case Builtin::BI__builtin_wcschr:
9316       StopAtNull = true;
9317       [[fallthrough]];
9318     case Builtin::BIwmemchr:
9319     case Builtin::BI__builtin_wmemchr:
9320       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
9321       DesiredVal = Desired.getZExtValue();
9322       break;
9323     }
9324 
9325     for (; MaxLength; --MaxLength) {
9326       APValue Char;
9327       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
9328           !Char.isInt())
9329         return false;
9330       if (Char.getInt().getZExtValue() == DesiredVal)
9331         return true;
9332       if (StopAtNull && !Char.getInt())
9333         break;
9334       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
9335         return false;
9336     }
9337     // Not found: return nullptr.
9338     return ZeroInitialization(E);
9339   }
9340 
9341   case Builtin::BImemcpy:
9342   case Builtin::BImemmove:
9343   case Builtin::BIwmemcpy:
9344   case Builtin::BIwmemmove:
9345     if (Info.getLangOpts().CPlusPlus11)
9346       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9347           << /*isConstexpr*/ 0 << /*isConstructor*/ 0
9348           << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
9349     else
9350       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9351     [[fallthrough]];
9352   case Builtin::BI__builtin_memcpy:
9353   case Builtin::BI__builtin_memmove:
9354   case Builtin::BI__builtin_wmemcpy:
9355   case Builtin::BI__builtin_wmemmove: {
9356     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
9357                  BuiltinOp == Builtin::BIwmemmove ||
9358                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
9359                  BuiltinOp == Builtin::BI__builtin_wmemmove;
9360     bool Move = BuiltinOp == Builtin::BImemmove ||
9361                 BuiltinOp == Builtin::BIwmemmove ||
9362                 BuiltinOp == Builtin::BI__builtin_memmove ||
9363                 BuiltinOp == Builtin::BI__builtin_wmemmove;
9364 
9365     // The result of mem* is the first argument.
9366     if (!Visit(E->getArg(0)))
9367       return false;
9368     LValue Dest = Result;
9369 
9370     LValue Src;
9371     if (!EvaluatePointer(E->getArg(1), Src, Info))
9372       return false;
9373 
9374     APSInt N;
9375     if (!EvaluateInteger(E->getArg(2), N, Info))
9376       return false;
9377     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
9378 
9379     // If the size is zero, we treat this as always being a valid no-op.
9380     // (Even if one of the src and dest pointers is null.)
9381     if (!N)
9382       return true;
9383 
9384     // Otherwise, if either of the operands is null, we can't proceed. Don't
9385     // try to determine the type of the copied objects, because there aren't
9386     // any.
9387     if (!Src.Base || !Dest.Base) {
9388       APValue Val;
9389       (!Src.Base ? Src : Dest).moveInto(Val);
9390       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
9391           << Move << WChar << !!Src.Base
9392           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
9393       return false;
9394     }
9395     if (Src.Designator.Invalid || Dest.Designator.Invalid)
9396       return false;
9397 
9398     // We require that Src and Dest are both pointers to arrays of
9399     // trivially-copyable type. (For the wide version, the designator will be
9400     // invalid if the designated object is not a wchar_t.)
9401     QualType T = Dest.Designator.getType(Info.Ctx);
9402     QualType SrcT = Src.Designator.getType(Info.Ctx);
9403     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
9404       // FIXME: Consider using our bit_cast implementation to support this.
9405       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
9406       return false;
9407     }
9408     if (T->isIncompleteType()) {
9409       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
9410       return false;
9411     }
9412     if (!T.isTriviallyCopyableType(Info.Ctx)) {
9413       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
9414       return false;
9415     }
9416 
9417     // Figure out how many T's we're copying.
9418     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
9419     if (!WChar) {
9420       uint64_t Remainder;
9421       llvm::APInt OrigN = N;
9422       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
9423       if (Remainder) {
9424         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9425             << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
9426             << (unsigned)TSize;
9427         return false;
9428       }
9429     }
9430 
9431     // Check that the copying will remain within the arrays, just so that we
9432     // can give a more meaningful diagnostic. This implicitly also checks that
9433     // N fits into 64 bits.
9434     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
9435     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
9436     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
9437       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9438           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
9439           << toString(N, 10, /*Signed*/false);
9440       return false;
9441     }
9442     uint64_t NElems = N.getZExtValue();
9443     uint64_t NBytes = NElems * TSize;
9444 
9445     // Check for overlap.
9446     int Direction = 1;
9447     if (HasSameBase(Src, Dest)) {
9448       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
9449       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
9450       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
9451         // Dest is inside the source region.
9452         if (!Move) {
9453           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9454           return false;
9455         }
9456         // For memmove and friends, copy backwards.
9457         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
9458             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
9459           return false;
9460         Direction = -1;
9461       } else if (!Move && SrcOffset >= DestOffset &&
9462                  SrcOffset - DestOffset < NBytes) {
9463         // Src is inside the destination region for memcpy: invalid.
9464         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9465         return false;
9466       }
9467     }
9468 
9469     while (true) {
9470       APValue Val;
9471       // FIXME: Set WantObjectRepresentation to true if we're copying a
9472       // char-like type?
9473       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
9474           !handleAssignment(Info, E, Dest, T, Val))
9475         return false;
9476       // Do not iterate past the last element; if we're copying backwards, that
9477       // might take us off the start of the array.
9478       if (--NElems == 0)
9479         return true;
9480       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
9481           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
9482         return false;
9483     }
9484   }
9485 
9486   default:
9487     return false;
9488   }
9489 }
9490 
9491 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9492                                      APValue &Result, const InitListExpr *ILE,
9493                                      QualType AllocType);
9494 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
9495                                           APValue &Result,
9496                                           const CXXConstructExpr *CCE,
9497                                           QualType AllocType);
9498 
9499 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
9500   if (!Info.getLangOpts().CPlusPlus20)
9501     Info.CCEDiag(E, diag::note_constexpr_new);
9502 
9503   // We cannot speculatively evaluate a delete expression.
9504   if (Info.SpeculativeEvaluationDepth)
9505     return false;
9506 
9507   FunctionDecl *OperatorNew = E->getOperatorNew();
9508 
9509   bool IsNothrow = false;
9510   bool IsPlacement = false;
9511   if (OperatorNew->isReservedGlobalPlacementOperator() &&
9512       Info.CurrentCall->isStdFunction() && !E->isArray()) {
9513     // FIXME Support array placement new.
9514     assert(E->getNumPlacementArgs() == 1);
9515     if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
9516       return false;
9517     if (Result.Designator.Invalid)
9518       return false;
9519     IsPlacement = true;
9520   } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
9521     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
9522         << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
9523     return false;
9524   } else if (E->getNumPlacementArgs()) {
9525     // The only new-placement list we support is of the form (std::nothrow).
9526     //
9527     // FIXME: There is no restriction on this, but it's not clear that any
9528     // other form makes any sense. We get here for cases such as:
9529     //
9530     //   new (std::align_val_t{N}) X(int)
9531     //
9532     // (which should presumably be valid only if N is a multiple of
9533     // alignof(int), and in any case can't be deallocated unless N is
9534     // alignof(X) and X has new-extended alignment).
9535     if (E->getNumPlacementArgs() != 1 ||
9536         !E->getPlacementArg(0)->getType()->isNothrowT())
9537       return Error(E, diag::note_constexpr_new_placement);
9538 
9539     LValue Nothrow;
9540     if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
9541       return false;
9542     IsNothrow = true;
9543   }
9544 
9545   const Expr *Init = E->getInitializer();
9546   const InitListExpr *ResizedArrayILE = nullptr;
9547   const CXXConstructExpr *ResizedArrayCCE = nullptr;
9548   bool ValueInit = false;
9549 
9550   QualType AllocType = E->getAllocatedType();
9551   if (std::optional<const Expr *> ArraySize = E->getArraySize()) {
9552     const Expr *Stripped = *ArraySize;
9553     for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
9554          Stripped = ICE->getSubExpr())
9555       if (ICE->getCastKind() != CK_NoOp &&
9556           ICE->getCastKind() != CK_IntegralCast)
9557         break;
9558 
9559     llvm::APSInt ArrayBound;
9560     if (!EvaluateInteger(Stripped, ArrayBound, Info))
9561       return false;
9562 
9563     // C++ [expr.new]p9:
9564     //   The expression is erroneous if:
9565     //   -- [...] its value before converting to size_t [or] applying the
9566     //      second standard conversion sequence is less than zero
9567     if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
9568       if (IsNothrow)
9569         return ZeroInitialization(E);
9570 
9571       Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
9572           << ArrayBound << (*ArraySize)->getSourceRange();
9573       return false;
9574     }
9575 
9576     //   -- its value is such that the size of the allocated object would
9577     //      exceed the implementation-defined limit
9578     if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
9579                                                 ArrayBound) >
9580         ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
9581       if (IsNothrow)
9582         return ZeroInitialization(E);
9583 
9584       Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
9585         << ArrayBound << (*ArraySize)->getSourceRange();
9586       return false;
9587     }
9588 
9589     //   -- the new-initializer is a braced-init-list and the number of
9590     //      array elements for which initializers are provided [...]
9591     //      exceeds the number of elements to initialize
9592     if (!Init) {
9593       // No initialization is performed.
9594     } else if (isa<CXXScalarValueInitExpr>(Init) ||
9595                isa<ImplicitValueInitExpr>(Init)) {
9596       ValueInit = true;
9597     } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
9598       ResizedArrayCCE = CCE;
9599     } else {
9600       auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
9601       assert(CAT && "unexpected type for array initializer");
9602 
9603       unsigned Bits =
9604           std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
9605       llvm::APInt InitBound = CAT->getSize().zext(Bits);
9606       llvm::APInt AllocBound = ArrayBound.zext(Bits);
9607       if (InitBound.ugt(AllocBound)) {
9608         if (IsNothrow)
9609           return ZeroInitialization(E);
9610 
9611         Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
9612             << toString(AllocBound, 10, /*Signed=*/false)
9613             << toString(InitBound, 10, /*Signed=*/false)
9614             << (*ArraySize)->getSourceRange();
9615         return false;
9616       }
9617 
9618       // If the sizes differ, we must have an initializer list, and we need
9619       // special handling for this case when we initialize.
9620       if (InitBound != AllocBound)
9621         ResizedArrayILE = cast<InitListExpr>(Init);
9622     }
9623 
9624     AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
9625                                               ArrayType::Normal, 0);
9626   } else {
9627     assert(!AllocType->isArrayType() &&
9628            "array allocation with non-array new");
9629   }
9630 
9631   APValue *Val;
9632   if (IsPlacement) {
9633     AccessKinds AK = AK_Construct;
9634     struct FindObjectHandler {
9635       EvalInfo &Info;
9636       const Expr *E;
9637       QualType AllocType;
9638       const AccessKinds AccessKind;
9639       APValue *Value;
9640 
9641       typedef bool result_type;
9642       bool failed() { return false; }
9643       bool found(APValue &Subobj, QualType SubobjType) {
9644         // FIXME: Reject the cases where [basic.life]p8 would not permit the
9645         // old name of the object to be used to name the new object.
9646         if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
9647           Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
9648             SubobjType << AllocType;
9649           return false;
9650         }
9651         Value = &Subobj;
9652         return true;
9653       }
9654       bool found(APSInt &Value, QualType SubobjType) {
9655         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9656         return false;
9657       }
9658       bool found(APFloat &Value, QualType SubobjType) {
9659         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9660         return false;
9661       }
9662     } Handler = {Info, E, AllocType, AK, nullptr};
9663 
9664     CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
9665     if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
9666       return false;
9667 
9668     Val = Handler.Value;
9669 
9670     // [basic.life]p1:
9671     //   The lifetime of an object o of type T ends when [...] the storage
9672     //   which the object occupies is [...] reused by an object that is not
9673     //   nested within o (6.6.2).
9674     *Val = APValue();
9675   } else {
9676     // Perform the allocation and obtain a pointer to the resulting object.
9677     Val = Info.createHeapAlloc(E, AllocType, Result);
9678     if (!Val)
9679       return false;
9680   }
9681 
9682   if (ValueInit) {
9683     ImplicitValueInitExpr VIE(AllocType);
9684     if (!EvaluateInPlace(*Val, Info, Result, &VIE))
9685       return false;
9686   } else if (ResizedArrayILE) {
9687     if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
9688                                   AllocType))
9689       return false;
9690   } else if (ResizedArrayCCE) {
9691     if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
9692                                        AllocType))
9693       return false;
9694   } else if (Init) {
9695     if (!EvaluateInPlace(*Val, Info, Result, Init))
9696       return false;
9697   } else if (!getDefaultInitValue(AllocType, *Val)) {
9698     return false;
9699   }
9700 
9701   // Array new returns a pointer to the first element, not a pointer to the
9702   // array.
9703   if (auto *AT = AllocType->getAsArrayTypeUnsafe())
9704     Result.addArray(Info, E, cast<ConstantArrayType>(AT));
9705 
9706   return true;
9707 }
9708 //===----------------------------------------------------------------------===//
9709 // Member Pointer Evaluation
9710 //===----------------------------------------------------------------------===//
9711 
9712 namespace {
9713 class MemberPointerExprEvaluator
9714   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
9715   MemberPtr &Result;
9716 
9717   bool Success(const ValueDecl *D) {
9718     Result = MemberPtr(D);
9719     return true;
9720   }
9721 public:
9722 
9723   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
9724     : ExprEvaluatorBaseTy(Info), Result(Result) {}
9725 
9726   bool Success(const APValue &V, const Expr *E) {
9727     Result.setFrom(V);
9728     return true;
9729   }
9730   bool ZeroInitialization(const Expr *E) {
9731     return Success((const ValueDecl*)nullptr);
9732   }
9733 
9734   bool VisitCastExpr(const CastExpr *E);
9735   bool VisitUnaryAddrOf(const UnaryOperator *E);
9736 };
9737 } // end anonymous namespace
9738 
9739 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
9740                                   EvalInfo &Info) {
9741   assert(!E->isValueDependent());
9742   assert(E->isPRValue() && E->getType()->isMemberPointerType());
9743   return MemberPointerExprEvaluator(Info, Result).Visit(E);
9744 }
9745 
9746 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9747   switch (E->getCastKind()) {
9748   default:
9749     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9750 
9751   case CK_NullToMemberPointer:
9752     VisitIgnoredValue(E->getSubExpr());
9753     return ZeroInitialization(E);
9754 
9755   case CK_BaseToDerivedMemberPointer: {
9756     if (!Visit(E->getSubExpr()))
9757       return false;
9758     if (E->path_empty())
9759       return true;
9760     // Base-to-derived member pointer casts store the path in derived-to-base
9761     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
9762     // the wrong end of the derived->base arc, so stagger the path by one class.
9763     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
9764     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
9765          PathI != PathE; ++PathI) {
9766       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9767       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
9768       if (!Result.castToDerived(Derived))
9769         return Error(E);
9770     }
9771     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
9772     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
9773       return Error(E);
9774     return true;
9775   }
9776 
9777   case CK_DerivedToBaseMemberPointer:
9778     if (!Visit(E->getSubExpr()))
9779       return false;
9780     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9781          PathE = E->path_end(); PathI != PathE; ++PathI) {
9782       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9783       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9784       if (!Result.castToBase(Base))
9785         return Error(E);
9786     }
9787     return true;
9788   }
9789 }
9790 
9791 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9792   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
9793   // member can be formed.
9794   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
9795 }
9796 
9797 //===----------------------------------------------------------------------===//
9798 // Record Evaluation
9799 //===----------------------------------------------------------------------===//
9800 
9801 namespace {
9802   class RecordExprEvaluator
9803   : public ExprEvaluatorBase<RecordExprEvaluator> {
9804     const LValue &This;
9805     APValue &Result;
9806   public:
9807 
9808     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
9809       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
9810 
9811     bool Success(const APValue &V, const Expr *E) {
9812       Result = V;
9813       return true;
9814     }
9815     bool ZeroInitialization(const Expr *E) {
9816       return ZeroInitialization(E, E->getType());
9817     }
9818     bool ZeroInitialization(const Expr *E, QualType T);
9819 
9820     bool VisitCallExpr(const CallExpr *E) {
9821       return handleCallExpr(E, Result, &This);
9822     }
9823     bool VisitCastExpr(const CastExpr *E);
9824     bool VisitInitListExpr(const InitListExpr *E);
9825     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9826       return VisitCXXConstructExpr(E, E->getType());
9827     }
9828     bool VisitLambdaExpr(const LambdaExpr *E);
9829     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
9830     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
9831     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
9832     bool VisitBinCmp(const BinaryOperator *E);
9833     bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
9834     bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
9835                                          ArrayRef<Expr *> Args);
9836   };
9837 }
9838 
9839 /// Perform zero-initialization on an object of non-union class type.
9840 /// C++11 [dcl.init]p5:
9841 ///  To zero-initialize an object or reference of type T means:
9842 ///    [...]
9843 ///    -- if T is a (possibly cv-qualified) non-union class type,
9844 ///       each non-static data member and each base-class subobject is
9845 ///       zero-initialized
9846 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
9847                                           const RecordDecl *RD,
9848                                           const LValue &This, APValue &Result) {
9849   assert(!RD->isUnion() && "Expected non-union class type");
9850   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
9851   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
9852                    std::distance(RD->field_begin(), RD->field_end()));
9853 
9854   if (RD->isInvalidDecl()) return false;
9855   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9856 
9857   if (CD) {
9858     unsigned Index = 0;
9859     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
9860            End = CD->bases_end(); I != End; ++I, ++Index) {
9861       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
9862       LValue Subobject = This;
9863       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
9864         return false;
9865       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
9866                                          Result.getStructBase(Index)))
9867         return false;
9868     }
9869   }
9870 
9871   for (const auto *I : RD->fields()) {
9872     // -- if T is a reference type, no initialization is performed.
9873     if (I->isUnnamedBitfield() || I->getType()->isReferenceType())
9874       continue;
9875 
9876     LValue Subobject = This;
9877     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
9878       return false;
9879 
9880     ImplicitValueInitExpr VIE(I->getType());
9881     if (!EvaluateInPlace(
9882           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
9883       return false;
9884   }
9885 
9886   return true;
9887 }
9888 
9889 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
9890   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
9891   if (RD->isInvalidDecl()) return false;
9892   if (RD->isUnion()) {
9893     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
9894     // object's first non-static named data member is zero-initialized
9895     RecordDecl::field_iterator I = RD->field_begin();
9896     while (I != RD->field_end() && (*I)->isUnnamedBitfield())
9897       ++I;
9898     if (I == RD->field_end()) {
9899       Result = APValue((const FieldDecl*)nullptr);
9900       return true;
9901     }
9902 
9903     LValue Subobject = This;
9904     if (!HandleLValueMember(Info, E, Subobject, *I))
9905       return false;
9906     Result = APValue(*I);
9907     ImplicitValueInitExpr VIE(I->getType());
9908     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
9909   }
9910 
9911   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
9912     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
9913     return false;
9914   }
9915 
9916   return HandleClassZeroInitialization(Info, E, RD, This, Result);
9917 }
9918 
9919 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
9920   switch (E->getCastKind()) {
9921   default:
9922     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9923 
9924   case CK_ConstructorConversion:
9925     return Visit(E->getSubExpr());
9926 
9927   case CK_DerivedToBase:
9928   case CK_UncheckedDerivedToBase: {
9929     APValue DerivedObject;
9930     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
9931       return false;
9932     if (!DerivedObject.isStruct())
9933       return Error(E->getSubExpr());
9934 
9935     // Derived-to-base rvalue conversion: just slice off the derived part.
9936     APValue *Value = &DerivedObject;
9937     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
9938     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9939          PathE = E->path_end(); PathI != PathE; ++PathI) {
9940       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
9941       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9942       Value = &Value->getStructBase(getBaseIndex(RD, Base));
9943       RD = Base;
9944     }
9945     Result = *Value;
9946     return true;
9947   }
9948   }
9949 }
9950 
9951 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9952   if (E->isTransparent())
9953     return Visit(E->getInit(0));
9954   return VisitCXXParenListOrInitListExpr(E, E->inits());
9955 }
9956 
9957 bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr(
9958     const Expr *ExprToVisit, ArrayRef<Expr *> Args) {
9959   const RecordDecl *RD =
9960       ExprToVisit->getType()->castAs<RecordType>()->getDecl();
9961   if (RD->isInvalidDecl()) return false;
9962   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9963   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
9964 
9965   EvalInfo::EvaluatingConstructorRAII EvalObj(
9966       Info,
9967       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
9968       CXXRD && CXXRD->getNumBases());
9969 
9970   if (RD->isUnion()) {
9971     const FieldDecl *Field;
9972     if (auto *ILE = dyn_cast<InitListExpr>(ExprToVisit)) {
9973       Field = ILE->getInitializedFieldInUnion();
9974     } else if (auto *PLIE = dyn_cast<CXXParenListInitExpr>(ExprToVisit)) {
9975       Field = PLIE->getInitializedFieldInUnion();
9976     } else {
9977       llvm_unreachable(
9978           "Expression is neither an init list nor a C++ paren list");
9979     }
9980 
9981     Result = APValue(Field);
9982     if (!Field)
9983       return true;
9984 
9985     // If the initializer list for a union does not contain any elements, the
9986     // first element of the union is value-initialized.
9987     // FIXME: The element should be initialized from an initializer list.
9988     //        Is this difference ever observable for initializer lists which
9989     //        we don't build?
9990     ImplicitValueInitExpr VIE(Field->getType());
9991     const Expr *InitExpr = Args.empty() ? &VIE : Args[0];
9992 
9993     LValue Subobject = This;
9994     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
9995       return false;
9996 
9997     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9998     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9999                                   isa<CXXDefaultInitExpr>(InitExpr));
10000 
10001     if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
10002       if (Field->isBitField())
10003         return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
10004                                      Field);
10005       return true;
10006     }
10007 
10008     return false;
10009   }
10010 
10011   if (!Result.hasValue())
10012     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
10013                      std::distance(RD->field_begin(), RD->field_end()));
10014   unsigned ElementNo = 0;
10015   bool Success = true;
10016 
10017   // Initialize base classes.
10018   if (CXXRD && CXXRD->getNumBases()) {
10019     for (const auto &Base : CXXRD->bases()) {
10020       assert(ElementNo < Args.size() && "missing init for base class");
10021       const Expr *Init = Args[ElementNo];
10022 
10023       LValue Subobject = This;
10024       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
10025         return false;
10026 
10027       APValue &FieldVal = Result.getStructBase(ElementNo);
10028       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
10029         if (!Info.noteFailure())
10030           return false;
10031         Success = false;
10032       }
10033       ++ElementNo;
10034     }
10035 
10036     EvalObj.finishedConstructingBases();
10037   }
10038 
10039   // Initialize members.
10040   for (const auto *Field : RD->fields()) {
10041     // Anonymous bit-fields are not considered members of the class for
10042     // purposes of aggregate initialization.
10043     if (Field->isUnnamedBitfield())
10044       continue;
10045 
10046     LValue Subobject = This;
10047 
10048     bool HaveInit = ElementNo < Args.size();
10049 
10050     // FIXME: Diagnostics here should point to the end of the initializer
10051     // list, not the start.
10052     if (!HandleLValueMember(Info, HaveInit ? Args[ElementNo] : ExprToVisit,
10053                             Subobject, Field, &Layout))
10054       return false;
10055 
10056     // Perform an implicit value-initialization for members beyond the end of
10057     // the initializer list.
10058     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
10059     const Expr *Init = HaveInit ? Args[ElementNo++] : &VIE;
10060 
10061     if (Field->getType()->isIncompleteArrayType()) {
10062       if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {
10063         if (!CAT->getSize().isZero()) {
10064           // Bail out for now. This might sort of "work", but the rest of the
10065           // code isn't really prepared to handle it.
10066           Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array);
10067           return false;
10068         }
10069       }
10070     }
10071 
10072     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10073     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10074                                   isa<CXXDefaultInitExpr>(Init));
10075 
10076     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10077     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
10078         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
10079                                                        FieldVal, Field))) {
10080       if (!Info.noteFailure())
10081         return false;
10082       Success = false;
10083     }
10084   }
10085 
10086   EvalObj.finishedConstructingFields();
10087 
10088   return Success;
10089 }
10090 
10091 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10092                                                 QualType T) {
10093   // Note that E's type is not necessarily the type of our class here; we might
10094   // be initializing an array element instead.
10095   const CXXConstructorDecl *FD = E->getConstructor();
10096   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
10097 
10098   bool ZeroInit = E->requiresZeroInitialization();
10099   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
10100     // If we've already performed zero-initialization, we're already done.
10101     if (Result.hasValue())
10102       return true;
10103 
10104     if (ZeroInit)
10105       return ZeroInitialization(E, T);
10106 
10107     return getDefaultInitValue(T, Result);
10108   }
10109 
10110   const FunctionDecl *Definition = nullptr;
10111   auto Body = FD->getBody(Definition);
10112 
10113   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10114     return false;
10115 
10116   // Avoid materializing a temporary for an elidable copy/move constructor.
10117   if (E->isElidable() && !ZeroInit) {
10118     // FIXME: This only handles the simplest case, where the source object
10119     //        is passed directly as the first argument to the constructor.
10120     //        This should also handle stepping though implicit casts and
10121     //        and conversion sequences which involve two steps, with a
10122     //        conversion operator followed by a converting constructor.
10123     const Expr *SrcObj = E->getArg(0);
10124     assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
10125     assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
10126     if (const MaterializeTemporaryExpr *ME =
10127             dyn_cast<MaterializeTemporaryExpr>(SrcObj))
10128       return Visit(ME->getSubExpr());
10129   }
10130 
10131   if (ZeroInit && !ZeroInitialization(E, T))
10132     return false;
10133 
10134   auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
10135   return HandleConstructorCall(E, This, Args,
10136                                cast<CXXConstructorDecl>(Definition), Info,
10137                                Result);
10138 }
10139 
10140 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
10141     const CXXInheritedCtorInitExpr *E) {
10142   if (!Info.CurrentCall) {
10143     assert(Info.checkingPotentialConstantExpression());
10144     return false;
10145   }
10146 
10147   const CXXConstructorDecl *FD = E->getConstructor();
10148   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
10149     return false;
10150 
10151   const FunctionDecl *Definition = nullptr;
10152   auto Body = FD->getBody(Definition);
10153 
10154   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10155     return false;
10156 
10157   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
10158                                cast<CXXConstructorDecl>(Definition), Info,
10159                                Result);
10160 }
10161 
10162 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
10163     const CXXStdInitializerListExpr *E) {
10164   const ConstantArrayType *ArrayType =
10165       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
10166 
10167   LValue Array;
10168   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
10169     return false;
10170 
10171   // Get a pointer to the first element of the array.
10172   Array.addArray(Info, E, ArrayType);
10173 
10174   auto InvalidType = [&] {
10175     Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
10176       << E->getType();
10177     return false;
10178   };
10179 
10180   // FIXME: Perform the checks on the field types in SemaInit.
10181   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
10182   RecordDecl::field_iterator Field = Record->field_begin();
10183   if (Field == Record->field_end())
10184     return InvalidType();
10185 
10186   // Start pointer.
10187   if (!Field->getType()->isPointerType() ||
10188       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10189                             ArrayType->getElementType()))
10190     return InvalidType();
10191 
10192   // FIXME: What if the initializer_list type has base classes, etc?
10193   Result = APValue(APValue::UninitStruct(), 0, 2);
10194   Array.moveInto(Result.getStructField(0));
10195 
10196   if (++Field == Record->field_end())
10197     return InvalidType();
10198 
10199   if (Field->getType()->isPointerType() &&
10200       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10201                            ArrayType->getElementType())) {
10202     // End pointer.
10203     if (!HandleLValueArrayAdjustment(Info, E, Array,
10204                                      ArrayType->getElementType(),
10205                                      ArrayType->getSize().getZExtValue()))
10206       return false;
10207     Array.moveInto(Result.getStructField(1));
10208   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
10209     // Length.
10210     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
10211   else
10212     return InvalidType();
10213 
10214   if (++Field != Record->field_end())
10215     return InvalidType();
10216 
10217   return true;
10218 }
10219 
10220 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
10221   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
10222   if (ClosureClass->isInvalidDecl())
10223     return false;
10224 
10225   const size_t NumFields =
10226       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
10227 
10228   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
10229                                             E->capture_init_end()) &&
10230          "The number of lambda capture initializers should equal the number of "
10231          "fields within the closure type");
10232 
10233   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
10234   // Iterate through all the lambda's closure object's fields and initialize
10235   // them.
10236   auto *CaptureInitIt = E->capture_init_begin();
10237   bool Success = true;
10238   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
10239   for (const auto *Field : ClosureClass->fields()) {
10240     assert(CaptureInitIt != E->capture_init_end());
10241     // Get the initializer for this field
10242     Expr *const CurFieldInit = *CaptureInitIt++;
10243 
10244     // If there is no initializer, either this is a VLA or an error has
10245     // occurred.
10246     if (!CurFieldInit)
10247       return Error(E);
10248 
10249     LValue Subobject = This;
10250 
10251     if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
10252       return false;
10253 
10254     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10255     if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
10256       if (!Info.keepEvaluatingAfterFailure())
10257         return false;
10258       Success = false;
10259     }
10260   }
10261   return Success;
10262 }
10263 
10264 static bool EvaluateRecord(const Expr *E, const LValue &This,
10265                            APValue &Result, EvalInfo &Info) {
10266   assert(!E->isValueDependent());
10267   assert(E->isPRValue() && E->getType()->isRecordType() &&
10268          "can't evaluate expression as a record rvalue");
10269   return RecordExprEvaluator(Info, This, Result).Visit(E);
10270 }
10271 
10272 //===----------------------------------------------------------------------===//
10273 // Temporary Evaluation
10274 //
10275 // Temporaries are represented in the AST as rvalues, but generally behave like
10276 // lvalues. The full-object of which the temporary is a subobject is implicitly
10277 // materialized so that a reference can bind to it.
10278 //===----------------------------------------------------------------------===//
10279 namespace {
10280 class TemporaryExprEvaluator
10281   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
10282 public:
10283   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
10284     LValueExprEvaluatorBaseTy(Info, Result, false) {}
10285 
10286   /// Visit an expression which constructs the value of this temporary.
10287   bool VisitConstructExpr(const Expr *E) {
10288     APValue &Value = Info.CurrentCall->createTemporary(
10289         E, E->getType(), ScopeKind::FullExpression, Result);
10290     return EvaluateInPlace(Value, Info, Result, E);
10291   }
10292 
10293   bool VisitCastExpr(const CastExpr *E) {
10294     switch (E->getCastKind()) {
10295     default:
10296       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
10297 
10298     case CK_ConstructorConversion:
10299       return VisitConstructExpr(E->getSubExpr());
10300     }
10301   }
10302   bool VisitInitListExpr(const InitListExpr *E) {
10303     return VisitConstructExpr(E);
10304   }
10305   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10306     return VisitConstructExpr(E);
10307   }
10308   bool VisitCallExpr(const CallExpr *E) {
10309     return VisitConstructExpr(E);
10310   }
10311   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
10312     return VisitConstructExpr(E);
10313   }
10314   bool VisitLambdaExpr(const LambdaExpr *E) {
10315     return VisitConstructExpr(E);
10316   }
10317 };
10318 } // end anonymous namespace
10319 
10320 /// Evaluate an expression of record type as a temporary.
10321 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
10322   assert(!E->isValueDependent());
10323   assert(E->isPRValue() && E->getType()->isRecordType());
10324   return TemporaryExprEvaluator(Info, Result).Visit(E);
10325 }
10326 
10327 //===----------------------------------------------------------------------===//
10328 // Vector Evaluation
10329 //===----------------------------------------------------------------------===//
10330 
10331 namespace {
10332   class VectorExprEvaluator
10333   : public ExprEvaluatorBase<VectorExprEvaluator> {
10334     APValue &Result;
10335   public:
10336 
10337     VectorExprEvaluator(EvalInfo &info, APValue &Result)
10338       : ExprEvaluatorBaseTy(info), Result(Result) {}
10339 
10340     bool Success(ArrayRef<APValue> V, const Expr *E) {
10341       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
10342       // FIXME: remove this APValue copy.
10343       Result = APValue(V.data(), V.size());
10344       return true;
10345     }
10346     bool Success(const APValue &V, const Expr *E) {
10347       assert(V.isVector());
10348       Result = V;
10349       return true;
10350     }
10351     bool ZeroInitialization(const Expr *E);
10352 
10353     bool VisitUnaryReal(const UnaryOperator *E)
10354       { return Visit(E->getSubExpr()); }
10355     bool VisitCastExpr(const CastExpr* E);
10356     bool VisitInitListExpr(const InitListExpr *E);
10357     bool VisitUnaryImag(const UnaryOperator *E);
10358     bool VisitBinaryOperator(const BinaryOperator *E);
10359     bool VisitUnaryOperator(const UnaryOperator *E);
10360     // FIXME: Missing: conditional operator (for GNU
10361     //                 conditional select), shufflevector, ExtVectorElementExpr
10362   };
10363 } // end anonymous namespace
10364 
10365 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
10366   assert(E->isPRValue() && E->getType()->isVectorType() &&
10367          "not a vector prvalue");
10368   return VectorExprEvaluator(Info, Result).Visit(E);
10369 }
10370 
10371 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
10372   const VectorType *VTy = E->getType()->castAs<VectorType>();
10373   unsigned NElts = VTy->getNumElements();
10374 
10375   const Expr *SE = E->getSubExpr();
10376   QualType SETy = SE->getType();
10377 
10378   switch (E->getCastKind()) {
10379   case CK_VectorSplat: {
10380     APValue Val = APValue();
10381     if (SETy->isIntegerType()) {
10382       APSInt IntResult;
10383       if (!EvaluateInteger(SE, IntResult, Info))
10384         return false;
10385       Val = APValue(std::move(IntResult));
10386     } else if (SETy->isRealFloatingType()) {
10387       APFloat FloatResult(0.0);
10388       if (!EvaluateFloat(SE, FloatResult, Info))
10389         return false;
10390       Val = APValue(std::move(FloatResult));
10391     } else {
10392       return Error(E);
10393     }
10394 
10395     // Splat and create vector APValue.
10396     SmallVector<APValue, 4> Elts(NElts, Val);
10397     return Success(Elts, E);
10398   }
10399   case CK_BitCast: {
10400     // Evaluate the operand into an APInt we can extract from.
10401     llvm::APInt SValInt;
10402     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
10403       return false;
10404     // Extract the elements
10405     QualType EltTy = VTy->getElementType();
10406     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
10407     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
10408     SmallVector<APValue, 4> Elts;
10409     if (EltTy->isRealFloatingType()) {
10410       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
10411       unsigned FloatEltSize = EltSize;
10412       if (&Sem == &APFloat::x87DoubleExtended())
10413         FloatEltSize = 80;
10414       for (unsigned i = 0; i < NElts; i++) {
10415         llvm::APInt Elt;
10416         if (BigEndian)
10417           Elt = SValInt.rotl(i * EltSize + FloatEltSize).trunc(FloatEltSize);
10418         else
10419           Elt = SValInt.rotr(i * EltSize).trunc(FloatEltSize);
10420         Elts.push_back(APValue(APFloat(Sem, Elt)));
10421       }
10422     } else if (EltTy->isIntegerType()) {
10423       for (unsigned i = 0; i < NElts; i++) {
10424         llvm::APInt Elt;
10425         if (BigEndian)
10426           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
10427         else
10428           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
10429         Elts.push_back(APValue(APSInt(Elt, !EltTy->isSignedIntegerType())));
10430       }
10431     } else {
10432       return Error(E);
10433     }
10434     return Success(Elts, E);
10435   }
10436   default:
10437     return ExprEvaluatorBaseTy::VisitCastExpr(E);
10438   }
10439 }
10440 
10441 bool
10442 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10443   const VectorType *VT = E->getType()->castAs<VectorType>();
10444   unsigned NumInits = E->getNumInits();
10445   unsigned NumElements = VT->getNumElements();
10446 
10447   QualType EltTy = VT->getElementType();
10448   SmallVector<APValue, 4> Elements;
10449 
10450   // The number of initializers can be less than the number of
10451   // vector elements. For OpenCL, this can be due to nested vector
10452   // initialization. For GCC compatibility, missing trailing elements
10453   // should be initialized with zeroes.
10454   unsigned CountInits = 0, CountElts = 0;
10455   while (CountElts < NumElements) {
10456     // Handle nested vector initialization.
10457     if (CountInits < NumInits
10458         && E->getInit(CountInits)->getType()->isVectorType()) {
10459       APValue v;
10460       if (!EvaluateVector(E->getInit(CountInits), v, Info))
10461         return Error(E);
10462       unsigned vlen = v.getVectorLength();
10463       for (unsigned j = 0; j < vlen; j++)
10464         Elements.push_back(v.getVectorElt(j));
10465       CountElts += vlen;
10466     } else if (EltTy->isIntegerType()) {
10467       llvm::APSInt sInt(32);
10468       if (CountInits < NumInits) {
10469         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
10470           return false;
10471       } else // trailing integer zero.
10472         sInt = Info.Ctx.MakeIntValue(0, EltTy);
10473       Elements.push_back(APValue(sInt));
10474       CountElts++;
10475     } else {
10476       llvm::APFloat f(0.0);
10477       if (CountInits < NumInits) {
10478         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
10479           return false;
10480       } else // trailing float zero.
10481         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
10482       Elements.push_back(APValue(f));
10483       CountElts++;
10484     }
10485     CountInits++;
10486   }
10487   return Success(Elements, E);
10488 }
10489 
10490 bool
10491 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
10492   const auto *VT = E->getType()->castAs<VectorType>();
10493   QualType EltTy = VT->getElementType();
10494   APValue ZeroElement;
10495   if (EltTy->isIntegerType())
10496     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
10497   else
10498     ZeroElement =
10499         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
10500 
10501   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
10502   return Success(Elements, E);
10503 }
10504 
10505 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
10506   VisitIgnoredValue(E->getSubExpr());
10507   return ZeroInitialization(E);
10508 }
10509 
10510 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10511   BinaryOperatorKind Op = E->getOpcode();
10512   assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
10513          "Operation not supported on vector types");
10514 
10515   if (Op == BO_Comma)
10516     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10517 
10518   Expr *LHS = E->getLHS();
10519   Expr *RHS = E->getRHS();
10520 
10521   assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
10522          "Must both be vector types");
10523   // Checking JUST the types are the same would be fine, except shifts don't
10524   // need to have their types be the same (since you always shift by an int).
10525   assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
10526              E->getType()->castAs<VectorType>()->getNumElements() &&
10527          RHS->getType()->castAs<VectorType>()->getNumElements() ==
10528              E->getType()->castAs<VectorType>()->getNumElements() &&
10529          "All operands must be the same size.");
10530 
10531   APValue LHSValue;
10532   APValue RHSValue;
10533   bool LHSOK = Evaluate(LHSValue, Info, LHS);
10534   if (!LHSOK && !Info.noteFailure())
10535     return false;
10536   if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
10537     return false;
10538 
10539   if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
10540     return false;
10541 
10542   return Success(LHSValue, E);
10543 }
10544 
10545 static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
10546                                                         QualType ResultTy,
10547                                                         UnaryOperatorKind Op,
10548                                                         APValue Elt) {
10549   switch (Op) {
10550   case UO_Plus:
10551     // Nothing to do here.
10552     return Elt;
10553   case UO_Minus:
10554     if (Elt.getKind() == APValue::Int) {
10555       Elt.getInt().negate();
10556     } else {
10557       assert(Elt.getKind() == APValue::Float &&
10558              "Vector can only be int or float type");
10559       Elt.getFloat().changeSign();
10560     }
10561     return Elt;
10562   case UO_Not:
10563     // This is only valid for integral types anyway, so we don't have to handle
10564     // float here.
10565     assert(Elt.getKind() == APValue::Int &&
10566            "Vector operator ~ can only be int");
10567     Elt.getInt().flipAllBits();
10568     return Elt;
10569   case UO_LNot: {
10570     if (Elt.getKind() == APValue::Int) {
10571       Elt.getInt() = !Elt.getInt();
10572       // operator ! on vectors returns -1 for 'truth', so negate it.
10573       Elt.getInt().negate();
10574       return Elt;
10575     }
10576     assert(Elt.getKind() == APValue::Float &&
10577            "Vector can only be int or float type");
10578     // Float types result in an int of the same size, but -1 for true, or 0 for
10579     // false.
10580     APSInt EltResult{Ctx.getIntWidth(ResultTy),
10581                      ResultTy->isUnsignedIntegerType()};
10582     if (Elt.getFloat().isZero())
10583       EltResult.setAllBits();
10584     else
10585       EltResult.clearAllBits();
10586 
10587     return APValue{EltResult};
10588   }
10589   default:
10590     // FIXME: Implement the rest of the unary operators.
10591     return std::nullopt;
10592   }
10593 }
10594 
10595 bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10596   Expr *SubExpr = E->getSubExpr();
10597   const auto *VD = SubExpr->getType()->castAs<VectorType>();
10598   // This result element type differs in the case of negating a floating point
10599   // vector, since the result type is the a vector of the equivilant sized
10600   // integer.
10601   const QualType ResultEltTy = VD->getElementType();
10602   UnaryOperatorKind Op = E->getOpcode();
10603 
10604   APValue SubExprValue;
10605   if (!Evaluate(SubExprValue, Info, SubExpr))
10606     return false;
10607 
10608   // FIXME: This vector evaluator someday needs to be changed to be LValue
10609   // aware/keep LValue information around, rather than dealing with just vector
10610   // types directly. Until then, we cannot handle cases where the operand to
10611   // these unary operators is an LValue. The only case I've been able to see
10612   // cause this is operator++ assigning to a member expression (only valid in
10613   // altivec compilations) in C mode, so this shouldn't limit us too much.
10614   if (SubExprValue.isLValue())
10615     return false;
10616 
10617   assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
10618          "Vector length doesn't match type?");
10619 
10620   SmallVector<APValue, 4> ResultElements;
10621   for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
10622     std::optional<APValue> Elt = handleVectorUnaryOperator(
10623         Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
10624     if (!Elt)
10625       return false;
10626     ResultElements.push_back(*Elt);
10627   }
10628   return Success(APValue(ResultElements.data(), ResultElements.size()), E);
10629 }
10630 
10631 //===----------------------------------------------------------------------===//
10632 // Array Evaluation
10633 //===----------------------------------------------------------------------===//
10634 
10635 namespace {
10636   class ArrayExprEvaluator
10637   : public ExprEvaluatorBase<ArrayExprEvaluator> {
10638     const LValue &This;
10639     APValue &Result;
10640   public:
10641 
10642     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
10643       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
10644 
10645     bool Success(const APValue &V, const Expr *E) {
10646       assert(V.isArray() && "expected array");
10647       Result = V;
10648       return true;
10649     }
10650 
10651     bool ZeroInitialization(const Expr *E) {
10652       const ConstantArrayType *CAT =
10653           Info.Ctx.getAsConstantArrayType(E->getType());
10654       if (!CAT) {
10655         if (E->getType()->isIncompleteArrayType()) {
10656           // We can be asked to zero-initialize a flexible array member; this
10657           // is represented as an ImplicitValueInitExpr of incomplete array
10658           // type. In this case, the array has zero elements.
10659           Result = APValue(APValue::UninitArray(), 0, 0);
10660           return true;
10661         }
10662         // FIXME: We could handle VLAs here.
10663         return Error(E);
10664       }
10665 
10666       Result = APValue(APValue::UninitArray(), 0,
10667                        CAT->getSize().getZExtValue());
10668       if (!Result.hasArrayFiller())
10669         return true;
10670 
10671       // Zero-initialize all elements.
10672       LValue Subobject = This;
10673       Subobject.addArray(Info, E, CAT);
10674       ImplicitValueInitExpr VIE(CAT->getElementType());
10675       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
10676     }
10677 
10678     bool VisitCallExpr(const CallExpr *E) {
10679       return handleCallExpr(E, Result, &This);
10680     }
10681     bool VisitInitListExpr(const InitListExpr *E,
10682                            QualType AllocType = QualType());
10683     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
10684     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
10685     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
10686                                const LValue &Subobject,
10687                                APValue *Value, QualType Type);
10688     bool VisitStringLiteral(const StringLiteral *E,
10689                             QualType AllocType = QualType()) {
10690       expandStringLiteral(Info, E, Result, AllocType);
10691       return true;
10692     }
10693     bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
10694     bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
10695                                          ArrayRef<Expr *> Args,
10696                                          const Expr *ArrayFiller,
10697                                          QualType AllocType = QualType());
10698   };
10699 } // end anonymous namespace
10700 
10701 static bool EvaluateArray(const Expr *E, const LValue &This,
10702                           APValue &Result, EvalInfo &Info) {
10703   assert(!E->isValueDependent());
10704   assert(E->isPRValue() && E->getType()->isArrayType() &&
10705          "not an array prvalue");
10706   return ArrayExprEvaluator(Info, This, Result).Visit(E);
10707 }
10708 
10709 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10710                                      APValue &Result, const InitListExpr *ILE,
10711                                      QualType AllocType) {
10712   assert(!ILE->isValueDependent());
10713   assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
10714          "not an array prvalue");
10715   return ArrayExprEvaluator(Info, This, Result)
10716       .VisitInitListExpr(ILE, AllocType);
10717 }
10718 
10719 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10720                                           APValue &Result,
10721                                           const CXXConstructExpr *CCE,
10722                                           QualType AllocType) {
10723   assert(!CCE->isValueDependent());
10724   assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
10725          "not an array prvalue");
10726   return ArrayExprEvaluator(Info, This, Result)
10727       .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
10728 }
10729 
10730 // Return true iff the given array filler may depend on the element index.
10731 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
10732   // For now, just allow non-class value-initialization and initialization
10733   // lists comprised of them.
10734   if (isa<ImplicitValueInitExpr>(FillerExpr))
10735     return false;
10736   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
10737     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
10738       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
10739         return true;
10740     }
10741 
10742     if (ILE->hasArrayFiller() &&
10743         MaybeElementDependentArrayFiller(ILE->getArrayFiller()))
10744       return true;
10745 
10746     return false;
10747   }
10748   return true;
10749 }
10750 
10751 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
10752                                            QualType AllocType) {
10753   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
10754       AllocType.isNull() ? E->getType() : AllocType);
10755   if (!CAT)
10756     return Error(E);
10757 
10758   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
10759   // an appropriately-typed string literal enclosed in braces.
10760   if (E->isStringLiteralInit()) {
10761     auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
10762     // FIXME: Support ObjCEncodeExpr here once we support it in
10763     // ArrayExprEvaluator generally.
10764     if (!SL)
10765       return Error(E);
10766     return VisitStringLiteral(SL, AllocType);
10767   }
10768   // Any other transparent list init will need proper handling of the
10769   // AllocType; we can't just recurse to the inner initializer.
10770   assert(!E->isTransparent() &&
10771          "transparent array list initialization is not string literal init?");
10772 
10773   return VisitCXXParenListOrInitListExpr(E, E->inits(), E->getArrayFiller(),
10774                                          AllocType);
10775 }
10776 
10777 bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr(
10778     const Expr *ExprToVisit, ArrayRef<Expr *> Args, const Expr *ArrayFiller,
10779     QualType AllocType) {
10780   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
10781       AllocType.isNull() ? ExprToVisit->getType() : AllocType);
10782 
10783   bool Success = true;
10784 
10785   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
10786          "zero-initialized array shouldn't have any initialized elts");
10787   APValue Filler;
10788   if (Result.isArray() && Result.hasArrayFiller())
10789     Filler = Result.getArrayFiller();
10790 
10791   unsigned NumEltsToInit = Args.size();
10792   unsigned NumElts = CAT->getSize().getZExtValue();
10793 
10794   // If the initializer might depend on the array index, run it for each
10795   // array element.
10796   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(ArrayFiller))
10797     NumEltsToInit = NumElts;
10798 
10799   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
10800                           << NumEltsToInit << ".\n");
10801 
10802   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
10803 
10804   // If the array was previously zero-initialized, preserve the
10805   // zero-initialized values.
10806   if (Filler.hasValue()) {
10807     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
10808       Result.getArrayInitializedElt(I) = Filler;
10809     if (Result.hasArrayFiller())
10810       Result.getArrayFiller() = Filler;
10811   }
10812 
10813   LValue Subobject = This;
10814   Subobject.addArray(Info, ExprToVisit, CAT);
10815   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
10816     const Expr *Init = Index < Args.size() ? Args[Index] : ArrayFiller;
10817     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10818                          Info, Subobject, Init) ||
10819         !HandleLValueArrayAdjustment(Info, Init, Subobject,
10820                                      CAT->getElementType(), 1)) {
10821       if (!Info.noteFailure())
10822         return false;
10823       Success = false;
10824     }
10825   }
10826 
10827   if (!Result.hasArrayFiller())
10828     return Success;
10829 
10830   // If we get here, we have a trivial filler, which we can just evaluate
10831   // once and splat over the rest of the array elements.
10832   assert(ArrayFiller && "no array filler for incomplete init list");
10833   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
10834                          ArrayFiller) &&
10835          Success;
10836 }
10837 
10838 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
10839   LValue CommonLV;
10840   if (E->getCommonExpr() &&
10841       !Evaluate(Info.CurrentCall->createTemporary(
10842                     E->getCommonExpr(),
10843                     getStorageType(Info.Ctx, E->getCommonExpr()),
10844                     ScopeKind::FullExpression, CommonLV),
10845                 Info, E->getCommonExpr()->getSourceExpr()))
10846     return false;
10847 
10848   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
10849 
10850   uint64_t Elements = CAT->getSize().getZExtValue();
10851   Result = APValue(APValue::UninitArray(), Elements, Elements);
10852 
10853   LValue Subobject = This;
10854   Subobject.addArray(Info, E, CAT);
10855 
10856   bool Success = true;
10857   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
10858     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10859                          Info, Subobject, E->getSubExpr()) ||
10860         !HandleLValueArrayAdjustment(Info, E, Subobject,
10861                                      CAT->getElementType(), 1)) {
10862       if (!Info.noteFailure())
10863         return false;
10864       Success = false;
10865     }
10866   }
10867 
10868   return Success;
10869 }
10870 
10871 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
10872   return VisitCXXConstructExpr(E, This, &Result, E->getType());
10873 }
10874 
10875 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10876                                                const LValue &Subobject,
10877                                                APValue *Value,
10878                                                QualType Type) {
10879   bool HadZeroInit = Value->hasValue();
10880 
10881   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
10882     unsigned FinalSize = CAT->getSize().getZExtValue();
10883 
10884     // Preserve the array filler if we had prior zero-initialization.
10885     APValue Filler =
10886       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
10887                                              : APValue();
10888 
10889     *Value = APValue(APValue::UninitArray(), 0, FinalSize);
10890     if (FinalSize == 0)
10891       return true;
10892 
10893     bool HasTrivialConstructor = CheckTrivialDefaultConstructor(
10894         Info, E->getExprLoc(), E->getConstructor(),
10895         E->requiresZeroInitialization());
10896     LValue ArrayElt = Subobject;
10897     ArrayElt.addArray(Info, E, CAT);
10898     // We do the whole initialization in two passes, first for just one element,
10899     // then for the whole array. It's possible we may find out we can't do const
10900     // init in the first pass, in which case we avoid allocating a potentially
10901     // large array. We don't do more passes because expanding array requires
10902     // copying the data, which is wasteful.
10903     for (const unsigned N : {1u, FinalSize}) {
10904       unsigned OldElts = Value->getArrayInitializedElts();
10905       if (OldElts == N)
10906         break;
10907 
10908       // Expand the array to appropriate size.
10909       APValue NewValue(APValue::UninitArray(), N, FinalSize);
10910       for (unsigned I = 0; I < OldElts; ++I)
10911         NewValue.getArrayInitializedElt(I).swap(
10912             Value->getArrayInitializedElt(I));
10913       Value->swap(NewValue);
10914 
10915       if (HadZeroInit)
10916         for (unsigned I = OldElts; I < N; ++I)
10917           Value->getArrayInitializedElt(I) = Filler;
10918 
10919       if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) {
10920         // If we have a trivial constructor, only evaluate it once and copy
10921         // the result into all the array elements.
10922         APValue &FirstResult = Value->getArrayInitializedElt(0);
10923         for (unsigned I = OldElts; I < FinalSize; ++I)
10924           Value->getArrayInitializedElt(I) = FirstResult;
10925       } else {
10926         for (unsigned I = OldElts; I < N; ++I) {
10927           if (!VisitCXXConstructExpr(E, ArrayElt,
10928                                      &Value->getArrayInitializedElt(I),
10929                                      CAT->getElementType()) ||
10930               !HandleLValueArrayAdjustment(Info, E, ArrayElt,
10931                                            CAT->getElementType(), 1))
10932             return false;
10933           // When checking for const initilization any diagnostic is considered
10934           // an error.
10935           if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
10936               !Info.keepEvaluatingAfterFailure())
10937             return false;
10938         }
10939       }
10940     }
10941 
10942     return true;
10943   }
10944 
10945   if (!Type->isRecordType())
10946     return Error(E);
10947 
10948   return RecordExprEvaluator(Info, Subobject, *Value)
10949              .VisitCXXConstructExpr(E, Type);
10950 }
10951 
10952 bool ArrayExprEvaluator::VisitCXXParenListInitExpr(
10953     const CXXParenListInitExpr *E) {
10954   assert(dyn_cast<ConstantArrayType>(E->getType()) &&
10955          "Expression result is not a constant array type");
10956 
10957   return VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),
10958                                          E->getArrayFiller());
10959 }
10960 
10961 //===----------------------------------------------------------------------===//
10962 // Integer Evaluation
10963 //
10964 // As a GNU extension, we support casting pointers to sufficiently-wide integer
10965 // types and back in constant folding. Integer values are thus represented
10966 // either as an integer-valued APValue, or as an lvalue-valued APValue.
10967 //===----------------------------------------------------------------------===//
10968 
10969 namespace {
10970 class IntExprEvaluator
10971         : public ExprEvaluatorBase<IntExprEvaluator> {
10972   APValue &Result;
10973 public:
10974   IntExprEvaluator(EvalInfo &info, APValue &result)
10975       : ExprEvaluatorBaseTy(info), Result(result) {}
10976 
10977   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
10978     assert(E->getType()->isIntegralOrEnumerationType() &&
10979            "Invalid evaluation result.");
10980     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
10981            "Invalid evaluation result.");
10982     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10983            "Invalid evaluation result.");
10984     Result = APValue(SI);
10985     return true;
10986   }
10987   bool Success(const llvm::APSInt &SI, const Expr *E) {
10988     return Success(SI, E, Result);
10989   }
10990 
10991   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
10992     assert(E->getType()->isIntegralOrEnumerationType() &&
10993            "Invalid evaluation result.");
10994     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10995            "Invalid evaluation result.");
10996     Result = APValue(APSInt(I));
10997     Result.getInt().setIsUnsigned(
10998                             E->getType()->isUnsignedIntegerOrEnumerationType());
10999     return true;
11000   }
11001   bool Success(const llvm::APInt &I, const Expr *E) {
11002     return Success(I, E, Result);
11003   }
11004 
11005   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
11006     assert(E->getType()->isIntegralOrEnumerationType() &&
11007            "Invalid evaluation result.");
11008     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
11009     return true;
11010   }
11011   bool Success(uint64_t Value, const Expr *E) {
11012     return Success(Value, E, Result);
11013   }
11014 
11015   bool Success(CharUnits Size, const Expr *E) {
11016     return Success(Size.getQuantity(), E);
11017   }
11018 
11019   bool Success(const APValue &V, const Expr *E) {
11020     if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
11021       Result = V;
11022       return true;
11023     }
11024     return Success(V.getInt(), E);
11025   }
11026 
11027   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
11028 
11029   //===--------------------------------------------------------------------===//
11030   //                            Visitor Methods
11031   //===--------------------------------------------------------------------===//
11032 
11033   bool VisitIntegerLiteral(const IntegerLiteral *E) {
11034     return Success(E->getValue(), E);
11035   }
11036   bool VisitCharacterLiteral(const CharacterLiteral *E) {
11037     return Success(E->getValue(), E);
11038   }
11039 
11040   bool CheckReferencedDecl(const Expr *E, const Decl *D);
11041   bool VisitDeclRefExpr(const DeclRefExpr *E) {
11042     if (CheckReferencedDecl(E, E->getDecl()))
11043       return true;
11044 
11045     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
11046   }
11047   bool VisitMemberExpr(const MemberExpr *E) {
11048     if (CheckReferencedDecl(E, E->getMemberDecl())) {
11049       VisitIgnoredBaseExpression(E->getBase());
11050       return true;
11051     }
11052 
11053     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
11054   }
11055 
11056   bool VisitCallExpr(const CallExpr *E);
11057   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
11058   bool VisitBinaryOperator(const BinaryOperator *E);
11059   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
11060   bool VisitUnaryOperator(const UnaryOperator *E);
11061 
11062   bool VisitCastExpr(const CastExpr* E);
11063   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
11064 
11065   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
11066     return Success(E->getValue(), E);
11067   }
11068 
11069   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
11070     return Success(E->getValue(), E);
11071   }
11072 
11073   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
11074     if (Info.ArrayInitIndex == uint64_t(-1)) {
11075       // We were asked to evaluate this subexpression independent of the
11076       // enclosing ArrayInitLoopExpr. We can't do that.
11077       Info.FFDiag(E);
11078       return false;
11079     }
11080     return Success(Info.ArrayInitIndex, E);
11081   }
11082 
11083   // Note, GNU defines __null as an integer, not a pointer.
11084   bool VisitGNUNullExpr(const GNUNullExpr *E) {
11085     return ZeroInitialization(E);
11086   }
11087 
11088   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
11089     return Success(E->getValue(), E);
11090   }
11091 
11092   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
11093     return Success(E->getValue(), E);
11094   }
11095 
11096   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
11097     return Success(E->getValue(), E);
11098   }
11099 
11100   bool VisitUnaryReal(const UnaryOperator *E);
11101   bool VisitUnaryImag(const UnaryOperator *E);
11102 
11103   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
11104   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
11105   bool VisitSourceLocExpr(const SourceLocExpr *E);
11106   bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
11107   bool VisitRequiresExpr(const RequiresExpr *E);
11108   // FIXME: Missing: array subscript of vector, member of vector
11109 };
11110 
11111 class FixedPointExprEvaluator
11112     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
11113   APValue &Result;
11114 
11115  public:
11116   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
11117       : ExprEvaluatorBaseTy(info), Result(result) {}
11118 
11119   bool Success(const llvm::APInt &I, const Expr *E) {
11120     return Success(
11121         APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
11122   }
11123 
11124   bool Success(uint64_t Value, const Expr *E) {
11125     return Success(
11126         APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
11127   }
11128 
11129   bool Success(const APValue &V, const Expr *E) {
11130     return Success(V.getFixedPoint(), E);
11131   }
11132 
11133   bool Success(const APFixedPoint &V, const Expr *E) {
11134     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
11135     assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11136            "Invalid evaluation result.");
11137     Result = APValue(V);
11138     return true;
11139   }
11140 
11141   //===--------------------------------------------------------------------===//
11142   //                            Visitor Methods
11143   //===--------------------------------------------------------------------===//
11144 
11145   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
11146     return Success(E->getValue(), E);
11147   }
11148 
11149   bool VisitCastExpr(const CastExpr *E);
11150   bool VisitUnaryOperator(const UnaryOperator *E);
11151   bool VisitBinaryOperator(const BinaryOperator *E);
11152 };
11153 } // end anonymous namespace
11154 
11155 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
11156 /// produce either the integer value or a pointer.
11157 ///
11158 /// GCC has a heinous extension which folds casts between pointer types and
11159 /// pointer-sized integral types. We support this by allowing the evaluation of
11160 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
11161 /// Some simple arithmetic on such values is supported (they are treated much
11162 /// like char*).
11163 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
11164                                     EvalInfo &Info) {
11165   assert(!E->isValueDependent());
11166   assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
11167   return IntExprEvaluator(Info, Result).Visit(E);
11168 }
11169 
11170 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
11171   assert(!E->isValueDependent());
11172   APValue Val;
11173   if (!EvaluateIntegerOrLValue(E, Val, Info))
11174     return false;
11175   if (!Val.isInt()) {
11176     // FIXME: It would be better to produce the diagnostic for casting
11177     //        a pointer to an integer.
11178     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11179     return false;
11180   }
11181   Result = Val.getInt();
11182   return true;
11183 }
11184 
11185 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
11186   APValue Evaluated = E->EvaluateInContext(
11187       Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
11188   return Success(Evaluated, E);
11189 }
11190 
11191 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
11192                                EvalInfo &Info) {
11193   assert(!E->isValueDependent());
11194   if (E->getType()->isFixedPointType()) {
11195     APValue Val;
11196     if (!FixedPointExprEvaluator(Info, Val).Visit(E))
11197       return false;
11198     if (!Val.isFixedPoint())
11199       return false;
11200 
11201     Result = Val.getFixedPoint();
11202     return true;
11203   }
11204   return false;
11205 }
11206 
11207 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
11208                                         EvalInfo &Info) {
11209   assert(!E->isValueDependent());
11210   if (E->getType()->isIntegerType()) {
11211     auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
11212     APSInt Val;
11213     if (!EvaluateInteger(E, Val, Info))
11214       return false;
11215     Result = APFixedPoint(Val, FXSema);
11216     return true;
11217   } else if (E->getType()->isFixedPointType()) {
11218     return EvaluateFixedPoint(E, Result, Info);
11219   }
11220   return false;
11221 }
11222 
11223 /// Check whether the given declaration can be directly converted to an integral
11224 /// rvalue. If not, no diagnostic is produced; there are other things we can
11225 /// try.
11226 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
11227   // Enums are integer constant exprs.
11228   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
11229     // Check for signedness/width mismatches between E type and ECD value.
11230     bool SameSign = (ECD->getInitVal().isSigned()
11231                      == E->getType()->isSignedIntegerOrEnumerationType());
11232     bool SameWidth = (ECD->getInitVal().getBitWidth()
11233                       == Info.Ctx.getIntWidth(E->getType()));
11234     if (SameSign && SameWidth)
11235       return Success(ECD->getInitVal(), E);
11236     else {
11237       // Get rid of mismatch (otherwise Success assertions will fail)
11238       // by computing a new value matching the type of E.
11239       llvm::APSInt Val = ECD->getInitVal();
11240       if (!SameSign)
11241         Val.setIsSigned(!ECD->getInitVal().isSigned());
11242       if (!SameWidth)
11243         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
11244       return Success(Val, E);
11245     }
11246   }
11247   return false;
11248 }
11249 
11250 /// Values returned by __builtin_classify_type, chosen to match the values
11251 /// produced by GCC's builtin.
11252 enum class GCCTypeClass {
11253   None = -1,
11254   Void = 0,
11255   Integer = 1,
11256   // GCC reserves 2 for character types, but instead classifies them as
11257   // integers.
11258   Enum = 3,
11259   Bool = 4,
11260   Pointer = 5,
11261   // GCC reserves 6 for references, but appears to never use it (because
11262   // expressions never have reference type, presumably).
11263   PointerToDataMember = 7,
11264   RealFloat = 8,
11265   Complex = 9,
11266   // GCC reserves 10 for functions, but does not use it since GCC version 6 due
11267   // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
11268   // GCC claims to reserve 11 for pointers to member functions, but *actually*
11269   // uses 12 for that purpose, same as for a class or struct. Maybe it
11270   // internally implements a pointer to member as a struct?  Who knows.
11271   PointerToMemberFunction = 12, // Not a bug, see above.
11272   ClassOrStruct = 12,
11273   Union = 13,
11274   // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
11275   // decay to pointer. (Prior to version 6 it was only used in C++ mode).
11276   // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
11277   // literals.
11278 };
11279 
11280 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11281 /// as GCC.
11282 static GCCTypeClass
11283 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
11284   assert(!T->isDependentType() && "unexpected dependent type");
11285 
11286   QualType CanTy = T.getCanonicalType();
11287   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
11288 
11289   switch (CanTy->getTypeClass()) {
11290 #define TYPE(ID, BASE)
11291 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
11292 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
11293 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
11294 #include "clang/AST/TypeNodes.inc"
11295   case Type::Auto:
11296   case Type::DeducedTemplateSpecialization:
11297       llvm_unreachable("unexpected non-canonical or dependent type");
11298 
11299   case Type::Builtin:
11300     switch (BT->getKind()) {
11301 #define BUILTIN_TYPE(ID, SINGLETON_ID)
11302 #define SIGNED_TYPE(ID, SINGLETON_ID) \
11303     case BuiltinType::ID: return GCCTypeClass::Integer;
11304 #define FLOATING_TYPE(ID, SINGLETON_ID) \
11305     case BuiltinType::ID: return GCCTypeClass::RealFloat;
11306 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
11307     case BuiltinType::ID: break;
11308 #include "clang/AST/BuiltinTypes.def"
11309     case BuiltinType::Void:
11310       return GCCTypeClass::Void;
11311 
11312     case BuiltinType::Bool:
11313       return GCCTypeClass::Bool;
11314 
11315     case BuiltinType::Char_U:
11316     case BuiltinType::UChar:
11317     case BuiltinType::WChar_U:
11318     case BuiltinType::Char8:
11319     case BuiltinType::Char16:
11320     case BuiltinType::Char32:
11321     case BuiltinType::UShort:
11322     case BuiltinType::UInt:
11323     case BuiltinType::ULong:
11324     case BuiltinType::ULongLong:
11325     case BuiltinType::UInt128:
11326       return GCCTypeClass::Integer;
11327 
11328     case BuiltinType::UShortAccum:
11329     case BuiltinType::UAccum:
11330     case BuiltinType::ULongAccum:
11331     case BuiltinType::UShortFract:
11332     case BuiltinType::UFract:
11333     case BuiltinType::ULongFract:
11334     case BuiltinType::SatUShortAccum:
11335     case BuiltinType::SatUAccum:
11336     case BuiltinType::SatULongAccum:
11337     case BuiltinType::SatUShortFract:
11338     case BuiltinType::SatUFract:
11339     case BuiltinType::SatULongFract:
11340       return GCCTypeClass::None;
11341 
11342     case BuiltinType::NullPtr:
11343 
11344     case BuiltinType::ObjCId:
11345     case BuiltinType::ObjCClass:
11346     case BuiltinType::ObjCSel:
11347 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
11348     case BuiltinType::Id:
11349 #include "clang/Basic/OpenCLImageTypes.def"
11350 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
11351     case BuiltinType::Id:
11352 #include "clang/Basic/OpenCLExtensionTypes.def"
11353     case BuiltinType::OCLSampler:
11354     case BuiltinType::OCLEvent:
11355     case BuiltinType::OCLClkEvent:
11356     case BuiltinType::OCLQueue:
11357     case BuiltinType::OCLReserveID:
11358 #define SVE_TYPE(Name, Id, SingletonId) \
11359     case BuiltinType::Id:
11360 #include "clang/Basic/AArch64SVEACLETypes.def"
11361 #define PPC_VECTOR_TYPE(Name, Id, Size) \
11362     case BuiltinType::Id:
11363 #include "clang/Basic/PPCTypes.def"
11364 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
11365 #include "clang/Basic/RISCVVTypes.def"
11366       return GCCTypeClass::None;
11367 
11368     case BuiltinType::Dependent:
11369       llvm_unreachable("unexpected dependent type");
11370     };
11371     llvm_unreachable("unexpected placeholder type");
11372 
11373   case Type::Enum:
11374     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
11375 
11376   case Type::Pointer:
11377   case Type::ConstantArray:
11378   case Type::VariableArray:
11379   case Type::IncompleteArray:
11380   case Type::FunctionNoProto:
11381   case Type::FunctionProto:
11382     return GCCTypeClass::Pointer;
11383 
11384   case Type::MemberPointer:
11385     return CanTy->isMemberDataPointerType()
11386                ? GCCTypeClass::PointerToDataMember
11387                : GCCTypeClass::PointerToMemberFunction;
11388 
11389   case Type::Complex:
11390     return GCCTypeClass::Complex;
11391 
11392   case Type::Record:
11393     return CanTy->isUnionType() ? GCCTypeClass::Union
11394                                 : GCCTypeClass::ClassOrStruct;
11395 
11396   case Type::Atomic:
11397     // GCC classifies _Atomic T the same as T.
11398     return EvaluateBuiltinClassifyType(
11399         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
11400 
11401   case Type::BlockPointer:
11402   case Type::Vector:
11403   case Type::ExtVector:
11404   case Type::ConstantMatrix:
11405   case Type::ObjCObject:
11406   case Type::ObjCInterface:
11407   case Type::ObjCObjectPointer:
11408   case Type::Pipe:
11409   case Type::BitInt:
11410     // GCC classifies vectors as None. We follow its lead and classify all
11411     // other types that don't fit into the regular classification the same way.
11412     return GCCTypeClass::None;
11413 
11414   case Type::LValueReference:
11415   case Type::RValueReference:
11416     llvm_unreachable("invalid type for expression");
11417   }
11418 
11419   llvm_unreachable("unexpected type class");
11420 }
11421 
11422 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11423 /// as GCC.
11424 static GCCTypeClass
11425 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
11426   // If no argument was supplied, default to None. This isn't
11427   // ideal, however it is what gcc does.
11428   if (E->getNumArgs() == 0)
11429     return GCCTypeClass::None;
11430 
11431   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
11432   // being an ICE, but still folds it to a constant using the type of the first
11433   // argument.
11434   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
11435 }
11436 
11437 /// EvaluateBuiltinConstantPForLValue - Determine the result of
11438 /// __builtin_constant_p when applied to the given pointer.
11439 ///
11440 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
11441 /// or it points to the first character of a string literal.
11442 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
11443   APValue::LValueBase Base = LV.getLValueBase();
11444   if (Base.isNull()) {
11445     // A null base is acceptable.
11446     return true;
11447   } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
11448     if (!isa<StringLiteral>(E))
11449       return false;
11450     return LV.getLValueOffset().isZero();
11451   } else if (Base.is<TypeInfoLValue>()) {
11452     // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
11453     // evaluate to true.
11454     return true;
11455   } else {
11456     // Any other base is not constant enough for GCC.
11457     return false;
11458   }
11459 }
11460 
11461 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
11462 /// GCC as we can manage.
11463 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
11464   // This evaluation is not permitted to have side-effects, so evaluate it in
11465   // a speculative evaluation context.
11466   SpeculativeEvaluationRAII SpeculativeEval(Info);
11467 
11468   // Constant-folding is always enabled for the operand of __builtin_constant_p
11469   // (even when the enclosing evaluation context otherwise requires a strict
11470   // language-specific constant expression).
11471   FoldConstant Fold(Info, true);
11472 
11473   QualType ArgType = Arg->getType();
11474 
11475   // __builtin_constant_p always has one operand. The rules which gcc follows
11476   // are not precisely documented, but are as follows:
11477   //
11478   //  - If the operand is of integral, floating, complex or enumeration type,
11479   //    and can be folded to a known value of that type, it returns 1.
11480   //  - If the operand can be folded to a pointer to the first character
11481   //    of a string literal (or such a pointer cast to an integral type)
11482   //    or to a null pointer or an integer cast to a pointer, it returns 1.
11483   //
11484   // Otherwise, it returns 0.
11485   //
11486   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
11487   // its support for this did not work prior to GCC 9 and is not yet well
11488   // understood.
11489   if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
11490       ArgType->isAnyComplexType() || ArgType->isPointerType() ||
11491       ArgType->isNullPtrType()) {
11492     APValue V;
11493     if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
11494       Fold.keepDiagnostics();
11495       return false;
11496     }
11497 
11498     // For a pointer (possibly cast to integer), there are special rules.
11499     if (V.getKind() == APValue::LValue)
11500       return EvaluateBuiltinConstantPForLValue(V);
11501 
11502     // Otherwise, any constant value is good enough.
11503     return V.hasValue();
11504   }
11505 
11506   // Anything else isn't considered to be sufficiently constant.
11507   return false;
11508 }
11509 
11510 /// Retrieves the "underlying object type" of the given expression,
11511 /// as used by __builtin_object_size.
11512 static QualType getObjectType(APValue::LValueBase B) {
11513   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
11514     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
11515       return VD->getType();
11516   } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
11517     if (isa<CompoundLiteralExpr>(E))
11518       return E->getType();
11519   } else if (B.is<TypeInfoLValue>()) {
11520     return B.getTypeInfoType();
11521   } else if (B.is<DynamicAllocLValue>()) {
11522     return B.getDynamicAllocType();
11523   }
11524 
11525   return QualType();
11526 }
11527 
11528 /// A more selective version of E->IgnoreParenCasts for
11529 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
11530 /// to change the type of E.
11531 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
11532 ///
11533 /// Always returns an RValue with a pointer representation.
11534 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
11535   assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
11536 
11537   auto *NoParens = E->IgnoreParens();
11538   auto *Cast = dyn_cast<CastExpr>(NoParens);
11539   if (Cast == nullptr)
11540     return NoParens;
11541 
11542   // We only conservatively allow a few kinds of casts, because this code is
11543   // inherently a simple solution that seeks to support the common case.
11544   auto CastKind = Cast->getCastKind();
11545   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
11546       CastKind != CK_AddressSpaceConversion)
11547     return NoParens;
11548 
11549   auto *SubExpr = Cast->getSubExpr();
11550   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
11551     return NoParens;
11552   return ignorePointerCastsAndParens(SubExpr);
11553 }
11554 
11555 /// Checks to see if the given LValue's Designator is at the end of the LValue's
11556 /// record layout. e.g.
11557 ///   struct { struct { int a, b; } fst, snd; } obj;
11558 ///   obj.fst   // no
11559 ///   obj.snd   // yes
11560 ///   obj.fst.a // no
11561 ///   obj.fst.b // no
11562 ///   obj.snd.a // no
11563 ///   obj.snd.b // yes
11564 ///
11565 /// Please note: this function is specialized for how __builtin_object_size
11566 /// views "objects".
11567 ///
11568 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
11569 /// correct result, it will always return true.
11570 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
11571   assert(!LVal.Designator.Invalid);
11572 
11573   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
11574     const RecordDecl *Parent = FD->getParent();
11575     Invalid = Parent->isInvalidDecl();
11576     if (Invalid || Parent->isUnion())
11577       return true;
11578     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
11579     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
11580   };
11581 
11582   auto &Base = LVal.getLValueBase();
11583   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
11584     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
11585       bool Invalid;
11586       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11587         return Invalid;
11588     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
11589       for (auto *FD : IFD->chain()) {
11590         bool Invalid;
11591         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
11592           return Invalid;
11593       }
11594     }
11595   }
11596 
11597   unsigned I = 0;
11598   QualType BaseType = getType(Base);
11599   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
11600     // If we don't know the array bound, conservatively assume we're looking at
11601     // the final array element.
11602     ++I;
11603     if (BaseType->isIncompleteArrayType())
11604       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
11605     else
11606       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
11607   }
11608 
11609   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
11610     const auto &Entry = LVal.Designator.Entries[I];
11611     if (BaseType->isArrayType()) {
11612       // Because __builtin_object_size treats arrays as objects, we can ignore
11613       // the index iff this is the last array in the Designator.
11614       if (I + 1 == E)
11615         return true;
11616       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
11617       uint64_t Index = Entry.getAsArrayIndex();
11618       if (Index + 1 != CAT->getSize())
11619         return false;
11620       BaseType = CAT->getElementType();
11621     } else if (BaseType->isAnyComplexType()) {
11622       const auto *CT = BaseType->castAs<ComplexType>();
11623       uint64_t Index = Entry.getAsArrayIndex();
11624       if (Index != 1)
11625         return false;
11626       BaseType = CT->getElementType();
11627     } else if (auto *FD = getAsField(Entry)) {
11628       bool Invalid;
11629       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11630         return Invalid;
11631       BaseType = FD->getType();
11632     } else {
11633       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
11634       return false;
11635     }
11636   }
11637   return true;
11638 }
11639 
11640 /// Tests to see if the LValue has a user-specified designator (that isn't
11641 /// necessarily valid). Note that this always returns 'true' if the LValue has
11642 /// an unsized array as its first designator entry, because there's currently no
11643 /// way to tell if the user typed *foo or foo[0].
11644 static bool refersToCompleteObject(const LValue &LVal) {
11645   if (LVal.Designator.Invalid)
11646     return false;
11647 
11648   if (!LVal.Designator.Entries.empty())
11649     return LVal.Designator.isMostDerivedAnUnsizedArray();
11650 
11651   if (!LVal.InvalidBase)
11652     return true;
11653 
11654   // If `E` is a MemberExpr, then the first part of the designator is hiding in
11655   // the LValueBase.
11656   const auto *E = LVal.Base.dyn_cast<const Expr *>();
11657   return !E || !isa<MemberExpr>(E);
11658 }
11659 
11660 /// Attempts to detect a user writing into a piece of memory that's impossible
11661 /// to figure out the size of by just using types.
11662 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
11663   const SubobjectDesignator &Designator = LVal.Designator;
11664   // Notes:
11665   // - Users can only write off of the end when we have an invalid base. Invalid
11666   //   bases imply we don't know where the memory came from.
11667   // - We used to be a bit more aggressive here; we'd only be conservative if
11668   //   the array at the end was flexible, or if it had 0 or 1 elements. This
11669   //   broke some common standard library extensions (PR30346), but was
11670   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
11671   //   with some sort of list. OTOH, it seems that GCC is always
11672   //   conservative with the last element in structs (if it's an array), so our
11673   //   current behavior is more compatible than an explicit list approach would
11674   //   be.
11675   auto isFlexibleArrayMember = [&] {
11676     using FAMKind = LangOptions::StrictFlexArraysLevelKind;
11677     FAMKind StrictFlexArraysLevel =
11678         Ctx.getLangOpts().getStrictFlexArraysLevel();
11679 
11680     if (Designator.isMostDerivedAnUnsizedArray())
11681       return true;
11682 
11683     if (StrictFlexArraysLevel == FAMKind::Default)
11684       return true;
11685 
11686     if (Designator.getMostDerivedArraySize() == 0 &&
11687         StrictFlexArraysLevel != FAMKind::IncompleteOnly)
11688       return true;
11689 
11690     if (Designator.getMostDerivedArraySize() == 1 &&
11691         StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete)
11692       return true;
11693 
11694     return false;
11695   };
11696 
11697   return LVal.InvalidBase &&
11698          Designator.Entries.size() == Designator.MostDerivedPathLength &&
11699          Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() &&
11700          isDesignatorAtObjectEnd(Ctx, LVal);
11701 }
11702 
11703 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
11704 /// Fails if the conversion would cause loss of precision.
11705 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
11706                                             CharUnits &Result) {
11707   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
11708   if (Int.ugt(CharUnitsMax))
11709     return false;
11710   Result = CharUnits::fromQuantity(Int.getZExtValue());
11711   return true;
11712 }
11713 
11714 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
11715 /// determine how many bytes exist from the beginning of the object to either
11716 /// the end of the current subobject, or the end of the object itself, depending
11717 /// on what the LValue looks like + the value of Type.
11718 ///
11719 /// If this returns false, the value of Result is undefined.
11720 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
11721                                unsigned Type, const LValue &LVal,
11722                                CharUnits &EndOffset) {
11723   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
11724 
11725   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
11726     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
11727       return false;
11728     return HandleSizeof(Info, ExprLoc, Ty, Result);
11729   };
11730 
11731   // We want to evaluate the size of the entire object. This is a valid fallback
11732   // for when Type=1 and the designator is invalid, because we're asked for an
11733   // upper-bound.
11734   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
11735     // Type=3 wants a lower bound, so we can't fall back to this.
11736     if (Type == 3 && !DetermineForCompleteObject)
11737       return false;
11738 
11739     llvm::APInt APEndOffset;
11740     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11741         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11742       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11743 
11744     if (LVal.InvalidBase)
11745       return false;
11746 
11747     QualType BaseTy = getObjectType(LVal.getLValueBase());
11748     return CheckedHandleSizeof(BaseTy, EndOffset);
11749   }
11750 
11751   // We want to evaluate the size of a subobject.
11752   const SubobjectDesignator &Designator = LVal.Designator;
11753 
11754   // The following is a moderately common idiom in C:
11755   //
11756   // struct Foo { int a; char c[1]; };
11757   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
11758   // strcpy(&F->c[0], Bar);
11759   //
11760   // In order to not break too much legacy code, we need to support it.
11761   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
11762     // If we can resolve this to an alloc_size call, we can hand that back,
11763     // because we know for certain how many bytes there are to write to.
11764     llvm::APInt APEndOffset;
11765     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11766         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11767       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11768 
11769     // If we cannot determine the size of the initial allocation, then we can't
11770     // given an accurate upper-bound. However, we are still able to give
11771     // conservative lower-bounds for Type=3.
11772     if (Type == 1)
11773       return false;
11774   }
11775 
11776   CharUnits BytesPerElem;
11777   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
11778     return false;
11779 
11780   // According to the GCC documentation, we want the size of the subobject
11781   // denoted by the pointer. But that's not quite right -- what we actually
11782   // want is the size of the immediately-enclosing array, if there is one.
11783   int64_t ElemsRemaining;
11784   if (Designator.MostDerivedIsArrayElement &&
11785       Designator.Entries.size() == Designator.MostDerivedPathLength) {
11786     uint64_t ArraySize = Designator.getMostDerivedArraySize();
11787     uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
11788     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
11789   } else {
11790     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
11791   }
11792 
11793   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
11794   return true;
11795 }
11796 
11797 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
11798 /// returns true and stores the result in @p Size.
11799 ///
11800 /// If @p WasError is non-null, this will report whether the failure to evaluate
11801 /// is to be treated as an Error in IntExprEvaluator.
11802 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
11803                                          EvalInfo &Info, uint64_t &Size) {
11804   // Determine the denoted object.
11805   LValue LVal;
11806   {
11807     // The operand of __builtin_object_size is never evaluated for side-effects.
11808     // If there are any, but we can determine the pointed-to object anyway, then
11809     // ignore the side-effects.
11810     SpeculativeEvaluationRAII SpeculativeEval(Info);
11811     IgnoreSideEffectsRAII Fold(Info);
11812 
11813     if (E->isGLValue()) {
11814       // It's possible for us to be given GLValues if we're called via
11815       // Expr::tryEvaluateObjectSize.
11816       APValue RVal;
11817       if (!EvaluateAsRValue(Info, E, RVal))
11818         return false;
11819       LVal.setFrom(Info.Ctx, RVal);
11820     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
11821                                 /*InvalidBaseOK=*/true))
11822       return false;
11823   }
11824 
11825   // If we point to before the start of the object, there are no accessible
11826   // bytes.
11827   if (LVal.getLValueOffset().isNegative()) {
11828     Size = 0;
11829     return true;
11830   }
11831 
11832   CharUnits EndOffset;
11833   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
11834     return false;
11835 
11836   // If we've fallen outside of the end offset, just pretend there's nothing to
11837   // write to/read from.
11838   if (EndOffset <= LVal.getLValueOffset())
11839     Size = 0;
11840   else
11841     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
11842   return true;
11843 }
11844 
11845 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
11846   if (!IsConstantEvaluatedBuiltinCall(E))
11847     return ExprEvaluatorBaseTy::VisitCallExpr(E);
11848   return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
11849 }
11850 
11851 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
11852                                      APValue &Val, APSInt &Alignment) {
11853   QualType SrcTy = E->getArg(0)->getType();
11854   if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
11855     return false;
11856   // Even though we are evaluating integer expressions we could get a pointer
11857   // argument for the __builtin_is_aligned() case.
11858   if (SrcTy->isPointerType()) {
11859     LValue Ptr;
11860     if (!EvaluatePointer(E->getArg(0), Ptr, Info))
11861       return false;
11862     Ptr.moveInto(Val);
11863   } else if (!SrcTy->isIntegralOrEnumerationType()) {
11864     Info.FFDiag(E->getArg(0));
11865     return false;
11866   } else {
11867     APSInt SrcInt;
11868     if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
11869       return false;
11870     assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
11871            "Bit widths must be the same");
11872     Val = APValue(SrcInt);
11873   }
11874   assert(Val.hasValue());
11875   return true;
11876 }
11877 
11878 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
11879                                             unsigned BuiltinOp) {
11880   switch (BuiltinOp) {
11881   default:
11882     return false;
11883 
11884   case Builtin::BI__builtin_dynamic_object_size:
11885   case Builtin::BI__builtin_object_size: {
11886     // The type was checked when we built the expression.
11887     unsigned Type =
11888         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11889     assert(Type <= 3 && "unexpected type");
11890 
11891     uint64_t Size;
11892     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
11893       return Success(Size, E);
11894 
11895     if (E->getArg(0)->HasSideEffects(Info.Ctx))
11896       return Success((Type & 2) ? 0 : -1, E);
11897 
11898     // Expression had no side effects, but we couldn't statically determine the
11899     // size of the referenced object.
11900     switch (Info.EvalMode) {
11901     case EvalInfo::EM_ConstantExpression:
11902     case EvalInfo::EM_ConstantFold:
11903     case EvalInfo::EM_IgnoreSideEffects:
11904       // Leave it to IR generation.
11905       return Error(E);
11906     case EvalInfo::EM_ConstantExpressionUnevaluated:
11907       // Reduce it to a constant now.
11908       return Success((Type & 2) ? 0 : -1, E);
11909     }
11910 
11911     llvm_unreachable("unexpected EvalMode");
11912   }
11913 
11914   case Builtin::BI__builtin_os_log_format_buffer_size: {
11915     analyze_os_log::OSLogBufferLayout Layout;
11916     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
11917     return Success(Layout.size().getQuantity(), E);
11918   }
11919 
11920   case Builtin::BI__builtin_is_aligned: {
11921     APValue Src;
11922     APSInt Alignment;
11923     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11924       return false;
11925     if (Src.isLValue()) {
11926       // If we evaluated a pointer, check the minimum known alignment.
11927       LValue Ptr;
11928       Ptr.setFrom(Info.Ctx, Src);
11929       CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
11930       CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
11931       // We can return true if the known alignment at the computed offset is
11932       // greater than the requested alignment.
11933       assert(PtrAlign.isPowerOfTwo());
11934       assert(Alignment.isPowerOf2());
11935       if (PtrAlign.getQuantity() >= Alignment)
11936         return Success(1, E);
11937       // If the alignment is not known to be sufficient, some cases could still
11938       // be aligned at run time. However, if the requested alignment is less or
11939       // equal to the base alignment and the offset is not aligned, we know that
11940       // the run-time value can never be aligned.
11941       if (BaseAlignment.getQuantity() >= Alignment &&
11942           PtrAlign.getQuantity() < Alignment)
11943         return Success(0, E);
11944       // Otherwise we can't infer whether the value is sufficiently aligned.
11945       // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
11946       //  in cases where we can't fully evaluate the pointer.
11947       Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
11948           << Alignment;
11949       return false;
11950     }
11951     assert(Src.isInt());
11952     return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
11953   }
11954   case Builtin::BI__builtin_align_up: {
11955     APValue Src;
11956     APSInt Alignment;
11957     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11958       return false;
11959     if (!Src.isInt())
11960       return Error(E);
11961     APSInt AlignedVal =
11962         APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
11963                Src.getInt().isUnsigned());
11964     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11965     return Success(AlignedVal, E);
11966   }
11967   case Builtin::BI__builtin_align_down: {
11968     APValue Src;
11969     APSInt Alignment;
11970     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11971       return false;
11972     if (!Src.isInt())
11973       return Error(E);
11974     APSInt AlignedVal =
11975         APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
11976     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11977     return Success(AlignedVal, E);
11978   }
11979 
11980   case Builtin::BI__builtin_bitreverse8:
11981   case Builtin::BI__builtin_bitreverse16:
11982   case Builtin::BI__builtin_bitreverse32:
11983   case Builtin::BI__builtin_bitreverse64: {
11984     APSInt Val;
11985     if (!EvaluateInteger(E->getArg(0), Val, Info))
11986       return false;
11987 
11988     return Success(Val.reverseBits(), E);
11989   }
11990 
11991   case Builtin::BI__builtin_bswap16:
11992   case Builtin::BI__builtin_bswap32:
11993   case Builtin::BI__builtin_bswap64: {
11994     APSInt Val;
11995     if (!EvaluateInteger(E->getArg(0), Val, Info))
11996       return false;
11997 
11998     return Success(Val.byteSwap(), E);
11999   }
12000 
12001   case Builtin::BI__builtin_classify_type:
12002     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
12003 
12004   case Builtin::BI__builtin_clrsb:
12005   case Builtin::BI__builtin_clrsbl:
12006   case Builtin::BI__builtin_clrsbll: {
12007     APSInt Val;
12008     if (!EvaluateInteger(E->getArg(0), Val, Info))
12009       return false;
12010 
12011     return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
12012   }
12013 
12014   case Builtin::BI__builtin_clz:
12015   case Builtin::BI__builtin_clzl:
12016   case Builtin::BI__builtin_clzll:
12017   case Builtin::BI__builtin_clzs: {
12018     APSInt Val;
12019     if (!EvaluateInteger(E->getArg(0), Val, Info))
12020       return false;
12021     if (!Val)
12022       return Error(E);
12023 
12024     return Success(Val.countLeadingZeros(), E);
12025   }
12026 
12027   case Builtin::BI__builtin_constant_p: {
12028     const Expr *Arg = E->getArg(0);
12029     if (EvaluateBuiltinConstantP(Info, Arg))
12030       return Success(true, E);
12031     if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
12032       // Outside a constant context, eagerly evaluate to false in the presence
12033       // of side-effects in order to avoid -Wunsequenced false-positives in
12034       // a branch on __builtin_constant_p(expr).
12035       return Success(false, E);
12036     }
12037     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12038     return false;
12039   }
12040 
12041   case Builtin::BI__builtin_is_constant_evaluated: {
12042     const auto *Callee = Info.CurrentCall->getCallee();
12043     if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
12044         (Info.CallStackDepth == 1 ||
12045          (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
12046           Callee->getIdentifier() &&
12047           Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
12048       // FIXME: Find a better way to avoid duplicated diagnostics.
12049       if (Info.EvalStatus.Diag)
12050         Info.report((Info.CallStackDepth == 1) ? E->getExprLoc()
12051                                                : Info.CurrentCall->CallLoc,
12052                     diag::warn_is_constant_evaluated_always_true_constexpr)
12053             << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
12054                                          : "std::is_constant_evaluated");
12055     }
12056 
12057     return Success(Info.InConstantContext, E);
12058   }
12059 
12060   case Builtin::BI__builtin_ctz:
12061   case Builtin::BI__builtin_ctzl:
12062   case Builtin::BI__builtin_ctzll:
12063   case Builtin::BI__builtin_ctzs: {
12064     APSInt Val;
12065     if (!EvaluateInteger(E->getArg(0), Val, Info))
12066       return false;
12067     if (!Val)
12068       return Error(E);
12069 
12070     return Success(Val.countTrailingZeros(), E);
12071   }
12072 
12073   case Builtin::BI__builtin_eh_return_data_regno: {
12074     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
12075     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
12076     return Success(Operand, E);
12077   }
12078 
12079   case Builtin::BI__builtin_expect:
12080   case Builtin::BI__builtin_expect_with_probability:
12081     return Visit(E->getArg(0));
12082 
12083   case Builtin::BI__builtin_ffs:
12084   case Builtin::BI__builtin_ffsl:
12085   case Builtin::BI__builtin_ffsll: {
12086     APSInt Val;
12087     if (!EvaluateInteger(E->getArg(0), Val, Info))
12088       return false;
12089 
12090     unsigned N = Val.countTrailingZeros();
12091     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
12092   }
12093 
12094   case Builtin::BI__builtin_fpclassify: {
12095     APFloat Val(0.0);
12096     if (!EvaluateFloat(E->getArg(5), Val, Info))
12097       return false;
12098     unsigned Arg;
12099     switch (Val.getCategory()) {
12100     case APFloat::fcNaN: Arg = 0; break;
12101     case APFloat::fcInfinity: Arg = 1; break;
12102     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
12103     case APFloat::fcZero: Arg = 4; break;
12104     }
12105     return Visit(E->getArg(Arg));
12106   }
12107 
12108   case Builtin::BI__builtin_isinf_sign: {
12109     APFloat Val(0.0);
12110     return EvaluateFloat(E->getArg(0), Val, Info) &&
12111            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
12112   }
12113 
12114   case Builtin::BI__builtin_isinf: {
12115     APFloat Val(0.0);
12116     return EvaluateFloat(E->getArg(0), Val, Info) &&
12117            Success(Val.isInfinity() ? 1 : 0, E);
12118   }
12119 
12120   case Builtin::BI__builtin_isfinite: {
12121     APFloat Val(0.0);
12122     return EvaluateFloat(E->getArg(0), Val, Info) &&
12123            Success(Val.isFinite() ? 1 : 0, E);
12124   }
12125 
12126   case Builtin::BI__builtin_isnan: {
12127     APFloat Val(0.0);
12128     return EvaluateFloat(E->getArg(0), Val, Info) &&
12129            Success(Val.isNaN() ? 1 : 0, E);
12130   }
12131 
12132   case Builtin::BI__builtin_isnormal: {
12133     APFloat Val(0.0);
12134     return EvaluateFloat(E->getArg(0), Val, Info) &&
12135            Success(Val.isNormal() ? 1 : 0, E);
12136   }
12137 
12138   case Builtin::BI__builtin_parity:
12139   case Builtin::BI__builtin_parityl:
12140   case Builtin::BI__builtin_parityll: {
12141     APSInt Val;
12142     if (!EvaluateInteger(E->getArg(0), Val, Info))
12143       return false;
12144 
12145     return Success(Val.countPopulation() % 2, E);
12146   }
12147 
12148   case Builtin::BI__builtin_popcount:
12149   case Builtin::BI__builtin_popcountl:
12150   case Builtin::BI__builtin_popcountll: {
12151     APSInt Val;
12152     if (!EvaluateInteger(E->getArg(0), Val, Info))
12153       return false;
12154 
12155     return Success(Val.countPopulation(), E);
12156   }
12157 
12158   case Builtin::BI__builtin_rotateleft8:
12159   case Builtin::BI__builtin_rotateleft16:
12160   case Builtin::BI__builtin_rotateleft32:
12161   case Builtin::BI__builtin_rotateleft64:
12162   case Builtin::BI_rotl8: // Microsoft variants of rotate right
12163   case Builtin::BI_rotl16:
12164   case Builtin::BI_rotl:
12165   case Builtin::BI_lrotl:
12166   case Builtin::BI_rotl64: {
12167     APSInt Val, Amt;
12168     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
12169         !EvaluateInteger(E->getArg(1), Amt, Info))
12170       return false;
12171 
12172     return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
12173   }
12174 
12175   case Builtin::BI__builtin_rotateright8:
12176   case Builtin::BI__builtin_rotateright16:
12177   case Builtin::BI__builtin_rotateright32:
12178   case Builtin::BI__builtin_rotateright64:
12179   case Builtin::BI_rotr8: // Microsoft variants of rotate right
12180   case Builtin::BI_rotr16:
12181   case Builtin::BI_rotr:
12182   case Builtin::BI_lrotr:
12183   case Builtin::BI_rotr64: {
12184     APSInt Val, Amt;
12185     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
12186         !EvaluateInteger(E->getArg(1), Amt, Info))
12187       return false;
12188 
12189     return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
12190   }
12191 
12192   case Builtin::BIstrlen:
12193   case Builtin::BIwcslen:
12194     // A call to strlen is not a constant expression.
12195     if (Info.getLangOpts().CPlusPlus11)
12196       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
12197           << /*isConstexpr*/ 0 << /*isConstructor*/ 0
12198           << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
12199     else
12200       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12201     [[fallthrough]];
12202   case Builtin::BI__builtin_strlen:
12203   case Builtin::BI__builtin_wcslen: {
12204     // As an extension, we support __builtin_strlen() as a constant expression,
12205     // and support folding strlen() to a constant.
12206     uint64_t StrLen;
12207     if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
12208       return Success(StrLen, E);
12209     return false;
12210   }
12211 
12212   case Builtin::BIstrcmp:
12213   case Builtin::BIwcscmp:
12214   case Builtin::BIstrncmp:
12215   case Builtin::BIwcsncmp:
12216   case Builtin::BImemcmp:
12217   case Builtin::BIbcmp:
12218   case Builtin::BIwmemcmp:
12219     // A call to strlen is not a constant expression.
12220     if (Info.getLangOpts().CPlusPlus11)
12221       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
12222           << /*isConstexpr*/ 0 << /*isConstructor*/ 0
12223           << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
12224     else
12225       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12226     [[fallthrough]];
12227   case Builtin::BI__builtin_strcmp:
12228   case Builtin::BI__builtin_wcscmp:
12229   case Builtin::BI__builtin_strncmp:
12230   case Builtin::BI__builtin_wcsncmp:
12231   case Builtin::BI__builtin_memcmp:
12232   case Builtin::BI__builtin_bcmp:
12233   case Builtin::BI__builtin_wmemcmp: {
12234     LValue String1, String2;
12235     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
12236         !EvaluatePointer(E->getArg(1), String2, Info))
12237       return false;
12238 
12239     uint64_t MaxLength = uint64_t(-1);
12240     if (BuiltinOp != Builtin::BIstrcmp &&
12241         BuiltinOp != Builtin::BIwcscmp &&
12242         BuiltinOp != Builtin::BI__builtin_strcmp &&
12243         BuiltinOp != Builtin::BI__builtin_wcscmp) {
12244       APSInt N;
12245       if (!EvaluateInteger(E->getArg(2), N, Info))
12246         return false;
12247       MaxLength = N.getExtValue();
12248     }
12249 
12250     // Empty substrings compare equal by definition.
12251     if (MaxLength == 0u)
12252       return Success(0, E);
12253 
12254     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
12255         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
12256         String1.Designator.Invalid || String2.Designator.Invalid)
12257       return false;
12258 
12259     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
12260     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
12261 
12262     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
12263                      BuiltinOp == Builtin::BIbcmp ||
12264                      BuiltinOp == Builtin::BI__builtin_memcmp ||
12265                      BuiltinOp == Builtin::BI__builtin_bcmp;
12266 
12267     assert(IsRawByte ||
12268            (Info.Ctx.hasSameUnqualifiedType(
12269                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
12270             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
12271 
12272     // For memcmp, allow comparing any arrays of '[[un]signed] char' or
12273     // 'char8_t', but no other types.
12274     if (IsRawByte &&
12275         !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
12276       // FIXME: Consider using our bit_cast implementation to support this.
12277       Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
12278           << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str()
12279           << CharTy1 << CharTy2;
12280       return false;
12281     }
12282 
12283     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
12284       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
12285              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
12286              Char1.isInt() && Char2.isInt();
12287     };
12288     const auto &AdvanceElems = [&] {
12289       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
12290              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
12291     };
12292 
12293     bool StopAtNull =
12294         (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
12295          BuiltinOp != Builtin::BIwmemcmp &&
12296          BuiltinOp != Builtin::BI__builtin_memcmp &&
12297          BuiltinOp != Builtin::BI__builtin_bcmp &&
12298          BuiltinOp != Builtin::BI__builtin_wmemcmp);
12299     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
12300                   BuiltinOp == Builtin::BIwcsncmp ||
12301                   BuiltinOp == Builtin::BIwmemcmp ||
12302                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
12303                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
12304                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
12305 
12306     for (; MaxLength; --MaxLength) {
12307       APValue Char1, Char2;
12308       if (!ReadCurElems(Char1, Char2))
12309         return false;
12310       if (Char1.getInt().ne(Char2.getInt())) {
12311         if (IsWide) // wmemcmp compares with wchar_t signedness.
12312           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
12313         // memcmp always compares unsigned chars.
12314         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
12315       }
12316       if (StopAtNull && !Char1.getInt())
12317         return Success(0, E);
12318       assert(!(StopAtNull && !Char2.getInt()));
12319       if (!AdvanceElems())
12320         return false;
12321     }
12322     // We hit the strncmp / memcmp limit.
12323     return Success(0, E);
12324   }
12325 
12326   case Builtin::BI__atomic_always_lock_free:
12327   case Builtin::BI__atomic_is_lock_free:
12328   case Builtin::BI__c11_atomic_is_lock_free: {
12329     APSInt SizeVal;
12330     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
12331       return false;
12332 
12333     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
12334     // of two less than or equal to the maximum inline atomic width, we know it
12335     // is lock-free.  If the size isn't a power of two, or greater than the
12336     // maximum alignment where we promote atomics, we know it is not lock-free
12337     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
12338     // the answer can only be determined at runtime; for example, 16-byte
12339     // atomics have lock-free implementations on some, but not all,
12340     // x86-64 processors.
12341 
12342     // Check power-of-two.
12343     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
12344     if (Size.isPowerOfTwo()) {
12345       // Check against inlining width.
12346       unsigned InlineWidthBits =
12347           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
12348       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
12349         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
12350             Size == CharUnits::One() ||
12351             E->getArg(1)->isNullPointerConstant(Info.Ctx,
12352                                                 Expr::NPC_NeverValueDependent))
12353           // OK, we will inline appropriately-aligned operations of this size,
12354           // and _Atomic(T) is appropriately-aligned.
12355           return Success(1, E);
12356 
12357         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
12358           castAs<PointerType>()->getPointeeType();
12359         if (!PointeeType->isIncompleteType() &&
12360             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
12361           // OK, we will inline operations on this object.
12362           return Success(1, E);
12363         }
12364       }
12365     }
12366 
12367     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
12368         Success(0, E) : Error(E);
12369   }
12370   case Builtin::BI__builtin_add_overflow:
12371   case Builtin::BI__builtin_sub_overflow:
12372   case Builtin::BI__builtin_mul_overflow:
12373   case Builtin::BI__builtin_sadd_overflow:
12374   case Builtin::BI__builtin_uadd_overflow:
12375   case Builtin::BI__builtin_uaddl_overflow:
12376   case Builtin::BI__builtin_uaddll_overflow:
12377   case Builtin::BI__builtin_usub_overflow:
12378   case Builtin::BI__builtin_usubl_overflow:
12379   case Builtin::BI__builtin_usubll_overflow:
12380   case Builtin::BI__builtin_umul_overflow:
12381   case Builtin::BI__builtin_umull_overflow:
12382   case Builtin::BI__builtin_umulll_overflow:
12383   case Builtin::BI__builtin_saddl_overflow:
12384   case Builtin::BI__builtin_saddll_overflow:
12385   case Builtin::BI__builtin_ssub_overflow:
12386   case Builtin::BI__builtin_ssubl_overflow:
12387   case Builtin::BI__builtin_ssubll_overflow:
12388   case Builtin::BI__builtin_smul_overflow:
12389   case Builtin::BI__builtin_smull_overflow:
12390   case Builtin::BI__builtin_smulll_overflow: {
12391     LValue ResultLValue;
12392     APSInt LHS, RHS;
12393 
12394     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
12395     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
12396         !EvaluateInteger(E->getArg(1), RHS, Info) ||
12397         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
12398       return false;
12399 
12400     APSInt Result;
12401     bool DidOverflow = false;
12402 
12403     // If the types don't have to match, enlarge all 3 to the largest of them.
12404     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12405         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12406         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12407       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
12408                       ResultType->isSignedIntegerOrEnumerationType();
12409       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
12410                       ResultType->isSignedIntegerOrEnumerationType();
12411       uint64_t LHSSize = LHS.getBitWidth();
12412       uint64_t RHSSize = RHS.getBitWidth();
12413       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
12414       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
12415 
12416       // Add an additional bit if the signedness isn't uniformly agreed to. We
12417       // could do this ONLY if there is a signed and an unsigned that both have
12418       // MaxBits, but the code to check that is pretty nasty.  The issue will be
12419       // caught in the shrink-to-result later anyway.
12420       if (IsSigned && !AllSigned)
12421         ++MaxBits;
12422 
12423       LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
12424       RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
12425       Result = APSInt(MaxBits, !IsSigned);
12426     }
12427 
12428     // Find largest int.
12429     switch (BuiltinOp) {
12430     default:
12431       llvm_unreachable("Invalid value for BuiltinOp");
12432     case Builtin::BI__builtin_add_overflow:
12433     case Builtin::BI__builtin_sadd_overflow:
12434     case Builtin::BI__builtin_saddl_overflow:
12435     case Builtin::BI__builtin_saddll_overflow:
12436     case Builtin::BI__builtin_uadd_overflow:
12437     case Builtin::BI__builtin_uaddl_overflow:
12438     case Builtin::BI__builtin_uaddll_overflow:
12439       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
12440                               : LHS.uadd_ov(RHS, DidOverflow);
12441       break;
12442     case Builtin::BI__builtin_sub_overflow:
12443     case Builtin::BI__builtin_ssub_overflow:
12444     case Builtin::BI__builtin_ssubl_overflow:
12445     case Builtin::BI__builtin_ssubll_overflow:
12446     case Builtin::BI__builtin_usub_overflow:
12447     case Builtin::BI__builtin_usubl_overflow:
12448     case Builtin::BI__builtin_usubll_overflow:
12449       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
12450                               : LHS.usub_ov(RHS, DidOverflow);
12451       break;
12452     case Builtin::BI__builtin_mul_overflow:
12453     case Builtin::BI__builtin_smul_overflow:
12454     case Builtin::BI__builtin_smull_overflow:
12455     case Builtin::BI__builtin_smulll_overflow:
12456     case Builtin::BI__builtin_umul_overflow:
12457     case Builtin::BI__builtin_umull_overflow:
12458     case Builtin::BI__builtin_umulll_overflow:
12459       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
12460                               : LHS.umul_ov(RHS, DidOverflow);
12461       break;
12462     }
12463 
12464     // In the case where multiple sizes are allowed, truncate and see if
12465     // the values are the same.
12466     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12467         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12468         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12469       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
12470       // since it will give us the behavior of a TruncOrSelf in the case where
12471       // its parameter <= its size.  We previously set Result to be at least the
12472       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
12473       // will work exactly like TruncOrSelf.
12474       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
12475       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
12476 
12477       if (!APSInt::isSameValue(Temp, Result))
12478         DidOverflow = true;
12479       Result = Temp;
12480     }
12481 
12482     APValue APV{Result};
12483     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
12484       return false;
12485     return Success(DidOverflow, E);
12486   }
12487   }
12488 }
12489 
12490 /// Determine whether this is a pointer past the end of the complete
12491 /// object referred to by the lvalue.
12492 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
12493                                             const LValue &LV) {
12494   // A null pointer can be viewed as being "past the end" but we don't
12495   // choose to look at it that way here.
12496   if (!LV.getLValueBase())
12497     return false;
12498 
12499   // If the designator is valid and refers to a subobject, we're not pointing
12500   // past the end.
12501   if (!LV.getLValueDesignator().Invalid &&
12502       !LV.getLValueDesignator().isOnePastTheEnd())
12503     return false;
12504 
12505   // A pointer to an incomplete type might be past-the-end if the type's size is
12506   // zero.  We cannot tell because the type is incomplete.
12507   QualType Ty = getType(LV.getLValueBase());
12508   if (Ty->isIncompleteType())
12509     return true;
12510 
12511   // We're a past-the-end pointer if we point to the byte after the object,
12512   // no matter what our type or path is.
12513   auto Size = Ctx.getTypeSizeInChars(Ty);
12514   return LV.getLValueOffset() == Size;
12515 }
12516 
12517 namespace {
12518 
12519 /// Data recursive integer evaluator of certain binary operators.
12520 ///
12521 /// We use a data recursive algorithm for binary operators so that we are able
12522 /// to handle extreme cases of chained binary operators without causing stack
12523 /// overflow.
12524 class DataRecursiveIntBinOpEvaluator {
12525   struct EvalResult {
12526     APValue Val;
12527     bool Failed;
12528 
12529     EvalResult() : Failed(false) { }
12530 
12531     void swap(EvalResult &RHS) {
12532       Val.swap(RHS.Val);
12533       Failed = RHS.Failed;
12534       RHS.Failed = false;
12535     }
12536   };
12537 
12538   struct Job {
12539     const Expr *E;
12540     EvalResult LHSResult; // meaningful only for binary operator expression.
12541     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
12542 
12543     Job() = default;
12544     Job(Job &&) = default;
12545 
12546     void startSpeculativeEval(EvalInfo &Info) {
12547       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
12548     }
12549 
12550   private:
12551     SpeculativeEvaluationRAII SpecEvalRAII;
12552   };
12553 
12554   SmallVector<Job, 16> Queue;
12555 
12556   IntExprEvaluator &IntEval;
12557   EvalInfo &Info;
12558   APValue &FinalResult;
12559 
12560 public:
12561   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
12562     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
12563 
12564   /// True if \param E is a binary operator that we are going to handle
12565   /// data recursively.
12566   /// We handle binary operators that are comma, logical, or that have operands
12567   /// with integral or enumeration type.
12568   static bool shouldEnqueue(const BinaryOperator *E) {
12569     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
12570            (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() &&
12571             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12572             E->getRHS()->getType()->isIntegralOrEnumerationType());
12573   }
12574 
12575   bool Traverse(const BinaryOperator *E) {
12576     enqueue(E);
12577     EvalResult PrevResult;
12578     while (!Queue.empty())
12579       process(PrevResult);
12580 
12581     if (PrevResult.Failed) return false;
12582 
12583     FinalResult.swap(PrevResult.Val);
12584     return true;
12585   }
12586 
12587 private:
12588   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
12589     return IntEval.Success(Value, E, Result);
12590   }
12591   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
12592     return IntEval.Success(Value, E, Result);
12593   }
12594   bool Error(const Expr *E) {
12595     return IntEval.Error(E);
12596   }
12597   bool Error(const Expr *E, diag::kind D) {
12598     return IntEval.Error(E, D);
12599   }
12600 
12601   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
12602     return Info.CCEDiag(E, D);
12603   }
12604 
12605   // Returns true if visiting the RHS is necessary, false otherwise.
12606   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12607                          bool &SuppressRHSDiags);
12608 
12609   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12610                   const BinaryOperator *E, APValue &Result);
12611 
12612   void EvaluateExpr(const Expr *E, EvalResult &Result) {
12613     Result.Failed = !Evaluate(Result.Val, Info, E);
12614     if (Result.Failed)
12615       Result.Val = APValue();
12616   }
12617 
12618   void process(EvalResult &Result);
12619 
12620   void enqueue(const Expr *E) {
12621     E = E->IgnoreParens();
12622     Queue.resize(Queue.size()+1);
12623     Queue.back().E = E;
12624     Queue.back().Kind = Job::AnyExprKind;
12625   }
12626 };
12627 
12628 }
12629 
12630 bool DataRecursiveIntBinOpEvaluator::
12631        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12632                          bool &SuppressRHSDiags) {
12633   if (E->getOpcode() == BO_Comma) {
12634     // Ignore LHS but note if we could not evaluate it.
12635     if (LHSResult.Failed)
12636       return Info.noteSideEffect();
12637     return true;
12638   }
12639 
12640   if (E->isLogicalOp()) {
12641     bool LHSAsBool;
12642     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
12643       // We were able to evaluate the LHS, see if we can get away with not
12644       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
12645       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
12646         Success(LHSAsBool, E, LHSResult.Val);
12647         return false; // Ignore RHS
12648       }
12649     } else {
12650       LHSResult.Failed = true;
12651 
12652       // Since we weren't able to evaluate the left hand side, it
12653       // might have had side effects.
12654       if (!Info.noteSideEffect())
12655         return false;
12656 
12657       // We can't evaluate the LHS; however, sometimes the result
12658       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12659       // Don't ignore RHS and suppress diagnostics from this arm.
12660       SuppressRHSDiags = true;
12661     }
12662 
12663     return true;
12664   }
12665 
12666   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12667          E->getRHS()->getType()->isIntegralOrEnumerationType());
12668 
12669   if (LHSResult.Failed && !Info.noteFailure())
12670     return false; // Ignore RHS;
12671 
12672   return true;
12673 }
12674 
12675 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
12676                                     bool IsSub) {
12677   // Compute the new offset in the appropriate width, wrapping at 64 bits.
12678   // FIXME: When compiling for a 32-bit target, we should use 32-bit
12679   // offsets.
12680   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
12681   CharUnits &Offset = LVal.getLValueOffset();
12682   uint64_t Offset64 = Offset.getQuantity();
12683   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
12684   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
12685                                          : Offset64 + Index64);
12686 }
12687 
12688 bool DataRecursiveIntBinOpEvaluator::
12689        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12690                   const BinaryOperator *E, APValue &Result) {
12691   if (E->getOpcode() == BO_Comma) {
12692     if (RHSResult.Failed)
12693       return false;
12694     Result = RHSResult.Val;
12695     return true;
12696   }
12697 
12698   if (E->isLogicalOp()) {
12699     bool lhsResult, rhsResult;
12700     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
12701     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
12702 
12703     if (LHSIsOK) {
12704       if (RHSIsOK) {
12705         if (E->getOpcode() == BO_LOr)
12706           return Success(lhsResult || rhsResult, E, Result);
12707         else
12708           return Success(lhsResult && rhsResult, E, Result);
12709       }
12710     } else {
12711       if (RHSIsOK) {
12712         // We can't evaluate the LHS; however, sometimes the result
12713         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12714         if (rhsResult == (E->getOpcode() == BO_LOr))
12715           return Success(rhsResult, E, Result);
12716       }
12717     }
12718 
12719     return false;
12720   }
12721 
12722   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12723          E->getRHS()->getType()->isIntegralOrEnumerationType());
12724 
12725   if (LHSResult.Failed || RHSResult.Failed)
12726     return false;
12727 
12728   const APValue &LHSVal = LHSResult.Val;
12729   const APValue &RHSVal = RHSResult.Val;
12730 
12731   // Handle cases like (unsigned long)&a + 4.
12732   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
12733     Result = LHSVal;
12734     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
12735     return true;
12736   }
12737 
12738   // Handle cases like 4 + (unsigned long)&a
12739   if (E->getOpcode() == BO_Add &&
12740       RHSVal.isLValue() && LHSVal.isInt()) {
12741     Result = RHSVal;
12742     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
12743     return true;
12744   }
12745 
12746   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
12747     // Handle (intptr_t)&&A - (intptr_t)&&B.
12748     if (!LHSVal.getLValueOffset().isZero() ||
12749         !RHSVal.getLValueOffset().isZero())
12750       return false;
12751     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
12752     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
12753     if (!LHSExpr || !RHSExpr)
12754       return false;
12755     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12756     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12757     if (!LHSAddrExpr || !RHSAddrExpr)
12758       return false;
12759     // Make sure both labels come from the same function.
12760     if (LHSAddrExpr->getLabel()->getDeclContext() !=
12761         RHSAddrExpr->getLabel()->getDeclContext())
12762       return false;
12763     Result = APValue(LHSAddrExpr, RHSAddrExpr);
12764     return true;
12765   }
12766 
12767   // All the remaining cases expect both operands to be an integer
12768   if (!LHSVal.isInt() || !RHSVal.isInt())
12769     return Error(E);
12770 
12771   // Set up the width and signedness manually, in case it can't be deduced
12772   // from the operation we're performing.
12773   // FIXME: Don't do this in the cases where we can deduce it.
12774   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
12775                E->getType()->isUnsignedIntegerOrEnumerationType());
12776   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
12777                          RHSVal.getInt(), Value))
12778     return false;
12779   return Success(Value, E, Result);
12780 }
12781 
12782 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
12783   Job &job = Queue.back();
12784 
12785   switch (job.Kind) {
12786     case Job::AnyExprKind: {
12787       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
12788         if (shouldEnqueue(Bop)) {
12789           job.Kind = Job::BinOpKind;
12790           enqueue(Bop->getLHS());
12791           return;
12792         }
12793       }
12794 
12795       EvaluateExpr(job.E, Result);
12796       Queue.pop_back();
12797       return;
12798     }
12799 
12800     case Job::BinOpKind: {
12801       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12802       bool SuppressRHSDiags = false;
12803       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
12804         Queue.pop_back();
12805         return;
12806       }
12807       if (SuppressRHSDiags)
12808         job.startSpeculativeEval(Info);
12809       job.LHSResult.swap(Result);
12810       job.Kind = Job::BinOpVisitedLHSKind;
12811       enqueue(Bop->getRHS());
12812       return;
12813     }
12814 
12815     case Job::BinOpVisitedLHSKind: {
12816       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12817       EvalResult RHS;
12818       RHS.swap(Result);
12819       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
12820       Queue.pop_back();
12821       return;
12822     }
12823   }
12824 
12825   llvm_unreachable("Invalid Job::Kind!");
12826 }
12827 
12828 namespace {
12829 enum class CmpResult {
12830   Unequal,
12831   Less,
12832   Equal,
12833   Greater,
12834   Unordered,
12835 };
12836 }
12837 
12838 template <class SuccessCB, class AfterCB>
12839 static bool
12840 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
12841                                  SuccessCB &&Success, AfterCB &&DoAfter) {
12842   assert(!E->isValueDependent());
12843   assert(E->isComparisonOp() && "expected comparison operator");
12844   assert((E->getOpcode() == BO_Cmp ||
12845           E->getType()->isIntegralOrEnumerationType()) &&
12846          "unsupported binary expression evaluation");
12847   auto Error = [&](const Expr *E) {
12848     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12849     return false;
12850   };
12851 
12852   bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
12853   bool IsEquality = E->isEqualityOp();
12854 
12855   QualType LHSTy = E->getLHS()->getType();
12856   QualType RHSTy = E->getRHS()->getType();
12857 
12858   if (LHSTy->isIntegralOrEnumerationType() &&
12859       RHSTy->isIntegralOrEnumerationType()) {
12860     APSInt LHS, RHS;
12861     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
12862     if (!LHSOK && !Info.noteFailure())
12863       return false;
12864     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
12865       return false;
12866     if (LHS < RHS)
12867       return Success(CmpResult::Less, E);
12868     if (LHS > RHS)
12869       return Success(CmpResult::Greater, E);
12870     return Success(CmpResult::Equal, E);
12871   }
12872 
12873   if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
12874     APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
12875     APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
12876 
12877     bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
12878     if (!LHSOK && !Info.noteFailure())
12879       return false;
12880     if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
12881       return false;
12882     if (LHSFX < RHSFX)
12883       return Success(CmpResult::Less, E);
12884     if (LHSFX > RHSFX)
12885       return Success(CmpResult::Greater, E);
12886     return Success(CmpResult::Equal, E);
12887   }
12888 
12889   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
12890     ComplexValue LHS, RHS;
12891     bool LHSOK;
12892     if (E->isAssignmentOp()) {
12893       LValue LV;
12894       EvaluateLValue(E->getLHS(), LV, Info);
12895       LHSOK = false;
12896     } else if (LHSTy->isRealFloatingType()) {
12897       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
12898       if (LHSOK) {
12899         LHS.makeComplexFloat();
12900         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
12901       }
12902     } else {
12903       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
12904     }
12905     if (!LHSOK && !Info.noteFailure())
12906       return false;
12907 
12908     if (E->getRHS()->getType()->isRealFloatingType()) {
12909       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
12910         return false;
12911       RHS.makeComplexFloat();
12912       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
12913     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
12914       return false;
12915 
12916     if (LHS.isComplexFloat()) {
12917       APFloat::cmpResult CR_r =
12918         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
12919       APFloat::cmpResult CR_i =
12920         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
12921       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
12922       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12923     } else {
12924       assert(IsEquality && "invalid complex comparison");
12925       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
12926                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
12927       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12928     }
12929   }
12930 
12931   if (LHSTy->isRealFloatingType() &&
12932       RHSTy->isRealFloatingType()) {
12933     APFloat RHS(0.0), LHS(0.0);
12934 
12935     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
12936     if (!LHSOK && !Info.noteFailure())
12937       return false;
12938 
12939     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
12940       return false;
12941 
12942     assert(E->isComparisonOp() && "Invalid binary operator!");
12943     llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
12944     if (!Info.InConstantContext &&
12945         APFloatCmpResult == APFloat::cmpUnordered &&
12946         E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
12947       // Note: Compares may raise invalid in some cases involving NaN or sNaN.
12948       Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
12949       return false;
12950     }
12951     auto GetCmpRes = [&]() {
12952       switch (APFloatCmpResult) {
12953       case APFloat::cmpEqual:
12954         return CmpResult::Equal;
12955       case APFloat::cmpLessThan:
12956         return CmpResult::Less;
12957       case APFloat::cmpGreaterThan:
12958         return CmpResult::Greater;
12959       case APFloat::cmpUnordered:
12960         return CmpResult::Unordered;
12961       }
12962       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
12963     };
12964     return Success(GetCmpRes(), E);
12965   }
12966 
12967   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
12968     LValue LHSValue, RHSValue;
12969 
12970     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12971     if (!LHSOK && !Info.noteFailure())
12972       return false;
12973 
12974     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12975       return false;
12976 
12977     // Reject differing bases from the normal codepath; we special-case
12978     // comparisons to null.
12979     if (!HasSameBase(LHSValue, RHSValue)) {
12980       auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {
12981         std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
12982         std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
12983         Info.FFDiag(E, DiagID)
12984             << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS);
12985         return false;
12986       };
12987       // Inequalities and subtractions between unrelated pointers have
12988       // unspecified or undefined behavior.
12989       if (!IsEquality)
12990         return DiagComparison(
12991             diag::note_constexpr_pointer_comparison_unspecified);
12992       // A constant address may compare equal to the address of a symbol.
12993       // The one exception is that address of an object cannot compare equal
12994       // to a null pointer constant.
12995       // TODO: Should we restrict this to actual null pointers, and exclude the
12996       // case of zero cast to pointer type?
12997       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
12998           (!RHSValue.Base && !RHSValue.Offset.isZero()))
12999         return DiagComparison(diag::note_constexpr_pointer_constant_comparison,
13000                               !RHSValue.Base);
13001       // It's implementation-defined whether distinct literals will have
13002       // distinct addresses. In clang, the result of such a comparison is
13003       // unspecified, so it is not a constant expression. However, we do know
13004       // that the address of a literal will be non-null.
13005       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
13006           LHSValue.Base && RHSValue.Base)
13007         return DiagComparison(diag::note_constexpr_literal_comparison);
13008       // We can't tell whether weak symbols will end up pointing to the same
13009       // object.
13010       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
13011         return DiagComparison(diag::note_constexpr_pointer_weak_comparison,
13012                               !IsWeakLValue(LHSValue));
13013       // We can't compare the address of the start of one object with the
13014       // past-the-end address of another object, per C++ DR1652.
13015       if (LHSValue.Base && LHSValue.Offset.isZero() &&
13016           isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue))
13017         return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
13018                               true);
13019       if (RHSValue.Base && RHSValue.Offset.isZero() &&
13020            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))
13021         return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
13022                               false);
13023       // We can't tell whether an object is at the same address as another
13024       // zero sized object.
13025       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
13026           (LHSValue.Base && isZeroSized(RHSValue)))
13027         return DiagComparison(
13028             diag::note_constexpr_pointer_comparison_zero_sized);
13029       return Success(CmpResult::Unequal, E);
13030     }
13031 
13032     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
13033     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
13034 
13035     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
13036     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
13037 
13038     // C++11 [expr.rel]p3:
13039     //   Pointers to void (after pointer conversions) can be compared, with a
13040     //   result defined as follows: If both pointers represent the same
13041     //   address or are both the null pointer value, the result is true if the
13042     //   operator is <= or >= and false otherwise; otherwise the result is
13043     //   unspecified.
13044     // We interpret this as applying to pointers to *cv* void.
13045     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
13046       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
13047 
13048     // C++11 [expr.rel]p2:
13049     // - If two pointers point to non-static data members of the same object,
13050     //   or to subobjects or array elements fo such members, recursively, the
13051     //   pointer to the later declared member compares greater provided the
13052     //   two members have the same access control and provided their class is
13053     //   not a union.
13054     //   [...]
13055     // - Otherwise pointer comparisons are unspecified.
13056     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
13057       bool WasArrayIndex;
13058       unsigned Mismatch = FindDesignatorMismatch(
13059           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
13060       // At the point where the designators diverge, the comparison has a
13061       // specified value if:
13062       //  - we are comparing array indices
13063       //  - we are comparing fields of a union, or fields with the same access
13064       // Otherwise, the result is unspecified and thus the comparison is not a
13065       // constant expression.
13066       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
13067           Mismatch < RHSDesignator.Entries.size()) {
13068         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
13069         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
13070         if (!LF && !RF)
13071           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
13072         else if (!LF)
13073           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
13074               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
13075               << RF->getParent() << RF;
13076         else if (!RF)
13077           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
13078               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
13079               << LF->getParent() << LF;
13080         else if (!LF->getParent()->isUnion() &&
13081                  LF->getAccess() != RF->getAccess())
13082           Info.CCEDiag(E,
13083                        diag::note_constexpr_pointer_comparison_differing_access)
13084               << LF << LF->getAccess() << RF << RF->getAccess()
13085               << LF->getParent();
13086       }
13087     }
13088 
13089     // The comparison here must be unsigned, and performed with the same
13090     // width as the pointer.
13091     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
13092     uint64_t CompareLHS = LHSOffset.getQuantity();
13093     uint64_t CompareRHS = RHSOffset.getQuantity();
13094     assert(PtrSize <= 64 && "Unexpected pointer width");
13095     uint64_t Mask = ~0ULL >> (64 - PtrSize);
13096     CompareLHS &= Mask;
13097     CompareRHS &= Mask;
13098 
13099     // If there is a base and this is a relational operator, we can only
13100     // compare pointers within the object in question; otherwise, the result
13101     // depends on where the object is located in memory.
13102     if (!LHSValue.Base.isNull() && IsRelational) {
13103       QualType BaseTy = getType(LHSValue.Base);
13104       if (BaseTy->isIncompleteType())
13105         return Error(E);
13106       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
13107       uint64_t OffsetLimit = Size.getQuantity();
13108       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
13109         return Error(E);
13110     }
13111 
13112     if (CompareLHS < CompareRHS)
13113       return Success(CmpResult::Less, E);
13114     if (CompareLHS > CompareRHS)
13115       return Success(CmpResult::Greater, E);
13116     return Success(CmpResult::Equal, E);
13117   }
13118 
13119   if (LHSTy->isMemberPointerType()) {
13120     assert(IsEquality && "unexpected member pointer operation");
13121     assert(RHSTy->isMemberPointerType() && "invalid comparison");
13122 
13123     MemberPtr LHSValue, RHSValue;
13124 
13125     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
13126     if (!LHSOK && !Info.noteFailure())
13127       return false;
13128 
13129     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13130       return false;
13131 
13132     // If either operand is a pointer to a weak function, the comparison is not
13133     // constant.
13134     if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) {
13135       Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
13136           << LHSValue.getDecl();
13137       return true;
13138     }
13139     if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) {
13140       Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
13141           << RHSValue.getDecl();
13142       return true;
13143     }
13144 
13145     // C++11 [expr.eq]p2:
13146     //   If both operands are null, they compare equal. Otherwise if only one is
13147     //   null, they compare unequal.
13148     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
13149       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
13150       return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
13151     }
13152 
13153     //   Otherwise if either is a pointer to a virtual member function, the
13154     //   result is unspecified.
13155     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
13156       if (MD->isVirtual())
13157         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
13158     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
13159       if (MD->isVirtual())
13160         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
13161 
13162     //   Otherwise they compare equal if and only if they would refer to the
13163     //   same member of the same most derived object or the same subobject if
13164     //   they were dereferenced with a hypothetical object of the associated
13165     //   class type.
13166     bool Equal = LHSValue == RHSValue;
13167     return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
13168   }
13169 
13170   if (LHSTy->isNullPtrType()) {
13171     assert(E->isComparisonOp() && "unexpected nullptr operation");
13172     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
13173     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
13174     // are compared, the result is true of the operator is <=, >= or ==, and
13175     // false otherwise.
13176     return Success(CmpResult::Equal, E);
13177   }
13178 
13179   return DoAfter();
13180 }
13181 
13182 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
13183   if (!CheckLiteralType(Info, E))
13184     return false;
13185 
13186   auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
13187     ComparisonCategoryResult CCR;
13188     switch (CR) {
13189     case CmpResult::Unequal:
13190       llvm_unreachable("should never produce Unequal for three-way comparison");
13191     case CmpResult::Less:
13192       CCR = ComparisonCategoryResult::Less;
13193       break;
13194     case CmpResult::Equal:
13195       CCR = ComparisonCategoryResult::Equal;
13196       break;
13197     case CmpResult::Greater:
13198       CCR = ComparisonCategoryResult::Greater;
13199       break;
13200     case CmpResult::Unordered:
13201       CCR = ComparisonCategoryResult::Unordered;
13202       break;
13203     }
13204     // Evaluation succeeded. Lookup the information for the comparison category
13205     // type and fetch the VarDecl for the result.
13206     const ComparisonCategoryInfo &CmpInfo =
13207         Info.Ctx.CompCategories.getInfoForType(E->getType());
13208     const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
13209     // Check and evaluate the result as a constant expression.
13210     LValue LV;
13211     LV.set(VD);
13212     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
13213       return false;
13214     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
13215                                    ConstantExprKind::Normal);
13216   };
13217   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
13218     return ExprEvaluatorBaseTy::VisitBinCmp(E);
13219   });
13220 }
13221 
13222 bool RecordExprEvaluator::VisitCXXParenListInitExpr(
13223     const CXXParenListInitExpr *E) {
13224   return VisitCXXParenListOrInitListExpr(E, E->getInitExprs());
13225 }
13226 
13227 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13228   // We don't support assignment in C. C++ assignments don't get here because
13229   // assignment is an lvalue in C++.
13230   if (E->isAssignmentOp()) {
13231     Error(E);
13232     if (!Info.noteFailure())
13233       return false;
13234   }
13235 
13236   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
13237     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
13238 
13239   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
13240           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
13241          "DataRecursiveIntBinOpEvaluator should have handled integral types");
13242 
13243   if (E->isComparisonOp()) {
13244     // Evaluate builtin binary comparisons by evaluating them as three-way
13245     // comparisons and then translating the result.
13246     auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
13247       assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
13248              "should only produce Unequal for equality comparisons");
13249       bool IsEqual   = CR == CmpResult::Equal,
13250            IsLess    = CR == CmpResult::Less,
13251            IsGreater = CR == CmpResult::Greater;
13252       auto Op = E->getOpcode();
13253       switch (Op) {
13254       default:
13255         llvm_unreachable("unsupported binary operator");
13256       case BO_EQ:
13257       case BO_NE:
13258         return Success(IsEqual == (Op == BO_EQ), E);
13259       case BO_LT:
13260         return Success(IsLess, E);
13261       case BO_GT:
13262         return Success(IsGreater, E);
13263       case BO_LE:
13264         return Success(IsEqual || IsLess, E);
13265       case BO_GE:
13266         return Success(IsEqual || IsGreater, E);
13267       }
13268     };
13269     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
13270       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13271     });
13272   }
13273 
13274   QualType LHSTy = E->getLHS()->getType();
13275   QualType RHSTy = E->getRHS()->getType();
13276 
13277   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
13278       E->getOpcode() == BO_Sub) {
13279     LValue LHSValue, RHSValue;
13280 
13281     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
13282     if (!LHSOK && !Info.noteFailure())
13283       return false;
13284 
13285     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13286       return false;
13287 
13288     // Reject differing bases from the normal codepath; we special-case
13289     // comparisons to null.
13290     if (!HasSameBase(LHSValue, RHSValue)) {
13291       // Handle &&A - &&B.
13292       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
13293         return Error(E);
13294       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
13295       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
13296       if (!LHSExpr || !RHSExpr)
13297         return Error(E);
13298       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
13299       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
13300       if (!LHSAddrExpr || !RHSAddrExpr)
13301         return Error(E);
13302       // Make sure both labels come from the same function.
13303       if (LHSAddrExpr->getLabel()->getDeclContext() !=
13304           RHSAddrExpr->getLabel()->getDeclContext())
13305         return Error(E);
13306       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
13307     }
13308     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
13309     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
13310 
13311     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
13312     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
13313 
13314     // C++11 [expr.add]p6:
13315     //   Unless both pointers point to elements of the same array object, or
13316     //   one past the last element of the array object, the behavior is
13317     //   undefined.
13318     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
13319         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
13320                                 RHSDesignator))
13321       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
13322 
13323     QualType Type = E->getLHS()->getType();
13324     QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
13325 
13326     CharUnits ElementSize;
13327     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
13328       return false;
13329 
13330     // As an extension, a type may have zero size (empty struct or union in
13331     // C, array of zero length). Pointer subtraction in such cases has
13332     // undefined behavior, so is not constant.
13333     if (ElementSize.isZero()) {
13334       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
13335           << ElementType;
13336       return false;
13337     }
13338 
13339     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
13340     // and produce incorrect results when it overflows. Such behavior
13341     // appears to be non-conforming, but is common, so perhaps we should
13342     // assume the standard intended for such cases to be undefined behavior
13343     // and check for them.
13344 
13345     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
13346     // overflow in the final conversion to ptrdiff_t.
13347     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
13348     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
13349     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
13350                     false);
13351     APSInt TrueResult = (LHS - RHS) / ElemSize;
13352     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
13353 
13354     if (Result.extend(65) != TrueResult &&
13355         !HandleOverflow(Info, E, TrueResult, E->getType()))
13356       return false;
13357     return Success(Result, E);
13358   }
13359 
13360   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13361 }
13362 
13363 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
13364 /// a result as the expression's type.
13365 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
13366                                     const UnaryExprOrTypeTraitExpr *E) {
13367   switch(E->getKind()) {
13368   case UETT_PreferredAlignOf:
13369   case UETT_AlignOf: {
13370     if (E->isArgumentType())
13371       return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
13372                      E);
13373     else
13374       return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
13375                      E);
13376   }
13377 
13378   case UETT_VecStep: {
13379     QualType Ty = E->getTypeOfArgument();
13380 
13381     if (Ty->isVectorType()) {
13382       unsigned n = Ty->castAs<VectorType>()->getNumElements();
13383 
13384       // The vec_step built-in functions that take a 3-component
13385       // vector return 4. (OpenCL 1.1 spec 6.11.12)
13386       if (n == 3)
13387         n = 4;
13388 
13389       return Success(n, E);
13390     } else
13391       return Success(1, E);
13392   }
13393 
13394   case UETT_SizeOf: {
13395     QualType SrcTy = E->getTypeOfArgument();
13396     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
13397     //   the result is the size of the referenced type."
13398     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
13399       SrcTy = Ref->getPointeeType();
13400 
13401     CharUnits Sizeof;
13402     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
13403       return false;
13404     return Success(Sizeof, E);
13405   }
13406   case UETT_OpenMPRequiredSimdAlign:
13407     assert(E->isArgumentType());
13408     return Success(
13409         Info.Ctx.toCharUnitsFromBits(
13410                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
13411             .getQuantity(),
13412         E);
13413   }
13414 
13415   llvm_unreachable("unknown expr/type trait");
13416 }
13417 
13418 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
13419   CharUnits Result;
13420   unsigned n = OOE->getNumComponents();
13421   if (n == 0)
13422     return Error(OOE);
13423   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
13424   for (unsigned i = 0; i != n; ++i) {
13425     OffsetOfNode ON = OOE->getComponent(i);
13426     switch (ON.getKind()) {
13427     case OffsetOfNode::Array: {
13428       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
13429       APSInt IdxResult;
13430       if (!EvaluateInteger(Idx, IdxResult, Info))
13431         return false;
13432       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
13433       if (!AT)
13434         return Error(OOE);
13435       CurrentType = AT->getElementType();
13436       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
13437       Result += IdxResult.getSExtValue() * ElementSize;
13438       break;
13439     }
13440 
13441     case OffsetOfNode::Field: {
13442       FieldDecl *MemberDecl = ON.getField();
13443       const RecordType *RT = CurrentType->getAs<RecordType>();
13444       if (!RT)
13445         return Error(OOE);
13446       RecordDecl *RD = RT->getDecl();
13447       if (RD->isInvalidDecl()) return false;
13448       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13449       unsigned i = MemberDecl->getFieldIndex();
13450       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
13451       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
13452       CurrentType = MemberDecl->getType().getNonReferenceType();
13453       break;
13454     }
13455 
13456     case OffsetOfNode::Identifier:
13457       llvm_unreachable("dependent __builtin_offsetof");
13458 
13459     case OffsetOfNode::Base: {
13460       CXXBaseSpecifier *BaseSpec = ON.getBase();
13461       if (BaseSpec->isVirtual())
13462         return Error(OOE);
13463 
13464       // Find the layout of the class whose base we are looking into.
13465       const RecordType *RT = CurrentType->getAs<RecordType>();
13466       if (!RT)
13467         return Error(OOE);
13468       RecordDecl *RD = RT->getDecl();
13469       if (RD->isInvalidDecl()) return false;
13470       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13471 
13472       // Find the base class itself.
13473       CurrentType = BaseSpec->getType();
13474       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
13475       if (!BaseRT)
13476         return Error(OOE);
13477 
13478       // Add the offset to the base.
13479       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
13480       break;
13481     }
13482     }
13483   }
13484   return Success(Result, OOE);
13485 }
13486 
13487 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13488   switch (E->getOpcode()) {
13489   default:
13490     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
13491     // See C99 6.6p3.
13492     return Error(E);
13493   case UO_Extension:
13494     // FIXME: Should extension allow i-c-e extension expressions in its scope?
13495     // If so, we could clear the diagnostic ID.
13496     return Visit(E->getSubExpr());
13497   case UO_Plus:
13498     // The result is just the value.
13499     return Visit(E->getSubExpr());
13500   case UO_Minus: {
13501     if (!Visit(E->getSubExpr()))
13502       return false;
13503     if (!Result.isInt()) return Error(E);
13504     const APSInt &Value = Result.getInt();
13505     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
13506         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
13507                         E->getType()))
13508       return false;
13509     return Success(-Value, E);
13510   }
13511   case UO_Not: {
13512     if (!Visit(E->getSubExpr()))
13513       return false;
13514     if (!Result.isInt()) return Error(E);
13515     return Success(~Result.getInt(), E);
13516   }
13517   case UO_LNot: {
13518     bool bres;
13519     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13520       return false;
13521     return Success(!bres, E);
13522   }
13523   }
13524 }
13525 
13526 /// HandleCast - This is used to evaluate implicit or explicit casts where the
13527 /// result type is integer.
13528 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
13529   const Expr *SubExpr = E->getSubExpr();
13530   QualType DestType = E->getType();
13531   QualType SrcType = SubExpr->getType();
13532 
13533   switch (E->getCastKind()) {
13534   case CK_BaseToDerived:
13535   case CK_DerivedToBase:
13536   case CK_UncheckedDerivedToBase:
13537   case CK_Dynamic:
13538   case CK_ToUnion:
13539   case CK_ArrayToPointerDecay:
13540   case CK_FunctionToPointerDecay:
13541   case CK_NullToPointer:
13542   case CK_NullToMemberPointer:
13543   case CK_BaseToDerivedMemberPointer:
13544   case CK_DerivedToBaseMemberPointer:
13545   case CK_ReinterpretMemberPointer:
13546   case CK_ConstructorConversion:
13547   case CK_IntegralToPointer:
13548   case CK_ToVoid:
13549   case CK_VectorSplat:
13550   case CK_IntegralToFloating:
13551   case CK_FloatingCast:
13552   case CK_CPointerToObjCPointerCast:
13553   case CK_BlockPointerToObjCPointerCast:
13554   case CK_AnyPointerToBlockPointerCast:
13555   case CK_ObjCObjectLValueCast:
13556   case CK_FloatingRealToComplex:
13557   case CK_FloatingComplexToReal:
13558   case CK_FloatingComplexCast:
13559   case CK_FloatingComplexToIntegralComplex:
13560   case CK_IntegralRealToComplex:
13561   case CK_IntegralComplexCast:
13562   case CK_IntegralComplexToFloatingComplex:
13563   case CK_BuiltinFnToFnPtr:
13564   case CK_ZeroToOCLOpaqueType:
13565   case CK_NonAtomicToAtomic:
13566   case CK_AddressSpaceConversion:
13567   case CK_IntToOCLSampler:
13568   case CK_FloatingToFixedPoint:
13569   case CK_FixedPointToFloating:
13570   case CK_FixedPointCast:
13571   case CK_IntegralToFixedPoint:
13572   case CK_MatrixCast:
13573     llvm_unreachable("invalid cast kind for integral value");
13574 
13575   case CK_BitCast:
13576   case CK_Dependent:
13577   case CK_LValueBitCast:
13578   case CK_ARCProduceObject:
13579   case CK_ARCConsumeObject:
13580   case CK_ARCReclaimReturnedObject:
13581   case CK_ARCExtendBlockObject:
13582   case CK_CopyAndAutoreleaseBlockObject:
13583     return Error(E);
13584 
13585   case CK_UserDefinedConversion:
13586   case CK_LValueToRValue:
13587   case CK_AtomicToNonAtomic:
13588   case CK_NoOp:
13589   case CK_LValueToRValueBitCast:
13590     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13591 
13592   case CK_MemberPointerToBoolean:
13593   case CK_PointerToBoolean:
13594   case CK_IntegralToBoolean:
13595   case CK_FloatingToBoolean:
13596   case CK_BooleanToSignedIntegral:
13597   case CK_FloatingComplexToBoolean:
13598   case CK_IntegralComplexToBoolean: {
13599     bool BoolResult;
13600     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
13601       return false;
13602     uint64_t IntResult = BoolResult;
13603     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
13604       IntResult = (uint64_t)-1;
13605     return Success(IntResult, E);
13606   }
13607 
13608   case CK_FixedPointToIntegral: {
13609     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
13610     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13611       return false;
13612     bool Overflowed;
13613     llvm::APSInt Result = Src.convertToInt(
13614         Info.Ctx.getIntWidth(DestType),
13615         DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
13616     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
13617       return false;
13618     return Success(Result, E);
13619   }
13620 
13621   case CK_FixedPointToBoolean: {
13622     // Unsigned padding does not affect this.
13623     APValue Val;
13624     if (!Evaluate(Val, Info, SubExpr))
13625       return false;
13626     return Success(Val.getFixedPoint().getBoolValue(), E);
13627   }
13628 
13629   case CK_IntegralCast: {
13630     if (!Visit(SubExpr))
13631       return false;
13632 
13633     if (!Result.isInt()) {
13634       // Allow casts of address-of-label differences if they are no-ops
13635       // or narrowing.  (The narrowing case isn't actually guaranteed to
13636       // be constant-evaluatable except in some narrow cases which are hard
13637       // to detect here.  We let it through on the assumption the user knows
13638       // what they are doing.)
13639       if (Result.isAddrLabelDiff())
13640         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
13641       // Only allow casts of lvalues if they are lossless.
13642       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
13643     }
13644 
13645     if (Info.Ctx.getLangOpts().CPlusPlus && Info.InConstantContext &&
13646         Info.EvalMode == EvalInfo::EM_ConstantExpression &&
13647         DestType->isEnumeralType()) {
13648 
13649       bool ConstexprVar = true;
13650 
13651       // We know if we are here that we are in a context that we might require
13652       // a constant expression or a context that requires a constant
13653       // value. But if we are initializing a value we don't know if it is a
13654       // constexpr variable or not. We can check the EvaluatingDecl to determine
13655       // if it constexpr or not. If not then we don't want to emit a diagnostic.
13656       if (const auto *VD = dyn_cast_or_null<VarDecl>(
13657               Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
13658         ConstexprVar = VD->isConstexpr();
13659 
13660       const EnumType *ET = dyn_cast<EnumType>(DestType.getCanonicalType());
13661       const EnumDecl *ED = ET->getDecl();
13662       // Check that the value is within the range of the enumeration values.
13663       //
13664       // This corressponds to [expr.static.cast]p10 which says:
13665       // A value of integral or enumeration type can be explicitly converted
13666       // to a complete enumeration type ... If the enumeration type does not
13667       // have a fixed underlying type, the value is unchanged if the original
13668       // value is within the range of the enumeration values ([dcl.enum]), and
13669       // otherwise, the behavior is undefined.
13670       //
13671       // This was resolved as part of DR2338 which has CD5 status.
13672       if (!ED->isFixed()) {
13673         llvm::APInt Min;
13674         llvm::APInt Max;
13675 
13676         ED->getValueRange(Max, Min);
13677         --Max;
13678 
13679         if (ED->getNumNegativeBits() && ConstexprVar &&
13680             (Max.slt(Result.getInt().getSExtValue()) ||
13681              Min.sgt(Result.getInt().getSExtValue())))
13682           Info.Ctx.getDiagnostics().Report(
13683               E->getExprLoc(), diag::warn_constexpr_unscoped_enum_out_of_range)
13684               << llvm::toString(Result.getInt(), 10) << Min.getSExtValue()
13685               << Max.getSExtValue() << ED;
13686         else if (!ED->getNumNegativeBits() && ConstexprVar &&
13687                  Max.ult(Result.getInt().getZExtValue()))
13688           Info.Ctx.getDiagnostics().Report(
13689               E->getExprLoc(), diag::warn_constexpr_unscoped_enum_out_of_range)
13690               << llvm::toString(Result.getInt(), 10) << Min.getZExtValue()
13691               << Max.getZExtValue() << ED;
13692       }
13693     }
13694 
13695     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
13696                                       Result.getInt()), E);
13697   }
13698 
13699   case CK_PointerToIntegral: {
13700     CCEDiag(E, diag::note_constexpr_invalid_cast)
13701         << 2 << Info.Ctx.getLangOpts().CPlusPlus;
13702 
13703     LValue LV;
13704     if (!EvaluatePointer(SubExpr, LV, Info))
13705       return false;
13706 
13707     if (LV.getLValueBase()) {
13708       // Only allow based lvalue casts if they are lossless.
13709       // FIXME: Allow a larger integer size than the pointer size, and allow
13710       // narrowing back down to pointer width in subsequent integral casts.
13711       // FIXME: Check integer type's active bits, not its type size.
13712       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
13713         return Error(E);
13714 
13715       LV.Designator.setInvalid();
13716       LV.moveInto(Result);
13717       return true;
13718     }
13719 
13720     APSInt AsInt;
13721     APValue V;
13722     LV.moveInto(V);
13723     if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
13724       llvm_unreachable("Can't cast this!");
13725 
13726     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
13727   }
13728 
13729   case CK_IntegralComplexToReal: {
13730     ComplexValue C;
13731     if (!EvaluateComplex(SubExpr, C, Info))
13732       return false;
13733     return Success(C.getComplexIntReal(), E);
13734   }
13735 
13736   case CK_FloatingToIntegral: {
13737     APFloat F(0.0);
13738     if (!EvaluateFloat(SubExpr, F, Info))
13739       return false;
13740 
13741     APSInt Value;
13742     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
13743       return false;
13744     return Success(Value, E);
13745   }
13746   }
13747 
13748   llvm_unreachable("unknown cast resulting in integral value");
13749 }
13750 
13751 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13752   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13753     ComplexValue LV;
13754     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13755       return false;
13756     if (!LV.isComplexInt())
13757       return Error(E);
13758     return Success(LV.getComplexIntReal(), E);
13759   }
13760 
13761   return Visit(E->getSubExpr());
13762 }
13763 
13764 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13765   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
13766     ComplexValue LV;
13767     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13768       return false;
13769     if (!LV.isComplexInt())
13770       return Error(E);
13771     return Success(LV.getComplexIntImag(), E);
13772   }
13773 
13774   VisitIgnoredValue(E->getSubExpr());
13775   return Success(0, E);
13776 }
13777 
13778 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
13779   return Success(E->getPackLength(), E);
13780 }
13781 
13782 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
13783   return Success(E->getValue(), E);
13784 }
13785 
13786 bool IntExprEvaluator::VisitConceptSpecializationExpr(
13787        const ConceptSpecializationExpr *E) {
13788   return Success(E->isSatisfied(), E);
13789 }
13790 
13791 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
13792   return Success(E->isSatisfied(), E);
13793 }
13794 
13795 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13796   switch (E->getOpcode()) {
13797     default:
13798       // Invalid unary operators
13799       return Error(E);
13800     case UO_Plus:
13801       // The result is just the value.
13802       return Visit(E->getSubExpr());
13803     case UO_Minus: {
13804       if (!Visit(E->getSubExpr())) return false;
13805       if (!Result.isFixedPoint())
13806         return Error(E);
13807       bool Overflowed;
13808       APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
13809       if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
13810         return false;
13811       return Success(Negated, E);
13812     }
13813     case UO_LNot: {
13814       bool bres;
13815       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13816         return false;
13817       return Success(!bres, E);
13818     }
13819   }
13820 }
13821 
13822 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
13823   const Expr *SubExpr = E->getSubExpr();
13824   QualType DestType = E->getType();
13825   assert(DestType->isFixedPointType() &&
13826          "Expected destination type to be a fixed point type");
13827   auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
13828 
13829   switch (E->getCastKind()) {
13830   case CK_FixedPointCast: {
13831     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13832     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13833       return false;
13834     bool Overflowed;
13835     APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
13836     if (Overflowed) {
13837       if (Info.checkingForUndefinedBehavior())
13838         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13839                                          diag::warn_fixedpoint_constant_overflow)
13840           << Result.toString() << E->getType();
13841       if (!HandleOverflow(Info, E, Result, E->getType()))
13842         return false;
13843     }
13844     return Success(Result, E);
13845   }
13846   case CK_IntegralToFixedPoint: {
13847     APSInt Src;
13848     if (!EvaluateInteger(SubExpr, Src, Info))
13849       return false;
13850 
13851     bool Overflowed;
13852     APFixedPoint IntResult = APFixedPoint::getFromIntValue(
13853         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13854 
13855     if (Overflowed) {
13856       if (Info.checkingForUndefinedBehavior())
13857         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13858                                          diag::warn_fixedpoint_constant_overflow)
13859           << IntResult.toString() << E->getType();
13860       if (!HandleOverflow(Info, E, IntResult, E->getType()))
13861         return false;
13862     }
13863 
13864     return Success(IntResult, E);
13865   }
13866   case CK_FloatingToFixedPoint: {
13867     APFloat Src(0.0);
13868     if (!EvaluateFloat(SubExpr, Src, Info))
13869       return false;
13870 
13871     bool Overflowed;
13872     APFixedPoint Result = APFixedPoint::getFromFloatValue(
13873         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13874 
13875     if (Overflowed) {
13876       if (Info.checkingForUndefinedBehavior())
13877         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13878                                          diag::warn_fixedpoint_constant_overflow)
13879           << Result.toString() << E->getType();
13880       if (!HandleOverflow(Info, E, Result, E->getType()))
13881         return false;
13882     }
13883 
13884     return Success(Result, E);
13885   }
13886   case CK_NoOp:
13887   case CK_LValueToRValue:
13888     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13889   default:
13890     return Error(E);
13891   }
13892 }
13893 
13894 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13895   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13896     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13897 
13898   const Expr *LHS = E->getLHS();
13899   const Expr *RHS = E->getRHS();
13900   FixedPointSemantics ResultFXSema =
13901       Info.Ctx.getFixedPointSemantics(E->getType());
13902 
13903   APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
13904   if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
13905     return false;
13906   APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
13907   if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
13908     return false;
13909 
13910   bool OpOverflow = false, ConversionOverflow = false;
13911   APFixedPoint Result(LHSFX.getSemantics());
13912   switch (E->getOpcode()) {
13913   case BO_Add: {
13914     Result = LHSFX.add(RHSFX, &OpOverflow)
13915                   .convert(ResultFXSema, &ConversionOverflow);
13916     break;
13917   }
13918   case BO_Sub: {
13919     Result = LHSFX.sub(RHSFX, &OpOverflow)
13920                   .convert(ResultFXSema, &ConversionOverflow);
13921     break;
13922   }
13923   case BO_Mul: {
13924     Result = LHSFX.mul(RHSFX, &OpOverflow)
13925                   .convert(ResultFXSema, &ConversionOverflow);
13926     break;
13927   }
13928   case BO_Div: {
13929     if (RHSFX.getValue() == 0) {
13930       Info.FFDiag(E, diag::note_expr_divide_by_zero);
13931       return false;
13932     }
13933     Result = LHSFX.div(RHSFX, &OpOverflow)
13934                   .convert(ResultFXSema, &ConversionOverflow);
13935     break;
13936   }
13937   case BO_Shl:
13938   case BO_Shr: {
13939     FixedPointSemantics LHSSema = LHSFX.getSemantics();
13940     llvm::APSInt RHSVal = RHSFX.getValue();
13941 
13942     unsigned ShiftBW =
13943         LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
13944     unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
13945     // Embedded-C 4.1.6.2.2:
13946     //   The right operand must be nonnegative and less than the total number
13947     //   of (nonpadding) bits of the fixed-point operand ...
13948     if (RHSVal.isNegative())
13949       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
13950     else if (Amt != RHSVal)
13951       Info.CCEDiag(E, diag::note_constexpr_large_shift)
13952           << RHSVal << E->getType() << ShiftBW;
13953 
13954     if (E->getOpcode() == BO_Shl)
13955       Result = LHSFX.shl(Amt, &OpOverflow);
13956     else
13957       Result = LHSFX.shr(Amt, &OpOverflow);
13958     break;
13959   }
13960   default:
13961     return false;
13962   }
13963   if (OpOverflow || ConversionOverflow) {
13964     if (Info.checkingForUndefinedBehavior())
13965       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13966                                        diag::warn_fixedpoint_constant_overflow)
13967         << Result.toString() << E->getType();
13968     if (!HandleOverflow(Info, E, Result, E->getType()))
13969       return false;
13970   }
13971   return Success(Result, E);
13972 }
13973 
13974 //===----------------------------------------------------------------------===//
13975 // Float Evaluation
13976 //===----------------------------------------------------------------------===//
13977 
13978 namespace {
13979 class FloatExprEvaluator
13980   : public ExprEvaluatorBase<FloatExprEvaluator> {
13981   APFloat &Result;
13982 public:
13983   FloatExprEvaluator(EvalInfo &info, APFloat &result)
13984     : ExprEvaluatorBaseTy(info), Result(result) {}
13985 
13986   bool Success(const APValue &V, const Expr *e) {
13987     Result = V.getFloat();
13988     return true;
13989   }
13990 
13991   bool ZeroInitialization(const Expr *E) {
13992     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
13993     return true;
13994   }
13995 
13996   bool VisitCallExpr(const CallExpr *E);
13997 
13998   bool VisitUnaryOperator(const UnaryOperator *E);
13999   bool VisitBinaryOperator(const BinaryOperator *E);
14000   bool VisitFloatingLiteral(const FloatingLiteral *E);
14001   bool VisitCastExpr(const CastExpr *E);
14002 
14003   bool VisitUnaryReal(const UnaryOperator *E);
14004   bool VisitUnaryImag(const UnaryOperator *E);
14005 
14006   // FIXME: Missing: array subscript of vector, member of vector
14007 };
14008 } // end anonymous namespace
14009 
14010 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
14011   assert(!E->isValueDependent());
14012   assert(E->isPRValue() && E->getType()->isRealFloatingType());
14013   return FloatExprEvaluator(Info, Result).Visit(E);
14014 }
14015 
14016 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
14017                                   QualType ResultTy,
14018                                   const Expr *Arg,
14019                                   bool SNaN,
14020                                   llvm::APFloat &Result) {
14021   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
14022   if (!S) return false;
14023 
14024   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
14025 
14026   llvm::APInt fill;
14027 
14028   // Treat empty strings as if they were zero.
14029   if (S->getString().empty())
14030     fill = llvm::APInt(32, 0);
14031   else if (S->getString().getAsInteger(0, fill))
14032     return false;
14033 
14034   if (Context.getTargetInfo().isNan2008()) {
14035     if (SNaN)
14036       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
14037     else
14038       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
14039   } else {
14040     // Prior to IEEE 754-2008, architectures were allowed to choose whether
14041     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
14042     // a different encoding to what became a standard in 2008, and for pre-
14043     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
14044     // sNaN. This is now known as "legacy NaN" encoding.
14045     if (SNaN)
14046       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
14047     else
14048       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
14049   }
14050 
14051   return true;
14052 }
14053 
14054 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
14055   if (!IsConstantEvaluatedBuiltinCall(E))
14056     return ExprEvaluatorBaseTy::VisitCallExpr(E);
14057 
14058   switch (E->getBuiltinCallee()) {
14059   default:
14060     return false;
14061 
14062   case Builtin::BI__builtin_huge_val:
14063   case Builtin::BI__builtin_huge_valf:
14064   case Builtin::BI__builtin_huge_vall:
14065   case Builtin::BI__builtin_huge_valf16:
14066   case Builtin::BI__builtin_huge_valf128:
14067   case Builtin::BI__builtin_inf:
14068   case Builtin::BI__builtin_inff:
14069   case Builtin::BI__builtin_infl:
14070   case Builtin::BI__builtin_inff16:
14071   case Builtin::BI__builtin_inff128: {
14072     const llvm::fltSemantics &Sem =
14073       Info.Ctx.getFloatTypeSemantics(E->getType());
14074     Result = llvm::APFloat::getInf(Sem);
14075     return true;
14076   }
14077 
14078   case Builtin::BI__builtin_nans:
14079   case Builtin::BI__builtin_nansf:
14080   case Builtin::BI__builtin_nansl:
14081   case Builtin::BI__builtin_nansf16:
14082   case Builtin::BI__builtin_nansf128:
14083     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
14084                                true, Result))
14085       return Error(E);
14086     return true;
14087 
14088   case Builtin::BI__builtin_nan:
14089   case Builtin::BI__builtin_nanf:
14090   case Builtin::BI__builtin_nanl:
14091   case Builtin::BI__builtin_nanf16:
14092   case Builtin::BI__builtin_nanf128:
14093     // If this is __builtin_nan() turn this into a nan, otherwise we
14094     // can't constant fold it.
14095     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
14096                                false, Result))
14097       return Error(E);
14098     return true;
14099 
14100   case Builtin::BI__builtin_fabs:
14101   case Builtin::BI__builtin_fabsf:
14102   case Builtin::BI__builtin_fabsl:
14103   case Builtin::BI__builtin_fabsf128:
14104     // The C standard says "fabs raises no floating-point exceptions,
14105     // even if x is a signaling NaN. The returned value is independent of
14106     // the current rounding direction mode."  Therefore constant folding can
14107     // proceed without regard to the floating point settings.
14108     // Reference, WG14 N2478 F.10.4.3
14109     if (!EvaluateFloat(E->getArg(0), Result, Info))
14110       return false;
14111 
14112     if (Result.isNegative())
14113       Result.changeSign();
14114     return true;
14115 
14116   case Builtin::BI__arithmetic_fence:
14117     return EvaluateFloat(E->getArg(0), Result, Info);
14118 
14119   // FIXME: Builtin::BI__builtin_powi
14120   // FIXME: Builtin::BI__builtin_powif
14121   // FIXME: Builtin::BI__builtin_powil
14122 
14123   case Builtin::BI__builtin_copysign:
14124   case Builtin::BI__builtin_copysignf:
14125   case Builtin::BI__builtin_copysignl:
14126   case Builtin::BI__builtin_copysignf128: {
14127     APFloat RHS(0.);
14128     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
14129         !EvaluateFloat(E->getArg(1), RHS, Info))
14130       return false;
14131     Result.copySign(RHS);
14132     return true;
14133   }
14134 
14135   case Builtin::BI__builtin_fmax:
14136   case Builtin::BI__builtin_fmaxf:
14137   case Builtin::BI__builtin_fmaxl:
14138   case Builtin::BI__builtin_fmaxf16:
14139   case Builtin::BI__builtin_fmaxf128: {
14140     // TODO: Handle sNaN.
14141     APFloat RHS(0.);
14142     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
14143         !EvaluateFloat(E->getArg(1), RHS, Info))
14144       return false;
14145     // When comparing zeroes, return +0.0 if one of the zeroes is positive.
14146     if (Result.isZero() && RHS.isZero() && Result.isNegative())
14147       Result = RHS;
14148     else if (Result.isNaN() || RHS > Result)
14149       Result = RHS;
14150     return true;
14151   }
14152 
14153   case Builtin::BI__builtin_fmin:
14154   case Builtin::BI__builtin_fminf:
14155   case Builtin::BI__builtin_fminl:
14156   case Builtin::BI__builtin_fminf16:
14157   case Builtin::BI__builtin_fminf128: {
14158     // TODO: Handle sNaN.
14159     APFloat RHS(0.);
14160     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
14161         !EvaluateFloat(E->getArg(1), RHS, Info))
14162       return false;
14163     // When comparing zeroes, return -0.0 if one of the zeroes is negative.
14164     if (Result.isZero() && RHS.isZero() && RHS.isNegative())
14165       Result = RHS;
14166     else if (Result.isNaN() || RHS < Result)
14167       Result = RHS;
14168     return true;
14169   }
14170   }
14171 }
14172 
14173 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
14174   if (E->getSubExpr()->getType()->isAnyComplexType()) {
14175     ComplexValue CV;
14176     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
14177       return false;
14178     Result = CV.FloatReal;
14179     return true;
14180   }
14181 
14182   return Visit(E->getSubExpr());
14183 }
14184 
14185 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
14186   if (E->getSubExpr()->getType()->isAnyComplexType()) {
14187     ComplexValue CV;
14188     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
14189       return false;
14190     Result = CV.FloatImag;
14191     return true;
14192   }
14193 
14194   VisitIgnoredValue(E->getSubExpr());
14195   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
14196   Result = llvm::APFloat::getZero(Sem);
14197   return true;
14198 }
14199 
14200 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14201   switch (E->getOpcode()) {
14202   default: return Error(E);
14203   case UO_Plus:
14204     return EvaluateFloat(E->getSubExpr(), Result, Info);
14205   case UO_Minus:
14206     // In C standard, WG14 N2478 F.3 p4
14207     // "the unary - raises no floating point exceptions,
14208     // even if the operand is signalling."
14209     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
14210       return false;
14211     Result.changeSign();
14212     return true;
14213   }
14214 }
14215 
14216 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14217   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14218     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14219 
14220   APFloat RHS(0.0);
14221   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
14222   if (!LHSOK && !Info.noteFailure())
14223     return false;
14224   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
14225          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
14226 }
14227 
14228 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
14229   Result = E->getValue();
14230   return true;
14231 }
14232 
14233 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
14234   const Expr* SubExpr = E->getSubExpr();
14235 
14236   switch (E->getCastKind()) {
14237   default:
14238     return ExprEvaluatorBaseTy::VisitCastExpr(E);
14239 
14240   case CK_IntegralToFloating: {
14241     APSInt IntResult;
14242     const FPOptions FPO = E->getFPFeaturesInEffect(
14243                                   Info.Ctx.getLangOpts());
14244     return EvaluateInteger(SubExpr, IntResult, Info) &&
14245            HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
14246                                 IntResult, E->getType(), Result);
14247   }
14248 
14249   case CK_FixedPointToFloating: {
14250     APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
14251     if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
14252       return false;
14253     Result =
14254         FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
14255     return true;
14256   }
14257 
14258   case CK_FloatingCast: {
14259     if (!Visit(SubExpr))
14260       return false;
14261     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
14262                                   Result);
14263   }
14264 
14265   case CK_FloatingComplexToReal: {
14266     ComplexValue V;
14267     if (!EvaluateComplex(SubExpr, V, Info))
14268       return false;
14269     Result = V.getComplexFloatReal();
14270     return true;
14271   }
14272   }
14273 }
14274 
14275 //===----------------------------------------------------------------------===//
14276 // Complex Evaluation (for float and integer)
14277 //===----------------------------------------------------------------------===//
14278 
14279 namespace {
14280 class ComplexExprEvaluator
14281   : public ExprEvaluatorBase<ComplexExprEvaluator> {
14282   ComplexValue &Result;
14283 
14284 public:
14285   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
14286     : ExprEvaluatorBaseTy(info), Result(Result) {}
14287 
14288   bool Success(const APValue &V, const Expr *e) {
14289     Result.setFrom(V);
14290     return true;
14291   }
14292 
14293   bool ZeroInitialization(const Expr *E);
14294 
14295   //===--------------------------------------------------------------------===//
14296   //                            Visitor Methods
14297   //===--------------------------------------------------------------------===//
14298 
14299   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
14300   bool VisitCastExpr(const CastExpr *E);
14301   bool VisitBinaryOperator(const BinaryOperator *E);
14302   bool VisitUnaryOperator(const UnaryOperator *E);
14303   bool VisitInitListExpr(const InitListExpr *E);
14304   bool VisitCallExpr(const CallExpr *E);
14305 };
14306 } // end anonymous namespace
14307 
14308 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
14309                             EvalInfo &Info) {
14310   assert(!E->isValueDependent());
14311   assert(E->isPRValue() && E->getType()->isAnyComplexType());
14312   return ComplexExprEvaluator(Info, Result).Visit(E);
14313 }
14314 
14315 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
14316   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
14317   if (ElemTy->isRealFloatingType()) {
14318     Result.makeComplexFloat();
14319     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
14320     Result.FloatReal = Zero;
14321     Result.FloatImag = Zero;
14322   } else {
14323     Result.makeComplexInt();
14324     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
14325     Result.IntReal = Zero;
14326     Result.IntImag = Zero;
14327   }
14328   return true;
14329 }
14330 
14331 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
14332   const Expr* SubExpr = E->getSubExpr();
14333 
14334   if (SubExpr->getType()->isRealFloatingType()) {
14335     Result.makeComplexFloat();
14336     APFloat &Imag = Result.FloatImag;
14337     if (!EvaluateFloat(SubExpr, Imag, Info))
14338       return false;
14339 
14340     Result.FloatReal = APFloat(Imag.getSemantics());
14341     return true;
14342   } else {
14343     assert(SubExpr->getType()->isIntegerType() &&
14344            "Unexpected imaginary literal.");
14345 
14346     Result.makeComplexInt();
14347     APSInt &Imag = Result.IntImag;
14348     if (!EvaluateInteger(SubExpr, Imag, Info))
14349       return false;
14350 
14351     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
14352     return true;
14353   }
14354 }
14355 
14356 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
14357 
14358   switch (E->getCastKind()) {
14359   case CK_BitCast:
14360   case CK_BaseToDerived:
14361   case CK_DerivedToBase:
14362   case CK_UncheckedDerivedToBase:
14363   case CK_Dynamic:
14364   case CK_ToUnion:
14365   case CK_ArrayToPointerDecay:
14366   case CK_FunctionToPointerDecay:
14367   case CK_NullToPointer:
14368   case CK_NullToMemberPointer:
14369   case CK_BaseToDerivedMemberPointer:
14370   case CK_DerivedToBaseMemberPointer:
14371   case CK_MemberPointerToBoolean:
14372   case CK_ReinterpretMemberPointer:
14373   case CK_ConstructorConversion:
14374   case CK_IntegralToPointer:
14375   case CK_PointerToIntegral:
14376   case CK_PointerToBoolean:
14377   case CK_ToVoid:
14378   case CK_VectorSplat:
14379   case CK_IntegralCast:
14380   case CK_BooleanToSignedIntegral:
14381   case CK_IntegralToBoolean:
14382   case CK_IntegralToFloating:
14383   case CK_FloatingToIntegral:
14384   case CK_FloatingToBoolean:
14385   case CK_FloatingCast:
14386   case CK_CPointerToObjCPointerCast:
14387   case CK_BlockPointerToObjCPointerCast:
14388   case CK_AnyPointerToBlockPointerCast:
14389   case CK_ObjCObjectLValueCast:
14390   case CK_FloatingComplexToReal:
14391   case CK_FloatingComplexToBoolean:
14392   case CK_IntegralComplexToReal:
14393   case CK_IntegralComplexToBoolean:
14394   case CK_ARCProduceObject:
14395   case CK_ARCConsumeObject:
14396   case CK_ARCReclaimReturnedObject:
14397   case CK_ARCExtendBlockObject:
14398   case CK_CopyAndAutoreleaseBlockObject:
14399   case CK_BuiltinFnToFnPtr:
14400   case CK_ZeroToOCLOpaqueType:
14401   case CK_NonAtomicToAtomic:
14402   case CK_AddressSpaceConversion:
14403   case CK_IntToOCLSampler:
14404   case CK_FloatingToFixedPoint:
14405   case CK_FixedPointToFloating:
14406   case CK_FixedPointCast:
14407   case CK_FixedPointToBoolean:
14408   case CK_FixedPointToIntegral:
14409   case CK_IntegralToFixedPoint:
14410   case CK_MatrixCast:
14411     llvm_unreachable("invalid cast kind for complex value");
14412 
14413   case CK_LValueToRValue:
14414   case CK_AtomicToNonAtomic:
14415   case CK_NoOp:
14416   case CK_LValueToRValueBitCast:
14417     return ExprEvaluatorBaseTy::VisitCastExpr(E);
14418 
14419   case CK_Dependent:
14420   case CK_LValueBitCast:
14421   case CK_UserDefinedConversion:
14422     return Error(E);
14423 
14424   case CK_FloatingRealToComplex: {
14425     APFloat &Real = Result.FloatReal;
14426     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
14427       return false;
14428 
14429     Result.makeComplexFloat();
14430     Result.FloatImag = APFloat(Real.getSemantics());
14431     return true;
14432   }
14433 
14434   case CK_FloatingComplexCast: {
14435     if (!Visit(E->getSubExpr()))
14436       return false;
14437 
14438     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14439     QualType From
14440       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14441 
14442     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
14443            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
14444   }
14445 
14446   case CK_FloatingComplexToIntegralComplex: {
14447     if (!Visit(E->getSubExpr()))
14448       return false;
14449 
14450     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14451     QualType From
14452       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14453     Result.makeComplexInt();
14454     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
14455                                 To, Result.IntReal) &&
14456            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
14457                                 To, Result.IntImag);
14458   }
14459 
14460   case CK_IntegralRealToComplex: {
14461     APSInt &Real = Result.IntReal;
14462     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
14463       return false;
14464 
14465     Result.makeComplexInt();
14466     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
14467     return true;
14468   }
14469 
14470   case CK_IntegralComplexCast: {
14471     if (!Visit(E->getSubExpr()))
14472       return false;
14473 
14474     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14475     QualType From
14476       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14477 
14478     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
14479     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
14480     return true;
14481   }
14482 
14483   case CK_IntegralComplexToFloatingComplex: {
14484     if (!Visit(E->getSubExpr()))
14485       return false;
14486 
14487     const FPOptions FPO = E->getFPFeaturesInEffect(
14488                                   Info.Ctx.getLangOpts());
14489     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14490     QualType From
14491       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14492     Result.makeComplexFloat();
14493     return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
14494                                 To, Result.FloatReal) &&
14495            HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
14496                                 To, Result.FloatImag);
14497   }
14498   }
14499 
14500   llvm_unreachable("unknown cast resulting in complex value");
14501 }
14502 
14503 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14504   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14505     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14506 
14507   // Track whether the LHS or RHS is real at the type system level. When this is
14508   // the case we can simplify our evaluation strategy.
14509   bool LHSReal = false, RHSReal = false;
14510 
14511   bool LHSOK;
14512   if (E->getLHS()->getType()->isRealFloatingType()) {
14513     LHSReal = true;
14514     APFloat &Real = Result.FloatReal;
14515     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
14516     if (LHSOK) {
14517       Result.makeComplexFloat();
14518       Result.FloatImag = APFloat(Real.getSemantics());
14519     }
14520   } else {
14521     LHSOK = Visit(E->getLHS());
14522   }
14523   if (!LHSOK && !Info.noteFailure())
14524     return false;
14525 
14526   ComplexValue RHS;
14527   if (E->getRHS()->getType()->isRealFloatingType()) {
14528     RHSReal = true;
14529     APFloat &Real = RHS.FloatReal;
14530     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
14531       return false;
14532     RHS.makeComplexFloat();
14533     RHS.FloatImag = APFloat(Real.getSemantics());
14534   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
14535     return false;
14536 
14537   assert(!(LHSReal && RHSReal) &&
14538          "Cannot have both operands of a complex operation be real.");
14539   switch (E->getOpcode()) {
14540   default: return Error(E);
14541   case BO_Add:
14542     if (Result.isComplexFloat()) {
14543       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
14544                                        APFloat::rmNearestTiesToEven);
14545       if (LHSReal)
14546         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14547       else if (!RHSReal)
14548         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
14549                                          APFloat::rmNearestTiesToEven);
14550     } else {
14551       Result.getComplexIntReal() += RHS.getComplexIntReal();
14552       Result.getComplexIntImag() += RHS.getComplexIntImag();
14553     }
14554     break;
14555   case BO_Sub:
14556     if (Result.isComplexFloat()) {
14557       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
14558                                             APFloat::rmNearestTiesToEven);
14559       if (LHSReal) {
14560         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14561         Result.getComplexFloatImag().changeSign();
14562       } else if (!RHSReal) {
14563         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
14564                                               APFloat::rmNearestTiesToEven);
14565       }
14566     } else {
14567       Result.getComplexIntReal() -= RHS.getComplexIntReal();
14568       Result.getComplexIntImag() -= RHS.getComplexIntImag();
14569     }
14570     break;
14571   case BO_Mul:
14572     if (Result.isComplexFloat()) {
14573       // This is an implementation of complex multiplication according to the
14574       // constraints laid out in C11 Annex G. The implementation uses the
14575       // following naming scheme:
14576       //   (a + ib) * (c + id)
14577       ComplexValue LHS = Result;
14578       APFloat &A = LHS.getComplexFloatReal();
14579       APFloat &B = LHS.getComplexFloatImag();
14580       APFloat &C = RHS.getComplexFloatReal();
14581       APFloat &D = RHS.getComplexFloatImag();
14582       APFloat &ResR = Result.getComplexFloatReal();
14583       APFloat &ResI = Result.getComplexFloatImag();
14584       if (LHSReal) {
14585         assert(!RHSReal && "Cannot have two real operands for a complex op!");
14586         ResR = A * C;
14587         ResI = A * D;
14588       } else if (RHSReal) {
14589         ResR = C * A;
14590         ResI = C * B;
14591       } else {
14592         // In the fully general case, we need to handle NaNs and infinities
14593         // robustly.
14594         APFloat AC = A * C;
14595         APFloat BD = B * D;
14596         APFloat AD = A * D;
14597         APFloat BC = B * C;
14598         ResR = AC - BD;
14599         ResI = AD + BC;
14600         if (ResR.isNaN() && ResI.isNaN()) {
14601           bool Recalc = false;
14602           if (A.isInfinity() || B.isInfinity()) {
14603             A = APFloat::copySign(
14604                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14605             B = APFloat::copySign(
14606                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14607             if (C.isNaN())
14608               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14609             if (D.isNaN())
14610               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14611             Recalc = true;
14612           }
14613           if (C.isInfinity() || D.isInfinity()) {
14614             C = APFloat::copySign(
14615                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14616             D = APFloat::copySign(
14617                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14618             if (A.isNaN())
14619               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14620             if (B.isNaN())
14621               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14622             Recalc = true;
14623           }
14624           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
14625                           AD.isInfinity() || BC.isInfinity())) {
14626             if (A.isNaN())
14627               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14628             if (B.isNaN())
14629               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14630             if (C.isNaN())
14631               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14632             if (D.isNaN())
14633               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14634             Recalc = true;
14635           }
14636           if (Recalc) {
14637             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
14638             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
14639           }
14640         }
14641       }
14642     } else {
14643       ComplexValue LHS = Result;
14644       Result.getComplexIntReal() =
14645         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
14646          LHS.getComplexIntImag() * RHS.getComplexIntImag());
14647       Result.getComplexIntImag() =
14648         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
14649          LHS.getComplexIntImag() * RHS.getComplexIntReal());
14650     }
14651     break;
14652   case BO_Div:
14653     if (Result.isComplexFloat()) {
14654       // This is an implementation of complex division according to the
14655       // constraints laid out in C11 Annex G. The implementation uses the
14656       // following naming scheme:
14657       //   (a + ib) / (c + id)
14658       ComplexValue LHS = Result;
14659       APFloat &A = LHS.getComplexFloatReal();
14660       APFloat &B = LHS.getComplexFloatImag();
14661       APFloat &C = RHS.getComplexFloatReal();
14662       APFloat &D = RHS.getComplexFloatImag();
14663       APFloat &ResR = Result.getComplexFloatReal();
14664       APFloat &ResI = Result.getComplexFloatImag();
14665       if (RHSReal) {
14666         ResR = A / C;
14667         ResI = B / C;
14668       } else {
14669         if (LHSReal) {
14670           // No real optimizations we can do here, stub out with zero.
14671           B = APFloat::getZero(A.getSemantics());
14672         }
14673         int DenomLogB = 0;
14674         APFloat MaxCD = maxnum(abs(C), abs(D));
14675         if (MaxCD.isFinite()) {
14676           DenomLogB = ilogb(MaxCD);
14677           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
14678           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
14679         }
14680         APFloat Denom = C * C + D * D;
14681         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
14682                       APFloat::rmNearestTiesToEven);
14683         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
14684                       APFloat::rmNearestTiesToEven);
14685         if (ResR.isNaN() && ResI.isNaN()) {
14686           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
14687             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
14688             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
14689           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
14690                      D.isFinite()) {
14691             A = APFloat::copySign(
14692                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14693             B = APFloat::copySign(
14694                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14695             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
14696             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
14697           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
14698             C = APFloat::copySign(
14699                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14700             D = APFloat::copySign(
14701                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14702             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
14703             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
14704           }
14705         }
14706       }
14707     } else {
14708       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
14709         return Error(E, diag::note_expr_divide_by_zero);
14710 
14711       ComplexValue LHS = Result;
14712       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
14713         RHS.getComplexIntImag() * RHS.getComplexIntImag();
14714       Result.getComplexIntReal() =
14715         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
14716          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
14717       Result.getComplexIntImag() =
14718         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
14719          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
14720     }
14721     break;
14722   }
14723 
14724   return true;
14725 }
14726 
14727 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14728   // Get the operand value into 'Result'.
14729   if (!Visit(E->getSubExpr()))
14730     return false;
14731 
14732   switch (E->getOpcode()) {
14733   default:
14734     return Error(E);
14735   case UO_Extension:
14736     return true;
14737   case UO_Plus:
14738     // The result is always just the subexpr.
14739     return true;
14740   case UO_Minus:
14741     if (Result.isComplexFloat()) {
14742       Result.getComplexFloatReal().changeSign();
14743       Result.getComplexFloatImag().changeSign();
14744     }
14745     else {
14746       Result.getComplexIntReal() = -Result.getComplexIntReal();
14747       Result.getComplexIntImag() = -Result.getComplexIntImag();
14748     }
14749     return true;
14750   case UO_Not:
14751     if (Result.isComplexFloat())
14752       Result.getComplexFloatImag().changeSign();
14753     else
14754       Result.getComplexIntImag() = -Result.getComplexIntImag();
14755     return true;
14756   }
14757 }
14758 
14759 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
14760   if (E->getNumInits() == 2) {
14761     if (E->getType()->isComplexType()) {
14762       Result.makeComplexFloat();
14763       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
14764         return false;
14765       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
14766         return false;
14767     } else {
14768       Result.makeComplexInt();
14769       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
14770         return false;
14771       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
14772         return false;
14773     }
14774     return true;
14775   }
14776   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
14777 }
14778 
14779 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
14780   if (!IsConstantEvaluatedBuiltinCall(E))
14781     return ExprEvaluatorBaseTy::VisitCallExpr(E);
14782 
14783   switch (E->getBuiltinCallee()) {
14784   case Builtin::BI__builtin_complex:
14785     Result.makeComplexFloat();
14786     if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
14787       return false;
14788     if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
14789       return false;
14790     return true;
14791 
14792   default:
14793     return false;
14794   }
14795 }
14796 
14797 //===----------------------------------------------------------------------===//
14798 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
14799 // implicit conversion.
14800 //===----------------------------------------------------------------------===//
14801 
14802 namespace {
14803 class AtomicExprEvaluator :
14804     public ExprEvaluatorBase<AtomicExprEvaluator> {
14805   const LValue *This;
14806   APValue &Result;
14807 public:
14808   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
14809       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
14810 
14811   bool Success(const APValue &V, const Expr *E) {
14812     Result = V;
14813     return true;
14814   }
14815 
14816   bool ZeroInitialization(const Expr *E) {
14817     ImplicitValueInitExpr VIE(
14818         E->getType()->castAs<AtomicType>()->getValueType());
14819     // For atomic-qualified class (and array) types in C++, initialize the
14820     // _Atomic-wrapped subobject directly, in-place.
14821     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
14822                 : Evaluate(Result, Info, &VIE);
14823   }
14824 
14825   bool VisitCastExpr(const CastExpr *E) {
14826     switch (E->getCastKind()) {
14827     default:
14828       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14829     case CK_NonAtomicToAtomic:
14830       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
14831                   : Evaluate(Result, Info, E->getSubExpr());
14832     }
14833   }
14834 };
14835 } // end anonymous namespace
14836 
14837 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
14838                            EvalInfo &Info) {
14839   assert(!E->isValueDependent());
14840   assert(E->isPRValue() && E->getType()->isAtomicType());
14841   return AtomicExprEvaluator(Info, This, Result).Visit(E);
14842 }
14843 
14844 //===----------------------------------------------------------------------===//
14845 // Void expression evaluation, primarily for a cast to void on the LHS of a
14846 // comma operator
14847 //===----------------------------------------------------------------------===//
14848 
14849 namespace {
14850 class VoidExprEvaluator
14851   : public ExprEvaluatorBase<VoidExprEvaluator> {
14852 public:
14853   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
14854 
14855   bool Success(const APValue &V, const Expr *e) { return true; }
14856 
14857   bool ZeroInitialization(const Expr *E) { return true; }
14858 
14859   bool VisitCastExpr(const CastExpr *E) {
14860     switch (E->getCastKind()) {
14861     default:
14862       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14863     case CK_ToVoid:
14864       VisitIgnoredValue(E->getSubExpr());
14865       return true;
14866     }
14867   }
14868 
14869   bool VisitCallExpr(const CallExpr *E) {
14870     if (!IsConstantEvaluatedBuiltinCall(E))
14871       return ExprEvaluatorBaseTy::VisitCallExpr(E);
14872 
14873     switch (E->getBuiltinCallee()) {
14874     case Builtin::BI__assume:
14875     case Builtin::BI__builtin_assume:
14876       // The argument is not evaluated!
14877       return true;
14878 
14879     case Builtin::BI__builtin_operator_delete:
14880       return HandleOperatorDeleteCall(Info, E);
14881 
14882     default:
14883       return false;
14884     }
14885   }
14886 
14887   bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
14888 };
14889 } // end anonymous namespace
14890 
14891 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
14892   // We cannot speculatively evaluate a delete expression.
14893   if (Info.SpeculativeEvaluationDepth)
14894     return false;
14895 
14896   FunctionDecl *OperatorDelete = E->getOperatorDelete();
14897   if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
14898     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14899         << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
14900     return false;
14901   }
14902 
14903   const Expr *Arg = E->getArgument();
14904 
14905   LValue Pointer;
14906   if (!EvaluatePointer(Arg, Pointer, Info))
14907     return false;
14908   if (Pointer.Designator.Invalid)
14909     return false;
14910 
14911   // Deleting a null pointer has no effect.
14912   if (Pointer.isNullPointer()) {
14913     // This is the only case where we need to produce an extension warning:
14914     // the only other way we can succeed is if we find a dynamic allocation,
14915     // and we will have warned when we allocated it in that case.
14916     if (!Info.getLangOpts().CPlusPlus20)
14917       Info.CCEDiag(E, diag::note_constexpr_new);
14918     return true;
14919   }
14920 
14921   std::optional<DynAlloc *> Alloc = CheckDeleteKind(
14922       Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
14923   if (!Alloc)
14924     return false;
14925   QualType AllocType = Pointer.Base.getDynamicAllocType();
14926 
14927   // For the non-array case, the designator must be empty if the static type
14928   // does not have a virtual destructor.
14929   if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
14930       !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
14931     Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
14932         << Arg->getType()->getPointeeType() << AllocType;
14933     return false;
14934   }
14935 
14936   // For a class type with a virtual destructor, the selected operator delete
14937   // is the one looked up when building the destructor.
14938   if (!E->isArrayForm() && !E->isGlobalDelete()) {
14939     const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
14940     if (VirtualDelete &&
14941         !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
14942       Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14943           << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
14944       return false;
14945     }
14946   }
14947 
14948   if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
14949                          (*Alloc)->Value, AllocType))
14950     return false;
14951 
14952   if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
14953     // The element was already erased. This means the destructor call also
14954     // deleted the object.
14955     // FIXME: This probably results in undefined behavior before we get this
14956     // far, and should be diagnosed elsewhere first.
14957     Info.FFDiag(E, diag::note_constexpr_double_delete);
14958     return false;
14959   }
14960 
14961   return true;
14962 }
14963 
14964 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
14965   assert(!E->isValueDependent());
14966   assert(E->isPRValue() && E->getType()->isVoidType());
14967   return VoidExprEvaluator(Info).Visit(E);
14968 }
14969 
14970 //===----------------------------------------------------------------------===//
14971 // Top level Expr::EvaluateAsRValue method.
14972 //===----------------------------------------------------------------------===//
14973 
14974 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
14975   assert(!E->isValueDependent());
14976   // In C, function designators are not lvalues, but we evaluate them as if they
14977   // are.
14978   QualType T = E->getType();
14979   if (E->isGLValue() || T->isFunctionType()) {
14980     LValue LV;
14981     if (!EvaluateLValue(E, LV, Info))
14982       return false;
14983     LV.moveInto(Result);
14984   } else if (T->isVectorType()) {
14985     if (!EvaluateVector(E, Result, Info))
14986       return false;
14987   } else if (T->isIntegralOrEnumerationType()) {
14988     if (!IntExprEvaluator(Info, Result).Visit(E))
14989       return false;
14990   } else if (T->hasPointerRepresentation()) {
14991     LValue LV;
14992     if (!EvaluatePointer(E, LV, Info))
14993       return false;
14994     LV.moveInto(Result);
14995   } else if (T->isRealFloatingType()) {
14996     llvm::APFloat F(0.0);
14997     if (!EvaluateFloat(E, F, Info))
14998       return false;
14999     Result = APValue(F);
15000   } else if (T->isAnyComplexType()) {
15001     ComplexValue C;
15002     if (!EvaluateComplex(E, C, Info))
15003       return false;
15004     C.moveInto(Result);
15005   } else if (T->isFixedPointType()) {
15006     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
15007   } else if (T->isMemberPointerType()) {
15008     MemberPtr P;
15009     if (!EvaluateMemberPointer(E, P, Info))
15010       return false;
15011     P.moveInto(Result);
15012     return true;
15013   } else if (T->isArrayType()) {
15014     LValue LV;
15015     APValue &Value =
15016         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
15017     if (!EvaluateArray(E, LV, Value, Info))
15018       return false;
15019     Result = Value;
15020   } else if (T->isRecordType()) {
15021     LValue LV;
15022     APValue &Value =
15023         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
15024     if (!EvaluateRecord(E, LV, Value, Info))
15025       return false;
15026     Result = Value;
15027   } else if (T->isVoidType()) {
15028     if (!Info.getLangOpts().CPlusPlus11)
15029       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
15030         << E->getType();
15031     if (!EvaluateVoid(E, Info))
15032       return false;
15033   } else if (T->isAtomicType()) {
15034     QualType Unqual = T.getAtomicUnqualifiedType();
15035     if (Unqual->isArrayType() || Unqual->isRecordType()) {
15036       LValue LV;
15037       APValue &Value = Info.CurrentCall->createTemporary(
15038           E, Unqual, ScopeKind::FullExpression, LV);
15039       if (!EvaluateAtomic(E, &LV, Value, Info))
15040         return false;
15041     } else {
15042       if (!EvaluateAtomic(E, nullptr, Result, Info))
15043         return false;
15044     }
15045   } else if (Info.getLangOpts().CPlusPlus11) {
15046     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
15047     return false;
15048   } else {
15049     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
15050     return false;
15051   }
15052 
15053   return true;
15054 }
15055 
15056 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
15057 /// cases, the in-place evaluation is essential, since later initializers for
15058 /// an object can indirectly refer to subobjects which were initialized earlier.
15059 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
15060                             const Expr *E, bool AllowNonLiteralTypes) {
15061   assert(!E->isValueDependent());
15062 
15063   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
15064     return false;
15065 
15066   if (E->isPRValue()) {
15067     // Evaluate arrays and record types in-place, so that later initializers can
15068     // refer to earlier-initialized members of the object.
15069     QualType T = E->getType();
15070     if (T->isArrayType())
15071       return EvaluateArray(E, This, Result, Info);
15072     else if (T->isRecordType())
15073       return EvaluateRecord(E, This, Result, Info);
15074     else if (T->isAtomicType()) {
15075       QualType Unqual = T.getAtomicUnqualifiedType();
15076       if (Unqual->isArrayType() || Unqual->isRecordType())
15077         return EvaluateAtomic(E, &This, Result, Info);
15078     }
15079   }
15080 
15081   // For any other type, in-place evaluation is unimportant.
15082   return Evaluate(Result, Info, E);
15083 }
15084 
15085 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
15086 /// lvalue-to-rvalue cast if it is an lvalue.
15087 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
15088   assert(!E->isValueDependent());
15089 
15090   if (E->getType().isNull())
15091     return false;
15092 
15093   if (!CheckLiteralType(Info, E))
15094     return false;
15095 
15096   if (Info.EnableNewConstInterp) {
15097     if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
15098       return false;
15099   } else {
15100     if (!::Evaluate(Result, Info, E))
15101       return false;
15102   }
15103 
15104   // Implicit lvalue-to-rvalue cast.
15105   if (E->isGLValue()) {
15106     LValue LV;
15107     LV.setFrom(Info.Ctx, Result);
15108     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
15109       return false;
15110   }
15111 
15112   // Check this core constant expression is a constant expression.
15113   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
15114                                  ConstantExprKind::Normal) &&
15115          CheckMemoryLeaks(Info);
15116 }
15117 
15118 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
15119                                  const ASTContext &Ctx, bool &IsConst) {
15120   // Fast-path evaluations of integer literals, since we sometimes see files
15121   // containing vast quantities of these.
15122   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
15123     Result.Val = APValue(APSInt(L->getValue(),
15124                                 L->getType()->isUnsignedIntegerType()));
15125     IsConst = true;
15126     return true;
15127   }
15128 
15129   if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Exp)) {
15130     Result.Val = APValue(APSInt(APInt(1, L->getValue())));
15131     IsConst = true;
15132     return true;
15133   }
15134 
15135   // This case should be rare, but we need to check it before we check on
15136   // the type below.
15137   if (Exp->getType().isNull()) {
15138     IsConst = false;
15139     return true;
15140   }
15141 
15142   // FIXME: Evaluating values of large array and record types can cause
15143   // performance problems. Only do so in C++11 for now.
15144   if (Exp->isPRValue() &&
15145       (Exp->getType()->isArrayType() || Exp->getType()->isRecordType()) &&
15146       !Ctx.getLangOpts().CPlusPlus11) {
15147     IsConst = false;
15148     return true;
15149   }
15150   return false;
15151 }
15152 
15153 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
15154                                       Expr::SideEffectsKind SEK) {
15155   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
15156          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
15157 }
15158 
15159 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
15160                              const ASTContext &Ctx, EvalInfo &Info) {
15161   assert(!E->isValueDependent());
15162   bool IsConst;
15163   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
15164     return IsConst;
15165 
15166   return EvaluateAsRValue(Info, E, Result.Val);
15167 }
15168 
15169 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
15170                           const ASTContext &Ctx,
15171                           Expr::SideEffectsKind AllowSideEffects,
15172                           EvalInfo &Info) {
15173   assert(!E->isValueDependent());
15174   if (!E->getType()->isIntegralOrEnumerationType())
15175     return false;
15176 
15177   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
15178       !ExprResult.Val.isInt() ||
15179       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
15180     return false;
15181 
15182   return true;
15183 }
15184 
15185 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
15186                                  const ASTContext &Ctx,
15187                                  Expr::SideEffectsKind AllowSideEffects,
15188                                  EvalInfo &Info) {
15189   assert(!E->isValueDependent());
15190   if (!E->getType()->isFixedPointType())
15191     return false;
15192 
15193   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
15194     return false;
15195 
15196   if (!ExprResult.Val.isFixedPoint() ||
15197       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
15198     return false;
15199 
15200   return true;
15201 }
15202 
15203 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
15204 /// any crazy technique (that has nothing to do with language standards) that
15205 /// we want to.  If this function returns true, it returns the folded constant
15206 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
15207 /// will be applied to the result.
15208 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
15209                             bool InConstantContext) const {
15210   assert(!isValueDependent() &&
15211          "Expression evaluator can't be called on a dependent expression.");
15212   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue");
15213   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
15214   Info.InConstantContext = InConstantContext;
15215   return ::EvaluateAsRValue(this, Result, Ctx, Info);
15216 }
15217 
15218 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
15219                                       bool InConstantContext) const {
15220   assert(!isValueDependent() &&
15221          "Expression evaluator can't be called on a dependent expression.");
15222   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition");
15223   EvalResult Scratch;
15224   return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
15225          HandleConversionToBool(Scratch.Val, Result);
15226 }
15227 
15228 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
15229                          SideEffectsKind AllowSideEffects,
15230                          bool InConstantContext) const {
15231   assert(!isValueDependent() &&
15232          "Expression evaluator can't be called on a dependent expression.");
15233   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt");
15234   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
15235   Info.InConstantContext = InConstantContext;
15236   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
15237 }
15238 
15239 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
15240                                 SideEffectsKind AllowSideEffects,
15241                                 bool InConstantContext) const {
15242   assert(!isValueDependent() &&
15243          "Expression evaluator can't be called on a dependent expression.");
15244   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint");
15245   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
15246   Info.InConstantContext = InConstantContext;
15247   return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
15248 }
15249 
15250 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
15251                            SideEffectsKind AllowSideEffects,
15252                            bool InConstantContext) const {
15253   assert(!isValueDependent() &&
15254          "Expression evaluator can't be called on a dependent expression.");
15255 
15256   if (!getType()->isRealFloatingType())
15257     return false;
15258 
15259   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat");
15260   EvalResult ExprResult;
15261   if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
15262       !ExprResult.Val.isFloat() ||
15263       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
15264     return false;
15265 
15266   Result = ExprResult.Val.getFloat();
15267   return true;
15268 }
15269 
15270 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
15271                             bool InConstantContext) const {
15272   assert(!isValueDependent() &&
15273          "Expression evaluator can't be called on a dependent expression.");
15274 
15275   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue");
15276   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
15277   Info.InConstantContext = InConstantContext;
15278   LValue LV;
15279   CheckedTemporaries CheckedTemps;
15280   if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
15281       Result.HasSideEffects ||
15282       !CheckLValueConstantExpression(Info, getExprLoc(),
15283                                      Ctx.getLValueReferenceType(getType()), LV,
15284                                      ConstantExprKind::Normal, CheckedTemps))
15285     return false;
15286 
15287   LV.moveInto(Result.Val);
15288   return true;
15289 }
15290 
15291 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base,
15292                                 APValue DestroyedValue, QualType Type,
15293                                 SourceLocation Loc, Expr::EvalStatus &EStatus,
15294                                 bool IsConstantDestruction) {
15295   EvalInfo Info(Ctx, EStatus,
15296                 IsConstantDestruction ? EvalInfo::EM_ConstantExpression
15297                                       : EvalInfo::EM_ConstantFold);
15298   Info.setEvaluatingDecl(Base, DestroyedValue,
15299                          EvalInfo::EvaluatingDeclKind::Dtor);
15300   Info.InConstantContext = IsConstantDestruction;
15301 
15302   LValue LVal;
15303   LVal.set(Base);
15304 
15305   if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
15306       EStatus.HasSideEffects)
15307     return false;
15308 
15309   if (!Info.discardCleanups())
15310     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15311 
15312   return true;
15313 }
15314 
15315 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx,
15316                                   ConstantExprKind Kind) const {
15317   assert(!isValueDependent() &&
15318          "Expression evaluator can't be called on a dependent expression.");
15319   bool IsConst;
15320   if (FastEvaluateAsRValue(this, Result, Ctx, IsConst) && Result.Val.hasValue())
15321     return true;
15322 
15323   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr");
15324   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
15325   EvalInfo Info(Ctx, Result, EM);
15326   Info.InConstantContext = true;
15327 
15328   // The type of the object we're initializing is 'const T' for a class NTTP.
15329   QualType T = getType();
15330   if (Kind == ConstantExprKind::ClassTemplateArgument)
15331     T.addConst();
15332 
15333   // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
15334   // represent the result of the evaluation. CheckConstantExpression ensures
15335   // this doesn't escape.
15336   MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
15337   APValue::LValueBase Base(&BaseMTE);
15338 
15339   Info.setEvaluatingDecl(Base, Result.Val);
15340   LValue LVal;
15341   LVal.set(Base);
15342 
15343   if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || Result.HasSideEffects)
15344     return false;
15345 
15346   if (!Info.discardCleanups())
15347     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15348 
15349   if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
15350                                Result.Val, Kind))
15351     return false;
15352   if (!CheckMemoryLeaks(Info))
15353     return false;
15354 
15355   // If this is a class template argument, it's required to have constant
15356   // destruction too.
15357   if (Kind == ConstantExprKind::ClassTemplateArgument &&
15358       (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result,
15359                             true) ||
15360        Result.HasSideEffects)) {
15361     // FIXME: Prefix a note to indicate that the problem is lack of constant
15362     // destruction.
15363     return false;
15364   }
15365 
15366   return true;
15367 }
15368 
15369 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
15370                                  const VarDecl *VD,
15371                             SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
15372   assert(!isValueDependent() &&
15373          "Expression evaluator can't be called on a dependent expression.");
15374 
15375   llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] {
15376     std::string Name;
15377     llvm::raw_string_ostream OS(Name);
15378     VD->printQualifiedName(OS);
15379     return Name;
15380   });
15381 
15382   // FIXME: Evaluating initializers for large array and record types can cause
15383   // performance problems. Only do so in C++11 for now.
15384   if (isPRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
15385       !Ctx.getLangOpts().CPlusPlus11)
15386     return false;
15387 
15388   Expr::EvalStatus EStatus;
15389   EStatus.Diag = &Notes;
15390 
15391   EvalInfo Info(Ctx, EStatus, VD->isConstexpr()
15392                                       ? EvalInfo::EM_ConstantExpression
15393                                       : EvalInfo::EM_ConstantFold);
15394   Info.setEvaluatingDecl(VD, Value);
15395   Info.InConstantContext = true;
15396 
15397   SourceLocation DeclLoc = VD->getLocation();
15398   QualType DeclTy = VD->getType();
15399 
15400   if (Info.EnableNewConstInterp) {
15401     auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
15402     if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
15403       return false;
15404   } else {
15405     LValue LVal;
15406     LVal.set(VD);
15407 
15408     if (!EvaluateInPlace(Value, Info, LVal, this,
15409                          /*AllowNonLiteralTypes=*/true) ||
15410         EStatus.HasSideEffects)
15411       return false;
15412 
15413     // At this point, any lifetime-extended temporaries are completely
15414     // initialized.
15415     Info.performLifetimeExtension();
15416 
15417     if (!Info.discardCleanups())
15418       llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15419   }
15420   return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
15421                                  ConstantExprKind::Normal) &&
15422          CheckMemoryLeaks(Info);
15423 }
15424 
15425 bool VarDecl::evaluateDestruction(
15426     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
15427   Expr::EvalStatus EStatus;
15428   EStatus.Diag = &Notes;
15429 
15430   // Only treat the destruction as constant destruction if we formally have
15431   // constant initialization (or are usable in a constant expression).
15432   bool IsConstantDestruction = hasConstantInitialization();
15433 
15434   // Make a copy of the value for the destructor to mutate, if we know it.
15435   // Otherwise, treat the value as default-initialized; if the destructor works
15436   // anyway, then the destruction is constant (and must be essentially empty).
15437   APValue DestroyedValue;
15438   if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
15439     DestroyedValue = *getEvaluatedValue();
15440   else if (!getDefaultInitValue(getType(), DestroyedValue))
15441     return false;
15442 
15443   if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
15444                            getType(), getLocation(), EStatus,
15445                            IsConstantDestruction) ||
15446       EStatus.HasSideEffects)
15447     return false;
15448 
15449   ensureEvaluatedStmt()->HasConstantDestruction = true;
15450   return true;
15451 }
15452 
15453 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
15454 /// constant folded, but discard the result.
15455 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
15456   assert(!isValueDependent() &&
15457          "Expression evaluator can't be called on a dependent expression.");
15458 
15459   EvalResult Result;
15460   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
15461          !hasUnacceptableSideEffect(Result, SEK);
15462 }
15463 
15464 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
15465                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
15466   assert(!isValueDependent() &&
15467          "Expression evaluator can't be called on a dependent expression.");
15468 
15469   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt");
15470   EvalResult EVResult;
15471   EVResult.Diag = Diag;
15472   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15473   Info.InConstantContext = true;
15474 
15475   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
15476   (void)Result;
15477   assert(Result && "Could not evaluate expression");
15478   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
15479 
15480   return EVResult.Val.getInt();
15481 }
15482 
15483 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
15484     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
15485   assert(!isValueDependent() &&
15486          "Expression evaluator can't be called on a dependent expression.");
15487 
15488   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow");
15489   EvalResult EVResult;
15490   EVResult.Diag = Diag;
15491   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15492   Info.InConstantContext = true;
15493   Info.CheckingForUndefinedBehavior = true;
15494 
15495   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
15496   (void)Result;
15497   assert(Result && "Could not evaluate expression");
15498   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
15499 
15500   return EVResult.Val.getInt();
15501 }
15502 
15503 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
15504   assert(!isValueDependent() &&
15505          "Expression evaluator can't be called on a dependent expression.");
15506 
15507   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow");
15508   bool IsConst;
15509   EvalResult EVResult;
15510   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
15511     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15512     Info.CheckingForUndefinedBehavior = true;
15513     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
15514   }
15515 }
15516 
15517 bool Expr::EvalResult::isGlobalLValue() const {
15518   assert(Val.isLValue());
15519   return IsGlobalLValue(Val.getLValueBase());
15520 }
15521 
15522 /// isIntegerConstantExpr - this recursive routine will test if an expression is
15523 /// an integer constant expression.
15524 
15525 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
15526 /// comma, etc
15527 
15528 // CheckICE - This function does the fundamental ICE checking: the returned
15529 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
15530 // and a (possibly null) SourceLocation indicating the location of the problem.
15531 //
15532 // Note that to reduce code duplication, this helper does no evaluation
15533 // itself; the caller checks whether the expression is evaluatable, and
15534 // in the rare cases where CheckICE actually cares about the evaluated
15535 // value, it calls into Evaluate.
15536 
15537 namespace {
15538 
15539 enum ICEKind {
15540   /// This expression is an ICE.
15541   IK_ICE,
15542   /// This expression is not an ICE, but if it isn't evaluated, it's
15543   /// a legal subexpression for an ICE. This return value is used to handle
15544   /// the comma operator in C99 mode, and non-constant subexpressions.
15545   IK_ICEIfUnevaluated,
15546   /// This expression is not an ICE, and is not a legal subexpression for one.
15547   IK_NotICE
15548 };
15549 
15550 struct ICEDiag {
15551   ICEKind Kind;
15552   SourceLocation Loc;
15553 
15554   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
15555 };
15556 
15557 }
15558 
15559 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
15560 
15561 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
15562 
15563 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
15564   Expr::EvalResult EVResult;
15565   Expr::EvalStatus Status;
15566   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15567 
15568   Info.InConstantContext = true;
15569   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
15570       !EVResult.Val.isInt())
15571     return ICEDiag(IK_NotICE, E->getBeginLoc());
15572 
15573   return NoDiag();
15574 }
15575 
15576 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
15577   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
15578   if (!E->getType()->isIntegralOrEnumerationType())
15579     return ICEDiag(IK_NotICE, E->getBeginLoc());
15580 
15581   switch (E->getStmtClass()) {
15582 #define ABSTRACT_STMT(Node)
15583 #define STMT(Node, Base) case Expr::Node##Class:
15584 #define EXPR(Node, Base)
15585 #include "clang/AST/StmtNodes.inc"
15586   case Expr::PredefinedExprClass:
15587   case Expr::FloatingLiteralClass:
15588   case Expr::ImaginaryLiteralClass:
15589   case Expr::StringLiteralClass:
15590   case Expr::ArraySubscriptExprClass:
15591   case Expr::MatrixSubscriptExprClass:
15592   case Expr::OMPArraySectionExprClass:
15593   case Expr::OMPArrayShapingExprClass:
15594   case Expr::OMPIteratorExprClass:
15595   case Expr::MemberExprClass:
15596   case Expr::CompoundAssignOperatorClass:
15597   case Expr::CompoundLiteralExprClass:
15598   case Expr::ExtVectorElementExprClass:
15599   case Expr::DesignatedInitExprClass:
15600   case Expr::ArrayInitLoopExprClass:
15601   case Expr::ArrayInitIndexExprClass:
15602   case Expr::NoInitExprClass:
15603   case Expr::DesignatedInitUpdateExprClass:
15604   case Expr::ImplicitValueInitExprClass:
15605   case Expr::ParenListExprClass:
15606   case Expr::VAArgExprClass:
15607   case Expr::AddrLabelExprClass:
15608   case Expr::StmtExprClass:
15609   case Expr::CXXMemberCallExprClass:
15610   case Expr::CUDAKernelCallExprClass:
15611   case Expr::CXXAddrspaceCastExprClass:
15612   case Expr::CXXDynamicCastExprClass:
15613   case Expr::CXXTypeidExprClass:
15614   case Expr::CXXUuidofExprClass:
15615   case Expr::MSPropertyRefExprClass:
15616   case Expr::MSPropertySubscriptExprClass:
15617   case Expr::CXXNullPtrLiteralExprClass:
15618   case Expr::UserDefinedLiteralClass:
15619   case Expr::CXXThisExprClass:
15620   case Expr::CXXThrowExprClass:
15621   case Expr::CXXNewExprClass:
15622   case Expr::CXXDeleteExprClass:
15623   case Expr::CXXPseudoDestructorExprClass:
15624   case Expr::UnresolvedLookupExprClass:
15625   case Expr::TypoExprClass:
15626   case Expr::RecoveryExprClass:
15627   case Expr::DependentScopeDeclRefExprClass:
15628   case Expr::CXXConstructExprClass:
15629   case Expr::CXXInheritedCtorInitExprClass:
15630   case Expr::CXXStdInitializerListExprClass:
15631   case Expr::CXXBindTemporaryExprClass:
15632   case Expr::ExprWithCleanupsClass:
15633   case Expr::CXXTemporaryObjectExprClass:
15634   case Expr::CXXUnresolvedConstructExprClass:
15635   case Expr::CXXDependentScopeMemberExprClass:
15636   case Expr::UnresolvedMemberExprClass:
15637   case Expr::ObjCStringLiteralClass:
15638   case Expr::ObjCBoxedExprClass:
15639   case Expr::ObjCArrayLiteralClass:
15640   case Expr::ObjCDictionaryLiteralClass:
15641   case Expr::ObjCEncodeExprClass:
15642   case Expr::ObjCMessageExprClass:
15643   case Expr::ObjCSelectorExprClass:
15644   case Expr::ObjCProtocolExprClass:
15645   case Expr::ObjCIvarRefExprClass:
15646   case Expr::ObjCPropertyRefExprClass:
15647   case Expr::ObjCSubscriptRefExprClass:
15648   case Expr::ObjCIsaExprClass:
15649   case Expr::ObjCAvailabilityCheckExprClass:
15650   case Expr::ShuffleVectorExprClass:
15651   case Expr::ConvertVectorExprClass:
15652   case Expr::BlockExprClass:
15653   case Expr::NoStmtClass:
15654   case Expr::OpaqueValueExprClass:
15655   case Expr::PackExpansionExprClass:
15656   case Expr::SubstNonTypeTemplateParmPackExprClass:
15657   case Expr::FunctionParmPackExprClass:
15658   case Expr::AsTypeExprClass:
15659   case Expr::ObjCIndirectCopyRestoreExprClass:
15660   case Expr::MaterializeTemporaryExprClass:
15661   case Expr::PseudoObjectExprClass:
15662   case Expr::AtomicExprClass:
15663   case Expr::LambdaExprClass:
15664   case Expr::CXXFoldExprClass:
15665   case Expr::CoawaitExprClass:
15666   case Expr::DependentCoawaitExprClass:
15667   case Expr::CoyieldExprClass:
15668   case Expr::SYCLUniqueStableNameExprClass:
15669   case Expr::CXXParenListInitExprClass:
15670     return ICEDiag(IK_NotICE, E->getBeginLoc());
15671 
15672   case Expr::InitListExprClass: {
15673     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
15674     // form "T x = { a };" is equivalent to "T x = a;".
15675     // Unless we're initializing a reference, T is a scalar as it is known to be
15676     // of integral or enumeration type.
15677     if (E->isPRValue())
15678       if (cast<InitListExpr>(E)->getNumInits() == 1)
15679         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
15680     return ICEDiag(IK_NotICE, E->getBeginLoc());
15681   }
15682 
15683   case Expr::SizeOfPackExprClass:
15684   case Expr::GNUNullExprClass:
15685   case Expr::SourceLocExprClass:
15686     return NoDiag();
15687 
15688   case Expr::SubstNonTypeTemplateParmExprClass:
15689     return
15690       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
15691 
15692   case Expr::ConstantExprClass:
15693     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
15694 
15695   case Expr::ParenExprClass:
15696     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
15697   case Expr::GenericSelectionExprClass:
15698     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
15699   case Expr::IntegerLiteralClass:
15700   case Expr::FixedPointLiteralClass:
15701   case Expr::CharacterLiteralClass:
15702   case Expr::ObjCBoolLiteralExprClass:
15703   case Expr::CXXBoolLiteralExprClass:
15704   case Expr::CXXScalarValueInitExprClass:
15705   case Expr::TypeTraitExprClass:
15706   case Expr::ConceptSpecializationExprClass:
15707   case Expr::RequiresExprClass:
15708   case Expr::ArrayTypeTraitExprClass:
15709   case Expr::ExpressionTraitExprClass:
15710   case Expr::CXXNoexceptExprClass:
15711     return NoDiag();
15712   case Expr::CallExprClass:
15713   case Expr::CXXOperatorCallExprClass: {
15714     // C99 6.6/3 allows function calls within unevaluated subexpressions of
15715     // constant expressions, but they can never be ICEs because an ICE cannot
15716     // contain an operand of (pointer to) function type.
15717     const CallExpr *CE = cast<CallExpr>(E);
15718     if (CE->getBuiltinCallee())
15719       return CheckEvalInICE(E, Ctx);
15720     return ICEDiag(IK_NotICE, E->getBeginLoc());
15721   }
15722   case Expr::CXXRewrittenBinaryOperatorClass:
15723     return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
15724                     Ctx);
15725   case Expr::DeclRefExprClass: {
15726     const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
15727     if (isa<EnumConstantDecl>(D))
15728       return NoDiag();
15729 
15730     // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
15731     // integer variables in constant expressions:
15732     //
15733     // C++ 7.1.5.1p2
15734     //   A variable of non-volatile const-qualified integral or enumeration
15735     //   type initialized by an ICE can be used in ICEs.
15736     //
15737     // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
15738     // that mode, use of reference variables should not be allowed.
15739     const VarDecl *VD = dyn_cast<VarDecl>(D);
15740     if (VD && VD->isUsableInConstantExpressions(Ctx) &&
15741         !VD->getType()->isReferenceType())
15742       return NoDiag();
15743 
15744     return ICEDiag(IK_NotICE, E->getBeginLoc());
15745   }
15746   case Expr::UnaryOperatorClass: {
15747     const UnaryOperator *Exp = cast<UnaryOperator>(E);
15748     switch (Exp->getOpcode()) {
15749     case UO_PostInc:
15750     case UO_PostDec:
15751     case UO_PreInc:
15752     case UO_PreDec:
15753     case UO_AddrOf:
15754     case UO_Deref:
15755     case UO_Coawait:
15756       // C99 6.6/3 allows increment and decrement within unevaluated
15757       // subexpressions of constant expressions, but they can never be ICEs
15758       // because an ICE cannot contain an lvalue operand.
15759       return ICEDiag(IK_NotICE, E->getBeginLoc());
15760     case UO_Extension:
15761     case UO_LNot:
15762     case UO_Plus:
15763     case UO_Minus:
15764     case UO_Not:
15765     case UO_Real:
15766     case UO_Imag:
15767       return CheckICE(Exp->getSubExpr(), Ctx);
15768     }
15769     llvm_unreachable("invalid unary operator class");
15770   }
15771   case Expr::OffsetOfExprClass: {
15772     // Note that per C99, offsetof must be an ICE. And AFAIK, using
15773     // EvaluateAsRValue matches the proposed gcc behavior for cases like
15774     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
15775     // compliance: we should warn earlier for offsetof expressions with
15776     // array subscripts that aren't ICEs, and if the array subscripts
15777     // are ICEs, the value of the offsetof must be an integer constant.
15778     return CheckEvalInICE(E, Ctx);
15779   }
15780   case Expr::UnaryExprOrTypeTraitExprClass: {
15781     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
15782     if ((Exp->getKind() ==  UETT_SizeOf) &&
15783         Exp->getTypeOfArgument()->isVariableArrayType())
15784       return ICEDiag(IK_NotICE, E->getBeginLoc());
15785     return NoDiag();
15786   }
15787   case Expr::BinaryOperatorClass: {
15788     const BinaryOperator *Exp = cast<BinaryOperator>(E);
15789     switch (Exp->getOpcode()) {
15790     case BO_PtrMemD:
15791     case BO_PtrMemI:
15792     case BO_Assign:
15793     case BO_MulAssign:
15794     case BO_DivAssign:
15795     case BO_RemAssign:
15796     case BO_AddAssign:
15797     case BO_SubAssign:
15798     case BO_ShlAssign:
15799     case BO_ShrAssign:
15800     case BO_AndAssign:
15801     case BO_XorAssign:
15802     case BO_OrAssign:
15803       // C99 6.6/3 allows assignments within unevaluated subexpressions of
15804       // constant expressions, but they can never be ICEs because an ICE cannot
15805       // contain an lvalue operand.
15806       return ICEDiag(IK_NotICE, E->getBeginLoc());
15807 
15808     case BO_Mul:
15809     case BO_Div:
15810     case BO_Rem:
15811     case BO_Add:
15812     case BO_Sub:
15813     case BO_Shl:
15814     case BO_Shr:
15815     case BO_LT:
15816     case BO_GT:
15817     case BO_LE:
15818     case BO_GE:
15819     case BO_EQ:
15820     case BO_NE:
15821     case BO_And:
15822     case BO_Xor:
15823     case BO_Or:
15824     case BO_Comma:
15825     case BO_Cmp: {
15826       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15827       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15828       if (Exp->getOpcode() == BO_Div ||
15829           Exp->getOpcode() == BO_Rem) {
15830         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
15831         // we don't evaluate one.
15832         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
15833           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
15834           if (REval == 0)
15835             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15836           if (REval.isSigned() && REval.isAllOnes()) {
15837             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
15838             if (LEval.isMinSignedValue())
15839               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15840           }
15841         }
15842       }
15843       if (Exp->getOpcode() == BO_Comma) {
15844         if (Ctx.getLangOpts().C99) {
15845           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
15846           // if it isn't evaluated.
15847           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
15848             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15849         } else {
15850           // In both C89 and C++, commas in ICEs are illegal.
15851           return ICEDiag(IK_NotICE, E->getBeginLoc());
15852         }
15853       }
15854       return Worst(LHSResult, RHSResult);
15855     }
15856     case BO_LAnd:
15857     case BO_LOr: {
15858       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15859       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15860       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
15861         // Rare case where the RHS has a comma "side-effect"; we need
15862         // to actually check the condition to see whether the side
15863         // with the comma is evaluated.
15864         if ((Exp->getOpcode() == BO_LAnd) !=
15865             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
15866           return RHSResult;
15867         return NoDiag();
15868       }
15869 
15870       return Worst(LHSResult, RHSResult);
15871     }
15872     }
15873     llvm_unreachable("invalid binary operator kind");
15874   }
15875   case Expr::ImplicitCastExprClass:
15876   case Expr::CStyleCastExprClass:
15877   case Expr::CXXFunctionalCastExprClass:
15878   case Expr::CXXStaticCastExprClass:
15879   case Expr::CXXReinterpretCastExprClass:
15880   case Expr::CXXConstCastExprClass:
15881   case Expr::ObjCBridgedCastExprClass: {
15882     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
15883     if (isa<ExplicitCastExpr>(E)) {
15884       if (const FloatingLiteral *FL
15885             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
15886         unsigned DestWidth = Ctx.getIntWidth(E->getType());
15887         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
15888         APSInt IgnoredVal(DestWidth, !DestSigned);
15889         bool Ignored;
15890         // If the value does not fit in the destination type, the behavior is
15891         // undefined, so we are not required to treat it as a constant
15892         // expression.
15893         if (FL->getValue().convertToInteger(IgnoredVal,
15894                                             llvm::APFloat::rmTowardZero,
15895                                             &Ignored) & APFloat::opInvalidOp)
15896           return ICEDiag(IK_NotICE, E->getBeginLoc());
15897         return NoDiag();
15898       }
15899     }
15900     switch (cast<CastExpr>(E)->getCastKind()) {
15901     case CK_LValueToRValue:
15902     case CK_AtomicToNonAtomic:
15903     case CK_NonAtomicToAtomic:
15904     case CK_NoOp:
15905     case CK_IntegralToBoolean:
15906     case CK_IntegralCast:
15907       return CheckICE(SubExpr, Ctx);
15908     default:
15909       return ICEDiag(IK_NotICE, E->getBeginLoc());
15910     }
15911   }
15912   case Expr::BinaryConditionalOperatorClass: {
15913     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
15914     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
15915     if (CommonResult.Kind == IK_NotICE) return CommonResult;
15916     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15917     if (FalseResult.Kind == IK_NotICE) return FalseResult;
15918     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
15919     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
15920         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
15921     return FalseResult;
15922   }
15923   case Expr::ConditionalOperatorClass: {
15924     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
15925     // If the condition (ignoring parens) is a __builtin_constant_p call,
15926     // then only the true side is actually considered in an integer constant
15927     // expression, and it is fully evaluated.  This is an important GNU
15928     // extension.  See GCC PR38377 for discussion.
15929     if (const CallExpr *CallCE
15930         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
15931       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
15932         return CheckEvalInICE(E, Ctx);
15933     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
15934     if (CondResult.Kind == IK_NotICE)
15935       return CondResult;
15936 
15937     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
15938     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15939 
15940     if (TrueResult.Kind == IK_NotICE)
15941       return TrueResult;
15942     if (FalseResult.Kind == IK_NotICE)
15943       return FalseResult;
15944     if (CondResult.Kind == IK_ICEIfUnevaluated)
15945       return CondResult;
15946     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
15947       return NoDiag();
15948     // Rare case where the diagnostics depend on which side is evaluated
15949     // Note that if we get here, CondResult is 0, and at least one of
15950     // TrueResult and FalseResult is non-zero.
15951     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
15952       return FalseResult;
15953     return TrueResult;
15954   }
15955   case Expr::CXXDefaultArgExprClass:
15956     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
15957   case Expr::CXXDefaultInitExprClass:
15958     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
15959   case Expr::ChooseExprClass: {
15960     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
15961   }
15962   case Expr::BuiltinBitCastExprClass: {
15963     if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
15964       return ICEDiag(IK_NotICE, E->getBeginLoc());
15965     return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
15966   }
15967   }
15968 
15969   llvm_unreachable("Invalid StmtClass!");
15970 }
15971 
15972 /// Evaluate an expression as a C++11 integral constant expression.
15973 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
15974                                                     const Expr *E,
15975                                                     llvm::APSInt *Value,
15976                                                     SourceLocation *Loc) {
15977   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15978     if (Loc) *Loc = E->getExprLoc();
15979     return false;
15980   }
15981 
15982   APValue Result;
15983   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
15984     return false;
15985 
15986   if (!Result.isInt()) {
15987     if (Loc) *Loc = E->getExprLoc();
15988     return false;
15989   }
15990 
15991   if (Value) *Value = Result.getInt();
15992   return true;
15993 }
15994 
15995 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
15996                                  SourceLocation *Loc) const {
15997   assert(!isValueDependent() &&
15998          "Expression evaluator can't be called on a dependent expression.");
15999 
16000   ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr");
16001 
16002   if (Ctx.getLangOpts().CPlusPlus11)
16003     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
16004 
16005   ICEDiag D = CheckICE(this, Ctx);
16006   if (D.Kind != IK_ICE) {
16007     if (Loc) *Loc = D.Loc;
16008     return false;
16009   }
16010   return true;
16011 }
16012 
16013 std::optional<llvm::APSInt>
16014 Expr::getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc,
16015                              bool isEvaluated) const {
16016   if (isValueDependent()) {
16017     // Expression evaluator can't succeed on a dependent expression.
16018     return std::nullopt;
16019   }
16020 
16021   APSInt Value;
16022 
16023   if (Ctx.getLangOpts().CPlusPlus11) {
16024     if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc))
16025       return Value;
16026     return std::nullopt;
16027   }
16028 
16029   if (!isIntegerConstantExpr(Ctx, Loc))
16030     return std::nullopt;
16031 
16032   // The only possible side-effects here are due to UB discovered in the
16033   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
16034   // required to treat the expression as an ICE, so we produce the folded
16035   // value.
16036   EvalResult ExprResult;
16037   Expr::EvalStatus Status;
16038   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
16039   Info.InConstantContext = true;
16040 
16041   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
16042     llvm_unreachable("ICE cannot be evaluated!");
16043 
16044   return ExprResult.Val.getInt();
16045 }
16046 
16047 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
16048   assert(!isValueDependent() &&
16049          "Expression evaluator can't be called on a dependent expression.");
16050 
16051   return CheckICE(this, Ctx).Kind == IK_ICE;
16052 }
16053 
16054 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
16055                                SourceLocation *Loc) const {
16056   assert(!isValueDependent() &&
16057          "Expression evaluator can't be called on a dependent expression.");
16058 
16059   // We support this checking in C++98 mode in order to diagnose compatibility
16060   // issues.
16061   assert(Ctx.getLangOpts().CPlusPlus);
16062 
16063   // Build evaluation settings.
16064   Expr::EvalStatus Status;
16065   SmallVector<PartialDiagnosticAt, 8> Diags;
16066   Status.Diag = &Diags;
16067   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
16068 
16069   APValue Scratch;
16070   bool IsConstExpr =
16071       ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
16072       // FIXME: We don't produce a diagnostic for this, but the callers that
16073       // call us on arbitrary full-expressions should generally not care.
16074       Info.discardCleanups() && !Status.HasSideEffects;
16075 
16076   if (!Diags.empty()) {
16077     IsConstExpr = false;
16078     if (Loc) *Loc = Diags[0].first;
16079   } else if (!IsConstExpr) {
16080     // FIXME: This shouldn't happen.
16081     if (Loc) *Loc = getExprLoc();
16082   }
16083 
16084   return IsConstExpr;
16085 }
16086 
16087 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
16088                                     const FunctionDecl *Callee,
16089                                     ArrayRef<const Expr*> Args,
16090                                     const Expr *This) const {
16091   assert(!isValueDependent() &&
16092          "Expression evaluator can't be called on a dependent expression.");
16093 
16094   llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] {
16095     std::string Name;
16096     llvm::raw_string_ostream OS(Name);
16097     Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(),
16098                                  /*Qualified=*/true);
16099     return Name;
16100   });
16101 
16102   Expr::EvalStatus Status;
16103   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
16104   Info.InConstantContext = true;
16105 
16106   LValue ThisVal;
16107   const LValue *ThisPtr = nullptr;
16108   if (This) {
16109 #ifndef NDEBUG
16110     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
16111     assert(MD && "Don't provide `this` for non-methods.");
16112     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
16113 #endif
16114     if (!This->isValueDependent() &&
16115         EvaluateObjectArgument(Info, This, ThisVal) &&
16116         !Info.EvalStatus.HasSideEffects)
16117       ThisPtr = &ThisVal;
16118 
16119     // Ignore any side-effects from a failed evaluation. This is safe because
16120     // they can't interfere with any other argument evaluation.
16121     Info.EvalStatus.HasSideEffects = false;
16122   }
16123 
16124   CallRef Call = Info.CurrentCall->createCall(Callee);
16125   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
16126        I != E; ++I) {
16127     unsigned Idx = I - Args.begin();
16128     if (Idx >= Callee->getNumParams())
16129       break;
16130     const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
16131     if ((*I)->isValueDependent() ||
16132         !EvaluateCallArg(PVD, *I, Call, Info) ||
16133         Info.EvalStatus.HasSideEffects) {
16134       // If evaluation fails, throw away the argument entirely.
16135       if (APValue *Slot = Info.getParamSlot(Call, PVD))
16136         *Slot = APValue();
16137     }
16138 
16139     // Ignore any side-effects from a failed evaluation. This is safe because
16140     // they can't interfere with any other argument evaluation.
16141     Info.EvalStatus.HasSideEffects = false;
16142   }
16143 
16144   // Parameter cleanups happen in the caller and are not part of this
16145   // evaluation.
16146   Info.discardCleanups();
16147   Info.EvalStatus.HasSideEffects = false;
16148 
16149   // Build fake call to Callee.
16150   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call);
16151   // FIXME: Missing ExprWithCleanups in enable_if conditions?
16152   FullExpressionRAII Scope(Info);
16153   return Evaluate(Value, Info, this) && Scope.destroy() &&
16154          !Info.EvalStatus.HasSideEffects;
16155 }
16156 
16157 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
16158                                    SmallVectorImpl<
16159                                      PartialDiagnosticAt> &Diags) {
16160   // FIXME: It would be useful to check constexpr function templates, but at the
16161   // moment the constant expression evaluator cannot cope with the non-rigorous
16162   // ASTs which we build for dependent expressions.
16163   if (FD->isDependentContext())
16164     return true;
16165 
16166   llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] {
16167     std::string Name;
16168     llvm::raw_string_ostream OS(Name);
16169     FD->getNameForDiagnostic(OS, FD->getASTContext().getPrintingPolicy(),
16170                              /*Qualified=*/true);
16171     return Name;
16172   });
16173 
16174   Expr::EvalStatus Status;
16175   Status.Diag = &Diags;
16176 
16177   EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
16178   Info.InConstantContext = true;
16179   Info.CheckingPotentialConstantExpression = true;
16180 
16181   // The constexpr VM attempts to compile all methods to bytecode here.
16182   if (Info.EnableNewConstInterp) {
16183     Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
16184     return Diags.empty();
16185   }
16186 
16187   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
16188   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
16189 
16190   // Fabricate an arbitrary expression on the stack and pretend that it
16191   // is a temporary being used as the 'this' pointer.
16192   LValue This;
16193   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
16194   This.set({&VIE, Info.CurrentCall->Index});
16195 
16196   ArrayRef<const Expr*> Args;
16197 
16198   APValue Scratch;
16199   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
16200     // Evaluate the call as a constant initializer, to allow the construction
16201     // of objects of non-literal types.
16202     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
16203     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
16204   } else {
16205     SourceLocation Loc = FD->getLocation();
16206     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
16207                        Args, CallRef(), FD->getBody(), Info, Scratch, nullptr);
16208   }
16209 
16210   return Diags.empty();
16211 }
16212 
16213 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
16214                                               const FunctionDecl *FD,
16215                                               SmallVectorImpl<
16216                                                 PartialDiagnosticAt> &Diags) {
16217   assert(!E->isValueDependent() &&
16218          "Expression evaluator can't be called on a dependent expression.");
16219 
16220   Expr::EvalStatus Status;
16221   Status.Diag = &Diags;
16222 
16223   EvalInfo Info(FD->getASTContext(), Status,
16224                 EvalInfo::EM_ConstantExpressionUnevaluated);
16225   Info.InConstantContext = true;
16226   Info.CheckingPotentialConstantExpression = true;
16227 
16228   // Fabricate a call stack frame to give the arguments a plausible cover story.
16229   CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef());
16230 
16231   APValue ResultScratch;
16232   Evaluate(ResultScratch, Info, E);
16233   return Diags.empty();
16234 }
16235 
16236 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
16237                                  unsigned Type) const {
16238   if (!getType()->isPointerType())
16239     return false;
16240 
16241   Expr::EvalStatus Status;
16242   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
16243   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
16244 }
16245 
16246 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
16247                                   EvalInfo &Info) {
16248   if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
16249     return false;
16250 
16251   LValue String;
16252 
16253   if (!EvaluatePointer(E, String, Info))
16254     return false;
16255 
16256   QualType CharTy = E->getType()->getPointeeType();
16257 
16258   // Fast path: if it's a string literal, search the string value.
16259   if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
16260           String.getLValueBase().dyn_cast<const Expr *>())) {
16261     StringRef Str = S->getBytes();
16262     int64_t Off = String.Offset.getQuantity();
16263     if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
16264         S->getCharByteWidth() == 1 &&
16265         // FIXME: Add fast-path for wchar_t too.
16266         Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
16267       Str = Str.substr(Off);
16268 
16269       StringRef::size_type Pos = Str.find(0);
16270       if (Pos != StringRef::npos)
16271         Str = Str.substr(0, Pos);
16272 
16273       Result = Str.size();
16274       return true;
16275     }
16276 
16277     // Fall through to slow path.
16278   }
16279 
16280   // Slow path: scan the bytes of the string looking for the terminating 0.
16281   for (uint64_t Strlen = 0; /**/; ++Strlen) {
16282     APValue Char;
16283     if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
16284         !Char.isInt())
16285       return false;
16286     if (!Char.getInt()) {
16287       Result = Strlen;
16288       return true;
16289     }
16290     if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
16291       return false;
16292   }
16293 }
16294 
16295 bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
16296   Expr::EvalStatus Status;
16297   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
16298   return EvaluateBuiltinStrLen(this, Result, Info);
16299 }
16300