xref: /llvm-project/clang/lib/AST/ExprConstant.cpp (revision cbdd14ee9de72c277d9f89a6aa57c54a495f5458)
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 "ByteCode/Context.h"
36 #include "ByteCode/Frame.h"
37 #include "ByteCode/State.h"
38 #include "ExprConstShared.h"
39 #include "clang/AST/APValue.h"
40 #include "clang/AST/ASTContext.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/DiagnosticSema.h"
54 #include "clang/Basic/TargetBuiltins.h"
55 #include "clang/Basic/TargetInfo.h"
56 #include "llvm/ADT/APFixedPoint.h"
57 #include "llvm/ADT/Sequence.h"
58 #include "llvm/ADT/SmallBitVector.h"
59 #include "llvm/ADT/StringExtras.h"
60 #include "llvm/Support/Casting.h"
61 #include "llvm/Support/Debug.h"
62 #include "llvm/Support/SaveAndRestore.h"
63 #include "llvm/Support/SipHash.h"
64 #include "llvm/Support/TimeProfiler.h"
65 #include "llvm/Support/raw_ostream.h"
66 #include <cstring>
67 #include <functional>
68 #include <optional>
69 
70 #define DEBUG_TYPE "exprconstant"
71 
72 using namespace clang;
73 using llvm::APFixedPoint;
74 using llvm::APInt;
75 using llvm::APSInt;
76 using llvm::APFloat;
77 using llvm::FixedPointSemantics;
78 
79 namespace {
80   struct LValue;
81   class CallStackFrame;
82   class EvalInfo;
83 
84   using SourceLocExprScopeGuard =
85       CurrentSourceLocExprScope::SourceLocExprScopeGuard;
86 
87   static QualType getType(APValue::LValueBase B) {
88     return B.getType();
89   }
90 
91   /// Get an LValue path entry, which is known to not be an array index, as a
92   /// field declaration.
93   static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
94     return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
95   }
96   /// Get an LValue path entry, which is known to not be an array index, as a
97   /// base class declaration.
98   static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
99     return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
100   }
101   /// Determine whether this LValue path entry for a base class names a virtual
102   /// base class.
103   static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
104     return E.getAsBaseOrMember().getInt();
105   }
106 
107   /// Given an expression, determine the type used to store the result of
108   /// evaluating that expression.
109   static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
110     if (E->isPRValue())
111       return E->getType();
112     return Ctx.getLValueReferenceType(E->getType());
113   }
114 
115   /// Given a CallExpr, try to get the alloc_size attribute. May return null.
116   static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
117     if (const FunctionDecl *DirectCallee = CE->getDirectCallee())
118       return DirectCallee->getAttr<AllocSizeAttr>();
119     if (const Decl *IndirectCallee = CE->getCalleeDecl())
120       return IndirectCallee->getAttr<AllocSizeAttr>();
121     return nullptr;
122   }
123 
124   /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
125   /// This will look through a single cast.
126   ///
127   /// Returns null if we couldn't unwrap a function with alloc_size.
128   static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
129     if (!E->getType()->isPointerType())
130       return nullptr;
131 
132     E = E->IgnoreParens();
133     // If we're doing a variable assignment from e.g. malloc(N), there will
134     // probably be a cast of some kind. In exotic cases, we might also see a
135     // top-level ExprWithCleanups. Ignore them either way.
136     if (const auto *FE = dyn_cast<FullExpr>(E))
137       E = FE->getSubExpr()->IgnoreParens();
138 
139     if (const auto *Cast = dyn_cast<CastExpr>(E))
140       E = Cast->getSubExpr()->IgnoreParens();
141 
142     if (const auto *CE = dyn_cast<CallExpr>(E))
143       return getAllocSizeAttr(CE) ? CE : nullptr;
144     return nullptr;
145   }
146 
147   /// Determines whether or not the given Base contains a call to a function
148   /// with the alloc_size attribute.
149   static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
150     const auto *E = Base.dyn_cast<const Expr *>();
151     return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
152   }
153 
154   /// Determines whether the given kind of constant expression is only ever
155   /// used for name mangling. If so, it's permitted to reference things that we
156   /// can't generate code for (in particular, dllimported functions).
157   static bool isForManglingOnly(ConstantExprKind Kind) {
158     switch (Kind) {
159     case ConstantExprKind::Normal:
160     case ConstantExprKind::ClassTemplateArgument:
161     case ConstantExprKind::ImmediateInvocation:
162       // Note that non-type template arguments of class type are emitted as
163       // template parameter objects.
164       return false;
165 
166     case ConstantExprKind::NonClassTemplateArgument:
167       return true;
168     }
169     llvm_unreachable("unknown ConstantExprKind");
170   }
171 
172   static bool isTemplateArgument(ConstantExprKind Kind) {
173     switch (Kind) {
174     case ConstantExprKind::Normal:
175     case ConstantExprKind::ImmediateInvocation:
176       return false;
177 
178     case ConstantExprKind::ClassTemplateArgument:
179     case ConstantExprKind::NonClassTemplateArgument:
180       return true;
181     }
182     llvm_unreachable("unknown ConstantExprKind");
183   }
184 
185   /// The bound to claim that an array of unknown bound has.
186   /// The value in MostDerivedArraySize is undefined in this case. So, set it
187   /// to an arbitrary value that's likely to loudly break things if it's used.
188   static const uint64_t AssumedSizeForUnsizedArray =
189       std::numeric_limits<uint64_t>::max() / 2;
190 
191   /// Determines if an LValue with the given LValueBase will have an unsized
192   /// array in its designator.
193   /// Find the path length and type of the most-derived subobject in the given
194   /// path, and find the size of the containing array, if any.
195   static unsigned
196   findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
197                            ArrayRef<APValue::LValuePathEntry> Path,
198                            uint64_t &ArraySize, QualType &Type, bool &IsArray,
199                            bool &FirstEntryIsUnsizedArray) {
200     // This only accepts LValueBases from APValues, and APValues don't support
201     // arrays that lack size info.
202     assert(!isBaseAnAllocSizeCall(Base) &&
203            "Unsized arrays shouldn't appear here");
204     unsigned MostDerivedLength = 0;
205     Type = getType(Base);
206 
207     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
208       if (Type->isArrayType()) {
209         const ArrayType *AT = Ctx.getAsArrayType(Type);
210         Type = AT->getElementType();
211         MostDerivedLength = I + 1;
212         IsArray = true;
213 
214         if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
215           ArraySize = CAT->getZExtSize();
216         } else {
217           assert(I == 0 && "unexpected unsized array designator");
218           FirstEntryIsUnsizedArray = true;
219           ArraySize = AssumedSizeForUnsizedArray;
220         }
221       } else if (Type->isAnyComplexType()) {
222         const ComplexType *CT = Type->castAs<ComplexType>();
223         Type = CT->getElementType();
224         ArraySize = 2;
225         MostDerivedLength = I + 1;
226         IsArray = true;
227       } else if (const auto *VT = Type->getAs<VectorType>()) {
228         Type = VT->getElementType();
229         ArraySize = VT->getNumElements();
230         MostDerivedLength = I + 1;
231         IsArray = true;
232       } else if (const FieldDecl *FD = getAsField(Path[I])) {
233         Type = FD->getType();
234         ArraySize = 0;
235         MostDerivedLength = I + 1;
236         IsArray = false;
237       } else {
238         // Path[I] describes a base class.
239         ArraySize = 0;
240         IsArray = false;
241       }
242     }
243     return MostDerivedLength;
244   }
245 
246   /// A path from a glvalue to a subobject of that glvalue.
247   struct SubobjectDesignator {
248     /// True if the subobject was named in a manner not supported by C++11. Such
249     /// lvalues can still be folded, but they are not core constant expressions
250     /// and we cannot perform lvalue-to-rvalue conversions on them.
251     LLVM_PREFERRED_TYPE(bool)
252     unsigned Invalid : 1;
253 
254     /// Is this a pointer one past the end of an object?
255     LLVM_PREFERRED_TYPE(bool)
256     unsigned IsOnePastTheEnd : 1;
257 
258     /// Indicator of whether the first entry is an unsized array.
259     LLVM_PREFERRED_TYPE(bool)
260     unsigned FirstEntryIsAnUnsizedArray : 1;
261 
262     /// Indicator of whether the most-derived object is an array element.
263     LLVM_PREFERRED_TYPE(bool)
264     unsigned MostDerivedIsArrayElement : 1;
265 
266     /// The length of the path to the most-derived object of which this is a
267     /// subobject.
268     unsigned MostDerivedPathLength : 28;
269 
270     /// The size of the array of which the most-derived object is an element.
271     /// This will always be 0 if the most-derived object is not an array
272     /// element. 0 is not an indicator of whether or not the most-derived object
273     /// is an array, however, because 0-length arrays are allowed.
274     ///
275     /// If the current array is an unsized array, the value of this is
276     /// undefined.
277     uint64_t MostDerivedArraySize;
278     /// The type of the most derived object referred to by this address.
279     QualType MostDerivedType;
280 
281     typedef APValue::LValuePathEntry PathEntry;
282 
283     /// The entries on the path from the glvalue to the designated subobject.
284     SmallVector<PathEntry, 8> Entries;
285 
286     SubobjectDesignator() : Invalid(true) {}
287 
288     explicit SubobjectDesignator(QualType T)
289         : Invalid(false), IsOnePastTheEnd(false),
290           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
291           MostDerivedPathLength(0), MostDerivedArraySize(0),
292           MostDerivedType(T) {}
293 
294     SubobjectDesignator(ASTContext &Ctx, const APValue &V)
295         : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
296           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
297           MostDerivedPathLength(0), MostDerivedArraySize(0) {
298       assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
299       if (!Invalid) {
300         IsOnePastTheEnd = V.isLValueOnePastTheEnd();
301         ArrayRef<PathEntry> VEntries = V.getLValuePath();
302         Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
303         if (V.getLValueBase()) {
304           bool IsArray = false;
305           bool FirstIsUnsizedArray = false;
306           MostDerivedPathLength = findMostDerivedSubobject(
307               Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
308               MostDerivedType, IsArray, FirstIsUnsizedArray);
309           MostDerivedIsArrayElement = IsArray;
310           FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
311         }
312       }
313     }
314 
315     void truncate(ASTContext &Ctx, APValue::LValueBase Base,
316                   unsigned NewLength) {
317       if (Invalid)
318         return;
319 
320       assert(Base && "cannot truncate path for null pointer");
321       assert(NewLength <= Entries.size() && "not a truncation");
322 
323       if (NewLength == Entries.size())
324         return;
325       Entries.resize(NewLength);
326 
327       bool IsArray = false;
328       bool FirstIsUnsizedArray = false;
329       MostDerivedPathLength = findMostDerivedSubobject(
330           Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
331           FirstIsUnsizedArray);
332       MostDerivedIsArrayElement = IsArray;
333       FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
334     }
335 
336     void setInvalid() {
337       Invalid = true;
338       Entries.clear();
339     }
340 
341     /// Determine whether the most derived subobject is an array without a
342     /// known bound.
343     bool isMostDerivedAnUnsizedArray() const {
344       assert(!Invalid && "Calling this makes no sense on invalid designators");
345       return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
346     }
347 
348     /// Determine what the most derived array's size is. Results in an assertion
349     /// failure if the most derived array lacks a size.
350     uint64_t getMostDerivedArraySize() const {
351       assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
352       return MostDerivedArraySize;
353     }
354 
355     /// Determine whether this is a one-past-the-end pointer.
356     bool isOnePastTheEnd() const {
357       assert(!Invalid);
358       if (IsOnePastTheEnd)
359         return true;
360       if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
361           Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
362               MostDerivedArraySize)
363         return true;
364       return false;
365     }
366 
367     /// Get the range of valid index adjustments in the form
368     ///   {maximum value that can be subtracted from this pointer,
369     ///    maximum value that can be added to this pointer}
370     std::pair<uint64_t, uint64_t> validIndexAdjustments() {
371       if (Invalid || isMostDerivedAnUnsizedArray())
372         return {0, 0};
373 
374       // [expr.add]p4: For the purposes of these operators, a pointer to a
375       // nonarray object behaves the same as a pointer to the first element of
376       // an array of length one with the type of the object as its element type.
377       bool IsArray = MostDerivedPathLength == Entries.size() &&
378                      MostDerivedIsArrayElement;
379       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
380                                     : (uint64_t)IsOnePastTheEnd;
381       uint64_t ArraySize =
382           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
383       return {ArrayIndex, ArraySize - ArrayIndex};
384     }
385 
386     /// Check that this refers to a valid subobject.
387     bool isValidSubobject() const {
388       if (Invalid)
389         return false;
390       return !isOnePastTheEnd();
391     }
392     /// Check that this refers to a valid subobject, and if not, produce a
393     /// relevant diagnostic and set the designator as invalid.
394     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
395 
396     /// Get the type of the designated object.
397     QualType getType(ASTContext &Ctx) const {
398       assert(!Invalid && "invalid designator has no subobject type");
399       return MostDerivedPathLength == Entries.size()
400                  ? MostDerivedType
401                  : Ctx.getRecordType(getAsBaseClass(Entries.back()));
402     }
403 
404     /// Update this designator to refer to the first element within this array.
405     void addArrayUnchecked(const ConstantArrayType *CAT) {
406       Entries.push_back(PathEntry::ArrayIndex(0));
407 
408       // This is a most-derived object.
409       MostDerivedType = CAT->getElementType();
410       MostDerivedIsArrayElement = true;
411       MostDerivedArraySize = CAT->getZExtSize();
412       MostDerivedPathLength = Entries.size();
413     }
414     /// Update this designator to refer to the first element within the array of
415     /// elements of type T. This is an array of unknown size.
416     void addUnsizedArrayUnchecked(QualType ElemTy) {
417       Entries.push_back(PathEntry::ArrayIndex(0));
418 
419       MostDerivedType = ElemTy;
420       MostDerivedIsArrayElement = true;
421       // The value in MostDerivedArraySize is undefined in this case. So, set it
422       // to an arbitrary value that's likely to loudly break things if it's
423       // used.
424       MostDerivedArraySize = AssumedSizeForUnsizedArray;
425       MostDerivedPathLength = Entries.size();
426     }
427     /// Update this designator to refer to the given base or member of this
428     /// object.
429     void addDeclUnchecked(const Decl *D, bool Virtual = false) {
430       Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
431 
432       // If this isn't a base class, it's a new most-derived object.
433       if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
434         MostDerivedType = FD->getType();
435         MostDerivedIsArrayElement = false;
436         MostDerivedArraySize = 0;
437         MostDerivedPathLength = Entries.size();
438       }
439     }
440     /// Update this designator to refer to the given complex component.
441     void addComplexUnchecked(QualType EltTy, bool Imag) {
442       Entries.push_back(PathEntry::ArrayIndex(Imag));
443 
444       // This is technically a most-derived object, though in practice this
445       // is unlikely to matter.
446       MostDerivedType = EltTy;
447       MostDerivedIsArrayElement = true;
448       MostDerivedArraySize = 2;
449       MostDerivedPathLength = Entries.size();
450     }
451 
452     void addVectorElementUnchecked(QualType EltTy, uint64_t Size,
453                                    uint64_t Idx) {
454       Entries.push_back(PathEntry::ArrayIndex(Idx));
455       MostDerivedType = EltTy;
456       MostDerivedPathLength = Entries.size();
457       MostDerivedArraySize = 0;
458       MostDerivedIsArrayElement = false;
459     }
460 
461     void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
462     void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
463                                    const APSInt &N);
464     /// Add N to the address of this subobject.
465     void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
466       if (Invalid || !N) return;
467       uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
468       if (isMostDerivedAnUnsizedArray()) {
469         diagnoseUnsizedArrayPointerArithmetic(Info, E);
470         // Can't verify -- trust that the user is doing the right thing (or if
471         // not, trust that the caller will catch the bad behavior).
472         // FIXME: Should we reject if this overflows, at least?
473         Entries.back() = PathEntry::ArrayIndex(
474             Entries.back().getAsArrayIndex() + TruncatedN);
475         return;
476       }
477 
478       // [expr.add]p4: For the purposes of these operators, a pointer to a
479       // nonarray object behaves the same as a pointer to the first element of
480       // an array of length one with the type of the object as its element type.
481       bool IsArray = MostDerivedPathLength == Entries.size() &&
482                      MostDerivedIsArrayElement;
483       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
484                                     : (uint64_t)IsOnePastTheEnd;
485       uint64_t ArraySize =
486           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
487 
488       if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
489         // Calculate the actual index in a wide enough type, so we can include
490         // it in the note.
491         N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
492         (llvm::APInt&)N += ArrayIndex;
493         assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
494         diagnosePointerArithmetic(Info, E, N);
495         setInvalid();
496         return;
497       }
498 
499       ArrayIndex += TruncatedN;
500       assert(ArrayIndex <= ArraySize &&
501              "bounds check succeeded for out-of-bounds index");
502 
503       if (IsArray)
504         Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
505       else
506         IsOnePastTheEnd = (ArrayIndex != 0);
507     }
508   };
509 
510   /// A scope at the end of which an object can need to be destroyed.
511   enum class ScopeKind {
512     Block,
513     FullExpression,
514     Call
515   };
516 
517   /// A reference to a particular call and its arguments.
518   struct CallRef {
519     CallRef() : OrigCallee(), CallIndex(0), Version() {}
520     CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
521         : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
522 
523     explicit operator bool() const { return OrigCallee; }
524 
525     /// Get the parameter that the caller initialized, corresponding to the
526     /// given parameter in the callee.
527     const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
528       return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
529                         : PVD;
530     }
531 
532     /// The callee at the point where the arguments were evaluated. This might
533     /// be different from the actual callee (a different redeclaration, or a
534     /// virtual override), but this function's parameters are the ones that
535     /// appear in the parameter map.
536     const FunctionDecl *OrigCallee;
537     /// The call index of the frame that holds the argument values.
538     unsigned CallIndex;
539     /// The version of the parameters corresponding to this call.
540     unsigned Version;
541   };
542 
543   /// A stack frame in the constexpr call stack.
544   class CallStackFrame : public interp::Frame {
545   public:
546     EvalInfo &Info;
547 
548     /// Parent - The caller of this stack frame.
549     CallStackFrame *Caller;
550 
551     /// Callee - The function which was called.
552     const FunctionDecl *Callee;
553 
554     /// This - The binding for the this pointer in this call, if any.
555     const LValue *This;
556 
557     /// CallExpr - The syntactical structure of member function calls
558     const Expr *CallExpr;
559 
560     /// Information on how to find the arguments to this call. Our arguments
561     /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
562     /// key and this value as the version.
563     CallRef Arguments;
564 
565     /// Source location information about the default argument or default
566     /// initializer expression we're evaluating, if any.
567     CurrentSourceLocExprScope CurSourceLocExprScope;
568 
569     // Note that we intentionally use std::map here so that references to
570     // values are stable.
571     typedef std::pair<const void *, unsigned> MapKeyTy;
572     typedef std::map<MapKeyTy, APValue> MapTy;
573     /// Temporaries - Temporary lvalues materialized within this stack frame.
574     MapTy Temporaries;
575 
576     /// CallRange - The source range of the call expression for this call.
577     SourceRange CallRange;
578 
579     /// Index - The call index of this call.
580     unsigned Index;
581 
582     /// The stack of integers for tracking version numbers for temporaries.
583     SmallVector<unsigned, 2> TempVersionStack = {1};
584     unsigned CurTempVersion = TempVersionStack.back();
585 
586     unsigned getTempVersion() const { return TempVersionStack.back(); }
587 
588     void pushTempVersion() {
589       TempVersionStack.push_back(++CurTempVersion);
590     }
591 
592     void popTempVersion() {
593       TempVersionStack.pop_back();
594     }
595 
596     CallRef createCall(const FunctionDecl *Callee) {
597       return {Callee, Index, ++CurTempVersion};
598     }
599 
600     // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
601     // on the overall stack usage of deeply-recursing constexpr evaluations.
602     // (We should cache this map rather than recomputing it repeatedly.)
603     // But let's try this and see how it goes; we can look into caching the map
604     // as a later change.
605 
606     /// LambdaCaptureFields - Mapping from captured variables/this to
607     /// corresponding data members in the closure class.
608     llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;
609     FieldDecl *LambdaThisCaptureField = nullptr;
610 
611     CallStackFrame(EvalInfo &Info, SourceRange CallRange,
612                    const FunctionDecl *Callee, const LValue *This,
613                    const Expr *CallExpr, CallRef Arguments);
614     ~CallStackFrame();
615 
616     // Return the temporary for Key whose version number is Version.
617     APValue *getTemporary(const void *Key, unsigned Version) {
618       MapKeyTy KV(Key, Version);
619       auto LB = Temporaries.lower_bound(KV);
620       if (LB != Temporaries.end() && LB->first == KV)
621         return &LB->second;
622       return nullptr;
623     }
624 
625     // Return the current temporary for Key in the map.
626     APValue *getCurrentTemporary(const void *Key) {
627       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
628       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
629         return &std::prev(UB)->second;
630       return nullptr;
631     }
632 
633     // Return the version number of the current temporary for Key.
634     unsigned getCurrentTemporaryVersion(const void *Key) const {
635       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
636       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
637         return std::prev(UB)->first.second;
638       return 0;
639     }
640 
641     /// Allocate storage for an object of type T in this stack frame.
642     /// Populates LV with a handle to the created object. Key identifies
643     /// the temporary within the stack frame, and must not be reused without
644     /// bumping the temporary version number.
645     template<typename KeyT>
646     APValue &createTemporary(const KeyT *Key, QualType T,
647                              ScopeKind Scope, LValue &LV);
648 
649     /// Allocate storage for a parameter of a function call made in this frame.
650     APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
651 
652     void describe(llvm::raw_ostream &OS) const override;
653 
654     Frame *getCaller() const override { return Caller; }
655     SourceRange getCallRange() const override { return CallRange; }
656     const FunctionDecl *getCallee() const override { return Callee; }
657 
658     bool isStdFunction() const {
659       for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
660         if (DC->isStdNamespace())
661           return true;
662       return false;
663     }
664 
665     /// Whether we're in a context where [[msvc::constexpr]] evaluation is
666     /// permitted. See MSConstexprDocs for description of permitted contexts.
667     bool CanEvalMSConstexpr = false;
668 
669   private:
670     APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
671                          ScopeKind Scope);
672   };
673 
674   /// Temporarily override 'this'.
675   class ThisOverrideRAII {
676   public:
677     ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
678         : Frame(Frame), OldThis(Frame.This) {
679       if (Enable)
680         Frame.This = NewThis;
681     }
682     ~ThisOverrideRAII() {
683       Frame.This = OldThis;
684     }
685   private:
686     CallStackFrame &Frame;
687     const LValue *OldThis;
688   };
689 
690   // A shorthand time trace scope struct, prints source range, for example
691   // {"name":"EvaluateAsRValue","args":{"detail":"<test.cc:8:21, col:25>"}}}
692   class ExprTimeTraceScope {
693   public:
694     ExprTimeTraceScope(const Expr *E, const ASTContext &Ctx, StringRef Name)
695         : TimeScope(Name, [E, &Ctx] {
696             return E->getSourceRange().printToString(Ctx.getSourceManager());
697           }) {}
698 
699   private:
700     llvm::TimeTraceScope TimeScope;
701   };
702 
703   /// RAII object used to change the current ability of
704   /// [[msvc::constexpr]] evaulation.
705   struct MSConstexprContextRAII {
706     CallStackFrame &Frame;
707     bool OldValue;
708     explicit MSConstexprContextRAII(CallStackFrame &Frame, bool Value)
709         : Frame(Frame), OldValue(Frame.CanEvalMSConstexpr) {
710       Frame.CanEvalMSConstexpr = Value;
711     }
712 
713     ~MSConstexprContextRAII() { Frame.CanEvalMSConstexpr = OldValue; }
714   };
715 }
716 
717 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
718                               const LValue &This, QualType ThisType);
719 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
720                               APValue::LValueBase LVBase, APValue &Value,
721                               QualType T);
722 
723 namespace {
724   /// A cleanup, and a flag indicating whether it is lifetime-extended.
725   class Cleanup {
726     llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
727     APValue::LValueBase Base;
728     QualType T;
729 
730   public:
731     Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
732             ScopeKind Scope)
733         : Value(Val, Scope), Base(Base), T(T) {}
734 
735     /// Determine whether this cleanup should be performed at the end of the
736     /// given kind of scope.
737     bool isDestroyedAtEndOf(ScopeKind K) const {
738       return (int)Value.getInt() >= (int)K;
739     }
740     bool endLifetime(EvalInfo &Info, bool RunDestructors) {
741       if (RunDestructors) {
742         SourceLocation Loc;
743         if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
744           Loc = VD->getLocation();
745         else if (const Expr *E = Base.dyn_cast<const Expr*>())
746           Loc = E->getExprLoc();
747         return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
748       }
749       *Value.getPointer() = APValue();
750       return true;
751     }
752 
753     bool hasSideEffect() {
754       return T.isDestructedType();
755     }
756   };
757 
758   /// A reference to an object whose construction we are currently evaluating.
759   struct ObjectUnderConstruction {
760     APValue::LValueBase Base;
761     ArrayRef<APValue::LValuePathEntry> Path;
762     friend bool operator==(const ObjectUnderConstruction &LHS,
763                            const ObjectUnderConstruction &RHS) {
764       return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
765     }
766     friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
767       return llvm::hash_combine(Obj.Base, Obj.Path);
768     }
769   };
770   enum class ConstructionPhase {
771     None,
772     Bases,
773     AfterBases,
774     AfterFields,
775     Destroying,
776     DestroyingBases
777   };
778 }
779 
780 namespace llvm {
781 template<> struct DenseMapInfo<ObjectUnderConstruction> {
782   using Base = DenseMapInfo<APValue::LValueBase>;
783   static ObjectUnderConstruction getEmptyKey() {
784     return {Base::getEmptyKey(), {}}; }
785   static ObjectUnderConstruction getTombstoneKey() {
786     return {Base::getTombstoneKey(), {}};
787   }
788   static unsigned getHashValue(const ObjectUnderConstruction &Object) {
789     return hash_value(Object);
790   }
791   static bool isEqual(const ObjectUnderConstruction &LHS,
792                       const ObjectUnderConstruction &RHS) {
793     return LHS == RHS;
794   }
795 };
796 }
797 
798 namespace {
799   /// A dynamically-allocated heap object.
800   struct DynAlloc {
801     /// The value of this heap-allocated object.
802     APValue Value;
803     /// The allocating expression; used for diagnostics. Either a CXXNewExpr
804     /// or a CallExpr (the latter is for direct calls to operator new inside
805     /// std::allocator<T>::allocate).
806     const Expr *AllocExpr = nullptr;
807 
808     enum Kind {
809       New,
810       ArrayNew,
811       StdAllocator
812     };
813 
814     /// Get the kind of the allocation. This must match between allocation
815     /// and deallocation.
816     Kind getKind() const {
817       if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
818         return NE->isArray() ? ArrayNew : New;
819       assert(isa<CallExpr>(AllocExpr));
820       return StdAllocator;
821     }
822   };
823 
824   struct DynAllocOrder {
825     bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
826       return L.getIndex() < R.getIndex();
827     }
828   };
829 
830   /// EvalInfo - This is a private struct used by the evaluator to capture
831   /// information about a subexpression as it is folded.  It retains information
832   /// about the AST context, but also maintains information about the folded
833   /// expression.
834   ///
835   /// If an expression could be evaluated, it is still possible it is not a C
836   /// "integer constant expression" or constant expression.  If not, this struct
837   /// captures information about how and why not.
838   ///
839   /// One bit of information passed *into* the request for constant folding
840   /// indicates whether the subexpression is "evaluated" or not according to C
841   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
842   /// evaluate the expression regardless of what the RHS is, but C only allows
843   /// certain things in certain situations.
844   class EvalInfo : public interp::State {
845   public:
846     ASTContext &Ctx;
847 
848     /// EvalStatus - Contains information about the evaluation.
849     Expr::EvalStatus &EvalStatus;
850 
851     /// CurrentCall - The top of the constexpr call stack.
852     CallStackFrame *CurrentCall;
853 
854     /// CallStackDepth - The number of calls in the call stack right now.
855     unsigned CallStackDepth;
856 
857     /// NextCallIndex - The next call index to assign.
858     unsigned NextCallIndex;
859 
860     /// StepsLeft - The remaining number of evaluation steps we're permitted
861     /// to perform. This is essentially a limit for the number of statements
862     /// we will evaluate.
863     unsigned StepsLeft;
864 
865     /// Enable the experimental new constant interpreter. If an expression is
866     /// not supported by the interpreter, an error is triggered.
867     bool EnableNewConstInterp;
868 
869     /// BottomFrame - The frame in which evaluation started. This must be
870     /// initialized after CurrentCall and CallStackDepth.
871     CallStackFrame BottomFrame;
872 
873     /// A stack of values whose lifetimes end at the end of some surrounding
874     /// evaluation frame.
875     llvm::SmallVector<Cleanup, 16> CleanupStack;
876 
877     /// EvaluatingDecl - This is the declaration whose initializer is being
878     /// evaluated, if any.
879     APValue::LValueBase EvaluatingDecl;
880 
881     enum class EvaluatingDeclKind {
882       None,
883       /// We're evaluating the construction of EvaluatingDecl.
884       Ctor,
885       /// We're evaluating the destruction of EvaluatingDecl.
886       Dtor,
887     };
888     EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
889 
890     /// EvaluatingDeclValue - This is the value being constructed for the
891     /// declaration whose initializer is being evaluated, if any.
892     APValue *EvaluatingDeclValue;
893 
894     /// Set of objects that are currently being constructed.
895     llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
896         ObjectsUnderConstruction;
897 
898     /// Current heap allocations, along with the location where each was
899     /// allocated. We use std::map here because we need stable addresses
900     /// for the stored APValues.
901     std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
902 
903     /// The number of heap allocations performed so far in this evaluation.
904     unsigned NumHeapAllocs = 0;
905 
906     struct EvaluatingConstructorRAII {
907       EvalInfo &EI;
908       ObjectUnderConstruction Object;
909       bool DidInsert;
910       EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
911                                 bool HasBases)
912           : EI(EI), Object(Object) {
913         DidInsert =
914             EI.ObjectsUnderConstruction
915                 .insert({Object, HasBases ? ConstructionPhase::Bases
916                                           : ConstructionPhase::AfterBases})
917                 .second;
918       }
919       void finishedConstructingBases() {
920         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
921       }
922       void finishedConstructingFields() {
923         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
924       }
925       ~EvaluatingConstructorRAII() {
926         if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
927       }
928     };
929 
930     struct EvaluatingDestructorRAII {
931       EvalInfo &EI;
932       ObjectUnderConstruction Object;
933       bool DidInsert;
934       EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
935           : EI(EI), Object(Object) {
936         DidInsert = EI.ObjectsUnderConstruction
937                         .insert({Object, ConstructionPhase::Destroying})
938                         .second;
939       }
940       void startedDestroyingBases() {
941         EI.ObjectsUnderConstruction[Object] =
942             ConstructionPhase::DestroyingBases;
943       }
944       ~EvaluatingDestructorRAII() {
945         if (DidInsert)
946           EI.ObjectsUnderConstruction.erase(Object);
947       }
948     };
949 
950     ConstructionPhase
951     isEvaluatingCtorDtor(APValue::LValueBase Base,
952                          ArrayRef<APValue::LValuePathEntry> Path) {
953       return ObjectsUnderConstruction.lookup({Base, Path});
954     }
955 
956     /// If we're currently speculatively evaluating, the outermost call stack
957     /// depth at which we can mutate state, otherwise 0.
958     unsigned SpeculativeEvaluationDepth = 0;
959 
960     /// The current array initialization index, if we're performing array
961     /// initialization.
962     uint64_t ArrayInitIndex = -1;
963 
964     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
965     /// notes attached to it will also be stored, otherwise they will not be.
966     bool HasActiveDiagnostic;
967 
968     /// Have we emitted a diagnostic explaining why we couldn't constant
969     /// fold (not just why it's not strictly a constant expression)?
970     bool HasFoldFailureDiagnostic;
971 
972     /// Whether we're checking that an expression is a potential constant
973     /// expression. If so, do not fail on constructs that could become constant
974     /// later on (such as a use of an undefined global).
975     bool CheckingPotentialConstantExpression = false;
976 
977     /// Whether we're checking for an expression that has undefined behavior.
978     /// If so, we will produce warnings if we encounter an operation that is
979     /// always undefined.
980     ///
981     /// Note that we still need to evaluate the expression normally when this
982     /// is set; this is used when evaluating ICEs in C.
983     bool CheckingForUndefinedBehavior = false;
984 
985     enum EvaluationMode {
986       /// Evaluate as a constant expression. Stop if we find that the expression
987       /// is not a constant expression.
988       EM_ConstantExpression,
989 
990       /// Evaluate as a constant expression. Stop if we find that the expression
991       /// is not a constant expression. Some expressions can be retried in the
992       /// optimizer if we don't constant fold them here, but in an unevaluated
993       /// context we try to fold them immediately since the optimizer never
994       /// gets a chance to look at it.
995       EM_ConstantExpressionUnevaluated,
996 
997       /// Fold the expression to a constant. Stop if we hit a side-effect that
998       /// we can't model.
999       EM_ConstantFold,
1000 
1001       /// Evaluate in any way we know how. Don't worry about side-effects that
1002       /// can't be modeled.
1003       EM_IgnoreSideEffects,
1004     } EvalMode;
1005 
1006     /// Are we checking whether the expression is a potential constant
1007     /// expression?
1008     bool checkingPotentialConstantExpression() const override  {
1009       return CheckingPotentialConstantExpression;
1010     }
1011 
1012     /// Are we checking an expression for overflow?
1013     // FIXME: We should check for any kind of undefined or suspicious behavior
1014     // in such constructs, not just overflow.
1015     bool checkingForUndefinedBehavior() const override {
1016       return CheckingForUndefinedBehavior;
1017     }
1018 
1019     EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
1020         : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
1021           CallStackDepth(0), NextCallIndex(1),
1022           StepsLeft(C.getLangOpts().ConstexprStepLimit),
1023           EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
1024           BottomFrame(*this, SourceLocation(), /*Callee=*/nullptr,
1025                       /*This=*/nullptr,
1026                       /*CallExpr=*/nullptr, CallRef()),
1027           EvaluatingDecl((const ValueDecl *)nullptr),
1028           EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
1029           HasFoldFailureDiagnostic(false), EvalMode(Mode) {}
1030 
1031     ~EvalInfo() {
1032       discardCleanups();
1033     }
1034 
1035     ASTContext &getASTContext() const override { return Ctx; }
1036 
1037     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
1038                            EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
1039       EvaluatingDecl = Base;
1040       IsEvaluatingDecl = EDK;
1041       EvaluatingDeclValue = &Value;
1042     }
1043 
1044     bool CheckCallLimit(SourceLocation Loc) {
1045       // Don't perform any constexpr calls (other than the call we're checking)
1046       // when checking a potential constant expression.
1047       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
1048         return false;
1049       if (NextCallIndex == 0) {
1050         // NextCallIndex has wrapped around.
1051         FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
1052         return false;
1053       }
1054       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
1055         return true;
1056       FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
1057         << getLangOpts().ConstexprCallDepth;
1058       return false;
1059     }
1060 
1061     bool CheckArraySize(SourceLocation Loc, unsigned BitWidth,
1062                         uint64_t ElemCount, bool Diag) {
1063       // FIXME: GH63562
1064       // APValue stores array extents as unsigned,
1065       // so anything that is greater that unsigned would overflow when
1066       // constructing the array, we catch this here.
1067       if (BitWidth > ConstantArrayType::getMaxSizeBits(Ctx) ||
1068           ElemCount > uint64_t(std::numeric_limits<unsigned>::max())) {
1069         if (Diag)
1070           FFDiag(Loc, diag::note_constexpr_new_too_large) << ElemCount;
1071         return false;
1072       }
1073 
1074       // FIXME: GH63562
1075       // Arrays allocate an APValue per element.
1076       // We use the number of constexpr steps as a proxy for the maximum size
1077       // of arrays to avoid exhausting the system resources, as initialization
1078       // of each element is likely to take some number of steps anyway.
1079       uint64_t Limit = Ctx.getLangOpts().ConstexprStepLimit;
1080       if (ElemCount > Limit) {
1081         if (Diag)
1082           FFDiag(Loc, diag::note_constexpr_new_exceeds_limits)
1083               << ElemCount << Limit;
1084         return false;
1085       }
1086       return true;
1087     }
1088 
1089     std::pair<CallStackFrame *, unsigned>
1090     getCallFrameAndDepth(unsigned CallIndex) {
1091       assert(CallIndex && "no call index in getCallFrameAndDepth");
1092       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1093       // be null in this loop.
1094       unsigned Depth = CallStackDepth;
1095       CallStackFrame *Frame = CurrentCall;
1096       while (Frame->Index > CallIndex) {
1097         Frame = Frame->Caller;
1098         --Depth;
1099       }
1100       if (Frame->Index == CallIndex)
1101         return {Frame, Depth};
1102       return {nullptr, 0};
1103     }
1104 
1105     bool nextStep(const Stmt *S) {
1106       if (!StepsLeft) {
1107         FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1108         return false;
1109       }
1110       --StepsLeft;
1111       return true;
1112     }
1113 
1114     APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1115 
1116     std::optional<DynAlloc *> lookupDynamicAlloc(DynamicAllocLValue DA) {
1117       std::optional<DynAlloc *> Result;
1118       auto It = HeapAllocs.find(DA);
1119       if (It != HeapAllocs.end())
1120         Result = &It->second;
1121       return Result;
1122     }
1123 
1124     /// Get the allocated storage for the given parameter of the given call.
1125     APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1126       CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1127       return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1128                    : nullptr;
1129     }
1130 
1131     /// Information about a stack frame for std::allocator<T>::[de]allocate.
1132     struct StdAllocatorCaller {
1133       unsigned FrameIndex;
1134       QualType ElemType;
1135       explicit operator bool() const { return FrameIndex != 0; };
1136     };
1137 
1138     StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1139       for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1140            Call = Call->Caller) {
1141         const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1142         if (!MD)
1143           continue;
1144         const IdentifierInfo *FnII = MD->getIdentifier();
1145         if (!FnII || !FnII->isStr(FnName))
1146           continue;
1147 
1148         const auto *CTSD =
1149             dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1150         if (!CTSD)
1151           continue;
1152 
1153         const IdentifierInfo *ClassII = CTSD->getIdentifier();
1154         const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1155         if (CTSD->isInStdNamespace() && ClassII &&
1156             ClassII->isStr("allocator") && TAL.size() >= 1 &&
1157             TAL[0].getKind() == TemplateArgument::Type)
1158           return {Call->Index, TAL[0].getAsType()};
1159       }
1160 
1161       return {};
1162     }
1163 
1164     void performLifetimeExtension() {
1165       // Disable the cleanups for lifetime-extended temporaries.
1166       llvm::erase_if(CleanupStack, [](Cleanup &C) {
1167         return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1168       });
1169     }
1170 
1171     /// Throw away any remaining cleanups at the end of evaluation. If any
1172     /// cleanups would have had a side-effect, note that as an unmodeled
1173     /// side-effect and return false. Otherwise, return true.
1174     bool discardCleanups() {
1175       for (Cleanup &C : CleanupStack) {
1176         if (C.hasSideEffect() && !noteSideEffect()) {
1177           CleanupStack.clear();
1178           return false;
1179         }
1180       }
1181       CleanupStack.clear();
1182       return true;
1183     }
1184 
1185   private:
1186     interp::Frame *getCurrentFrame() override { return CurrentCall; }
1187     const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1188 
1189     bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1190     void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1191 
1192     void setFoldFailureDiagnostic(bool Flag) override {
1193       HasFoldFailureDiagnostic = Flag;
1194     }
1195 
1196     Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1197 
1198     // If we have a prior diagnostic, it will be noting that the expression
1199     // isn't a constant expression. This diagnostic is more important,
1200     // unless we require this evaluation to produce a constant expression.
1201     //
1202     // FIXME: We might want to show both diagnostics to the user in
1203     // EM_ConstantFold mode.
1204     bool hasPriorDiagnostic() override {
1205       if (!EvalStatus.Diag->empty()) {
1206         switch (EvalMode) {
1207         case EM_ConstantFold:
1208         case EM_IgnoreSideEffects:
1209           if (!HasFoldFailureDiagnostic)
1210             break;
1211           // We've already failed to fold something. Keep that diagnostic.
1212           [[fallthrough]];
1213         case EM_ConstantExpression:
1214         case EM_ConstantExpressionUnevaluated:
1215           setActiveDiagnostic(false);
1216           return true;
1217         }
1218       }
1219       return false;
1220     }
1221 
1222     unsigned getCallStackDepth() override { return CallStackDepth; }
1223 
1224   public:
1225     /// Should we continue evaluation after encountering a side-effect that we
1226     /// couldn't model?
1227     bool keepEvaluatingAfterSideEffect() const override {
1228       switch (EvalMode) {
1229       case EM_IgnoreSideEffects:
1230         return true;
1231 
1232       case EM_ConstantExpression:
1233       case EM_ConstantExpressionUnevaluated:
1234       case EM_ConstantFold:
1235         // By default, assume any side effect might be valid in some other
1236         // evaluation of this expression from a different context.
1237         return checkingPotentialConstantExpression() ||
1238                checkingForUndefinedBehavior();
1239       }
1240       llvm_unreachable("Missed EvalMode case");
1241     }
1242 
1243     /// Note that we have had a side-effect, and determine whether we should
1244     /// keep evaluating.
1245     bool noteSideEffect() override {
1246       EvalStatus.HasSideEffects = true;
1247       return keepEvaluatingAfterSideEffect();
1248     }
1249 
1250     /// Should we continue evaluation after encountering undefined behavior?
1251     bool keepEvaluatingAfterUndefinedBehavior() {
1252       switch (EvalMode) {
1253       case EM_IgnoreSideEffects:
1254       case EM_ConstantFold:
1255         return true;
1256 
1257       case EM_ConstantExpression:
1258       case EM_ConstantExpressionUnevaluated:
1259         return checkingForUndefinedBehavior();
1260       }
1261       llvm_unreachable("Missed EvalMode case");
1262     }
1263 
1264     /// Note that we hit something that was technically undefined behavior, but
1265     /// that we can evaluate past it (such as signed overflow or floating-point
1266     /// division by zero.)
1267     bool noteUndefinedBehavior() override {
1268       EvalStatus.HasUndefinedBehavior = true;
1269       return keepEvaluatingAfterUndefinedBehavior();
1270     }
1271 
1272     /// Should we continue evaluation as much as possible after encountering a
1273     /// construct which can't be reduced to a value?
1274     bool keepEvaluatingAfterFailure() const override {
1275       if (!StepsLeft)
1276         return false;
1277 
1278       switch (EvalMode) {
1279       case EM_ConstantExpression:
1280       case EM_ConstantExpressionUnevaluated:
1281       case EM_ConstantFold:
1282       case EM_IgnoreSideEffects:
1283         return checkingPotentialConstantExpression() ||
1284                checkingForUndefinedBehavior();
1285       }
1286       llvm_unreachable("Missed EvalMode case");
1287     }
1288 
1289     /// Notes that we failed to evaluate an expression that other expressions
1290     /// directly depend on, and determine if we should keep evaluating. This
1291     /// should only be called if we actually intend to keep evaluating.
1292     ///
1293     /// Call noteSideEffect() instead if we may be able to ignore the value that
1294     /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1295     ///
1296     /// (Foo(), 1)      // use noteSideEffect
1297     /// (Foo() || true) // use noteSideEffect
1298     /// Foo() + 1       // use noteFailure
1299     [[nodiscard]] bool noteFailure() {
1300       // Failure when evaluating some expression often means there is some
1301       // subexpression whose evaluation was skipped. Therefore, (because we
1302       // don't track whether we skipped an expression when unwinding after an
1303       // evaluation failure) every evaluation failure that bubbles up from a
1304       // subexpression implies that a side-effect has potentially happened. We
1305       // skip setting the HasSideEffects flag to true until we decide to
1306       // continue evaluating after that point, which happens here.
1307       bool KeepGoing = keepEvaluatingAfterFailure();
1308       EvalStatus.HasSideEffects |= KeepGoing;
1309       return KeepGoing;
1310     }
1311 
1312     class ArrayInitLoopIndex {
1313       EvalInfo &Info;
1314       uint64_t OuterIndex;
1315 
1316     public:
1317       ArrayInitLoopIndex(EvalInfo &Info)
1318           : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1319         Info.ArrayInitIndex = 0;
1320       }
1321       ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1322 
1323       operator uint64_t&() { return Info.ArrayInitIndex; }
1324     };
1325   };
1326 
1327   /// Object used to treat all foldable expressions as constant expressions.
1328   struct FoldConstant {
1329     EvalInfo &Info;
1330     bool Enabled;
1331     bool HadNoPriorDiags;
1332     EvalInfo::EvaluationMode OldMode;
1333 
1334     explicit FoldConstant(EvalInfo &Info, bool Enabled)
1335       : Info(Info),
1336         Enabled(Enabled),
1337         HadNoPriorDiags(Info.EvalStatus.Diag &&
1338                         Info.EvalStatus.Diag->empty() &&
1339                         !Info.EvalStatus.HasSideEffects),
1340         OldMode(Info.EvalMode) {
1341       if (Enabled)
1342         Info.EvalMode = EvalInfo::EM_ConstantFold;
1343     }
1344     void keepDiagnostics() { Enabled = false; }
1345     ~FoldConstant() {
1346       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1347           !Info.EvalStatus.HasSideEffects)
1348         Info.EvalStatus.Diag->clear();
1349       Info.EvalMode = OldMode;
1350     }
1351   };
1352 
1353   /// RAII object used to set the current evaluation mode to ignore
1354   /// side-effects.
1355   struct IgnoreSideEffectsRAII {
1356     EvalInfo &Info;
1357     EvalInfo::EvaluationMode OldMode;
1358     explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1359         : Info(Info), OldMode(Info.EvalMode) {
1360       Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1361     }
1362 
1363     ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1364   };
1365 
1366   /// RAII object used to optionally suppress diagnostics and side-effects from
1367   /// a speculative evaluation.
1368   class SpeculativeEvaluationRAII {
1369     EvalInfo *Info = nullptr;
1370     Expr::EvalStatus OldStatus;
1371     unsigned OldSpeculativeEvaluationDepth = 0;
1372 
1373     void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1374       Info = Other.Info;
1375       OldStatus = Other.OldStatus;
1376       OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1377       Other.Info = nullptr;
1378     }
1379 
1380     void maybeRestoreState() {
1381       if (!Info)
1382         return;
1383 
1384       Info->EvalStatus = OldStatus;
1385       Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1386     }
1387 
1388   public:
1389     SpeculativeEvaluationRAII() = default;
1390 
1391     SpeculativeEvaluationRAII(
1392         EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1393         : Info(&Info), OldStatus(Info.EvalStatus),
1394           OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1395       Info.EvalStatus.Diag = NewDiag;
1396       Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1397     }
1398 
1399     SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1400     SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1401       moveFromAndCancel(std::move(Other));
1402     }
1403 
1404     SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1405       maybeRestoreState();
1406       moveFromAndCancel(std::move(Other));
1407       return *this;
1408     }
1409 
1410     ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1411   };
1412 
1413   /// RAII object wrapping a full-expression or block scope, and handling
1414   /// the ending of the lifetime of temporaries created within it.
1415   template<ScopeKind Kind>
1416   class ScopeRAII {
1417     EvalInfo &Info;
1418     unsigned OldStackSize;
1419   public:
1420     ScopeRAII(EvalInfo &Info)
1421         : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1422       // Push a new temporary version. This is needed to distinguish between
1423       // temporaries created in different iterations of a loop.
1424       Info.CurrentCall->pushTempVersion();
1425     }
1426     bool destroy(bool RunDestructors = true) {
1427       bool OK = cleanup(Info, RunDestructors, OldStackSize);
1428       OldStackSize = -1U;
1429       return OK;
1430     }
1431     ~ScopeRAII() {
1432       if (OldStackSize != -1U)
1433         destroy(false);
1434       // Body moved to a static method to encourage the compiler to inline away
1435       // instances of this class.
1436       Info.CurrentCall->popTempVersion();
1437     }
1438   private:
1439     static bool cleanup(EvalInfo &Info, bool RunDestructors,
1440                         unsigned OldStackSize) {
1441       assert(OldStackSize <= Info.CleanupStack.size() &&
1442              "running cleanups out of order?");
1443 
1444       // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1445       // for a full-expression scope.
1446       bool Success = true;
1447       for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1448         if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1449           if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1450             Success = false;
1451             break;
1452           }
1453         }
1454       }
1455 
1456       // Compact any retained cleanups.
1457       auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1458       if (Kind != ScopeKind::Block)
1459         NewEnd =
1460             std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1461               return C.isDestroyedAtEndOf(Kind);
1462             });
1463       Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1464       return Success;
1465     }
1466   };
1467   typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1468   typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1469   typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1470 }
1471 
1472 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1473                                          CheckSubobjectKind CSK) {
1474   if (Invalid)
1475     return false;
1476   if (isOnePastTheEnd()) {
1477     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1478       << CSK;
1479     setInvalid();
1480     return false;
1481   }
1482   // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1483   // must actually be at least one array element; even a VLA cannot have a
1484   // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1485   return true;
1486 }
1487 
1488 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1489                                                                 const Expr *E) {
1490   Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1491   // Do not set the designator as invalid: we can represent this situation,
1492   // and correct handling of __builtin_object_size requires us to do so.
1493 }
1494 
1495 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1496                                                     const Expr *E,
1497                                                     const APSInt &N) {
1498   // If we're complaining, we must be able to statically determine the size of
1499   // the most derived array.
1500   if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1501     Info.CCEDiag(E, diag::note_constexpr_array_index)
1502       << N << /*array*/ 0
1503       << static_cast<unsigned>(getMostDerivedArraySize());
1504   else
1505     Info.CCEDiag(E, diag::note_constexpr_array_index)
1506       << N << /*non-array*/ 1;
1507   setInvalid();
1508 }
1509 
1510 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceRange CallRange,
1511                                const FunctionDecl *Callee, const LValue *This,
1512                                const Expr *CallExpr, CallRef Call)
1513     : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1514       CallExpr(CallExpr), Arguments(Call), CallRange(CallRange),
1515       Index(Info.NextCallIndex++) {
1516   Info.CurrentCall = this;
1517   ++Info.CallStackDepth;
1518 }
1519 
1520 CallStackFrame::~CallStackFrame() {
1521   assert(Info.CurrentCall == this && "calls retired out of order");
1522   --Info.CallStackDepth;
1523   Info.CurrentCall = Caller;
1524 }
1525 
1526 static bool isRead(AccessKinds AK) {
1527   return AK == AK_Read || AK == AK_ReadObjectRepresentation ||
1528          AK == AK_IsWithinLifetime;
1529 }
1530 
1531 static bool isModification(AccessKinds AK) {
1532   switch (AK) {
1533   case AK_Read:
1534   case AK_ReadObjectRepresentation:
1535   case AK_MemberCall:
1536   case AK_DynamicCast:
1537   case AK_TypeId:
1538   case AK_IsWithinLifetime:
1539     return false;
1540   case AK_Assign:
1541   case AK_Increment:
1542   case AK_Decrement:
1543   case AK_Construct:
1544   case AK_Destroy:
1545     return true;
1546   }
1547   llvm_unreachable("unknown access kind");
1548 }
1549 
1550 static bool isAnyAccess(AccessKinds AK) {
1551   return isRead(AK) || isModification(AK);
1552 }
1553 
1554 /// Is this an access per the C++ definition?
1555 static bool isFormalAccess(AccessKinds AK) {
1556   return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy &&
1557          AK != AK_IsWithinLifetime;
1558 }
1559 
1560 /// Is this kind of axcess valid on an indeterminate object value?
1561 static bool isValidIndeterminateAccess(AccessKinds AK) {
1562   switch (AK) {
1563   case AK_Read:
1564   case AK_Increment:
1565   case AK_Decrement:
1566     // These need the object's value.
1567     return false;
1568 
1569   case AK_IsWithinLifetime:
1570   case AK_ReadObjectRepresentation:
1571   case AK_Assign:
1572   case AK_Construct:
1573   case AK_Destroy:
1574     // Construction and destruction don't need the value.
1575     return true;
1576 
1577   case AK_MemberCall:
1578   case AK_DynamicCast:
1579   case AK_TypeId:
1580     // These aren't really meaningful on scalars.
1581     return true;
1582   }
1583   llvm_unreachable("unknown access kind");
1584 }
1585 
1586 namespace {
1587   struct ComplexValue {
1588   private:
1589     bool IsInt;
1590 
1591   public:
1592     APSInt IntReal, IntImag;
1593     APFloat FloatReal, FloatImag;
1594 
1595     ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1596 
1597     void makeComplexFloat() { IsInt = false; }
1598     bool isComplexFloat() const { return !IsInt; }
1599     APFloat &getComplexFloatReal() { return FloatReal; }
1600     APFloat &getComplexFloatImag() { return FloatImag; }
1601 
1602     void makeComplexInt() { IsInt = true; }
1603     bool isComplexInt() const { return IsInt; }
1604     APSInt &getComplexIntReal() { return IntReal; }
1605     APSInt &getComplexIntImag() { return IntImag; }
1606 
1607     void moveInto(APValue &v) const {
1608       if (isComplexFloat())
1609         v = APValue(FloatReal, FloatImag);
1610       else
1611         v = APValue(IntReal, IntImag);
1612     }
1613     void setFrom(const APValue &v) {
1614       assert(v.isComplexFloat() || v.isComplexInt());
1615       if (v.isComplexFloat()) {
1616         makeComplexFloat();
1617         FloatReal = v.getComplexFloatReal();
1618         FloatImag = v.getComplexFloatImag();
1619       } else {
1620         makeComplexInt();
1621         IntReal = v.getComplexIntReal();
1622         IntImag = v.getComplexIntImag();
1623       }
1624     }
1625   };
1626 
1627   struct LValue {
1628     APValue::LValueBase Base;
1629     CharUnits Offset;
1630     SubobjectDesignator Designator;
1631     bool IsNullPtr : 1;
1632     bool InvalidBase : 1;
1633 
1634     const APValue::LValueBase getLValueBase() const { return Base; }
1635     CharUnits &getLValueOffset() { return Offset; }
1636     const CharUnits &getLValueOffset() const { return Offset; }
1637     SubobjectDesignator &getLValueDesignator() { return Designator; }
1638     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1639     bool isNullPointer() const { return IsNullPtr;}
1640 
1641     unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1642     unsigned getLValueVersion() const { return Base.getVersion(); }
1643 
1644     void moveInto(APValue &V) const {
1645       if (Designator.Invalid)
1646         V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1647       else {
1648         assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1649         V = APValue(Base, Offset, Designator.Entries,
1650                     Designator.IsOnePastTheEnd, IsNullPtr);
1651       }
1652     }
1653     void setFrom(ASTContext &Ctx, const APValue &V) {
1654       assert(V.isLValue() && "Setting LValue from a non-LValue?");
1655       Base = V.getLValueBase();
1656       Offset = V.getLValueOffset();
1657       InvalidBase = false;
1658       Designator = SubobjectDesignator(Ctx, V);
1659       IsNullPtr = V.isNullPointer();
1660     }
1661 
1662     void set(APValue::LValueBase B, bool BInvalid = false) {
1663 #ifndef NDEBUG
1664       // We only allow a few types of invalid bases. Enforce that here.
1665       if (BInvalid) {
1666         const auto *E = B.get<const Expr *>();
1667         assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1668                "Unexpected type of invalid base");
1669       }
1670 #endif
1671 
1672       Base = B;
1673       Offset = CharUnits::fromQuantity(0);
1674       InvalidBase = BInvalid;
1675       Designator = SubobjectDesignator(getType(B));
1676       IsNullPtr = false;
1677     }
1678 
1679     void setNull(ASTContext &Ctx, QualType PointerTy) {
1680       Base = (const ValueDecl *)nullptr;
1681       Offset =
1682           CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
1683       InvalidBase = false;
1684       Designator = SubobjectDesignator(PointerTy->getPointeeType());
1685       IsNullPtr = true;
1686     }
1687 
1688     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1689       set(B, true);
1690     }
1691 
1692     std::string toString(ASTContext &Ctx, QualType T) const {
1693       APValue Printable;
1694       moveInto(Printable);
1695       return Printable.getAsString(Ctx, T);
1696     }
1697 
1698   private:
1699     // Check that this LValue is not based on a null pointer. If it is, produce
1700     // a diagnostic and mark the designator as invalid.
1701     template <typename GenDiagType>
1702     bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1703       if (Designator.Invalid)
1704         return false;
1705       if (IsNullPtr) {
1706         GenDiag();
1707         Designator.setInvalid();
1708         return false;
1709       }
1710       return true;
1711     }
1712 
1713   public:
1714     bool checkNullPointer(EvalInfo &Info, const Expr *E,
1715                           CheckSubobjectKind CSK) {
1716       return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1717         Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1718       });
1719     }
1720 
1721     bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1722                                        AccessKinds AK) {
1723       return checkNullPointerDiagnosingWith([&Info, E, AK] {
1724         Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1725       });
1726     }
1727 
1728     // Check this LValue refers to an object. If not, set the designator to be
1729     // invalid and emit a diagnostic.
1730     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1731       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1732              Designator.checkSubobject(Info, E, CSK);
1733     }
1734 
1735     void addDecl(EvalInfo &Info, const Expr *E,
1736                  const Decl *D, bool Virtual = false) {
1737       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1738         Designator.addDeclUnchecked(D, Virtual);
1739     }
1740     void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1741       if (!Designator.Entries.empty()) {
1742         Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1743         Designator.setInvalid();
1744         return;
1745       }
1746       if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1747         assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1748         Designator.FirstEntryIsAnUnsizedArray = true;
1749         Designator.addUnsizedArrayUnchecked(ElemTy);
1750       }
1751     }
1752     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1753       if (checkSubobject(Info, E, CSK_ArrayToPointer))
1754         Designator.addArrayUnchecked(CAT);
1755     }
1756     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1757       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1758         Designator.addComplexUnchecked(EltTy, Imag);
1759     }
1760     void addVectorElement(EvalInfo &Info, const Expr *E, QualType EltTy,
1761                           uint64_t Size, uint64_t Idx) {
1762       if (checkSubobject(Info, E, CSK_VectorElement))
1763         Designator.addVectorElementUnchecked(EltTy, Size, Idx);
1764     }
1765     void clearIsNullPointer() {
1766       IsNullPtr = false;
1767     }
1768     void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1769                               const APSInt &Index, CharUnits ElementSize) {
1770       // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1771       // but we're not required to diagnose it and it's valid in C++.)
1772       if (!Index)
1773         return;
1774 
1775       // Compute the new offset in the appropriate width, wrapping at 64 bits.
1776       // FIXME: When compiling for a 32-bit target, we should use 32-bit
1777       // offsets.
1778       uint64_t Offset64 = Offset.getQuantity();
1779       uint64_t ElemSize64 = ElementSize.getQuantity();
1780       uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1781       Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1782 
1783       if (checkNullPointer(Info, E, CSK_ArrayIndex))
1784         Designator.adjustIndex(Info, E, Index);
1785       clearIsNullPointer();
1786     }
1787     void adjustOffset(CharUnits N) {
1788       Offset += N;
1789       if (N.getQuantity())
1790         clearIsNullPointer();
1791     }
1792   };
1793 
1794   struct MemberPtr {
1795     MemberPtr() {}
1796     explicit MemberPtr(const ValueDecl *Decl)
1797         : DeclAndIsDerivedMember(Decl, false) {}
1798 
1799     /// The member or (direct or indirect) field referred to by this member
1800     /// pointer, or 0 if this is a null member pointer.
1801     const ValueDecl *getDecl() const {
1802       return DeclAndIsDerivedMember.getPointer();
1803     }
1804     /// Is this actually a member of some type derived from the relevant class?
1805     bool isDerivedMember() const {
1806       return DeclAndIsDerivedMember.getInt();
1807     }
1808     /// Get the class which the declaration actually lives in.
1809     const CXXRecordDecl *getContainingRecord() const {
1810       return cast<CXXRecordDecl>(
1811           DeclAndIsDerivedMember.getPointer()->getDeclContext());
1812     }
1813 
1814     void moveInto(APValue &V) const {
1815       V = APValue(getDecl(), isDerivedMember(), Path);
1816     }
1817     void setFrom(const APValue &V) {
1818       assert(V.isMemberPointer());
1819       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1820       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1821       Path.clear();
1822       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1823       Path.insert(Path.end(), P.begin(), P.end());
1824     }
1825 
1826     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1827     /// whether the member is a member of some class derived from the class type
1828     /// of the member pointer.
1829     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1830     /// Path - The path of base/derived classes from the member declaration's
1831     /// class (exclusive) to the class type of the member pointer (inclusive).
1832     SmallVector<const CXXRecordDecl*, 4> Path;
1833 
1834     /// Perform a cast towards the class of the Decl (either up or down the
1835     /// hierarchy).
1836     bool castBack(const CXXRecordDecl *Class) {
1837       assert(!Path.empty());
1838       const CXXRecordDecl *Expected;
1839       if (Path.size() >= 2)
1840         Expected = Path[Path.size() - 2];
1841       else
1842         Expected = getContainingRecord();
1843       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1844         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1845         // if B does not contain the original member and is not a base or
1846         // derived class of the class containing the original member, the result
1847         // of the cast is undefined.
1848         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1849         // (D::*). We consider that to be a language defect.
1850         return false;
1851       }
1852       Path.pop_back();
1853       return true;
1854     }
1855     /// Perform a base-to-derived member pointer cast.
1856     bool castToDerived(const CXXRecordDecl *Derived) {
1857       if (!getDecl())
1858         return true;
1859       if (!isDerivedMember()) {
1860         Path.push_back(Derived);
1861         return true;
1862       }
1863       if (!castBack(Derived))
1864         return false;
1865       if (Path.empty())
1866         DeclAndIsDerivedMember.setInt(false);
1867       return true;
1868     }
1869     /// Perform a derived-to-base member pointer cast.
1870     bool castToBase(const CXXRecordDecl *Base) {
1871       if (!getDecl())
1872         return true;
1873       if (Path.empty())
1874         DeclAndIsDerivedMember.setInt(true);
1875       if (isDerivedMember()) {
1876         Path.push_back(Base);
1877         return true;
1878       }
1879       return castBack(Base);
1880     }
1881   };
1882 
1883   /// Compare two member pointers, which are assumed to be of the same type.
1884   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1885     if (!LHS.getDecl() || !RHS.getDecl())
1886       return !LHS.getDecl() && !RHS.getDecl();
1887     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1888       return false;
1889     return LHS.Path == RHS.Path;
1890   }
1891 }
1892 
1893 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1894 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1895                             const LValue &This, const Expr *E,
1896                             bool AllowNonLiteralTypes = false);
1897 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1898                            bool InvalidBaseOK = false);
1899 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1900                             bool InvalidBaseOK = false);
1901 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1902                                   EvalInfo &Info);
1903 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1904 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1905 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1906                                     EvalInfo &Info);
1907 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1908 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1909 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1910                            EvalInfo &Info);
1911 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1912 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
1913                                   EvalInfo &Info,
1914                                   std::string *StringResult = nullptr);
1915 
1916 /// Evaluate an integer or fixed point expression into an APResult.
1917 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1918                                         EvalInfo &Info);
1919 
1920 /// Evaluate only a fixed point expression into an APResult.
1921 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1922                                EvalInfo &Info);
1923 
1924 //===----------------------------------------------------------------------===//
1925 // Misc utilities
1926 //===----------------------------------------------------------------------===//
1927 
1928 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1929 /// preserving its value (by extending by up to one bit as needed).
1930 static void negateAsSigned(APSInt &Int) {
1931   if (Int.isUnsigned() || Int.isMinSignedValue()) {
1932     Int = Int.extend(Int.getBitWidth() + 1);
1933     Int.setIsSigned(true);
1934   }
1935   Int = -Int;
1936 }
1937 
1938 template<typename KeyT>
1939 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1940                                          ScopeKind Scope, LValue &LV) {
1941   unsigned Version = getTempVersion();
1942   APValue::LValueBase Base(Key, Index, Version);
1943   LV.set(Base);
1944   return createLocal(Base, Key, T, Scope);
1945 }
1946 
1947 /// Allocate storage for a parameter of a function call made in this frame.
1948 APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1949                                      LValue &LV) {
1950   assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1951   APValue::LValueBase Base(PVD, Index, Args.Version);
1952   LV.set(Base);
1953   // We always destroy parameters at the end of the call, even if we'd allow
1954   // them to live to the end of the full-expression at runtime, in order to
1955   // give portable results and match other compilers.
1956   return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1957 }
1958 
1959 APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1960                                      QualType T, ScopeKind Scope) {
1961   assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1962   unsigned Version = Base.getVersion();
1963   APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1964   assert(Result.isAbsent() && "local created multiple times");
1965 
1966   // If we're creating a local immediately in the operand of a speculative
1967   // evaluation, don't register a cleanup to be run outside the speculative
1968   // evaluation context, since we won't actually be able to initialize this
1969   // object.
1970   if (Index <= Info.SpeculativeEvaluationDepth) {
1971     if (T.isDestructedType())
1972       Info.noteSideEffect();
1973   } else {
1974     Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1975   }
1976   return Result;
1977 }
1978 
1979 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1980   if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1981     FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1982     return nullptr;
1983   }
1984 
1985   DynamicAllocLValue DA(NumHeapAllocs++);
1986   LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1987   auto Result = HeapAllocs.emplace(std::piecewise_construct,
1988                                    std::forward_as_tuple(DA), std::tuple<>());
1989   assert(Result.second && "reused a heap alloc index?");
1990   Result.first->second.AllocExpr = E;
1991   return &Result.first->second.Value;
1992 }
1993 
1994 /// Produce a string describing the given constexpr call.
1995 void CallStackFrame::describe(raw_ostream &Out) const {
1996   unsigned ArgIndex = 0;
1997   bool IsMemberCall =
1998       isa<CXXMethodDecl>(Callee) && !isa<CXXConstructorDecl>(Callee) &&
1999       cast<CXXMethodDecl>(Callee)->isImplicitObjectMemberFunction();
2000 
2001   if (!IsMemberCall)
2002     Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
2003                                  /*Qualified=*/false);
2004 
2005   if (This && IsMemberCall) {
2006     if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {
2007       const Expr *Object = MCE->getImplicitObjectArgument();
2008       Object->printPretty(Out, /*Helper=*/nullptr, Info.Ctx.getPrintingPolicy(),
2009                           /*Indentation=*/0);
2010       if (Object->getType()->isPointerType())
2011           Out << "->";
2012       else
2013           Out << ".";
2014     } else if (const auto *OCE =
2015                    dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {
2016       OCE->getArg(0)->printPretty(Out, /*Helper=*/nullptr,
2017                                   Info.Ctx.getPrintingPolicy(),
2018                                   /*Indentation=*/0);
2019       Out << ".";
2020     } else {
2021       APValue Val;
2022       This->moveInto(Val);
2023       Val.printPretty(
2024           Out, Info.Ctx,
2025           Info.Ctx.getLValueReferenceType(This->Designator.MostDerivedType));
2026       Out << ".";
2027     }
2028     Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
2029                                  /*Qualified=*/false);
2030     IsMemberCall = false;
2031   }
2032 
2033   Out << '(';
2034 
2035   for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
2036        E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
2037     if (ArgIndex > (unsigned)IsMemberCall)
2038       Out << ", ";
2039 
2040     const ParmVarDecl *Param = *I;
2041     APValue *V = Info.getParamSlot(Arguments, Param);
2042     if (V)
2043       V->printPretty(Out, Info.Ctx, Param->getType());
2044     else
2045       Out << "<...>";
2046 
2047     if (ArgIndex == 0 && IsMemberCall)
2048       Out << "->" << *Callee << '(';
2049   }
2050 
2051   Out << ')';
2052 }
2053 
2054 /// Evaluate an expression to see if it had side-effects, and discard its
2055 /// result.
2056 /// \return \c true if the caller should keep evaluating.
2057 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
2058   assert(!E->isValueDependent());
2059   APValue Scratch;
2060   if (!Evaluate(Scratch, Info, E))
2061     // We don't need the value, but we might have skipped a side effect here.
2062     return Info.noteSideEffect();
2063   return true;
2064 }
2065 
2066 /// Should this call expression be treated as forming an opaque constant?
2067 static bool IsOpaqueConstantCall(const CallExpr *E) {
2068   unsigned Builtin = E->getBuiltinCallee();
2069   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
2070           Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
2071           Builtin == Builtin::BI__builtin_ptrauth_sign_constant ||
2072           Builtin == Builtin::BI__builtin_function_start);
2073 }
2074 
2075 static bool IsOpaqueConstantCall(const LValue &LVal) {
2076   const auto *BaseExpr =
2077       llvm::dyn_cast_if_present<CallExpr>(LVal.Base.dyn_cast<const Expr *>());
2078   return BaseExpr && IsOpaqueConstantCall(BaseExpr);
2079 }
2080 
2081 static bool IsGlobalLValue(APValue::LValueBase B) {
2082   // C++11 [expr.const]p3 An address constant expression is a prvalue core
2083   // constant expression of pointer type that evaluates to...
2084 
2085   // ... a null pointer value, or a prvalue core constant expression of type
2086   // std::nullptr_t.
2087   if (!B)
2088     return true;
2089 
2090   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
2091     // ... the address of an object with static storage duration,
2092     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
2093       return VD->hasGlobalStorage();
2094     if (isa<TemplateParamObjectDecl>(D))
2095       return true;
2096     // ... the address of a function,
2097     // ... the address of a GUID [MS extension],
2098     // ... the address of an unnamed global constant
2099     return isa<FunctionDecl, MSGuidDecl, UnnamedGlobalConstantDecl>(D);
2100   }
2101 
2102   if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
2103     return true;
2104 
2105   const Expr *E = B.get<const Expr*>();
2106   switch (E->getStmtClass()) {
2107   default:
2108     return false;
2109   case Expr::CompoundLiteralExprClass: {
2110     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
2111     return CLE->isFileScope() && CLE->isLValue();
2112   }
2113   case Expr::MaterializeTemporaryExprClass:
2114     // A materialized temporary might have been lifetime-extended to static
2115     // storage duration.
2116     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
2117   // A string literal has static storage duration.
2118   case Expr::StringLiteralClass:
2119   case Expr::PredefinedExprClass:
2120   case Expr::ObjCStringLiteralClass:
2121   case Expr::ObjCEncodeExprClass:
2122     return true;
2123   case Expr::ObjCBoxedExprClass:
2124     return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2125   case Expr::CallExprClass:
2126     return IsOpaqueConstantCall(cast<CallExpr>(E));
2127   // For GCC compatibility, &&label has static storage duration.
2128   case Expr::AddrLabelExprClass:
2129     return true;
2130   // A Block literal expression may be used as the initialization value for
2131   // Block variables at global or local static scope.
2132   case Expr::BlockExprClass:
2133     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2134   // The APValue generated from a __builtin_source_location will be emitted as a
2135   // literal.
2136   case Expr::SourceLocExprClass:
2137     return true;
2138   case Expr::ImplicitValueInitExprClass:
2139     // FIXME:
2140     // We can never form an lvalue with an implicit value initialization as its
2141     // base through expression evaluation, so these only appear in one case: the
2142     // implicit variable declaration we invent when checking whether a constexpr
2143     // constructor can produce a constant expression. We must assume that such
2144     // an expression might be a global lvalue.
2145     return true;
2146   }
2147 }
2148 
2149 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2150   return LVal.Base.dyn_cast<const ValueDecl*>();
2151 }
2152 
2153 // Information about an LValueBase that is some kind of string.
2154 struct LValueBaseString {
2155   std::string ObjCEncodeStorage;
2156   StringRef Bytes;
2157   int CharWidth;
2158 };
2159 
2160 // Gets the lvalue base of LVal as a string.
2161 static bool GetLValueBaseAsString(const EvalInfo &Info, const LValue &LVal,
2162                                   LValueBaseString &AsString) {
2163   const auto *BaseExpr = LVal.Base.dyn_cast<const Expr *>();
2164   if (!BaseExpr)
2165     return false;
2166 
2167   // For ObjCEncodeExpr, we need to compute and store the string.
2168   if (const auto *EE = dyn_cast<ObjCEncodeExpr>(BaseExpr)) {
2169     Info.Ctx.getObjCEncodingForType(EE->getEncodedType(),
2170                                     AsString.ObjCEncodeStorage);
2171     AsString.Bytes = AsString.ObjCEncodeStorage;
2172     AsString.CharWidth = 1;
2173     return true;
2174   }
2175 
2176   // Otherwise, we have a StringLiteral.
2177   const auto *Lit = dyn_cast<StringLiteral>(BaseExpr);
2178   if (const auto *PE = dyn_cast<PredefinedExpr>(BaseExpr))
2179     Lit = PE->getFunctionName();
2180 
2181   if (!Lit)
2182     return false;
2183 
2184   AsString.Bytes = Lit->getBytes();
2185   AsString.CharWidth = Lit->getCharByteWidth();
2186   return true;
2187 }
2188 
2189 // Determine whether two string literals potentially overlap. This will be the
2190 // case if they agree on the values of all the bytes on the overlapping region
2191 // between them.
2192 //
2193 // The overlapping region is the portion of the two string literals that must
2194 // overlap in memory if the pointers actually point to the same address at
2195 // runtime. For example, if LHS is "abcdef" + 3 and RHS is "cdef\0gh" + 1 then
2196 // the overlapping region is "cdef\0", which in this case does agree, so the
2197 // strings are potentially overlapping. Conversely, for "foobar" + 3 versus
2198 // "bazbar" + 3, the overlapping region contains all of both strings, so they
2199 // are not potentially overlapping, even though they agree from the given
2200 // addresses onwards.
2201 //
2202 // See open core issue CWG2765 which is discussing the desired rule here.
2203 static bool ArePotentiallyOverlappingStringLiterals(const EvalInfo &Info,
2204                                                     const LValue &LHS,
2205                                                     const LValue &RHS) {
2206   LValueBaseString LHSString, RHSString;
2207   if (!GetLValueBaseAsString(Info, LHS, LHSString) ||
2208       !GetLValueBaseAsString(Info, RHS, RHSString))
2209     return false;
2210 
2211   // This is the byte offset to the location of the first character of LHS
2212   // within RHS. We don't need to look at the characters of one string that
2213   // would appear before the start of the other string if they were merged.
2214   CharUnits Offset = RHS.Offset - LHS.Offset;
2215   if (Offset.isNegative())
2216     LHSString.Bytes = LHSString.Bytes.drop_front(-Offset.getQuantity());
2217   else
2218     RHSString.Bytes = RHSString.Bytes.drop_front(Offset.getQuantity());
2219 
2220   bool LHSIsLonger = LHSString.Bytes.size() > RHSString.Bytes.size();
2221   StringRef Longer = LHSIsLonger ? LHSString.Bytes : RHSString.Bytes;
2222   StringRef Shorter = LHSIsLonger ? RHSString.Bytes : LHSString.Bytes;
2223   int ShorterCharWidth = (LHSIsLonger ? RHSString : LHSString).CharWidth;
2224 
2225   // The null terminator isn't included in the string data, so check for it
2226   // manually. If the longer string doesn't have a null terminator where the
2227   // shorter string ends, they aren't potentially overlapping.
2228   for (int NullByte : llvm::seq(ShorterCharWidth)) {
2229     if (Shorter.size() + NullByte >= Longer.size())
2230       break;
2231     if (Longer[Shorter.size() + NullByte])
2232       return false;
2233   }
2234 
2235   // Otherwise, they're potentially overlapping if and only if the overlapping
2236   // region is the same.
2237   return Shorter == Longer.take_front(Shorter.size());
2238 }
2239 
2240 static bool IsWeakLValue(const LValue &Value) {
2241   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2242   return Decl && Decl->isWeak();
2243 }
2244 
2245 static bool isZeroSized(const LValue &Value) {
2246   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2247   if (isa_and_nonnull<VarDecl>(Decl)) {
2248     QualType Ty = Decl->getType();
2249     if (Ty->isArrayType())
2250       return Ty->isIncompleteType() ||
2251              Decl->getASTContext().getTypeSize(Ty) == 0;
2252   }
2253   return false;
2254 }
2255 
2256 static bool HasSameBase(const LValue &A, const LValue &B) {
2257   if (!A.getLValueBase())
2258     return !B.getLValueBase();
2259   if (!B.getLValueBase())
2260     return false;
2261 
2262   if (A.getLValueBase().getOpaqueValue() !=
2263       B.getLValueBase().getOpaqueValue())
2264     return false;
2265 
2266   return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2267          A.getLValueVersion() == B.getLValueVersion();
2268 }
2269 
2270 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2271   assert(Base && "no location for a null lvalue");
2272   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2273 
2274   // For a parameter, find the corresponding call stack frame (if it still
2275   // exists), and point at the parameter of the function definition we actually
2276   // invoked.
2277   if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2278     unsigned Idx = PVD->getFunctionScopeIndex();
2279     for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2280       if (F->Arguments.CallIndex == Base.getCallIndex() &&
2281           F->Arguments.Version == Base.getVersion() && F->Callee &&
2282           Idx < F->Callee->getNumParams()) {
2283         VD = F->Callee->getParamDecl(Idx);
2284         break;
2285       }
2286     }
2287   }
2288 
2289   if (VD)
2290     Info.Note(VD->getLocation(), diag::note_declared_at);
2291   else if (const Expr *E = Base.dyn_cast<const Expr*>())
2292     Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2293   else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2294     // FIXME: Produce a note for dangling pointers too.
2295     if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA))
2296       Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2297                 diag::note_constexpr_dynamic_alloc_here);
2298   }
2299 
2300   // We have no information to show for a typeid(T) object.
2301 }
2302 
2303 enum class CheckEvaluationResultKind {
2304   ConstantExpression,
2305   FullyInitialized,
2306 };
2307 
2308 /// Materialized temporaries that we've already checked to determine if they're
2309 /// initializsed by a constant expression.
2310 using CheckedTemporaries =
2311     llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
2312 
2313 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2314                                   EvalInfo &Info, SourceLocation DiagLoc,
2315                                   QualType Type, const APValue &Value,
2316                                   ConstantExprKind Kind,
2317                                   const FieldDecl *SubobjectDecl,
2318                                   CheckedTemporaries &CheckedTemps);
2319 
2320 /// Check that this reference or pointer core constant expression is a valid
2321 /// value for an address or reference constant expression. Return true if we
2322 /// can fold this expression, whether or not it's a constant expression.
2323 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2324                                           QualType Type, const LValue &LVal,
2325                                           ConstantExprKind Kind,
2326                                           CheckedTemporaries &CheckedTemps) {
2327   bool IsReferenceType = Type->isReferenceType();
2328 
2329   APValue::LValueBase Base = LVal.getLValueBase();
2330   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2331 
2332   const Expr *BaseE = Base.dyn_cast<const Expr *>();
2333   const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2334 
2335   // Additional restrictions apply in a template argument. We only enforce the
2336   // C++20 restrictions here; additional syntactic and semantic restrictions
2337   // are applied elsewhere.
2338   if (isTemplateArgument(Kind)) {
2339     int InvalidBaseKind = -1;
2340     StringRef Ident;
2341     if (Base.is<TypeInfoLValue>())
2342       InvalidBaseKind = 0;
2343     else if (isa_and_nonnull<StringLiteral>(BaseE))
2344       InvalidBaseKind = 1;
2345     else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2346              isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2347       InvalidBaseKind = 2;
2348     else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2349       InvalidBaseKind = 3;
2350       Ident = PE->getIdentKindName();
2351     }
2352 
2353     if (InvalidBaseKind != -1) {
2354       Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2355           << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2356           << Ident;
2357       return false;
2358     }
2359   }
2360 
2361   if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD);
2362       FD && FD->isImmediateFunction()) {
2363     Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2364         << !Type->isAnyPointerType();
2365     Info.Note(FD->getLocation(), diag::note_declared_at);
2366     return false;
2367   }
2368 
2369   // Check that the object is a global. Note that the fake 'this' object we
2370   // manufacture when checking potential constant expressions is conservatively
2371   // assumed to be global here.
2372   if (!IsGlobalLValue(Base)) {
2373     if (Info.getLangOpts().CPlusPlus11) {
2374       Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2375           << IsReferenceType << !Designator.Entries.empty() << !!BaseVD
2376           << BaseVD;
2377       auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD);
2378       if (VarD && VarD->isConstexpr()) {
2379         // Non-static local constexpr variables have unintuitive semantics:
2380         //   constexpr int a = 1;
2381         //   constexpr const int *p = &a;
2382         // ... is invalid because the address of 'a' is not constant. Suggest
2383         // adding a 'static' in this case.
2384         Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2385             << VarD
2386             << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2387       } else {
2388         NoteLValueLocation(Info, Base);
2389       }
2390     } else {
2391       Info.FFDiag(Loc);
2392     }
2393     // Don't allow references to temporaries to escape.
2394     return false;
2395   }
2396   assert((Info.checkingPotentialConstantExpression() ||
2397           LVal.getLValueCallIndex() == 0) &&
2398          "have call index for global lvalue");
2399 
2400   if (Base.is<DynamicAllocLValue>()) {
2401     Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2402         << IsReferenceType << !Designator.Entries.empty();
2403     NoteLValueLocation(Info, Base);
2404     return false;
2405   }
2406 
2407   if (BaseVD) {
2408     if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2409       // Check if this is a thread-local variable.
2410       if (Var->getTLSKind())
2411         // FIXME: Diagnostic!
2412         return false;
2413 
2414       // A dllimport variable never acts like a constant, unless we're
2415       // evaluating a value for use only in name mangling.
2416       if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2417         // FIXME: Diagnostic!
2418         return false;
2419 
2420       // In CUDA/HIP device compilation, only device side variables have
2421       // constant addresses.
2422       if (Info.getASTContext().getLangOpts().CUDA &&
2423           Info.getASTContext().getLangOpts().CUDAIsDevice &&
2424           Info.getASTContext().CUDAConstantEvalCtx.NoWrongSidedVars) {
2425         if ((!Var->hasAttr<CUDADeviceAttr>() &&
2426              !Var->hasAttr<CUDAConstantAttr>() &&
2427              !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2428              !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
2429             Var->hasAttr<HIPManagedAttr>())
2430           return false;
2431       }
2432     }
2433     if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2434       // __declspec(dllimport) must be handled very carefully:
2435       // We must never initialize an expression with the thunk in C++.
2436       // Doing otherwise would allow the same id-expression to yield
2437       // different addresses for the same function in different translation
2438       // units.  However, this means that we must dynamically initialize the
2439       // expression with the contents of the import address table at runtime.
2440       //
2441       // The C language has no notion of ODR; furthermore, it has no notion of
2442       // dynamic initialization.  This means that we are permitted to
2443       // perform initialization with the address of the thunk.
2444       if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2445           FD->hasAttr<DLLImportAttr>())
2446         // FIXME: Diagnostic!
2447         return false;
2448     }
2449   } else if (const auto *MTE =
2450                  dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2451     if (CheckedTemps.insert(MTE).second) {
2452       QualType TempType = getType(Base);
2453       if (TempType.isDestructedType()) {
2454         Info.FFDiag(MTE->getExprLoc(),
2455                     diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2456             << TempType;
2457         return false;
2458       }
2459 
2460       APValue *V = MTE->getOrCreateValue(false);
2461       assert(V && "evasluation result refers to uninitialised temporary");
2462       if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2463                                  Info, MTE->getExprLoc(), TempType, *V, Kind,
2464                                  /*SubobjectDecl=*/nullptr, CheckedTemps))
2465         return false;
2466     }
2467   }
2468 
2469   // Allow address constant expressions to be past-the-end pointers. This is
2470   // an extension: the standard requires them to point to an object.
2471   if (!IsReferenceType)
2472     return true;
2473 
2474   // A reference constant expression must refer to an object.
2475   if (!Base) {
2476     // FIXME: diagnostic
2477     Info.CCEDiag(Loc);
2478     return true;
2479   }
2480 
2481   // Does this refer one past the end of some object?
2482   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2483     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2484       << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2485     NoteLValueLocation(Info, Base);
2486   }
2487 
2488   return true;
2489 }
2490 
2491 /// Member pointers are constant expressions unless they point to a
2492 /// non-virtual dllimport member function.
2493 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2494                                                  SourceLocation Loc,
2495                                                  QualType Type,
2496                                                  const APValue &Value,
2497                                                  ConstantExprKind Kind) {
2498   const ValueDecl *Member = Value.getMemberPointerDecl();
2499   const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2500   if (!FD)
2501     return true;
2502   if (FD->isImmediateFunction()) {
2503     Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2504     Info.Note(FD->getLocation(), diag::note_declared_at);
2505     return false;
2506   }
2507   return isForManglingOnly(Kind) || FD->isVirtual() ||
2508          !FD->hasAttr<DLLImportAttr>();
2509 }
2510 
2511 /// Check that this core constant expression is of literal type, and if not,
2512 /// produce an appropriate diagnostic.
2513 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2514                              const LValue *This = nullptr) {
2515   // The restriction to literal types does not exist in C++23 anymore.
2516   if (Info.getLangOpts().CPlusPlus23)
2517     return true;
2518 
2519   if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2520     return true;
2521 
2522   // C++1y: A constant initializer for an object o [...] may also invoke
2523   // constexpr constructors for o and its subobjects even if those objects
2524   // are of non-literal class types.
2525   //
2526   // C++11 missed this detail for aggregates, so classes like this:
2527   //   struct foo_t { union { int i; volatile int j; } u; };
2528   // are not (obviously) initializable like so:
2529   //   __attribute__((__require_constant_initialization__))
2530   //   static const foo_t x = {{0}};
2531   // because "i" is a subobject with non-literal initialization (due to the
2532   // volatile member of the union). See:
2533   //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2534   // Therefore, we use the C++1y behavior.
2535   if (This && Info.EvaluatingDecl == This->getLValueBase())
2536     return true;
2537 
2538   // Prvalue constant expressions must be of literal types.
2539   if (Info.getLangOpts().CPlusPlus11)
2540     Info.FFDiag(E, diag::note_constexpr_nonliteral)
2541       << E->getType();
2542   else
2543     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2544   return false;
2545 }
2546 
2547 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2548                                   EvalInfo &Info, SourceLocation DiagLoc,
2549                                   QualType Type, const APValue &Value,
2550                                   ConstantExprKind Kind,
2551                                   const FieldDecl *SubobjectDecl,
2552                                   CheckedTemporaries &CheckedTemps) {
2553   if (!Value.hasValue()) {
2554     if (SubobjectDecl) {
2555       Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2556           << /*(name)*/ 1 << SubobjectDecl;
2557       Info.Note(SubobjectDecl->getLocation(),
2558                 diag::note_constexpr_subobject_declared_here);
2559     } else {
2560       Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2561           << /*of type*/ 0 << Type;
2562     }
2563     return false;
2564   }
2565 
2566   // We allow _Atomic(T) to be initialized from anything that T can be
2567   // initialized from.
2568   if (const AtomicType *AT = Type->getAs<AtomicType>())
2569     Type = AT->getValueType();
2570 
2571   // Core issue 1454: For a literal constant expression of array or class type,
2572   // each subobject of its value shall have been initialized by a constant
2573   // expression.
2574   if (Value.isArray()) {
2575     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2576     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2577       if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2578                                  Value.getArrayInitializedElt(I), Kind,
2579                                  SubobjectDecl, CheckedTemps))
2580         return false;
2581     }
2582     if (!Value.hasArrayFiller())
2583       return true;
2584     return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2585                                  Value.getArrayFiller(), Kind, SubobjectDecl,
2586                                  CheckedTemps);
2587   }
2588   if (Value.isUnion() && Value.getUnionField()) {
2589     return CheckEvaluationResult(
2590         CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2591         Value.getUnionValue(), Kind, Value.getUnionField(), CheckedTemps);
2592   }
2593   if (Value.isStruct()) {
2594     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2595     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2596       unsigned BaseIndex = 0;
2597       for (const CXXBaseSpecifier &BS : CD->bases()) {
2598         const APValue &BaseValue = Value.getStructBase(BaseIndex);
2599         if (!BaseValue.hasValue()) {
2600           SourceLocation TypeBeginLoc = BS.getBaseTypeLoc();
2601           Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base)
2602               << BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc());
2603           return false;
2604         }
2605         if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), BaseValue,
2606                                    Kind, /*SubobjectDecl=*/nullptr,
2607                                    CheckedTemps))
2608           return false;
2609         ++BaseIndex;
2610       }
2611     }
2612     for (const auto *I : RD->fields()) {
2613       if (I->isUnnamedBitField())
2614         continue;
2615 
2616       if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2617                                  Value.getStructField(I->getFieldIndex()), Kind,
2618                                  I, CheckedTemps))
2619         return false;
2620     }
2621   }
2622 
2623   if (Value.isLValue() &&
2624       CERK == CheckEvaluationResultKind::ConstantExpression) {
2625     LValue LVal;
2626     LVal.setFrom(Info.Ctx, Value);
2627     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2628                                          CheckedTemps);
2629   }
2630 
2631   if (Value.isMemberPointer() &&
2632       CERK == CheckEvaluationResultKind::ConstantExpression)
2633     return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2634 
2635   // Everything else is fine.
2636   return true;
2637 }
2638 
2639 /// Check that this core constant expression value is a valid value for a
2640 /// constant expression. If not, report an appropriate diagnostic. Does not
2641 /// check that the expression is of literal type.
2642 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2643                                     QualType Type, const APValue &Value,
2644                                     ConstantExprKind Kind) {
2645   // Nothing to check for a constant expression of type 'cv void'.
2646   if (Type->isVoidType())
2647     return true;
2648 
2649   CheckedTemporaries CheckedTemps;
2650   return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2651                                Info, DiagLoc, Type, Value, Kind,
2652                                /*SubobjectDecl=*/nullptr, CheckedTemps);
2653 }
2654 
2655 /// Check that this evaluated value is fully-initialized and can be loaded by
2656 /// an lvalue-to-rvalue conversion.
2657 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2658                                   QualType Type, const APValue &Value) {
2659   CheckedTemporaries CheckedTemps;
2660   return CheckEvaluationResult(
2661       CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2662       ConstantExprKind::Normal, /*SubobjectDecl=*/nullptr, CheckedTemps);
2663 }
2664 
2665 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2666 /// "the allocated storage is deallocated within the evaluation".
2667 static bool CheckMemoryLeaks(EvalInfo &Info) {
2668   if (!Info.HeapAllocs.empty()) {
2669     // We can still fold to a constant despite a compile-time memory leak,
2670     // so long as the heap allocation isn't referenced in the result (we check
2671     // that in CheckConstantExpression).
2672     Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2673                  diag::note_constexpr_memory_leak)
2674         << unsigned(Info.HeapAllocs.size() - 1);
2675   }
2676   return true;
2677 }
2678 
2679 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2680   // A null base expression indicates a null pointer.  These are always
2681   // evaluatable, and they are false unless the offset is zero.
2682   if (!Value.getLValueBase()) {
2683     // TODO: Should a non-null pointer with an offset of zero evaluate to true?
2684     Result = !Value.getLValueOffset().isZero();
2685     return true;
2686   }
2687 
2688   // We have a non-null base.  These are generally known to be true, but if it's
2689   // a weak declaration it can be null at runtime.
2690   Result = true;
2691   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2692   return !Decl || !Decl->isWeak();
2693 }
2694 
2695 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2696   // TODO: This function should produce notes if it fails.
2697   switch (Val.getKind()) {
2698   case APValue::None:
2699   case APValue::Indeterminate:
2700     return false;
2701   case APValue::Int:
2702     Result = Val.getInt().getBoolValue();
2703     return true;
2704   case APValue::FixedPoint:
2705     Result = Val.getFixedPoint().getBoolValue();
2706     return true;
2707   case APValue::Float:
2708     Result = !Val.getFloat().isZero();
2709     return true;
2710   case APValue::ComplexInt:
2711     Result = Val.getComplexIntReal().getBoolValue() ||
2712              Val.getComplexIntImag().getBoolValue();
2713     return true;
2714   case APValue::ComplexFloat:
2715     Result = !Val.getComplexFloatReal().isZero() ||
2716              !Val.getComplexFloatImag().isZero();
2717     return true;
2718   case APValue::LValue:
2719     return EvalPointerValueAsBool(Val, Result);
2720   case APValue::MemberPointer:
2721     if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) {
2722       return false;
2723     }
2724     Result = Val.getMemberPointerDecl();
2725     return true;
2726   case APValue::Vector:
2727   case APValue::Array:
2728   case APValue::Struct:
2729   case APValue::Union:
2730   case APValue::AddrLabelDiff:
2731     return false;
2732   }
2733 
2734   llvm_unreachable("unknown APValue kind");
2735 }
2736 
2737 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2738                                        EvalInfo &Info) {
2739   assert(!E->isValueDependent());
2740   assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2741   APValue Val;
2742   if (!Evaluate(Val, Info, E))
2743     return false;
2744   return HandleConversionToBool(Val, Result);
2745 }
2746 
2747 template<typename T>
2748 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2749                            const T &SrcValue, QualType DestType) {
2750   Info.CCEDiag(E, diag::note_constexpr_overflow)
2751     << SrcValue << DestType;
2752   return Info.noteUndefinedBehavior();
2753 }
2754 
2755 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2756                                  QualType SrcType, const APFloat &Value,
2757                                  QualType DestType, APSInt &Result) {
2758   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2759   // Determine whether we are converting to unsigned or signed.
2760   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2761 
2762   Result = APSInt(DestWidth, !DestSigned);
2763   bool ignored;
2764   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2765       & APFloat::opInvalidOp)
2766     return HandleOverflow(Info, E, Value, DestType);
2767   return true;
2768 }
2769 
2770 /// Get rounding mode to use in evaluation of the specified expression.
2771 ///
2772 /// If rounding mode is unknown at compile time, still try to evaluate the
2773 /// expression. If the result is exact, it does not depend on rounding mode.
2774 /// So return "tonearest" mode instead of "dynamic".
2775 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
2776   llvm::RoundingMode RM =
2777       E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2778   if (RM == llvm::RoundingMode::Dynamic)
2779     RM = llvm::RoundingMode::NearestTiesToEven;
2780   return RM;
2781 }
2782 
2783 /// Check if the given evaluation result is allowed for constant evaluation.
2784 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2785                                      APFloat::opStatus St) {
2786   // In a constant context, assume that any dynamic rounding mode or FP
2787   // exception state matches the default floating-point environment.
2788   if (Info.InConstantContext)
2789     return true;
2790 
2791   FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2792   if ((St & APFloat::opInexact) &&
2793       FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2794     // Inexact result means that it depends on rounding mode. If the requested
2795     // mode is dynamic, the evaluation cannot be made in compile time.
2796     Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2797     return false;
2798   }
2799 
2800   if ((St != APFloat::opOK) &&
2801       (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2802        FPO.getExceptionMode() != LangOptions::FPE_Ignore ||
2803        FPO.getAllowFEnvAccess())) {
2804     Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2805     return false;
2806   }
2807 
2808   if ((St & APFloat::opStatus::opInvalidOp) &&
2809       FPO.getExceptionMode() != LangOptions::FPE_Ignore) {
2810     // There is no usefully definable result.
2811     Info.FFDiag(E);
2812     return false;
2813   }
2814 
2815   // FIXME: if:
2816   // - evaluation triggered other FP exception, and
2817   // - exception mode is not "ignore", and
2818   // - the expression being evaluated is not a part of global variable
2819   //   initializer,
2820   // the evaluation probably need to be rejected.
2821   return true;
2822 }
2823 
2824 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2825                                    QualType SrcType, QualType DestType,
2826                                    APFloat &Result) {
2827   assert((isa<CastExpr>(E) || isa<CompoundAssignOperator>(E) ||
2828           isa<ConvertVectorExpr>(E)) &&
2829          "HandleFloatToFloatCast has been checked with only CastExpr, "
2830          "CompoundAssignOperator and ConvertVectorExpr. Please either validate "
2831          "the new expression or address the root cause of this usage.");
2832   llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2833   APFloat::opStatus St;
2834   APFloat Value = Result;
2835   bool ignored;
2836   St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2837   return checkFloatingPointResult(Info, E, St);
2838 }
2839 
2840 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2841                                  QualType DestType, QualType SrcType,
2842                                  const APSInt &Value) {
2843   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2844   // Figure out if this is a truncate, extend or noop cast.
2845   // If the input is signed, do a sign extend, noop, or truncate.
2846   APSInt Result = Value.extOrTrunc(DestWidth);
2847   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2848   if (DestType->isBooleanType())
2849     Result = Value.getBoolValue();
2850   return Result;
2851 }
2852 
2853 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2854                                  const FPOptions FPO,
2855                                  QualType SrcType, const APSInt &Value,
2856                                  QualType DestType, APFloat &Result) {
2857   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2858   llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2859   APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), RM);
2860   return checkFloatingPointResult(Info, E, St);
2861 }
2862 
2863 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2864                                   APValue &Value, const FieldDecl *FD) {
2865   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2866 
2867   if (!Value.isInt()) {
2868     // Trying to store a pointer-cast-to-integer into a bitfield.
2869     // FIXME: In this case, we should provide the diagnostic for casting
2870     // a pointer to an integer.
2871     assert(Value.isLValue() && "integral value neither int nor lvalue?");
2872     Info.FFDiag(E);
2873     return false;
2874   }
2875 
2876   APSInt &Int = Value.getInt();
2877   unsigned OldBitWidth = Int.getBitWidth();
2878   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2879   if (NewBitWidth < OldBitWidth)
2880     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2881   return true;
2882 }
2883 
2884 /// Perform the given integer operation, which is known to need at most BitWidth
2885 /// bits, and check for overflow in the original type (if that type was not an
2886 /// unsigned type).
2887 template<typename Operation>
2888 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2889                                  const APSInt &LHS, const APSInt &RHS,
2890                                  unsigned BitWidth, Operation Op,
2891                                  APSInt &Result) {
2892   if (LHS.isUnsigned()) {
2893     Result = Op(LHS, RHS);
2894     return true;
2895   }
2896 
2897   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2898   Result = Value.trunc(LHS.getBitWidth());
2899   if (Result.extend(BitWidth) != Value) {
2900     if (Info.checkingForUndefinedBehavior())
2901       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2902                                        diag::warn_integer_constant_overflow)
2903           << toString(Result, 10, Result.isSigned(), /*formatAsCLiteral=*/false,
2904                       /*UpperCase=*/true, /*InsertSeparators=*/true)
2905           << E->getType() << E->getSourceRange();
2906     return HandleOverflow(Info, E, Value, E->getType());
2907   }
2908   return true;
2909 }
2910 
2911 /// Perform the given binary integer operation.
2912 static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E,
2913                               const APSInt &LHS, BinaryOperatorKind Opcode,
2914                               APSInt RHS, APSInt &Result) {
2915   bool HandleOverflowResult = true;
2916   switch (Opcode) {
2917   default:
2918     Info.FFDiag(E);
2919     return false;
2920   case BO_Mul:
2921     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2922                                 std::multiplies<APSInt>(), Result);
2923   case BO_Add:
2924     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2925                                 std::plus<APSInt>(), Result);
2926   case BO_Sub:
2927     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2928                                 std::minus<APSInt>(), Result);
2929   case BO_And: Result = LHS & RHS; return true;
2930   case BO_Xor: Result = LHS ^ RHS; return true;
2931   case BO_Or:  Result = LHS | RHS; return true;
2932   case BO_Div:
2933   case BO_Rem:
2934     if (RHS == 0) {
2935       Info.FFDiag(E, diag::note_expr_divide_by_zero)
2936           << E->getRHS()->getSourceRange();
2937       return false;
2938     }
2939     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2940     // this operation and gives the two's complement result.
2941     if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2942         LHS.isMinSignedValue())
2943       HandleOverflowResult = HandleOverflow(
2944           Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
2945     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2946     return HandleOverflowResult;
2947   case BO_Shl: {
2948     if (Info.getLangOpts().OpenCL)
2949       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2950       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2951                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2952                     RHS.isUnsigned());
2953     else if (RHS.isSigned() && RHS.isNegative()) {
2954       // During constant-folding, a negative shift is an opposite shift. Such
2955       // a shift is not a constant expression.
2956       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2957       if (!Info.noteUndefinedBehavior())
2958         return false;
2959       RHS = -RHS;
2960       goto shift_right;
2961     }
2962   shift_left:
2963     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2964     // the shifted type.
2965     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2966     if (SA != RHS) {
2967       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2968         << RHS << E->getType() << LHS.getBitWidth();
2969       if (!Info.noteUndefinedBehavior())
2970         return false;
2971     } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2972       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2973       // operand, and must not overflow the corresponding unsigned type.
2974       // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2975       // E1 x 2^E2 module 2^N.
2976       if (LHS.isNegative()) {
2977         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2978         if (!Info.noteUndefinedBehavior())
2979           return false;
2980       } else if (LHS.countl_zero() < SA) {
2981         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2982         if (!Info.noteUndefinedBehavior())
2983           return false;
2984       }
2985     }
2986     Result = LHS << SA;
2987     return true;
2988   }
2989   case BO_Shr: {
2990     if (Info.getLangOpts().OpenCL)
2991       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2992       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2993                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2994                     RHS.isUnsigned());
2995     else if (RHS.isSigned() && RHS.isNegative()) {
2996       // During constant-folding, a negative shift is an opposite shift. Such a
2997       // shift is not a constant expression.
2998       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2999       if (!Info.noteUndefinedBehavior())
3000         return false;
3001       RHS = -RHS;
3002       goto shift_left;
3003     }
3004   shift_right:
3005     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
3006     // shifted type.
3007     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
3008     if (SA != RHS) {
3009       Info.CCEDiag(E, diag::note_constexpr_large_shift)
3010         << RHS << E->getType() << LHS.getBitWidth();
3011       if (!Info.noteUndefinedBehavior())
3012         return false;
3013     }
3014 
3015     Result = LHS >> SA;
3016     return true;
3017   }
3018 
3019   case BO_LT: Result = LHS < RHS; return true;
3020   case BO_GT: Result = LHS > RHS; return true;
3021   case BO_LE: Result = LHS <= RHS; return true;
3022   case BO_GE: Result = LHS >= RHS; return true;
3023   case BO_EQ: Result = LHS == RHS; return true;
3024   case BO_NE: Result = LHS != RHS; return true;
3025   case BO_Cmp:
3026     llvm_unreachable("BO_Cmp should be handled elsewhere");
3027   }
3028 }
3029 
3030 /// Perform the given binary floating-point operation, in-place, on LHS.
3031 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
3032                                   APFloat &LHS, BinaryOperatorKind Opcode,
3033                                   const APFloat &RHS) {
3034   llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
3035   APFloat::opStatus St;
3036   switch (Opcode) {
3037   default:
3038     Info.FFDiag(E);
3039     return false;
3040   case BO_Mul:
3041     St = LHS.multiply(RHS, RM);
3042     break;
3043   case BO_Add:
3044     St = LHS.add(RHS, RM);
3045     break;
3046   case BO_Sub:
3047     St = LHS.subtract(RHS, RM);
3048     break;
3049   case BO_Div:
3050     // [expr.mul]p4:
3051     //   If the second operand of / or % is zero the behavior is undefined.
3052     if (RHS.isZero())
3053       Info.CCEDiag(E, diag::note_expr_divide_by_zero);
3054     St = LHS.divide(RHS, RM);
3055     break;
3056   }
3057 
3058   // [expr.pre]p4:
3059   //   If during the evaluation of an expression, the result is not
3060   //   mathematically defined [...], the behavior is undefined.
3061   // FIXME: C++ rules require us to not conform to IEEE 754 here.
3062   if (LHS.isNaN()) {
3063     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
3064     return Info.noteUndefinedBehavior();
3065   }
3066 
3067   return checkFloatingPointResult(Info, E, St);
3068 }
3069 
3070 static bool handleLogicalOpForVector(const APInt &LHSValue,
3071                                      BinaryOperatorKind Opcode,
3072                                      const APInt &RHSValue, APInt &Result) {
3073   bool LHS = (LHSValue != 0);
3074   bool RHS = (RHSValue != 0);
3075 
3076   if (Opcode == BO_LAnd)
3077     Result = LHS && RHS;
3078   else
3079     Result = LHS || RHS;
3080   return true;
3081 }
3082 static bool handleLogicalOpForVector(const APFloat &LHSValue,
3083                                      BinaryOperatorKind Opcode,
3084                                      const APFloat &RHSValue, APInt &Result) {
3085   bool LHS = !LHSValue.isZero();
3086   bool RHS = !RHSValue.isZero();
3087 
3088   if (Opcode == BO_LAnd)
3089     Result = LHS && RHS;
3090   else
3091     Result = LHS || RHS;
3092   return true;
3093 }
3094 
3095 static bool handleLogicalOpForVector(const APValue &LHSValue,
3096                                      BinaryOperatorKind Opcode,
3097                                      const APValue &RHSValue, APInt &Result) {
3098   // The result is always an int type, however operands match the first.
3099   if (LHSValue.getKind() == APValue::Int)
3100     return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
3101                                     RHSValue.getInt(), Result);
3102   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3103   return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
3104                                   RHSValue.getFloat(), Result);
3105 }
3106 
3107 template <typename APTy>
3108 static bool
3109 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
3110                                const APTy &RHSValue, APInt &Result) {
3111   switch (Opcode) {
3112   default:
3113     llvm_unreachable("unsupported binary operator");
3114   case BO_EQ:
3115     Result = (LHSValue == RHSValue);
3116     break;
3117   case BO_NE:
3118     Result = (LHSValue != RHSValue);
3119     break;
3120   case BO_LT:
3121     Result = (LHSValue < RHSValue);
3122     break;
3123   case BO_GT:
3124     Result = (LHSValue > RHSValue);
3125     break;
3126   case BO_LE:
3127     Result = (LHSValue <= RHSValue);
3128     break;
3129   case BO_GE:
3130     Result = (LHSValue >= RHSValue);
3131     break;
3132   }
3133 
3134   // The boolean operations on these vector types use an instruction that
3135   // results in a mask of '-1' for the 'truth' value.  Ensure that we negate 1
3136   // to -1 to make sure that we produce the correct value.
3137   Result.negate();
3138 
3139   return true;
3140 }
3141 
3142 static bool handleCompareOpForVector(const APValue &LHSValue,
3143                                      BinaryOperatorKind Opcode,
3144                                      const APValue &RHSValue, APInt &Result) {
3145   // The result is always an int type, however operands match the first.
3146   if (LHSValue.getKind() == APValue::Int)
3147     return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
3148                                           RHSValue.getInt(), Result);
3149   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3150   return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
3151                                         RHSValue.getFloat(), Result);
3152 }
3153 
3154 // Perform binary operations for vector types, in place on the LHS.
3155 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
3156                                     BinaryOperatorKind Opcode,
3157                                     APValue &LHSValue,
3158                                     const APValue &RHSValue) {
3159   assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
3160          "Operation not supported on vector types");
3161 
3162   const auto *VT = E->getType()->castAs<VectorType>();
3163   unsigned NumElements = VT->getNumElements();
3164   QualType EltTy = VT->getElementType();
3165 
3166   // In the cases (typically C as I've observed) where we aren't evaluating
3167   // constexpr but are checking for cases where the LHS isn't yet evaluatable,
3168   // just give up.
3169   if (!LHSValue.isVector()) {
3170     assert(LHSValue.isLValue() &&
3171            "A vector result that isn't a vector OR uncalculated LValue");
3172     Info.FFDiag(E);
3173     return false;
3174   }
3175 
3176   assert(LHSValue.getVectorLength() == NumElements &&
3177          RHSValue.getVectorLength() == NumElements && "Different vector sizes");
3178 
3179   SmallVector<APValue, 4> ResultElements;
3180 
3181   for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
3182     APValue LHSElt = LHSValue.getVectorElt(EltNum);
3183     APValue RHSElt = RHSValue.getVectorElt(EltNum);
3184 
3185     if (EltTy->isIntegerType()) {
3186       APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3187                        EltTy->isUnsignedIntegerType()};
3188       bool Success = true;
3189 
3190       if (BinaryOperator::isLogicalOp(Opcode))
3191         Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3192       else if (BinaryOperator::isComparisonOp(Opcode))
3193         Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3194       else
3195         Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3196                                     RHSElt.getInt(), EltResult);
3197 
3198       if (!Success) {
3199         Info.FFDiag(E);
3200         return false;
3201       }
3202       ResultElements.emplace_back(EltResult);
3203 
3204     } else if (EltTy->isFloatingType()) {
3205       assert(LHSElt.getKind() == APValue::Float &&
3206              RHSElt.getKind() == APValue::Float &&
3207              "Mismatched LHS/RHS/Result Type");
3208       APFloat LHSFloat = LHSElt.getFloat();
3209 
3210       if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3211                                  RHSElt.getFloat())) {
3212         Info.FFDiag(E);
3213         return false;
3214       }
3215 
3216       ResultElements.emplace_back(LHSFloat);
3217     }
3218   }
3219 
3220   LHSValue = APValue(ResultElements.data(), ResultElements.size());
3221   return true;
3222 }
3223 
3224 /// Cast an lvalue referring to a base subobject to a derived class, by
3225 /// truncating the lvalue's path to the given length.
3226 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3227                                const RecordDecl *TruncatedType,
3228                                unsigned TruncatedElements) {
3229   SubobjectDesignator &D = Result.Designator;
3230 
3231   // Check we actually point to a derived class object.
3232   if (TruncatedElements == D.Entries.size())
3233     return true;
3234   assert(TruncatedElements >= D.MostDerivedPathLength &&
3235          "not casting to a derived class");
3236   if (!Result.checkSubobject(Info, E, CSK_Derived))
3237     return false;
3238 
3239   // Truncate the path to the subobject, and remove any derived-to-base offsets.
3240   const RecordDecl *RD = TruncatedType;
3241   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3242     if (RD->isInvalidDecl()) return false;
3243     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3244     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3245     if (isVirtualBaseClass(D.Entries[I]))
3246       Result.Offset -= Layout.getVBaseClassOffset(Base);
3247     else
3248       Result.Offset -= Layout.getBaseClassOffset(Base);
3249     RD = Base;
3250   }
3251   D.Entries.resize(TruncatedElements);
3252   return true;
3253 }
3254 
3255 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3256                                    const CXXRecordDecl *Derived,
3257                                    const CXXRecordDecl *Base,
3258                                    const ASTRecordLayout *RL = nullptr) {
3259   if (!RL) {
3260     if (Derived->isInvalidDecl()) return false;
3261     RL = &Info.Ctx.getASTRecordLayout(Derived);
3262   }
3263 
3264   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3265   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3266   return true;
3267 }
3268 
3269 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3270                              const CXXRecordDecl *DerivedDecl,
3271                              const CXXBaseSpecifier *Base) {
3272   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3273 
3274   if (!Base->isVirtual())
3275     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3276 
3277   SubobjectDesignator &D = Obj.Designator;
3278   if (D.Invalid)
3279     return false;
3280 
3281   // Extract most-derived object and corresponding type.
3282   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3283   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3284     return false;
3285 
3286   // Find the virtual base class.
3287   if (DerivedDecl->isInvalidDecl()) return false;
3288   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3289   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3290   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3291   return true;
3292 }
3293 
3294 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3295                                  QualType Type, LValue &Result) {
3296   for (CastExpr::path_const_iterator PathI = E->path_begin(),
3297                                      PathE = E->path_end();
3298        PathI != PathE; ++PathI) {
3299     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3300                           *PathI))
3301       return false;
3302     Type = (*PathI)->getType();
3303   }
3304   return true;
3305 }
3306 
3307 /// Cast an lvalue referring to a derived class to a known base subobject.
3308 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3309                             const CXXRecordDecl *DerivedRD,
3310                             const CXXRecordDecl *BaseRD) {
3311   CXXBasePaths Paths(/*FindAmbiguities=*/false,
3312                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
3313   if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3314     llvm_unreachable("Class must be derived from the passed in base class!");
3315 
3316   for (CXXBasePathElement &Elem : Paths.front())
3317     if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3318       return false;
3319   return true;
3320 }
3321 
3322 /// Update LVal to refer to the given field, which must be a member of the type
3323 /// currently described by LVal.
3324 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3325                                const FieldDecl *FD,
3326                                const ASTRecordLayout *RL = nullptr) {
3327   if (!RL) {
3328     if (FD->getParent()->isInvalidDecl()) return false;
3329     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3330   }
3331 
3332   unsigned I = FD->getFieldIndex();
3333   LVal.addDecl(Info, E, FD);
3334   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3335   return true;
3336 }
3337 
3338 /// Update LVal to refer to the given indirect field.
3339 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3340                                        LValue &LVal,
3341                                        const IndirectFieldDecl *IFD) {
3342   for (const auto *C : IFD->chain())
3343     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3344       return false;
3345   return true;
3346 }
3347 
3348 enum class SizeOfType {
3349   SizeOf,
3350   DataSizeOf,
3351 };
3352 
3353 /// Get the size of the given type in char units.
3354 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type,
3355                          CharUnits &Size, SizeOfType SOT = SizeOfType::SizeOf) {
3356   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3357   // extension.
3358   if (Type->isVoidType() || Type->isFunctionType()) {
3359     Size = CharUnits::One();
3360     return true;
3361   }
3362 
3363   if (Type->isDependentType()) {
3364     Info.FFDiag(Loc);
3365     return false;
3366   }
3367 
3368   if (!Type->isConstantSizeType()) {
3369     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3370     // FIXME: Better diagnostic.
3371     Info.FFDiag(Loc);
3372     return false;
3373   }
3374 
3375   if (SOT == SizeOfType::SizeOf)
3376     Size = Info.Ctx.getTypeSizeInChars(Type);
3377   else
3378     Size = Info.Ctx.getTypeInfoDataSizeInChars(Type).Width;
3379   return true;
3380 }
3381 
3382 /// Update a pointer value to model pointer arithmetic.
3383 /// \param Info - Information about the ongoing evaluation.
3384 /// \param E - The expression being evaluated, for diagnostic purposes.
3385 /// \param LVal - The pointer value to be updated.
3386 /// \param EltTy - The pointee type represented by LVal.
3387 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3388 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3389                                         LValue &LVal, QualType EltTy,
3390                                         APSInt Adjustment) {
3391   CharUnits SizeOfPointee;
3392   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3393     return false;
3394 
3395   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3396   return true;
3397 }
3398 
3399 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3400                                         LValue &LVal, QualType EltTy,
3401                                         int64_t Adjustment) {
3402   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3403                                      APSInt::get(Adjustment));
3404 }
3405 
3406 /// Update an lvalue to refer to a component of a complex number.
3407 /// \param Info - Information about the ongoing evaluation.
3408 /// \param LVal - The lvalue to be updated.
3409 /// \param EltTy - The complex number's component type.
3410 /// \param Imag - False for the real component, true for the imaginary.
3411 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3412                                        LValue &LVal, QualType EltTy,
3413                                        bool Imag) {
3414   if (Imag) {
3415     CharUnits SizeOfComponent;
3416     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3417       return false;
3418     LVal.Offset += SizeOfComponent;
3419   }
3420   LVal.addComplex(Info, E, EltTy, Imag);
3421   return true;
3422 }
3423 
3424 static bool HandleLValueVectorElement(EvalInfo &Info, const Expr *E,
3425                                       LValue &LVal, QualType EltTy,
3426                                       uint64_t Size, uint64_t Idx) {
3427   if (Idx) {
3428     CharUnits SizeOfElement;
3429     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfElement))
3430       return false;
3431     LVal.Offset += SizeOfElement * Idx;
3432   }
3433   LVal.addVectorElement(Info, E, EltTy, Size, Idx);
3434   return true;
3435 }
3436 
3437 /// Try to evaluate the initializer for a variable declaration.
3438 ///
3439 /// \param Info   Information about the ongoing evaluation.
3440 /// \param E      An expression to be used when printing diagnostics.
3441 /// \param VD     The variable whose initializer should be obtained.
3442 /// \param Version The version of the variable within the frame.
3443 /// \param Frame  The frame in which the variable was created. Must be null
3444 ///               if this variable is not local to the evaluation.
3445 /// \param Result Filled in with a pointer to the value of the variable.
3446 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3447                                 const VarDecl *VD, CallStackFrame *Frame,
3448                                 unsigned Version, APValue *&Result) {
3449   APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3450 
3451   // If this is a local variable, dig out its value.
3452   if (Frame) {
3453     Result = Frame->getTemporary(VD, Version);
3454     if (Result)
3455       return true;
3456 
3457     if (!isa<ParmVarDecl>(VD)) {
3458       // Assume variables referenced within a lambda's call operator that were
3459       // not declared within the call operator are captures and during checking
3460       // of a potential constant expression, assume they are unknown constant
3461       // expressions.
3462       assert(isLambdaCallOperator(Frame->Callee) &&
3463              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3464              "missing value for local variable");
3465       if (Info.checkingPotentialConstantExpression())
3466         return false;
3467       // FIXME: This diagnostic is bogus; we do support captures. Is this code
3468       // still reachable at all?
3469       Info.FFDiag(E->getBeginLoc(),
3470                   diag::note_unimplemented_constexpr_lambda_feature_ast)
3471           << "captures not currently allowed";
3472       return false;
3473     }
3474   }
3475 
3476   // If we're currently evaluating the initializer of this declaration, use that
3477   // in-flight value.
3478   if (Info.EvaluatingDecl == Base) {
3479     Result = Info.EvaluatingDeclValue;
3480     return true;
3481   }
3482 
3483   if (isa<ParmVarDecl>(VD)) {
3484     // Assume parameters of a potential constant expression are usable in
3485     // constant expressions.
3486     if (!Info.checkingPotentialConstantExpression() ||
3487         !Info.CurrentCall->Callee ||
3488         !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3489       if (Info.getLangOpts().CPlusPlus11) {
3490         Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3491             << VD;
3492         NoteLValueLocation(Info, Base);
3493       } else {
3494         Info.FFDiag(E);
3495       }
3496     }
3497     return false;
3498   }
3499 
3500   if (E->isValueDependent())
3501     return false;
3502 
3503   // Dig out the initializer, and use the declaration which it's attached to.
3504   // FIXME: We should eventually check whether the variable has a reachable
3505   // initializing declaration.
3506   const Expr *Init = VD->getAnyInitializer(VD);
3507   if (!Init) {
3508     // Don't diagnose during potential constant expression checking; an
3509     // initializer might be added later.
3510     if (!Info.checkingPotentialConstantExpression()) {
3511       Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3512         << VD;
3513       NoteLValueLocation(Info, Base);
3514     }
3515     return false;
3516   }
3517 
3518   if (Init->isValueDependent()) {
3519     // The DeclRefExpr is not value-dependent, but the variable it refers to
3520     // has a value-dependent initializer. This should only happen in
3521     // constant-folding cases, where the variable is not actually of a suitable
3522     // type for use in a constant expression (otherwise the DeclRefExpr would
3523     // have been value-dependent too), so diagnose that.
3524     assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3525     if (!Info.checkingPotentialConstantExpression()) {
3526       Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3527                          ? diag::note_constexpr_ltor_non_constexpr
3528                          : diag::note_constexpr_ltor_non_integral, 1)
3529           << VD << VD->getType();
3530       NoteLValueLocation(Info, Base);
3531     }
3532     return false;
3533   }
3534 
3535   // Check that we can fold the initializer. In C++, we will have already done
3536   // this in the cases where it matters for conformance.
3537   if (!VD->evaluateValue()) {
3538     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3539     NoteLValueLocation(Info, Base);
3540     return false;
3541   }
3542 
3543   // Check that the variable is actually usable in constant expressions. For a
3544   // const integral variable or a reference, we might have a non-constant
3545   // initializer that we can nonetheless evaluate the initializer for. Such
3546   // variables are not usable in constant expressions. In C++98, the
3547   // initializer also syntactically needs to be an ICE.
3548   //
3549   // FIXME: We don't diagnose cases that aren't potentially usable in constant
3550   // expressions here; doing so would regress diagnostics for things like
3551   // reading from a volatile constexpr variable.
3552   if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3553        VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||
3554       ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3555        !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3556     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3557     NoteLValueLocation(Info, Base);
3558   }
3559 
3560   // Never use the initializer of a weak variable, not even for constant
3561   // folding. We can't be sure that this is the definition that will be used.
3562   if (VD->isWeak()) {
3563     Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3564     NoteLValueLocation(Info, Base);
3565     return false;
3566   }
3567 
3568   Result = VD->getEvaluatedValue();
3569   return true;
3570 }
3571 
3572 /// Get the base index of the given base class within an APValue representing
3573 /// the given derived class.
3574 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3575                              const CXXRecordDecl *Base) {
3576   Base = Base->getCanonicalDecl();
3577   unsigned Index = 0;
3578   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3579          E = Derived->bases_end(); I != E; ++I, ++Index) {
3580     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3581       return Index;
3582   }
3583 
3584   llvm_unreachable("base class missing from derived class's bases list");
3585 }
3586 
3587 /// Extract the value of a character from a string literal.
3588 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3589                                             uint64_t Index) {
3590   assert(!isa<SourceLocExpr>(Lit) &&
3591          "SourceLocExpr should have already been converted to a StringLiteral");
3592 
3593   // FIXME: Support MakeStringConstant
3594   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3595     std::string Str;
3596     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3597     assert(Index <= Str.size() && "Index too large");
3598     return APSInt::getUnsigned(Str.c_str()[Index]);
3599   }
3600 
3601   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3602     Lit = PE->getFunctionName();
3603   const StringLiteral *S = cast<StringLiteral>(Lit);
3604   const ConstantArrayType *CAT =
3605       Info.Ctx.getAsConstantArrayType(S->getType());
3606   assert(CAT && "string literal isn't an array");
3607   QualType CharType = CAT->getElementType();
3608   assert(CharType->isIntegerType() && "unexpected character type");
3609   APSInt Value(Info.Ctx.getTypeSize(CharType),
3610                CharType->isUnsignedIntegerType());
3611   if (Index < S->getLength())
3612     Value = S->getCodeUnit(Index);
3613   return Value;
3614 }
3615 
3616 // Expand a string literal into an array of characters.
3617 //
3618 // FIXME: This is inefficient; we should probably introduce something similar
3619 // to the LLVM ConstantDataArray to make this cheaper.
3620 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3621                                 APValue &Result,
3622                                 QualType AllocType = QualType()) {
3623   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3624       AllocType.isNull() ? S->getType() : AllocType);
3625   assert(CAT && "string literal isn't an array");
3626   QualType CharType = CAT->getElementType();
3627   assert(CharType->isIntegerType() && "unexpected character type");
3628 
3629   unsigned Elts = CAT->getZExtSize();
3630   Result = APValue(APValue::UninitArray(),
3631                    std::min(S->getLength(), Elts), Elts);
3632   APSInt Value(Info.Ctx.getTypeSize(CharType),
3633                CharType->isUnsignedIntegerType());
3634   if (Result.hasArrayFiller())
3635     Result.getArrayFiller() = APValue(Value);
3636   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3637     Value = S->getCodeUnit(I);
3638     Result.getArrayInitializedElt(I) = APValue(Value);
3639   }
3640 }
3641 
3642 // Expand an array so that it has more than Index filled elements.
3643 static void expandArray(APValue &Array, unsigned Index) {
3644   unsigned Size = Array.getArraySize();
3645   assert(Index < Size);
3646 
3647   // Always at least double the number of elements for which we store a value.
3648   unsigned OldElts = Array.getArrayInitializedElts();
3649   unsigned NewElts = std::max(Index+1, OldElts * 2);
3650   NewElts = std::min(Size, std::max(NewElts, 8u));
3651 
3652   // Copy the data across.
3653   APValue NewValue(APValue::UninitArray(), NewElts, Size);
3654   for (unsigned I = 0; I != OldElts; ++I)
3655     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3656   for (unsigned I = OldElts; I != NewElts; ++I)
3657     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3658   if (NewValue.hasArrayFiller())
3659     NewValue.getArrayFiller() = Array.getArrayFiller();
3660   Array.swap(NewValue);
3661 }
3662 
3663 /// Determine whether a type would actually be read by an lvalue-to-rvalue
3664 /// conversion. If it's of class type, we may assume that the copy operation
3665 /// is trivial. Note that this is never true for a union type with fields
3666 /// (because the copy always "reads" the active member) and always true for
3667 /// a non-class type.
3668 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3669 static bool isReadByLvalueToRvalueConversion(QualType T) {
3670   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3671   return !RD || isReadByLvalueToRvalueConversion(RD);
3672 }
3673 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3674   // FIXME: A trivial copy of a union copies the object representation, even if
3675   // the union is empty.
3676   if (RD->isUnion())
3677     return !RD->field_empty();
3678   if (RD->isEmpty())
3679     return false;
3680 
3681   for (auto *Field : RD->fields())
3682     if (!Field->isUnnamedBitField() &&
3683         isReadByLvalueToRvalueConversion(Field->getType()))
3684       return true;
3685 
3686   for (auto &BaseSpec : RD->bases())
3687     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3688       return true;
3689 
3690   return false;
3691 }
3692 
3693 /// Diagnose an attempt to read from any unreadable field within the specified
3694 /// type, which might be a class type.
3695 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3696                                   QualType T) {
3697   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3698   if (!RD)
3699     return false;
3700 
3701   if (!RD->hasMutableFields())
3702     return false;
3703 
3704   for (auto *Field : RD->fields()) {
3705     // If we're actually going to read this field in some way, then it can't
3706     // be mutable. If we're in a union, then assigning to a mutable field
3707     // (even an empty one) can change the active member, so that's not OK.
3708     // FIXME: Add core issue number for the union case.
3709     if (Field->isMutable() &&
3710         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3711       Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3712       Info.Note(Field->getLocation(), diag::note_declared_at);
3713       return true;
3714     }
3715 
3716     if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3717       return true;
3718   }
3719 
3720   for (auto &BaseSpec : RD->bases())
3721     if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3722       return true;
3723 
3724   // All mutable fields were empty, and thus not actually read.
3725   return false;
3726 }
3727 
3728 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3729                                         APValue::LValueBase Base,
3730                                         bool MutableSubobject = false) {
3731   // A temporary or transient heap allocation we created.
3732   if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3733     return true;
3734 
3735   switch (Info.IsEvaluatingDecl) {
3736   case EvalInfo::EvaluatingDeclKind::None:
3737     return false;
3738 
3739   case EvalInfo::EvaluatingDeclKind::Ctor:
3740     // The variable whose initializer we're evaluating.
3741     if (Info.EvaluatingDecl == Base)
3742       return true;
3743 
3744     // A temporary lifetime-extended by the variable whose initializer we're
3745     // evaluating.
3746     if (auto *BaseE = Base.dyn_cast<const Expr *>())
3747       if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3748         return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3749     return false;
3750 
3751   case EvalInfo::EvaluatingDeclKind::Dtor:
3752     // C++2a [expr.const]p6:
3753     //   [during constant destruction] the lifetime of a and its non-mutable
3754     //   subobjects (but not its mutable subobjects) [are] considered to start
3755     //   within e.
3756     if (MutableSubobject || Base != Info.EvaluatingDecl)
3757       return false;
3758     // FIXME: We can meaningfully extend this to cover non-const objects, but
3759     // we will need special handling: we should be able to access only
3760     // subobjects of such objects that are themselves declared const.
3761     QualType T = getType(Base);
3762     return T.isConstQualified() || T->isReferenceType();
3763   }
3764 
3765   llvm_unreachable("unknown evaluating decl kind");
3766 }
3767 
3768 static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT,
3769                            SourceLocation CallLoc = {}) {
3770   return Info.CheckArraySize(
3771       CAT->getSizeExpr() ? CAT->getSizeExpr()->getBeginLoc() : CallLoc,
3772       CAT->getNumAddressingBits(Info.Ctx), CAT->getZExtSize(),
3773       /*Diag=*/true);
3774 }
3775 
3776 namespace {
3777 /// A handle to a complete object (an object that is not a subobject of
3778 /// another object).
3779 struct CompleteObject {
3780   /// The identity of the object.
3781   APValue::LValueBase Base;
3782   /// The value of the complete object.
3783   APValue *Value;
3784   /// The type of the complete object.
3785   QualType Type;
3786 
3787   CompleteObject() : Value(nullptr) {}
3788   CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3789       : Base(Base), Value(Value), Type(Type) {}
3790 
3791   bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3792     // If this isn't a "real" access (eg, if it's just accessing the type
3793     // info), allow it. We assume the type doesn't change dynamically for
3794     // subobjects of constexpr objects (even though we'd hit UB here if it
3795     // did). FIXME: Is this right?
3796     if (!isAnyAccess(AK))
3797       return true;
3798 
3799     // In C++14 onwards, it is permitted to read a mutable member whose
3800     // lifetime began within the evaluation.
3801     // FIXME: Should we also allow this in C++11?
3802     if (!Info.getLangOpts().CPlusPlus14 &&
3803         AK != AccessKinds::AK_IsWithinLifetime)
3804       return false;
3805     return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3806   }
3807 
3808   explicit operator bool() const { return !Type.isNull(); }
3809 };
3810 } // end anonymous namespace
3811 
3812 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3813                                  bool IsMutable = false) {
3814   // C++ [basic.type.qualifier]p1:
3815   // - A const object is an object of type const T or a non-mutable subobject
3816   //   of a const object.
3817   if (ObjType.isConstQualified() && !IsMutable)
3818     SubobjType.addConst();
3819   // - A volatile object is an object of type const T or a subobject of a
3820   //   volatile object.
3821   if (ObjType.isVolatileQualified())
3822     SubobjType.addVolatile();
3823   return SubobjType;
3824 }
3825 
3826 /// Find the designated sub-object of an rvalue.
3827 template <typename SubobjectHandler>
3828 static typename SubobjectHandler::result_type
3829 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3830               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3831   if (Sub.Invalid)
3832     // A diagnostic will have already been produced.
3833     return handler.failed();
3834   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3835     if (Info.getLangOpts().CPlusPlus11)
3836       Info.FFDiag(E, Sub.isOnePastTheEnd()
3837                          ? diag::note_constexpr_access_past_end
3838                          : diag::note_constexpr_access_unsized_array)
3839           << handler.AccessKind;
3840     else
3841       Info.FFDiag(E);
3842     return handler.failed();
3843   }
3844 
3845   APValue *O = Obj.Value;
3846   QualType ObjType = Obj.Type;
3847   const FieldDecl *LastField = nullptr;
3848   const FieldDecl *VolatileField = nullptr;
3849 
3850   // Walk the designator's path to find the subobject.
3851   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3852     // Reading an indeterminate value is undefined, but assigning over one is OK.
3853     if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3854         (O->isIndeterminate() &&
3855          !isValidIndeterminateAccess(handler.AccessKind))) {
3856       // Object has ended lifetime.
3857       // If I is non-zero, some subobject (member or array element) of a
3858       // complete object has ended its lifetime, so this is valid for
3859       // IsWithinLifetime, resulting in false.
3860       if (I != 0 && handler.AccessKind == AK_IsWithinLifetime)
3861         return false;
3862       if (!Info.checkingPotentialConstantExpression())
3863         Info.FFDiag(E, diag::note_constexpr_access_uninit)
3864             << handler.AccessKind << O->isIndeterminate()
3865             << E->getSourceRange();
3866       return handler.failed();
3867     }
3868 
3869     // C++ [class.ctor]p5, C++ [class.dtor]p5:
3870     //    const and volatile semantics are not applied on an object under
3871     //    {con,de}struction.
3872     if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3873         ObjType->isRecordType() &&
3874         Info.isEvaluatingCtorDtor(
3875             Obj.Base,
3876             llvm::ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
3877             ConstructionPhase::None) {
3878       ObjType = Info.Ctx.getCanonicalType(ObjType);
3879       ObjType.removeLocalConst();
3880       ObjType.removeLocalVolatile();
3881     }
3882 
3883     // If this is our last pass, check that the final object type is OK.
3884     if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3885       // Accesses to volatile objects are prohibited.
3886       if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3887         if (Info.getLangOpts().CPlusPlus) {
3888           int DiagKind;
3889           SourceLocation Loc;
3890           const NamedDecl *Decl = nullptr;
3891           if (VolatileField) {
3892             DiagKind = 2;
3893             Loc = VolatileField->getLocation();
3894             Decl = VolatileField;
3895           } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3896             DiagKind = 1;
3897             Loc = VD->getLocation();
3898             Decl = VD;
3899           } else {
3900             DiagKind = 0;
3901             if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3902               Loc = E->getExprLoc();
3903           }
3904           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3905               << handler.AccessKind << DiagKind << Decl;
3906           Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3907         } else {
3908           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3909         }
3910         return handler.failed();
3911       }
3912 
3913       // If we are reading an object of class type, there may still be more
3914       // things we need to check: if there are any mutable subobjects, we
3915       // cannot perform this read. (This only happens when performing a trivial
3916       // copy or assignment.)
3917       if (ObjType->isRecordType() &&
3918           !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3919           diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3920         return handler.failed();
3921     }
3922 
3923     if (I == N) {
3924       if (!handler.found(*O, ObjType))
3925         return false;
3926 
3927       // If we modified a bit-field, truncate it to the right width.
3928       if (isModification(handler.AccessKind) &&
3929           LastField && LastField->isBitField() &&
3930           !truncateBitfieldValue(Info, E, *O, LastField))
3931         return false;
3932 
3933       return true;
3934     }
3935 
3936     LastField = nullptr;
3937     if (ObjType->isArrayType()) {
3938       // Next subobject is an array element.
3939       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3940       assert(CAT && "vla in literal type?");
3941       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3942       if (CAT->getSize().ule(Index)) {
3943         // Note, it should not be possible to form a pointer with a valid
3944         // designator which points more than one past the end of the array.
3945         if (Info.getLangOpts().CPlusPlus11)
3946           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3947             << handler.AccessKind;
3948         else
3949           Info.FFDiag(E);
3950         return handler.failed();
3951       }
3952 
3953       ObjType = CAT->getElementType();
3954 
3955       if (O->getArrayInitializedElts() > Index)
3956         O = &O->getArrayInitializedElt(Index);
3957       else if (!isRead(handler.AccessKind)) {
3958         if (!CheckArraySize(Info, CAT, E->getExprLoc()))
3959           return handler.failed();
3960 
3961         expandArray(*O, Index);
3962         O = &O->getArrayInitializedElt(Index);
3963       } else
3964         O = &O->getArrayFiller();
3965     } else if (ObjType->isAnyComplexType()) {
3966       // Next subobject is a complex number.
3967       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3968       if (Index > 1) {
3969         if (Info.getLangOpts().CPlusPlus11)
3970           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3971             << handler.AccessKind;
3972         else
3973           Info.FFDiag(E);
3974         return handler.failed();
3975       }
3976 
3977       ObjType = getSubobjectType(
3978           ObjType, ObjType->castAs<ComplexType>()->getElementType());
3979 
3980       assert(I == N - 1 && "extracting subobject of scalar?");
3981       if (O->isComplexInt()) {
3982         return handler.found(Index ? O->getComplexIntImag()
3983                                    : O->getComplexIntReal(), ObjType);
3984       } else {
3985         assert(O->isComplexFloat());
3986         return handler.found(Index ? O->getComplexFloatImag()
3987                                    : O->getComplexFloatReal(), ObjType);
3988       }
3989     } else if (const auto *VT = ObjType->getAs<VectorType>()) {
3990       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3991       unsigned NumElements = VT->getNumElements();
3992       if (Index == NumElements) {
3993         if (Info.getLangOpts().CPlusPlus11)
3994           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3995               << handler.AccessKind;
3996         else
3997           Info.FFDiag(E);
3998         return handler.failed();
3999       }
4000 
4001       if (Index > NumElements) {
4002         Info.CCEDiag(E, diag::note_constexpr_array_index)
4003             << Index << /*array*/ 0 << NumElements;
4004         return handler.failed();
4005       }
4006 
4007       ObjType = VT->getElementType();
4008       assert(I == N - 1 && "extracting subobject of scalar?");
4009       return handler.found(O->getVectorElt(Index), ObjType);
4010     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
4011       if (Field->isMutable() &&
4012           !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
4013         Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
4014           << handler.AccessKind << Field;
4015         Info.Note(Field->getLocation(), diag::note_declared_at);
4016         return handler.failed();
4017       }
4018 
4019       // Next subobject is a class, struct or union field.
4020       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
4021       if (RD->isUnion()) {
4022         const FieldDecl *UnionField = O->getUnionField();
4023         if (!UnionField ||
4024             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
4025           if (I == N - 1 && handler.AccessKind == AK_Construct) {
4026             // Placement new onto an inactive union member makes it active.
4027             O->setUnion(Field, APValue());
4028           } else {
4029             // Pointer to/into inactive union member: Not within lifetime
4030             if (handler.AccessKind == AK_IsWithinLifetime)
4031               return false;
4032             // FIXME: If O->getUnionValue() is absent, report that there's no
4033             // active union member rather than reporting the prior active union
4034             // member. We'll need to fix nullptr_t to not use APValue() as its
4035             // representation first.
4036             Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
4037                 << handler.AccessKind << Field << !UnionField << UnionField;
4038             return handler.failed();
4039           }
4040         }
4041         O = &O->getUnionValue();
4042       } else
4043         O = &O->getStructField(Field->getFieldIndex());
4044 
4045       ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
4046       LastField = Field;
4047       if (Field->getType().isVolatileQualified())
4048         VolatileField = Field;
4049     } else {
4050       // Next subobject is a base class.
4051       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
4052       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
4053       O = &O->getStructBase(getBaseIndex(Derived, Base));
4054 
4055       ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
4056     }
4057   }
4058 }
4059 
4060 namespace {
4061 struct ExtractSubobjectHandler {
4062   EvalInfo &Info;
4063   const Expr *E;
4064   APValue &Result;
4065   const AccessKinds AccessKind;
4066 
4067   typedef bool result_type;
4068   bool failed() { return false; }
4069   bool found(APValue &Subobj, QualType SubobjType) {
4070     Result = Subobj;
4071     if (AccessKind == AK_ReadObjectRepresentation)
4072       return true;
4073     return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
4074   }
4075   bool found(APSInt &Value, QualType SubobjType) {
4076     Result = APValue(Value);
4077     return true;
4078   }
4079   bool found(APFloat &Value, QualType SubobjType) {
4080     Result = APValue(Value);
4081     return true;
4082   }
4083 };
4084 } // end anonymous namespace
4085 
4086 /// Extract the designated sub-object of an rvalue.
4087 static bool extractSubobject(EvalInfo &Info, const Expr *E,
4088                              const CompleteObject &Obj,
4089                              const SubobjectDesignator &Sub, APValue &Result,
4090                              AccessKinds AK = AK_Read) {
4091   assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
4092   ExtractSubobjectHandler Handler = {Info, E, Result, AK};
4093   return findSubobject(Info, E, Obj, Sub, Handler);
4094 }
4095 
4096 namespace {
4097 struct ModifySubobjectHandler {
4098   EvalInfo &Info;
4099   APValue &NewVal;
4100   const Expr *E;
4101 
4102   typedef bool result_type;
4103   static const AccessKinds AccessKind = AK_Assign;
4104 
4105   bool checkConst(QualType QT) {
4106     // Assigning to a const object has undefined behavior.
4107     if (QT.isConstQualified()) {
4108       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4109       return false;
4110     }
4111     return true;
4112   }
4113 
4114   bool failed() { return false; }
4115   bool found(APValue &Subobj, QualType SubobjType) {
4116     if (!checkConst(SubobjType))
4117       return false;
4118     // We've been given ownership of NewVal, so just swap it in.
4119     Subobj.swap(NewVal);
4120     return true;
4121   }
4122   bool found(APSInt &Value, QualType SubobjType) {
4123     if (!checkConst(SubobjType))
4124       return false;
4125     if (!NewVal.isInt()) {
4126       // Maybe trying to write a cast pointer value into a complex?
4127       Info.FFDiag(E);
4128       return false;
4129     }
4130     Value = NewVal.getInt();
4131     return true;
4132   }
4133   bool found(APFloat &Value, QualType SubobjType) {
4134     if (!checkConst(SubobjType))
4135       return false;
4136     Value = NewVal.getFloat();
4137     return true;
4138   }
4139 };
4140 } // end anonymous namespace
4141 
4142 const AccessKinds ModifySubobjectHandler::AccessKind;
4143 
4144 /// Update the designated sub-object of an rvalue to the given value.
4145 static bool modifySubobject(EvalInfo &Info, const Expr *E,
4146                             const CompleteObject &Obj,
4147                             const SubobjectDesignator &Sub,
4148                             APValue &NewVal) {
4149   ModifySubobjectHandler Handler = { Info, NewVal, E };
4150   return findSubobject(Info, E, Obj, Sub, Handler);
4151 }
4152 
4153 /// Find the position where two subobject designators diverge, or equivalently
4154 /// the length of the common initial subsequence.
4155 static unsigned FindDesignatorMismatch(QualType ObjType,
4156                                        const SubobjectDesignator &A,
4157                                        const SubobjectDesignator &B,
4158                                        bool &WasArrayIndex) {
4159   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
4160   for (/**/; I != N; ++I) {
4161     if (!ObjType.isNull() &&
4162         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
4163       // Next subobject is an array element.
4164       if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
4165         WasArrayIndex = true;
4166         return I;
4167       }
4168       if (ObjType->isAnyComplexType())
4169         ObjType = ObjType->castAs<ComplexType>()->getElementType();
4170       else
4171         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
4172     } else {
4173       if (A.Entries[I].getAsBaseOrMember() !=
4174           B.Entries[I].getAsBaseOrMember()) {
4175         WasArrayIndex = false;
4176         return I;
4177       }
4178       if (const FieldDecl *FD = getAsField(A.Entries[I]))
4179         // Next subobject is a field.
4180         ObjType = FD->getType();
4181       else
4182         // Next subobject is a base class.
4183         ObjType = QualType();
4184     }
4185   }
4186   WasArrayIndex = false;
4187   return I;
4188 }
4189 
4190 /// Determine whether the given subobject designators refer to elements of the
4191 /// same array object.
4192 static bool AreElementsOfSameArray(QualType ObjType,
4193                                    const SubobjectDesignator &A,
4194                                    const SubobjectDesignator &B) {
4195   if (A.Entries.size() != B.Entries.size())
4196     return false;
4197 
4198   bool IsArray = A.MostDerivedIsArrayElement;
4199   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
4200     // A is a subobject of the array element.
4201     return false;
4202 
4203   // If A (and B) designates an array element, the last entry will be the array
4204   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
4205   // of length 1' case, and the entire path must match.
4206   bool WasArrayIndex;
4207   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
4208   return CommonLength >= A.Entries.size() - IsArray;
4209 }
4210 
4211 /// Find the complete object to which an LValue refers.
4212 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
4213                                          AccessKinds AK, const LValue &LVal,
4214                                          QualType LValType) {
4215   if (LVal.InvalidBase) {
4216     Info.FFDiag(E);
4217     return CompleteObject();
4218   }
4219 
4220   if (!LVal.Base) {
4221     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
4222     return CompleteObject();
4223   }
4224 
4225   CallStackFrame *Frame = nullptr;
4226   unsigned Depth = 0;
4227   if (LVal.getLValueCallIndex()) {
4228     std::tie(Frame, Depth) =
4229         Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
4230     if (!Frame) {
4231       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
4232         << AK << LVal.Base.is<const ValueDecl*>();
4233       NoteLValueLocation(Info, LVal.Base);
4234       return CompleteObject();
4235     }
4236   }
4237 
4238   bool IsAccess = isAnyAccess(AK);
4239 
4240   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
4241   // is not a constant expression (even if the object is non-volatile). We also
4242   // apply this rule to C++98, in order to conform to the expected 'volatile'
4243   // semantics.
4244   if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
4245     if (Info.getLangOpts().CPlusPlus)
4246       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
4247         << AK << LValType;
4248     else
4249       Info.FFDiag(E);
4250     return CompleteObject();
4251   }
4252 
4253   // Compute value storage location and type of base object.
4254   APValue *BaseVal = nullptr;
4255   QualType BaseType = getType(LVal.Base);
4256 
4257   if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4258       lifetimeStartedInEvaluation(Info, LVal.Base)) {
4259     // This is the object whose initializer we're evaluating, so its lifetime
4260     // started in the current evaluation.
4261     BaseVal = Info.EvaluatingDeclValue;
4262   } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4263     // Allow reading from a GUID declaration.
4264     if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4265       if (isModification(AK)) {
4266         // All the remaining cases do not permit modification of the object.
4267         Info.FFDiag(E, diag::note_constexpr_modify_global);
4268         return CompleteObject();
4269       }
4270       APValue &V = GD->getAsAPValue();
4271       if (V.isAbsent()) {
4272         Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4273             << GD->getType();
4274         return CompleteObject();
4275       }
4276       return CompleteObject(LVal.Base, &V, GD->getType());
4277     }
4278 
4279     // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4280     if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4281       if (isModification(AK)) {
4282         Info.FFDiag(E, diag::note_constexpr_modify_global);
4283         return CompleteObject();
4284       }
4285       return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4286                             GCD->getType());
4287     }
4288 
4289     // Allow reading from template parameter objects.
4290     if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4291       if (isModification(AK)) {
4292         Info.FFDiag(E, diag::note_constexpr_modify_global);
4293         return CompleteObject();
4294       }
4295       return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4296                             TPO->getType());
4297     }
4298 
4299     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4300     // In C++11, constexpr, non-volatile variables initialized with constant
4301     // expressions are constant expressions too. Inside constexpr functions,
4302     // parameters are constant expressions even if they're non-const.
4303     // In C++1y, objects local to a constant expression (those with a Frame) are
4304     // both readable and writable inside constant expressions.
4305     // In C, such things can also be folded, although they are not ICEs.
4306     const VarDecl *VD = dyn_cast<VarDecl>(D);
4307     if (VD) {
4308       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4309         VD = VDef;
4310     }
4311     if (!VD || VD->isInvalidDecl()) {
4312       Info.FFDiag(E);
4313       return CompleteObject();
4314     }
4315 
4316     bool IsConstant = BaseType.isConstant(Info.Ctx);
4317     bool ConstexprVar = false;
4318     if (const auto *VD = dyn_cast_if_present<VarDecl>(
4319             Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
4320       ConstexprVar = VD->isConstexpr();
4321 
4322     // Unless we're looking at a local variable or argument in a constexpr call,
4323     // the variable we're reading must be const.
4324     if (!Frame) {
4325       if (IsAccess && isa<ParmVarDecl>(VD)) {
4326         // Access of a parameter that's not associated with a frame isn't going
4327         // to work out, but we can leave it to evaluateVarDeclInit to provide a
4328         // suitable diagnostic.
4329       } else if (Info.getLangOpts().CPlusPlus14 &&
4330                  lifetimeStartedInEvaluation(Info, LVal.Base)) {
4331         // OK, we can read and modify an object if we're in the process of
4332         // evaluating its initializer, because its lifetime began in this
4333         // evaluation.
4334       } else if (isModification(AK)) {
4335         // All the remaining cases do not permit modification of the object.
4336         Info.FFDiag(E, diag::note_constexpr_modify_global);
4337         return CompleteObject();
4338       } else if (VD->isConstexpr()) {
4339         // OK, we can read this variable.
4340       } else if (Info.getLangOpts().C23 && ConstexprVar) {
4341         Info.FFDiag(E);
4342         return CompleteObject();
4343       } else if (BaseType->isIntegralOrEnumerationType()) {
4344         if (!IsConstant) {
4345           if (!IsAccess)
4346             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4347           if (Info.getLangOpts().CPlusPlus) {
4348             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4349             Info.Note(VD->getLocation(), diag::note_declared_at);
4350           } else {
4351             Info.FFDiag(E);
4352           }
4353           return CompleteObject();
4354         }
4355       } else if (!IsAccess) {
4356         return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4357       } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
4358                  BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4359         // This variable might end up being constexpr. Don't diagnose it yet.
4360       } else if (IsConstant) {
4361         // Keep evaluating to see what we can do. In particular, we support
4362         // folding of const floating-point types, in order to make static const
4363         // data members of such types (supported as an extension) more useful.
4364         if (Info.getLangOpts().CPlusPlus) {
4365           Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4366                               ? diag::note_constexpr_ltor_non_constexpr
4367                               : diag::note_constexpr_ltor_non_integral, 1)
4368               << VD << BaseType;
4369           Info.Note(VD->getLocation(), diag::note_declared_at);
4370         } else {
4371           Info.CCEDiag(E);
4372         }
4373       } else {
4374         // Never allow reading a non-const value.
4375         if (Info.getLangOpts().CPlusPlus) {
4376           Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4377                              ? diag::note_constexpr_ltor_non_constexpr
4378                              : diag::note_constexpr_ltor_non_integral, 1)
4379               << VD << BaseType;
4380           Info.Note(VD->getLocation(), diag::note_declared_at);
4381         } else {
4382           Info.FFDiag(E);
4383         }
4384         return CompleteObject();
4385       }
4386     }
4387 
4388     if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
4389       return CompleteObject();
4390   } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4391     std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
4392     if (!Alloc) {
4393       Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4394       return CompleteObject();
4395     }
4396     return CompleteObject(LVal.Base, &(*Alloc)->Value,
4397                           LVal.Base.getDynamicAllocType());
4398   } else {
4399     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4400 
4401     if (!Frame) {
4402       if (const MaterializeTemporaryExpr *MTE =
4403               dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4404         assert(MTE->getStorageDuration() == SD_Static &&
4405                "should have a frame for a non-global materialized temporary");
4406 
4407         // C++20 [expr.const]p4: [DR2126]
4408         //   An object or reference is usable in constant expressions if it is
4409         //   - a temporary object of non-volatile const-qualified literal type
4410         //     whose lifetime is extended to that of a variable that is usable
4411         //     in constant expressions
4412         //
4413         // C++20 [expr.const]p5:
4414         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4415         //   - a non-volatile glvalue that refers to an object that is usable
4416         //     in constant expressions, or
4417         //   - a non-volatile glvalue of literal type that refers to a
4418         //     non-volatile object whose lifetime began within the evaluation
4419         //     of E;
4420         //
4421         // C++11 misses the 'began within the evaluation of e' check and
4422         // instead allows all temporaries, including things like:
4423         //   int &&r = 1;
4424         //   int x = ++r;
4425         //   constexpr int k = r;
4426         // Therefore we use the C++14-onwards rules in C++11 too.
4427         //
4428         // Note that temporaries whose lifetimes began while evaluating a
4429         // variable's constructor are not usable while evaluating the
4430         // corresponding destructor, not even if they're of const-qualified
4431         // types.
4432         if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4433             !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4434           if (!IsAccess)
4435             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4436           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4437           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4438           return CompleteObject();
4439         }
4440 
4441         BaseVal = MTE->getOrCreateValue(false);
4442         assert(BaseVal && "got reference to unevaluated temporary");
4443       } else {
4444         if (!IsAccess)
4445           return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4446         APValue Val;
4447         LVal.moveInto(Val);
4448         Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4449             << AK
4450             << Val.getAsString(Info.Ctx,
4451                                Info.Ctx.getLValueReferenceType(LValType));
4452         NoteLValueLocation(Info, LVal.Base);
4453         return CompleteObject();
4454       }
4455     } else {
4456       BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4457       assert(BaseVal && "missing value for temporary");
4458     }
4459   }
4460 
4461   // In C++14, we can't safely access any mutable state when we might be
4462   // evaluating after an unmodeled side effect. Parameters are modeled as state
4463   // in the caller, but aren't visible once the call returns, so they can be
4464   // modified in a speculatively-evaluated call.
4465   //
4466   // FIXME: Not all local state is mutable. Allow local constant subobjects
4467   // to be read here (but take care with 'mutable' fields).
4468   unsigned VisibleDepth = Depth;
4469   if (llvm::isa_and_nonnull<ParmVarDecl>(
4470           LVal.Base.dyn_cast<const ValueDecl *>()))
4471     ++VisibleDepth;
4472   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4473        Info.EvalStatus.HasSideEffects) ||
4474       (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4475     return CompleteObject();
4476 
4477   return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4478 }
4479 
4480 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4481 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4482 /// glvalue referred to by an entity of reference type.
4483 ///
4484 /// \param Info - Information about the ongoing evaluation.
4485 /// \param Conv - The expression for which we are performing the conversion.
4486 ///               Used for diagnostics.
4487 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4488 ///               case of a non-class type).
4489 /// \param LVal - The glvalue on which we are attempting to perform this action.
4490 /// \param RVal - The produced value will be placed here.
4491 /// \param WantObjectRepresentation - If true, we're looking for the object
4492 ///               representation rather than the value, and in particular,
4493 ///               there is no requirement that the result be fully initialized.
4494 static bool
4495 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
4496                                const LValue &LVal, APValue &RVal,
4497                                bool WantObjectRepresentation = false) {
4498   if (LVal.Designator.Invalid)
4499     return false;
4500 
4501   // Check for special cases where there is no existing APValue to look at.
4502   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4503 
4504   AccessKinds AK =
4505       WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4506 
4507   if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4508     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4509       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4510       // initializer until now for such expressions. Such an expression can't be
4511       // an ICE in C, so this only matters for fold.
4512       if (Type.isVolatileQualified()) {
4513         Info.FFDiag(Conv);
4514         return false;
4515       }
4516 
4517       APValue Lit;
4518       if (!Evaluate(Lit, Info, CLE->getInitializer()))
4519         return false;
4520 
4521       // According to GCC info page:
4522       //
4523       // 6.28 Compound Literals
4524       //
4525       // As an optimization, G++ sometimes gives array compound literals longer
4526       // lifetimes: when the array either appears outside a function or has a
4527       // const-qualified type. If foo and its initializer had elements of type
4528       // char *const rather than char *, or if foo were a global variable, the
4529       // array would have static storage duration. But it is probably safest
4530       // just to avoid the use of array compound literals in C++ code.
4531       //
4532       // Obey that rule by checking constness for converted array types.
4533 
4534       QualType CLETy = CLE->getType();
4535       if (CLETy->isArrayType() && !Type->isArrayType()) {
4536         if (!CLETy.isConstant(Info.Ctx)) {
4537           Info.FFDiag(Conv);
4538           Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4539           return false;
4540         }
4541       }
4542 
4543       CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4544       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4545     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4546       // Special-case character extraction so we don't have to construct an
4547       // APValue for the whole string.
4548       assert(LVal.Designator.Entries.size() <= 1 &&
4549              "Can only read characters from string literals");
4550       if (LVal.Designator.Entries.empty()) {
4551         // Fail for now for LValue to RValue conversion of an array.
4552         // (This shouldn't show up in C/C++, but it could be triggered by a
4553         // weird EvaluateAsRValue call from a tool.)
4554         Info.FFDiag(Conv);
4555         return false;
4556       }
4557       if (LVal.Designator.isOnePastTheEnd()) {
4558         if (Info.getLangOpts().CPlusPlus11)
4559           Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4560         else
4561           Info.FFDiag(Conv);
4562         return false;
4563       }
4564       uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4565       RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4566       return true;
4567     }
4568   }
4569 
4570   CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4571   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4572 }
4573 
4574 /// Perform an assignment of Val to LVal. Takes ownership of Val.
4575 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4576                              QualType LValType, APValue &Val) {
4577   if (LVal.Designator.Invalid)
4578     return false;
4579 
4580   if (!Info.getLangOpts().CPlusPlus14) {
4581     Info.FFDiag(E);
4582     return false;
4583   }
4584 
4585   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4586   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4587 }
4588 
4589 namespace {
4590 struct CompoundAssignSubobjectHandler {
4591   EvalInfo &Info;
4592   const CompoundAssignOperator *E;
4593   QualType PromotedLHSType;
4594   BinaryOperatorKind Opcode;
4595   const APValue &RHS;
4596 
4597   static const AccessKinds AccessKind = AK_Assign;
4598 
4599   typedef bool result_type;
4600 
4601   bool checkConst(QualType QT) {
4602     // Assigning to a const object has undefined behavior.
4603     if (QT.isConstQualified()) {
4604       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4605       return false;
4606     }
4607     return true;
4608   }
4609 
4610   bool failed() { return false; }
4611   bool found(APValue &Subobj, QualType SubobjType) {
4612     switch (Subobj.getKind()) {
4613     case APValue::Int:
4614       return found(Subobj.getInt(), SubobjType);
4615     case APValue::Float:
4616       return found(Subobj.getFloat(), SubobjType);
4617     case APValue::ComplexInt:
4618     case APValue::ComplexFloat:
4619       // FIXME: Implement complex compound assignment.
4620       Info.FFDiag(E);
4621       return false;
4622     case APValue::LValue:
4623       return foundPointer(Subobj, SubobjType);
4624     case APValue::Vector:
4625       return foundVector(Subobj, SubobjType);
4626     case APValue::Indeterminate:
4627       Info.FFDiag(E, diag::note_constexpr_access_uninit)
4628           << /*read of=*/0 << /*uninitialized object=*/1
4629           << E->getLHS()->getSourceRange();
4630       return false;
4631     default:
4632       // FIXME: can this happen?
4633       Info.FFDiag(E);
4634       return false;
4635     }
4636   }
4637 
4638   bool foundVector(APValue &Value, QualType SubobjType) {
4639     if (!checkConst(SubobjType))
4640       return false;
4641 
4642     if (!SubobjType->isVectorType()) {
4643       Info.FFDiag(E);
4644       return false;
4645     }
4646     return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4647   }
4648 
4649   bool found(APSInt &Value, QualType SubobjType) {
4650     if (!checkConst(SubobjType))
4651       return false;
4652 
4653     if (!SubobjType->isIntegerType()) {
4654       // We don't support compound assignment on integer-cast-to-pointer
4655       // values.
4656       Info.FFDiag(E);
4657       return false;
4658     }
4659 
4660     if (RHS.isInt()) {
4661       APSInt LHS =
4662           HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4663       if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4664         return false;
4665       Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4666       return true;
4667     } else if (RHS.isFloat()) {
4668       const FPOptions FPO = E->getFPFeaturesInEffect(
4669                                     Info.Ctx.getLangOpts());
4670       APFloat FValue(0.0);
4671       return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4672                                   PromotedLHSType, FValue) &&
4673              handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4674              HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4675                                   Value);
4676     }
4677 
4678     Info.FFDiag(E);
4679     return false;
4680   }
4681   bool found(APFloat &Value, QualType SubobjType) {
4682     return checkConst(SubobjType) &&
4683            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4684                                   Value) &&
4685            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4686            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4687   }
4688   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4689     if (!checkConst(SubobjType))
4690       return false;
4691 
4692     QualType PointeeType;
4693     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4694       PointeeType = PT->getPointeeType();
4695 
4696     if (PointeeType.isNull() || !RHS.isInt() ||
4697         (Opcode != BO_Add && Opcode != BO_Sub)) {
4698       Info.FFDiag(E);
4699       return false;
4700     }
4701 
4702     APSInt Offset = RHS.getInt();
4703     if (Opcode == BO_Sub)
4704       negateAsSigned(Offset);
4705 
4706     LValue LVal;
4707     LVal.setFrom(Info.Ctx, Subobj);
4708     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4709       return false;
4710     LVal.moveInto(Subobj);
4711     return true;
4712   }
4713 };
4714 } // end anonymous namespace
4715 
4716 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4717 
4718 /// Perform a compound assignment of LVal <op>= RVal.
4719 static bool handleCompoundAssignment(EvalInfo &Info,
4720                                      const CompoundAssignOperator *E,
4721                                      const LValue &LVal, QualType LValType,
4722                                      QualType PromotedLValType,
4723                                      BinaryOperatorKind Opcode,
4724                                      const APValue &RVal) {
4725   if (LVal.Designator.Invalid)
4726     return false;
4727 
4728   if (!Info.getLangOpts().CPlusPlus14) {
4729     Info.FFDiag(E);
4730     return false;
4731   }
4732 
4733   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4734   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4735                                              RVal };
4736   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4737 }
4738 
4739 namespace {
4740 struct IncDecSubobjectHandler {
4741   EvalInfo &Info;
4742   const UnaryOperator *E;
4743   AccessKinds AccessKind;
4744   APValue *Old;
4745 
4746   typedef bool result_type;
4747 
4748   bool checkConst(QualType QT) {
4749     // Assigning to a const object has undefined behavior.
4750     if (QT.isConstQualified()) {
4751       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4752       return false;
4753     }
4754     return true;
4755   }
4756 
4757   bool failed() { return false; }
4758   bool found(APValue &Subobj, QualType SubobjType) {
4759     // Stash the old value. Also clear Old, so we don't clobber it later
4760     // if we're post-incrementing a complex.
4761     if (Old) {
4762       *Old = Subobj;
4763       Old = nullptr;
4764     }
4765 
4766     switch (Subobj.getKind()) {
4767     case APValue::Int:
4768       return found(Subobj.getInt(), SubobjType);
4769     case APValue::Float:
4770       return found(Subobj.getFloat(), SubobjType);
4771     case APValue::ComplexInt:
4772       return found(Subobj.getComplexIntReal(),
4773                    SubobjType->castAs<ComplexType>()->getElementType()
4774                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4775     case APValue::ComplexFloat:
4776       return found(Subobj.getComplexFloatReal(),
4777                    SubobjType->castAs<ComplexType>()->getElementType()
4778                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4779     case APValue::LValue:
4780       return foundPointer(Subobj, SubobjType);
4781     default:
4782       // FIXME: can this happen?
4783       Info.FFDiag(E);
4784       return false;
4785     }
4786   }
4787   bool found(APSInt &Value, QualType SubobjType) {
4788     if (!checkConst(SubobjType))
4789       return false;
4790 
4791     if (!SubobjType->isIntegerType()) {
4792       // We don't support increment / decrement on integer-cast-to-pointer
4793       // values.
4794       Info.FFDiag(E);
4795       return false;
4796     }
4797 
4798     if (Old) *Old = APValue(Value);
4799 
4800     // bool arithmetic promotes to int, and the conversion back to bool
4801     // doesn't reduce mod 2^n, so special-case it.
4802     if (SubobjType->isBooleanType()) {
4803       if (AccessKind == AK_Increment)
4804         Value = 1;
4805       else
4806         Value = !Value;
4807       return true;
4808     }
4809 
4810     bool WasNegative = Value.isNegative();
4811     if (AccessKind == AK_Increment) {
4812       ++Value;
4813 
4814       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4815         APSInt ActualValue(Value, /*IsUnsigned*/true);
4816         return HandleOverflow(Info, E, ActualValue, SubobjType);
4817       }
4818     } else {
4819       --Value;
4820 
4821       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4822         unsigned BitWidth = Value.getBitWidth();
4823         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4824         ActualValue.setBit(BitWidth);
4825         return HandleOverflow(Info, E, ActualValue, SubobjType);
4826       }
4827     }
4828     return true;
4829   }
4830   bool found(APFloat &Value, QualType SubobjType) {
4831     if (!checkConst(SubobjType))
4832       return false;
4833 
4834     if (Old) *Old = APValue(Value);
4835 
4836     APFloat One(Value.getSemantics(), 1);
4837     llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
4838     APFloat::opStatus St;
4839     if (AccessKind == AK_Increment)
4840       St = Value.add(One, RM);
4841     else
4842       St = Value.subtract(One, RM);
4843     return checkFloatingPointResult(Info, E, St);
4844   }
4845   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4846     if (!checkConst(SubobjType))
4847       return false;
4848 
4849     QualType PointeeType;
4850     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4851       PointeeType = PT->getPointeeType();
4852     else {
4853       Info.FFDiag(E);
4854       return false;
4855     }
4856 
4857     LValue LVal;
4858     LVal.setFrom(Info.Ctx, Subobj);
4859     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4860                                      AccessKind == AK_Increment ? 1 : -1))
4861       return false;
4862     LVal.moveInto(Subobj);
4863     return true;
4864   }
4865 };
4866 } // end anonymous namespace
4867 
4868 /// Perform an increment or decrement on LVal.
4869 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4870                          QualType LValType, bool IsIncrement, APValue *Old) {
4871   if (LVal.Designator.Invalid)
4872     return false;
4873 
4874   if (!Info.getLangOpts().CPlusPlus14) {
4875     Info.FFDiag(E);
4876     return false;
4877   }
4878 
4879   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4880   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4881   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4882   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4883 }
4884 
4885 /// Build an lvalue for the object argument of a member function call.
4886 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4887                                    LValue &This) {
4888   if (Object->getType()->isPointerType() && Object->isPRValue())
4889     return EvaluatePointer(Object, This, Info);
4890 
4891   if (Object->isGLValue())
4892     return EvaluateLValue(Object, This, Info);
4893 
4894   if (Object->getType()->isLiteralType(Info.Ctx))
4895     return EvaluateTemporary(Object, This, Info);
4896 
4897   if (Object->getType()->isRecordType() && Object->isPRValue())
4898     return EvaluateTemporary(Object, This, Info);
4899 
4900   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4901   return false;
4902 }
4903 
4904 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
4905 /// lvalue referring to the result.
4906 ///
4907 /// \param Info - Information about the ongoing evaluation.
4908 /// \param LV - An lvalue referring to the base of the member pointer.
4909 /// \param RHS - The member pointer expression.
4910 /// \param IncludeMember - Specifies whether the member itself is included in
4911 ///        the resulting LValue subobject designator. This is not possible when
4912 ///        creating a bound member function.
4913 /// \return The field or method declaration to which the member pointer refers,
4914 ///         or 0 if evaluation fails.
4915 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4916                                                   QualType LVType,
4917                                                   LValue &LV,
4918                                                   const Expr *RHS,
4919                                                   bool IncludeMember = true) {
4920   MemberPtr MemPtr;
4921   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4922     return nullptr;
4923 
4924   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4925   // member value, the behavior is undefined.
4926   if (!MemPtr.getDecl()) {
4927     // FIXME: Specific diagnostic.
4928     Info.FFDiag(RHS);
4929     return nullptr;
4930   }
4931 
4932   if (MemPtr.isDerivedMember()) {
4933     // This is a member of some derived class. Truncate LV appropriately.
4934     // The end of the derived-to-base path for the base object must match the
4935     // derived-to-base path for the member pointer.
4936     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4937         LV.Designator.Entries.size()) {
4938       Info.FFDiag(RHS);
4939       return nullptr;
4940     }
4941     unsigned PathLengthToMember =
4942         LV.Designator.Entries.size() - MemPtr.Path.size();
4943     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4944       const CXXRecordDecl *LVDecl = getAsBaseClass(
4945           LV.Designator.Entries[PathLengthToMember + I]);
4946       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4947       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4948         Info.FFDiag(RHS);
4949         return nullptr;
4950       }
4951     }
4952 
4953     // Truncate the lvalue to the appropriate derived class.
4954     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4955                             PathLengthToMember))
4956       return nullptr;
4957   } else if (!MemPtr.Path.empty()) {
4958     // Extend the LValue path with the member pointer's path.
4959     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4960                                   MemPtr.Path.size() + IncludeMember);
4961 
4962     // Walk down to the appropriate base class.
4963     if (const PointerType *PT = LVType->getAs<PointerType>())
4964       LVType = PT->getPointeeType();
4965     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4966     assert(RD && "member pointer access on non-class-type expression");
4967     // The first class in the path is that of the lvalue.
4968     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4969       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4970       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4971         return nullptr;
4972       RD = Base;
4973     }
4974     // Finally cast to the class containing the member.
4975     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4976                                 MemPtr.getContainingRecord()))
4977       return nullptr;
4978   }
4979 
4980   // Add the member. Note that we cannot build bound member functions here.
4981   if (IncludeMember) {
4982     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4983       if (!HandleLValueMember(Info, RHS, LV, FD))
4984         return nullptr;
4985     } else if (const IndirectFieldDecl *IFD =
4986                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4987       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4988         return nullptr;
4989     } else {
4990       llvm_unreachable("can't construct reference to bound member function");
4991     }
4992   }
4993 
4994   return MemPtr.getDecl();
4995 }
4996 
4997 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4998                                                   const BinaryOperator *BO,
4999                                                   LValue &LV,
5000                                                   bool IncludeMember = true) {
5001   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
5002 
5003   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
5004     if (Info.noteFailure()) {
5005       MemberPtr MemPtr;
5006       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
5007     }
5008     return nullptr;
5009   }
5010 
5011   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
5012                                    BO->getRHS(), IncludeMember);
5013 }
5014 
5015 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
5016 /// the provided lvalue, which currently refers to the base object.
5017 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
5018                                     LValue &Result) {
5019   SubobjectDesignator &D = Result.Designator;
5020   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
5021     return false;
5022 
5023   QualType TargetQT = E->getType();
5024   if (const PointerType *PT = TargetQT->getAs<PointerType>())
5025     TargetQT = PT->getPointeeType();
5026 
5027   // Check this cast lands within the final derived-to-base subobject path.
5028   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
5029     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
5030       << D.MostDerivedType << TargetQT;
5031     return false;
5032   }
5033 
5034   // Check the type of the final cast. We don't need to check the path,
5035   // since a cast can only be formed if the path is unique.
5036   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
5037   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
5038   const CXXRecordDecl *FinalType;
5039   if (NewEntriesSize == D.MostDerivedPathLength)
5040     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
5041   else
5042     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
5043   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
5044     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
5045       << D.MostDerivedType << TargetQT;
5046     return false;
5047   }
5048 
5049   // Truncate the lvalue to the appropriate derived class.
5050   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
5051 }
5052 
5053 /// Get the value to use for a default-initialized object of type T.
5054 /// Return false if it encounters something invalid.
5055 static bool handleDefaultInitValue(QualType T, APValue &Result) {
5056   bool Success = true;
5057 
5058   // If there is already a value present don't overwrite it.
5059   if (!Result.isAbsent())
5060     return true;
5061 
5062   if (auto *RD = T->getAsCXXRecordDecl()) {
5063     if (RD->isInvalidDecl()) {
5064       Result = APValue();
5065       return false;
5066     }
5067     if (RD->isUnion()) {
5068       Result = APValue((const FieldDecl *)nullptr);
5069       return true;
5070     }
5071     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
5072                      std::distance(RD->field_begin(), RD->field_end()));
5073 
5074     unsigned Index = 0;
5075     for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
5076                                                   End = RD->bases_end();
5077          I != End; ++I, ++Index)
5078       Success &=
5079           handleDefaultInitValue(I->getType(), Result.getStructBase(Index));
5080 
5081     for (const auto *I : RD->fields()) {
5082       if (I->isUnnamedBitField())
5083         continue;
5084       Success &= handleDefaultInitValue(
5085           I->getType(), Result.getStructField(I->getFieldIndex()));
5086     }
5087     return Success;
5088   }
5089 
5090   if (auto *AT =
5091           dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
5092     Result = APValue(APValue::UninitArray(), 0, AT->getZExtSize());
5093     if (Result.hasArrayFiller())
5094       Success &=
5095           handleDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
5096 
5097     return Success;
5098   }
5099 
5100   Result = APValue::IndeterminateValue();
5101   return true;
5102 }
5103 
5104 namespace {
5105 enum EvalStmtResult {
5106   /// Evaluation failed.
5107   ESR_Failed,
5108   /// Hit a 'return' statement.
5109   ESR_Returned,
5110   /// Evaluation succeeded.
5111   ESR_Succeeded,
5112   /// Hit a 'continue' statement.
5113   ESR_Continue,
5114   /// Hit a 'break' statement.
5115   ESR_Break,
5116   /// Still scanning for 'case' or 'default' statement.
5117   ESR_CaseNotFound
5118 };
5119 }
5120 
5121 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
5122   if (VD->isInvalidDecl())
5123     return false;
5124   // We don't need to evaluate the initializer for a static local.
5125   if (!VD->hasLocalStorage())
5126     return true;
5127 
5128   LValue Result;
5129   APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
5130                                                    ScopeKind::Block, Result);
5131 
5132   const Expr *InitE = VD->getInit();
5133   if (!InitE) {
5134     if (VD->getType()->isDependentType())
5135       return Info.noteSideEffect();
5136     return handleDefaultInitValue(VD->getType(), Val);
5137   }
5138   if (InitE->isValueDependent())
5139     return false;
5140 
5141   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
5142     // Wipe out any partially-computed value, to allow tracking that this
5143     // evaluation failed.
5144     Val = APValue();
5145     return false;
5146   }
5147 
5148   return true;
5149 }
5150 
5151 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
5152   bool OK = true;
5153 
5154   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
5155     OK &= EvaluateVarDecl(Info, VD);
5156 
5157   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
5158     for (auto *BD : DD->bindings())
5159       if (auto *VD = BD->getHoldingVar())
5160         OK &= EvaluateDecl(Info, VD);
5161 
5162   return OK;
5163 }
5164 
5165 static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
5166   assert(E->isValueDependent());
5167   if (Info.noteSideEffect())
5168     return true;
5169   assert(E->containsErrors() && "valid value-dependent expression should never "
5170                                 "reach invalid code path.");
5171   return false;
5172 }
5173 
5174 /// Evaluate a condition (either a variable declaration or an expression).
5175 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
5176                          const Expr *Cond, bool &Result) {
5177   if (Cond->isValueDependent())
5178     return false;
5179   FullExpressionRAII Scope(Info);
5180   if (CondDecl && !EvaluateDecl(Info, CondDecl))
5181     return false;
5182   if (!EvaluateAsBooleanCondition(Cond, Result, Info))
5183     return false;
5184   return Scope.destroy();
5185 }
5186 
5187 namespace {
5188 /// A location where the result (returned value) of evaluating a
5189 /// statement should be stored.
5190 struct StmtResult {
5191   /// The APValue that should be filled in with the returned value.
5192   APValue &Value;
5193   /// The location containing the result, if any (used to support RVO).
5194   const LValue *Slot;
5195 };
5196 
5197 struct TempVersionRAII {
5198   CallStackFrame &Frame;
5199 
5200   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
5201     Frame.pushTempVersion();
5202   }
5203 
5204   ~TempVersionRAII() {
5205     Frame.popTempVersion();
5206   }
5207 };
5208 
5209 }
5210 
5211 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5212                                    const Stmt *S,
5213                                    const SwitchCase *SC = nullptr);
5214 
5215 /// Evaluate the body of a loop, and translate the result as appropriate.
5216 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
5217                                        const Stmt *Body,
5218                                        const SwitchCase *Case = nullptr) {
5219   BlockScopeRAII Scope(Info);
5220 
5221   EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
5222   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5223     ESR = ESR_Failed;
5224 
5225   switch (ESR) {
5226   case ESR_Break:
5227     return ESR_Succeeded;
5228   case ESR_Succeeded:
5229   case ESR_Continue:
5230     return ESR_Continue;
5231   case ESR_Failed:
5232   case ESR_Returned:
5233   case ESR_CaseNotFound:
5234     return ESR;
5235   }
5236   llvm_unreachable("Invalid EvalStmtResult!");
5237 }
5238 
5239 /// Evaluate a switch statement.
5240 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
5241                                      const SwitchStmt *SS) {
5242   BlockScopeRAII Scope(Info);
5243 
5244   // Evaluate the switch condition.
5245   APSInt Value;
5246   {
5247     if (const Stmt *Init = SS->getInit()) {
5248       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5249       if (ESR != ESR_Succeeded) {
5250         if (ESR != ESR_Failed && !Scope.destroy())
5251           ESR = ESR_Failed;
5252         return ESR;
5253       }
5254     }
5255 
5256     FullExpressionRAII CondScope(Info);
5257     if (SS->getConditionVariable() &&
5258         !EvaluateDecl(Info, SS->getConditionVariable()))
5259       return ESR_Failed;
5260     if (SS->getCond()->isValueDependent()) {
5261       // We don't know what the value is, and which branch should jump to.
5262       EvaluateDependentExpr(SS->getCond(), Info);
5263       return ESR_Failed;
5264     }
5265     if (!EvaluateInteger(SS->getCond(), Value, Info))
5266       return ESR_Failed;
5267 
5268     if (!CondScope.destroy())
5269       return ESR_Failed;
5270   }
5271 
5272   // Find the switch case corresponding to the value of the condition.
5273   // FIXME: Cache this lookup.
5274   const SwitchCase *Found = nullptr;
5275   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
5276        SC = SC->getNextSwitchCase()) {
5277     if (isa<DefaultStmt>(SC)) {
5278       Found = SC;
5279       continue;
5280     }
5281 
5282     const CaseStmt *CS = cast<CaseStmt>(SC);
5283     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
5284     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
5285                               : LHS;
5286     if (LHS <= Value && Value <= RHS) {
5287       Found = SC;
5288       break;
5289     }
5290   }
5291 
5292   if (!Found)
5293     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5294 
5295   // Search the switch body for the switch case and evaluate it from there.
5296   EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5297   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5298     return ESR_Failed;
5299 
5300   switch (ESR) {
5301   case ESR_Break:
5302     return ESR_Succeeded;
5303   case ESR_Succeeded:
5304   case ESR_Continue:
5305   case ESR_Failed:
5306   case ESR_Returned:
5307     return ESR;
5308   case ESR_CaseNotFound:
5309     // This can only happen if the switch case is nested within a statement
5310     // expression. We have no intention of supporting that.
5311     Info.FFDiag(Found->getBeginLoc(),
5312                 diag::note_constexpr_stmt_expr_unsupported);
5313     return ESR_Failed;
5314   }
5315   llvm_unreachable("Invalid EvalStmtResult!");
5316 }
5317 
5318 static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5319   // An expression E is a core constant expression unless the evaluation of E
5320   // would evaluate one of the following: [C++23] - a control flow that passes
5321   // through a declaration of a variable with static or thread storage duration
5322   // unless that variable is usable in constant expressions.
5323   if (VD->isLocalVarDecl() && VD->isStaticLocal() &&
5324       !VD->isUsableInConstantExpressions(Info.Ctx)) {
5325     Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5326         << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5327     return false;
5328   }
5329   return true;
5330 }
5331 
5332 // Evaluate a statement.
5333 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5334                                    const Stmt *S, const SwitchCase *Case) {
5335   if (!Info.nextStep(S))
5336     return ESR_Failed;
5337 
5338   // If we're hunting down a 'case' or 'default' label, recurse through
5339   // substatements until we hit the label.
5340   if (Case) {
5341     switch (S->getStmtClass()) {
5342     case Stmt::CompoundStmtClass:
5343       // FIXME: Precompute which substatement of a compound statement we
5344       // would jump to, and go straight there rather than performing a
5345       // linear scan each time.
5346     case Stmt::LabelStmtClass:
5347     case Stmt::AttributedStmtClass:
5348     case Stmt::DoStmtClass:
5349       break;
5350 
5351     case Stmt::CaseStmtClass:
5352     case Stmt::DefaultStmtClass:
5353       if (Case == S)
5354         Case = nullptr;
5355       break;
5356 
5357     case Stmt::IfStmtClass: {
5358       // FIXME: Precompute which side of an 'if' we would jump to, and go
5359       // straight there rather than scanning both sides.
5360       const IfStmt *IS = cast<IfStmt>(S);
5361 
5362       // Wrap the evaluation in a block scope, in case it's a DeclStmt
5363       // preceded by our switch label.
5364       BlockScopeRAII Scope(Info);
5365 
5366       // Step into the init statement in case it brings an (uninitialized)
5367       // variable into scope.
5368       if (const Stmt *Init = IS->getInit()) {
5369         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5370         if (ESR != ESR_CaseNotFound) {
5371           assert(ESR != ESR_Succeeded);
5372           return ESR;
5373         }
5374       }
5375 
5376       // Condition variable must be initialized if it exists.
5377       // FIXME: We can skip evaluating the body if there's a condition
5378       // variable, as there can't be any case labels within it.
5379       // (The same is true for 'for' statements.)
5380 
5381       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5382       if (ESR == ESR_Failed)
5383         return ESR;
5384       if (ESR != ESR_CaseNotFound)
5385         return Scope.destroy() ? ESR : ESR_Failed;
5386       if (!IS->getElse())
5387         return ESR_CaseNotFound;
5388 
5389       ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5390       if (ESR == ESR_Failed)
5391         return ESR;
5392       if (ESR != ESR_CaseNotFound)
5393         return Scope.destroy() ? ESR : ESR_Failed;
5394       return ESR_CaseNotFound;
5395     }
5396 
5397     case Stmt::WhileStmtClass: {
5398       EvalStmtResult ESR =
5399           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5400       if (ESR != ESR_Continue)
5401         return ESR;
5402       break;
5403     }
5404 
5405     case Stmt::ForStmtClass: {
5406       const ForStmt *FS = cast<ForStmt>(S);
5407       BlockScopeRAII Scope(Info);
5408 
5409       // Step into the init statement in case it brings an (uninitialized)
5410       // variable into scope.
5411       if (const Stmt *Init = FS->getInit()) {
5412         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5413         if (ESR != ESR_CaseNotFound) {
5414           assert(ESR != ESR_Succeeded);
5415           return ESR;
5416         }
5417       }
5418 
5419       EvalStmtResult ESR =
5420           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5421       if (ESR != ESR_Continue)
5422         return ESR;
5423       if (const auto *Inc = FS->getInc()) {
5424         if (Inc->isValueDependent()) {
5425           if (!EvaluateDependentExpr(Inc, Info))
5426             return ESR_Failed;
5427         } else {
5428           FullExpressionRAII IncScope(Info);
5429           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5430             return ESR_Failed;
5431         }
5432       }
5433       break;
5434     }
5435 
5436     case Stmt::DeclStmtClass: {
5437       // Start the lifetime of any uninitialized variables we encounter. They
5438       // might be used by the selected branch of the switch.
5439       const DeclStmt *DS = cast<DeclStmt>(S);
5440       for (const auto *D : DS->decls()) {
5441         if (const auto *VD = dyn_cast<VarDecl>(D)) {
5442           if (!CheckLocalVariableDeclaration(Info, VD))
5443             return ESR_Failed;
5444           if (VD->hasLocalStorage() && !VD->getInit())
5445             if (!EvaluateVarDecl(Info, VD))
5446               return ESR_Failed;
5447           // FIXME: If the variable has initialization that can't be jumped
5448           // over, bail out of any immediately-surrounding compound-statement
5449           // too. There can't be any case labels here.
5450         }
5451       }
5452       return ESR_CaseNotFound;
5453     }
5454 
5455     default:
5456       return ESR_CaseNotFound;
5457     }
5458   }
5459 
5460   switch (S->getStmtClass()) {
5461   default:
5462     if (const Expr *E = dyn_cast<Expr>(S)) {
5463       if (E->isValueDependent()) {
5464         if (!EvaluateDependentExpr(E, Info))
5465           return ESR_Failed;
5466       } else {
5467         // Don't bother evaluating beyond an expression-statement which couldn't
5468         // be evaluated.
5469         // FIXME: Do we need the FullExpressionRAII object here?
5470         // VisitExprWithCleanups should create one when necessary.
5471         FullExpressionRAII Scope(Info);
5472         if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5473           return ESR_Failed;
5474       }
5475       return ESR_Succeeded;
5476     }
5477 
5478     Info.FFDiag(S->getBeginLoc()) << S->getSourceRange();
5479     return ESR_Failed;
5480 
5481   case Stmt::NullStmtClass:
5482     return ESR_Succeeded;
5483 
5484   case Stmt::DeclStmtClass: {
5485     const DeclStmt *DS = cast<DeclStmt>(S);
5486     for (const auto *D : DS->decls()) {
5487       const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
5488       if (VD && !CheckLocalVariableDeclaration(Info, VD))
5489         return ESR_Failed;
5490       // Each declaration initialization is its own full-expression.
5491       FullExpressionRAII Scope(Info);
5492       if (!EvaluateDecl(Info, D) && !Info.noteFailure())
5493         return ESR_Failed;
5494       if (!Scope.destroy())
5495         return ESR_Failed;
5496     }
5497     return ESR_Succeeded;
5498   }
5499 
5500   case Stmt::ReturnStmtClass: {
5501     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5502     FullExpressionRAII Scope(Info);
5503     if (RetExpr && RetExpr->isValueDependent()) {
5504       EvaluateDependentExpr(RetExpr, Info);
5505       // We know we returned, but we don't know what the value is.
5506       return ESR_Failed;
5507     }
5508     if (RetExpr &&
5509         !(Result.Slot
5510               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5511               : Evaluate(Result.Value, Info, RetExpr)))
5512       return ESR_Failed;
5513     return Scope.destroy() ? ESR_Returned : ESR_Failed;
5514   }
5515 
5516   case Stmt::CompoundStmtClass: {
5517     BlockScopeRAII Scope(Info);
5518 
5519     const CompoundStmt *CS = cast<CompoundStmt>(S);
5520     for (const auto *BI : CS->body()) {
5521       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5522       if (ESR == ESR_Succeeded)
5523         Case = nullptr;
5524       else if (ESR != ESR_CaseNotFound) {
5525         if (ESR != ESR_Failed && !Scope.destroy())
5526           return ESR_Failed;
5527         return ESR;
5528       }
5529     }
5530     if (Case)
5531       return ESR_CaseNotFound;
5532     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5533   }
5534 
5535   case Stmt::IfStmtClass: {
5536     const IfStmt *IS = cast<IfStmt>(S);
5537 
5538     // Evaluate the condition, as either a var decl or as an expression.
5539     BlockScopeRAII Scope(Info);
5540     if (const Stmt *Init = IS->getInit()) {
5541       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5542       if (ESR != ESR_Succeeded) {
5543         if (ESR != ESR_Failed && !Scope.destroy())
5544           return ESR_Failed;
5545         return ESR;
5546       }
5547     }
5548     bool Cond;
5549     if (IS->isConsteval()) {
5550       Cond = IS->isNonNegatedConsteval();
5551       // If we are not in a constant context, if consteval should not evaluate
5552       // to true.
5553       if (!Info.InConstantContext)
5554         Cond = !Cond;
5555     } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
5556                              Cond))
5557       return ESR_Failed;
5558 
5559     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5560       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5561       if (ESR != ESR_Succeeded) {
5562         if (ESR != ESR_Failed && !Scope.destroy())
5563           return ESR_Failed;
5564         return ESR;
5565       }
5566     }
5567     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5568   }
5569 
5570   case Stmt::WhileStmtClass: {
5571     const WhileStmt *WS = cast<WhileStmt>(S);
5572     while (true) {
5573       BlockScopeRAII Scope(Info);
5574       bool Continue;
5575       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5576                         Continue))
5577         return ESR_Failed;
5578       if (!Continue)
5579         break;
5580 
5581       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5582       if (ESR != ESR_Continue) {
5583         if (ESR != ESR_Failed && !Scope.destroy())
5584           return ESR_Failed;
5585         return ESR;
5586       }
5587       if (!Scope.destroy())
5588         return ESR_Failed;
5589     }
5590     return ESR_Succeeded;
5591   }
5592 
5593   case Stmt::DoStmtClass: {
5594     const DoStmt *DS = cast<DoStmt>(S);
5595     bool Continue;
5596     do {
5597       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5598       if (ESR != ESR_Continue)
5599         return ESR;
5600       Case = nullptr;
5601 
5602       if (DS->getCond()->isValueDependent()) {
5603         EvaluateDependentExpr(DS->getCond(), Info);
5604         // Bailout as we don't know whether to keep going or terminate the loop.
5605         return ESR_Failed;
5606       }
5607       FullExpressionRAII CondScope(Info);
5608       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5609           !CondScope.destroy())
5610         return ESR_Failed;
5611     } while (Continue);
5612     return ESR_Succeeded;
5613   }
5614 
5615   case Stmt::ForStmtClass: {
5616     const ForStmt *FS = cast<ForStmt>(S);
5617     BlockScopeRAII ForScope(Info);
5618     if (FS->getInit()) {
5619       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5620       if (ESR != ESR_Succeeded) {
5621         if (ESR != ESR_Failed && !ForScope.destroy())
5622           return ESR_Failed;
5623         return ESR;
5624       }
5625     }
5626     while (true) {
5627       BlockScopeRAII IterScope(Info);
5628       bool Continue = true;
5629       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5630                                          FS->getCond(), Continue))
5631         return ESR_Failed;
5632       if (!Continue)
5633         break;
5634 
5635       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5636       if (ESR != ESR_Continue) {
5637         if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5638           return ESR_Failed;
5639         return ESR;
5640       }
5641 
5642       if (const auto *Inc = FS->getInc()) {
5643         if (Inc->isValueDependent()) {
5644           if (!EvaluateDependentExpr(Inc, Info))
5645             return ESR_Failed;
5646         } else {
5647           FullExpressionRAII IncScope(Info);
5648           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5649             return ESR_Failed;
5650         }
5651       }
5652 
5653       if (!IterScope.destroy())
5654         return ESR_Failed;
5655     }
5656     return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5657   }
5658 
5659   case Stmt::CXXForRangeStmtClass: {
5660     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5661     BlockScopeRAII Scope(Info);
5662 
5663     // Evaluate the init-statement if present.
5664     if (FS->getInit()) {
5665       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5666       if (ESR != ESR_Succeeded) {
5667         if (ESR != ESR_Failed && !Scope.destroy())
5668           return ESR_Failed;
5669         return ESR;
5670       }
5671     }
5672 
5673     // Initialize the __range variable.
5674     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5675     if (ESR != ESR_Succeeded) {
5676       if (ESR != ESR_Failed && !Scope.destroy())
5677         return ESR_Failed;
5678       return ESR;
5679     }
5680 
5681     // In error-recovery cases it's possible to get here even if we failed to
5682     // synthesize the __begin and __end variables.
5683     if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
5684       return ESR_Failed;
5685 
5686     // Create the __begin and __end iterators.
5687     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5688     if (ESR != ESR_Succeeded) {
5689       if (ESR != ESR_Failed && !Scope.destroy())
5690         return ESR_Failed;
5691       return ESR;
5692     }
5693     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5694     if (ESR != ESR_Succeeded) {
5695       if (ESR != ESR_Failed && !Scope.destroy())
5696         return ESR_Failed;
5697       return ESR;
5698     }
5699 
5700     while (true) {
5701       // Condition: __begin != __end.
5702       {
5703         if (FS->getCond()->isValueDependent()) {
5704           EvaluateDependentExpr(FS->getCond(), Info);
5705           // We don't know whether to keep going or terminate the loop.
5706           return ESR_Failed;
5707         }
5708         bool Continue = true;
5709         FullExpressionRAII CondExpr(Info);
5710         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5711           return ESR_Failed;
5712         if (!Continue)
5713           break;
5714       }
5715 
5716       // User's variable declaration, initialized by *__begin.
5717       BlockScopeRAII InnerScope(Info);
5718       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5719       if (ESR != ESR_Succeeded) {
5720         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5721           return ESR_Failed;
5722         return ESR;
5723       }
5724 
5725       // Loop body.
5726       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5727       if (ESR != ESR_Continue) {
5728         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5729           return ESR_Failed;
5730         return ESR;
5731       }
5732       if (FS->getInc()->isValueDependent()) {
5733         if (!EvaluateDependentExpr(FS->getInc(), Info))
5734           return ESR_Failed;
5735       } else {
5736         // Increment: ++__begin
5737         if (!EvaluateIgnoredValue(Info, FS->getInc()))
5738           return ESR_Failed;
5739       }
5740 
5741       if (!InnerScope.destroy())
5742         return ESR_Failed;
5743     }
5744 
5745     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5746   }
5747 
5748   case Stmt::SwitchStmtClass:
5749     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5750 
5751   case Stmt::ContinueStmtClass:
5752     return ESR_Continue;
5753 
5754   case Stmt::BreakStmtClass:
5755     return ESR_Break;
5756 
5757   case Stmt::LabelStmtClass:
5758     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5759 
5760   case Stmt::AttributedStmtClass: {
5761     const auto *AS = cast<AttributedStmt>(S);
5762     const auto *SS = AS->getSubStmt();
5763     MSConstexprContextRAII ConstexprContext(
5764         *Info.CurrentCall, hasSpecificAttr<MSConstexprAttr>(AS->getAttrs()) &&
5765                                isa<ReturnStmt>(SS));
5766 
5767     auto LO = Info.getASTContext().getLangOpts();
5768     if (LO.CXXAssumptions && !LO.MSVCCompat) {
5769       for (auto *Attr : AS->getAttrs()) {
5770         auto *AA = dyn_cast<CXXAssumeAttr>(Attr);
5771         if (!AA)
5772           continue;
5773 
5774         auto *Assumption = AA->getAssumption();
5775         if (Assumption->isValueDependent())
5776           return ESR_Failed;
5777 
5778         if (Assumption->HasSideEffects(Info.getASTContext()))
5779           continue;
5780 
5781         bool Value;
5782         if (!EvaluateAsBooleanCondition(Assumption, Value, Info))
5783           return ESR_Failed;
5784         if (!Value) {
5785           Info.CCEDiag(Assumption->getExprLoc(),
5786                        diag::note_constexpr_assumption_failed);
5787           return ESR_Failed;
5788         }
5789       }
5790     }
5791 
5792     return EvaluateStmt(Result, Info, SS, Case);
5793   }
5794 
5795   case Stmt::CaseStmtClass:
5796   case Stmt::DefaultStmtClass:
5797     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5798   case Stmt::CXXTryStmtClass:
5799     // Evaluate try blocks by evaluating all sub statements.
5800     return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5801   }
5802 }
5803 
5804 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5805 /// default constructor. If so, we'll fold it whether or not it's marked as
5806 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
5807 /// so we need special handling.
5808 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5809                                            const CXXConstructorDecl *CD,
5810                                            bool IsValueInitialization) {
5811   if (!CD->isTrivial() || !CD->isDefaultConstructor())
5812     return false;
5813 
5814   // Value-initialization does not call a trivial default constructor, so such a
5815   // call is a core constant expression whether or not the constructor is
5816   // constexpr.
5817   if (!CD->isConstexpr() && !IsValueInitialization) {
5818     if (Info.getLangOpts().CPlusPlus11) {
5819       // FIXME: If DiagDecl is an implicitly-declared special member function,
5820       // we should be much more explicit about why it's not constexpr.
5821       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5822         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5823       Info.Note(CD->getLocation(), diag::note_declared_at);
5824     } else {
5825       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5826     }
5827   }
5828   return true;
5829 }
5830 
5831 /// CheckConstexprFunction - Check that a function can be called in a constant
5832 /// expression.
5833 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5834                                    const FunctionDecl *Declaration,
5835                                    const FunctionDecl *Definition,
5836                                    const Stmt *Body) {
5837   // Potential constant expressions can contain calls to declared, but not yet
5838   // defined, constexpr functions.
5839   if (Info.checkingPotentialConstantExpression() && !Definition &&
5840       Declaration->isConstexpr())
5841     return false;
5842 
5843   // Bail out if the function declaration itself is invalid.  We will
5844   // have produced a relevant diagnostic while parsing it, so just
5845   // note the problematic sub-expression.
5846   if (Declaration->isInvalidDecl()) {
5847     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5848     return false;
5849   }
5850 
5851   // DR1872: An instantiated virtual constexpr function can't be called in a
5852   // constant expression (prior to C++20). We can still constant-fold such a
5853   // call.
5854   if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5855       cast<CXXMethodDecl>(Declaration)->isVirtual())
5856     Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5857 
5858   if (Definition && Definition->isInvalidDecl()) {
5859     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5860     return false;
5861   }
5862 
5863   // Can we evaluate this function call?
5864   if (Definition && Body &&
5865       (Definition->isConstexpr() || (Info.CurrentCall->CanEvalMSConstexpr &&
5866                                         Definition->hasAttr<MSConstexprAttr>())))
5867     return true;
5868 
5869   if (Info.getLangOpts().CPlusPlus11) {
5870     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5871 
5872     // If this function is not constexpr because it is an inherited
5873     // non-constexpr constructor, diagnose that directly.
5874     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5875     if (CD && CD->isInheritingConstructor()) {
5876       auto *Inherited = CD->getInheritedConstructor().getConstructor();
5877       if (!Inherited->isConstexpr())
5878         DiagDecl = CD = Inherited;
5879     }
5880 
5881     // FIXME: If DiagDecl is an implicitly-declared special member function
5882     // or an inheriting constructor, we should be much more explicit about why
5883     // it's not constexpr.
5884     if (CD && CD->isInheritingConstructor())
5885       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5886         << CD->getInheritedConstructor().getConstructor()->getParent();
5887     else
5888       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5889         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5890     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5891   } else {
5892     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5893   }
5894   return false;
5895 }
5896 
5897 namespace {
5898 struct CheckDynamicTypeHandler {
5899   AccessKinds AccessKind;
5900   typedef bool result_type;
5901   bool failed() { return false; }
5902   bool found(APValue &Subobj, QualType SubobjType) { return true; }
5903   bool found(APSInt &Value, QualType SubobjType) { return true; }
5904   bool found(APFloat &Value, QualType SubobjType) { return true; }
5905 };
5906 } // end anonymous namespace
5907 
5908 /// Check that we can access the notional vptr of an object / determine its
5909 /// dynamic type.
5910 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5911                              AccessKinds AK, bool Polymorphic) {
5912   if (This.Designator.Invalid)
5913     return false;
5914 
5915   CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5916 
5917   if (!Obj)
5918     return false;
5919 
5920   if (!Obj.Value) {
5921     // The object is not usable in constant expressions, so we can't inspect
5922     // its value to see if it's in-lifetime or what the active union members
5923     // are. We can still check for a one-past-the-end lvalue.
5924     if (This.Designator.isOnePastTheEnd() ||
5925         This.Designator.isMostDerivedAnUnsizedArray()) {
5926       Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5927                          ? diag::note_constexpr_access_past_end
5928                          : diag::note_constexpr_access_unsized_array)
5929           << AK;
5930       return false;
5931     } else if (Polymorphic) {
5932       // Conservatively refuse to perform a polymorphic operation if we would
5933       // not be able to read a notional 'vptr' value.
5934       APValue Val;
5935       This.moveInto(Val);
5936       QualType StarThisType =
5937           Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5938       Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5939           << AK << Val.getAsString(Info.Ctx, StarThisType);
5940       return false;
5941     }
5942     return true;
5943   }
5944 
5945   CheckDynamicTypeHandler Handler{AK};
5946   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5947 }
5948 
5949 /// Check that the pointee of the 'this' pointer in a member function call is
5950 /// either within its lifetime or in its period of construction or destruction.
5951 static bool
5952 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5953                                      const LValue &This,
5954                                      const CXXMethodDecl *NamedMember) {
5955   return checkDynamicType(
5956       Info, E, This,
5957       isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5958 }
5959 
5960 struct DynamicType {
5961   /// The dynamic class type of the object.
5962   const CXXRecordDecl *Type;
5963   /// The corresponding path length in the lvalue.
5964   unsigned PathLength;
5965 };
5966 
5967 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5968                                              unsigned PathLength) {
5969   assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5970       Designator.Entries.size() && "invalid path length");
5971   return (PathLength == Designator.MostDerivedPathLength)
5972              ? Designator.MostDerivedType->getAsCXXRecordDecl()
5973              : getAsBaseClass(Designator.Entries[PathLength - 1]);
5974 }
5975 
5976 /// Determine the dynamic type of an object.
5977 static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info,
5978                                                      const Expr *E,
5979                                                      LValue &This,
5980                                                      AccessKinds AK) {
5981   // If we don't have an lvalue denoting an object of class type, there is no
5982   // meaningful dynamic type. (We consider objects of non-class type to have no
5983   // dynamic type.)
5984   if (!checkDynamicType(Info, E, This, AK, true))
5985     return std::nullopt;
5986 
5987   // Refuse to compute a dynamic type in the presence of virtual bases. This
5988   // shouldn't happen other than in constant-folding situations, since literal
5989   // types can't have virtual bases.
5990   //
5991   // Note that consumers of DynamicType assume that the type has no virtual
5992   // bases, and will need modifications if this restriction is relaxed.
5993   const CXXRecordDecl *Class =
5994       This.Designator.MostDerivedType->getAsCXXRecordDecl();
5995   if (!Class || Class->getNumVBases()) {
5996     Info.FFDiag(E);
5997     return std::nullopt;
5998   }
5999 
6000   // FIXME: For very deep class hierarchies, it might be beneficial to use a
6001   // binary search here instead. But the overwhelmingly common case is that
6002   // we're not in the middle of a constructor, so it probably doesn't matter
6003   // in practice.
6004   ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
6005   for (unsigned PathLength = This.Designator.MostDerivedPathLength;
6006        PathLength <= Path.size(); ++PathLength) {
6007     switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
6008                                       Path.slice(0, PathLength))) {
6009     case ConstructionPhase::Bases:
6010     case ConstructionPhase::DestroyingBases:
6011       // We're constructing or destroying a base class. This is not the dynamic
6012       // type.
6013       break;
6014 
6015     case ConstructionPhase::None:
6016     case ConstructionPhase::AfterBases:
6017     case ConstructionPhase::AfterFields:
6018     case ConstructionPhase::Destroying:
6019       // We've finished constructing the base classes and not yet started
6020       // destroying them again, so this is the dynamic type.
6021       return DynamicType{getBaseClassType(This.Designator, PathLength),
6022                          PathLength};
6023     }
6024   }
6025 
6026   // CWG issue 1517: we're constructing a base class of the object described by
6027   // 'This', so that object has not yet begun its period of construction and
6028   // any polymorphic operation on it results in undefined behavior.
6029   Info.FFDiag(E);
6030   return std::nullopt;
6031 }
6032 
6033 /// Perform virtual dispatch.
6034 static const CXXMethodDecl *HandleVirtualDispatch(
6035     EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
6036     llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
6037   std::optional<DynamicType> DynType = ComputeDynamicType(
6038       Info, E, This,
6039       isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
6040   if (!DynType)
6041     return nullptr;
6042 
6043   // Find the final overrider. It must be declared in one of the classes on the
6044   // path from the dynamic type to the static type.
6045   // FIXME: If we ever allow literal types to have virtual base classes, that
6046   // won't be true.
6047   const CXXMethodDecl *Callee = Found;
6048   unsigned PathLength = DynType->PathLength;
6049   for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
6050     const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
6051     const CXXMethodDecl *Overrider =
6052         Found->getCorrespondingMethodDeclaredInClass(Class, false);
6053     if (Overrider) {
6054       Callee = Overrider;
6055       break;
6056     }
6057   }
6058 
6059   // C++2a [class.abstract]p6:
6060   //   the effect of making a virtual call to a pure virtual function [...] is
6061   //   undefined
6062   if (Callee->isPureVirtual()) {
6063     Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
6064     Info.Note(Callee->getLocation(), diag::note_declared_at);
6065     return nullptr;
6066   }
6067 
6068   // If necessary, walk the rest of the path to determine the sequence of
6069   // covariant adjustment steps to apply.
6070   if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
6071                                        Found->getReturnType())) {
6072     CovariantAdjustmentPath.push_back(Callee->getReturnType());
6073     for (unsigned CovariantPathLength = PathLength + 1;
6074          CovariantPathLength != This.Designator.Entries.size();
6075          ++CovariantPathLength) {
6076       const CXXRecordDecl *NextClass =
6077           getBaseClassType(This.Designator, CovariantPathLength);
6078       const CXXMethodDecl *Next =
6079           Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
6080       if (Next && !Info.Ctx.hasSameUnqualifiedType(
6081                       Next->getReturnType(), CovariantAdjustmentPath.back()))
6082         CovariantAdjustmentPath.push_back(Next->getReturnType());
6083     }
6084     if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
6085                                          CovariantAdjustmentPath.back()))
6086       CovariantAdjustmentPath.push_back(Found->getReturnType());
6087   }
6088 
6089   // Perform 'this' adjustment.
6090   if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
6091     return nullptr;
6092 
6093   return Callee;
6094 }
6095 
6096 /// Perform the adjustment from a value returned by a virtual function to
6097 /// a value of the statically expected type, which may be a pointer or
6098 /// reference to a base class of the returned type.
6099 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
6100                                             APValue &Result,
6101                                             ArrayRef<QualType> Path) {
6102   assert(Result.isLValue() &&
6103          "unexpected kind of APValue for covariant return");
6104   if (Result.isNullPointer())
6105     return true;
6106 
6107   LValue LVal;
6108   LVal.setFrom(Info.Ctx, Result);
6109 
6110   const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
6111   for (unsigned I = 1; I != Path.size(); ++I) {
6112     const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
6113     assert(OldClass && NewClass && "unexpected kind of covariant return");
6114     if (OldClass != NewClass &&
6115         !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
6116       return false;
6117     OldClass = NewClass;
6118   }
6119 
6120   LVal.moveInto(Result);
6121   return true;
6122 }
6123 
6124 /// Determine whether \p Base, which is known to be a direct base class of
6125 /// \p Derived, is a public base class.
6126 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
6127                               const CXXRecordDecl *Base) {
6128   for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
6129     auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
6130     if (BaseClass && declaresSameEntity(BaseClass, Base))
6131       return BaseSpec.getAccessSpecifier() == AS_public;
6132   }
6133   llvm_unreachable("Base is not a direct base of Derived");
6134 }
6135 
6136 /// Apply the given dynamic cast operation on the provided lvalue.
6137 ///
6138 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
6139 /// to find a suitable target subobject.
6140 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
6141                               LValue &Ptr) {
6142   // We can't do anything with a non-symbolic pointer value.
6143   SubobjectDesignator &D = Ptr.Designator;
6144   if (D.Invalid)
6145     return false;
6146 
6147   // C++ [expr.dynamic.cast]p6:
6148   //   If v is a null pointer value, the result is a null pointer value.
6149   if (Ptr.isNullPointer() && !E->isGLValue())
6150     return true;
6151 
6152   // For all the other cases, we need the pointer to point to an object within
6153   // its lifetime / period of construction / destruction, and we need to know
6154   // its dynamic type.
6155   std::optional<DynamicType> DynType =
6156       ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
6157   if (!DynType)
6158     return false;
6159 
6160   // C++ [expr.dynamic.cast]p7:
6161   //   If T is "pointer to cv void", then the result is a pointer to the most
6162   //   derived object
6163   if (E->getType()->isVoidPointerType())
6164     return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
6165 
6166   const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
6167   assert(C && "dynamic_cast target is not void pointer nor class");
6168   CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
6169 
6170   auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
6171     // C++ [expr.dynamic.cast]p9:
6172     if (!E->isGLValue()) {
6173       //   The value of a failed cast to pointer type is the null pointer value
6174       //   of the required result type.
6175       Ptr.setNull(Info.Ctx, E->getType());
6176       return true;
6177     }
6178 
6179     //   A failed cast to reference type throws [...] std::bad_cast.
6180     unsigned DiagKind;
6181     if (!Paths && (declaresSameEntity(DynType->Type, C) ||
6182                    DynType->Type->isDerivedFrom(C)))
6183       DiagKind = 0;
6184     else if (!Paths || Paths->begin() == Paths->end())
6185       DiagKind = 1;
6186     else if (Paths->isAmbiguous(CQT))
6187       DiagKind = 2;
6188     else {
6189       assert(Paths->front().Access != AS_public && "why did the cast fail?");
6190       DiagKind = 3;
6191     }
6192     Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
6193         << DiagKind << Ptr.Designator.getType(Info.Ctx)
6194         << Info.Ctx.getRecordType(DynType->Type)
6195         << E->getType().getUnqualifiedType();
6196     return false;
6197   };
6198 
6199   // Runtime check, phase 1:
6200   //   Walk from the base subobject towards the derived object looking for the
6201   //   target type.
6202   for (int PathLength = Ptr.Designator.Entries.size();
6203        PathLength >= (int)DynType->PathLength; --PathLength) {
6204     const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
6205     if (declaresSameEntity(Class, C))
6206       return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
6207     // We can only walk across public inheritance edges.
6208     if (PathLength > (int)DynType->PathLength &&
6209         !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
6210                            Class))
6211       return RuntimeCheckFailed(nullptr);
6212   }
6213 
6214   // Runtime check, phase 2:
6215   //   Search the dynamic type for an unambiguous public base of type C.
6216   CXXBasePaths Paths(/*FindAmbiguities=*/true,
6217                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
6218   if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
6219       Paths.front().Access == AS_public) {
6220     // Downcast to the dynamic type...
6221     if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
6222       return false;
6223     // ... then upcast to the chosen base class subobject.
6224     for (CXXBasePathElement &Elem : Paths.front())
6225       if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
6226         return false;
6227     return true;
6228   }
6229 
6230   // Otherwise, the runtime check fails.
6231   return RuntimeCheckFailed(&Paths);
6232 }
6233 
6234 namespace {
6235 struct StartLifetimeOfUnionMemberHandler {
6236   EvalInfo &Info;
6237   const Expr *LHSExpr;
6238   const FieldDecl *Field;
6239   bool DuringInit;
6240   bool Failed = false;
6241   static const AccessKinds AccessKind = AK_Assign;
6242 
6243   typedef bool result_type;
6244   bool failed() { return Failed; }
6245   bool found(APValue &Subobj, QualType SubobjType) {
6246     // We are supposed to perform no initialization but begin the lifetime of
6247     // the object. We interpret that as meaning to do what default
6248     // initialization of the object would do if all constructors involved were
6249     // trivial:
6250     //  * All base, non-variant member, and array element subobjects' lifetimes
6251     //    begin
6252     //  * No variant members' lifetimes begin
6253     //  * All scalar subobjects whose lifetimes begin have indeterminate values
6254     assert(SubobjType->isUnionType());
6255     if (declaresSameEntity(Subobj.getUnionField(), Field)) {
6256       // This union member is already active. If it's also in-lifetime, there's
6257       // nothing to do.
6258       if (Subobj.getUnionValue().hasValue())
6259         return true;
6260     } else if (DuringInit) {
6261       // We're currently in the process of initializing a different union
6262       // member.  If we carried on, that initialization would attempt to
6263       // store to an inactive union member, resulting in undefined behavior.
6264       Info.FFDiag(LHSExpr,
6265                   diag::note_constexpr_union_member_change_during_init);
6266       return false;
6267     }
6268     APValue Result;
6269     Failed = !handleDefaultInitValue(Field->getType(), Result);
6270     Subobj.setUnion(Field, Result);
6271     return true;
6272   }
6273   bool found(APSInt &Value, QualType SubobjType) {
6274     llvm_unreachable("wrong value kind for union object");
6275   }
6276   bool found(APFloat &Value, QualType SubobjType) {
6277     llvm_unreachable("wrong value kind for union object");
6278   }
6279 };
6280 } // end anonymous namespace
6281 
6282 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
6283 
6284 /// Handle a builtin simple-assignment or a call to a trivial assignment
6285 /// operator whose left-hand side might involve a union member access. If it
6286 /// does, implicitly start the lifetime of any accessed union elements per
6287 /// C++20 [class.union]5.
6288 static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info,
6289                                                const Expr *LHSExpr,
6290                                                const LValue &LHS) {
6291   if (LHS.InvalidBase || LHS.Designator.Invalid)
6292     return false;
6293 
6294   llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
6295   // C++ [class.union]p5:
6296   //   define the set S(E) of subexpressions of E as follows:
6297   unsigned PathLength = LHS.Designator.Entries.size();
6298   for (const Expr *E = LHSExpr; E != nullptr;) {
6299     //   -- If E is of the form A.B, S(E) contains the elements of S(A)...
6300     if (auto *ME = dyn_cast<MemberExpr>(E)) {
6301       auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
6302       // Note that we can't implicitly start the lifetime of a reference,
6303       // so we don't need to proceed any further if we reach one.
6304       if (!FD || FD->getType()->isReferenceType())
6305         break;
6306 
6307       //    ... and also contains A.B if B names a union member ...
6308       if (FD->getParent()->isUnion()) {
6309         //    ... of a non-class, non-array type, or of a class type with a
6310         //    trivial default constructor that is not deleted, or an array of
6311         //    such types.
6312         auto *RD =
6313             FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6314         if (!RD || RD->hasTrivialDefaultConstructor())
6315           UnionPathLengths.push_back({PathLength - 1, FD});
6316       }
6317 
6318       E = ME->getBase();
6319       --PathLength;
6320       assert(declaresSameEntity(FD,
6321                                 LHS.Designator.Entries[PathLength]
6322                                     .getAsBaseOrMember().getPointer()));
6323 
6324       //   -- If E is of the form A[B] and is interpreted as a built-in array
6325       //      subscripting operator, S(E) is [S(the array operand, if any)].
6326     } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6327       // Step over an ArrayToPointerDecay implicit cast.
6328       auto *Base = ASE->getBase()->IgnoreImplicit();
6329       if (!Base->getType()->isArrayType())
6330         break;
6331 
6332       E = Base;
6333       --PathLength;
6334 
6335     } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6336       // Step over a derived-to-base conversion.
6337       E = ICE->getSubExpr();
6338       if (ICE->getCastKind() == CK_NoOp)
6339         continue;
6340       if (ICE->getCastKind() != CK_DerivedToBase &&
6341           ICE->getCastKind() != CK_UncheckedDerivedToBase)
6342         break;
6343       // Walk path backwards as we walk up from the base to the derived class.
6344       for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
6345         if (Elt->isVirtual()) {
6346           // A class with virtual base classes never has a trivial default
6347           // constructor, so S(E) is empty in this case.
6348           E = nullptr;
6349           break;
6350         }
6351 
6352         --PathLength;
6353         assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
6354                                   LHS.Designator.Entries[PathLength]
6355                                       .getAsBaseOrMember().getPointer()));
6356       }
6357 
6358     //   -- Otherwise, S(E) is empty.
6359     } else {
6360       break;
6361     }
6362   }
6363 
6364   // Common case: no unions' lifetimes are started.
6365   if (UnionPathLengths.empty())
6366     return true;
6367 
6368   //   if modification of X [would access an inactive union member], an object
6369   //   of the type of X is implicitly created
6370   CompleteObject Obj =
6371       findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
6372   if (!Obj)
6373     return false;
6374   for (std::pair<unsigned, const FieldDecl *> LengthAndField :
6375            llvm::reverse(UnionPathLengths)) {
6376     // Form a designator for the union object.
6377     SubobjectDesignator D = LHS.Designator;
6378     D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
6379 
6380     bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
6381                       ConstructionPhase::AfterBases;
6382     StartLifetimeOfUnionMemberHandler StartLifetime{
6383         Info, LHSExpr, LengthAndField.second, DuringInit};
6384     if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
6385       return false;
6386   }
6387 
6388   return true;
6389 }
6390 
6391 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
6392                             CallRef Call, EvalInfo &Info,
6393                             bool NonNull = false) {
6394   LValue LV;
6395   // Create the parameter slot and register its destruction. For a vararg
6396   // argument, create a temporary.
6397   // FIXME: For calling conventions that destroy parameters in the callee,
6398   // should we consider performing destruction when the function returns
6399   // instead?
6400   APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6401                    : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6402                                                        ScopeKind::Call, LV);
6403   if (!EvaluateInPlace(V, Info, LV, Arg))
6404     return false;
6405 
6406   // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6407   // undefined behavior, so is non-constant.
6408   if (NonNull && V.isLValue() && V.isNullPointer()) {
6409     Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6410     return false;
6411   }
6412 
6413   return true;
6414 }
6415 
6416 /// Evaluate the arguments to a function call.
6417 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6418                          EvalInfo &Info, const FunctionDecl *Callee,
6419                          bool RightToLeft = false) {
6420   bool Success = true;
6421   llvm::SmallBitVector ForbiddenNullArgs;
6422   if (Callee->hasAttr<NonNullAttr>()) {
6423     ForbiddenNullArgs.resize(Args.size());
6424     for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6425       if (!Attr->args_size()) {
6426         ForbiddenNullArgs.set();
6427         break;
6428       } else
6429         for (auto Idx : Attr->args()) {
6430           unsigned ASTIdx = Idx.getASTIndex();
6431           if (ASTIdx >= Args.size())
6432             continue;
6433           ForbiddenNullArgs[ASTIdx] = true;
6434         }
6435     }
6436   }
6437   for (unsigned I = 0; I < Args.size(); I++) {
6438     unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6439     const ParmVarDecl *PVD =
6440         Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6441     bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6442     if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) {
6443       // If we're checking for a potential constant expression, evaluate all
6444       // initializers even if some of them fail.
6445       if (!Info.noteFailure())
6446         return false;
6447       Success = false;
6448     }
6449   }
6450   return Success;
6451 }
6452 
6453 /// Perform a trivial copy from Param, which is the parameter of a copy or move
6454 /// constructor or assignment operator.
6455 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6456                               const Expr *E, APValue &Result,
6457                               bool CopyObjectRepresentation) {
6458   // Find the reference argument.
6459   CallStackFrame *Frame = Info.CurrentCall;
6460   APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6461   if (!RefValue) {
6462     Info.FFDiag(E);
6463     return false;
6464   }
6465 
6466   // Copy out the contents of the RHS object.
6467   LValue RefLValue;
6468   RefLValue.setFrom(Info.Ctx, *RefValue);
6469   return handleLValueToRValueConversion(
6470       Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6471       CopyObjectRepresentation);
6472 }
6473 
6474 /// Evaluate a function call.
6475 static bool HandleFunctionCall(SourceLocation CallLoc,
6476                                const FunctionDecl *Callee, const LValue *This,
6477                                const Expr *E, ArrayRef<const Expr *> Args,
6478                                CallRef Call, const Stmt *Body, EvalInfo &Info,
6479                                APValue &Result, const LValue *ResultSlot) {
6480   if (!Info.CheckCallLimit(CallLoc))
6481     return false;
6482 
6483   CallStackFrame Frame(Info, E->getSourceRange(), Callee, This, E, Call);
6484 
6485   // For a trivial copy or move assignment, perform an APValue copy. This is
6486   // essential for unions, where the operations performed by the assignment
6487   // operator cannot be represented as statements.
6488   //
6489   // Skip this for non-union classes with no fields; in that case, the defaulted
6490   // copy/move does not actually read the object.
6491   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6492   if (MD && MD->isDefaulted() &&
6493       (MD->getParent()->isUnion() ||
6494        (MD->isTrivial() &&
6495         isReadByLvalueToRvalueConversion(MD->getParent())))) {
6496     assert(This &&
6497            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
6498     APValue RHSValue;
6499     if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6500                            MD->getParent()->isUnion()))
6501       return false;
6502     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
6503                           RHSValue))
6504       return false;
6505     This->moveInto(Result);
6506     return true;
6507   } else if (MD && isLambdaCallOperator(MD)) {
6508     // We're in a lambda; determine the lambda capture field maps unless we're
6509     // just constexpr checking a lambda's call operator. constexpr checking is
6510     // done before the captures have been added to the closure object (unless
6511     // we're inferring constexpr-ness), so we don't have access to them in this
6512     // case. But since we don't need the captures to constexpr check, we can
6513     // just ignore them.
6514     if (!Info.checkingPotentialConstantExpression())
6515       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6516                                         Frame.LambdaThisCaptureField);
6517   }
6518 
6519   StmtResult Ret = {Result, ResultSlot};
6520   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6521   if (ESR == ESR_Succeeded) {
6522     if (Callee->getReturnType()->isVoidType())
6523       return true;
6524     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6525   }
6526   return ESR == ESR_Returned;
6527 }
6528 
6529 /// Evaluate a constructor call.
6530 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6531                                   CallRef Call,
6532                                   const CXXConstructorDecl *Definition,
6533                                   EvalInfo &Info, APValue &Result) {
6534   SourceLocation CallLoc = E->getExprLoc();
6535   if (!Info.CheckCallLimit(CallLoc))
6536     return false;
6537 
6538   const CXXRecordDecl *RD = Definition->getParent();
6539   if (RD->getNumVBases()) {
6540     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6541     return false;
6542   }
6543 
6544   EvalInfo::EvaluatingConstructorRAII EvalObj(
6545       Info,
6546       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6547       RD->getNumBases());
6548   CallStackFrame Frame(Info, E->getSourceRange(), Definition, &This, E, Call);
6549 
6550   // FIXME: Creating an APValue just to hold a nonexistent return value is
6551   // wasteful.
6552   APValue RetVal;
6553   StmtResult Ret = {RetVal, nullptr};
6554 
6555   // If it's a delegating constructor, delegate.
6556   if (Definition->isDelegatingConstructor()) {
6557     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
6558     if ((*I)->getInit()->isValueDependent()) {
6559       if (!EvaluateDependentExpr((*I)->getInit(), Info))
6560         return false;
6561     } else {
6562       FullExpressionRAII InitScope(Info);
6563       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6564           !InitScope.destroy())
6565         return false;
6566     }
6567     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6568   }
6569 
6570   // For a trivial copy or move constructor, perform an APValue copy. This is
6571   // essential for unions (or classes with anonymous union members), where the
6572   // operations performed by the constructor cannot be represented by
6573   // ctor-initializers.
6574   //
6575   // Skip this for empty non-union classes; we should not perform an
6576   // lvalue-to-rvalue conversion on them because their copy constructor does not
6577   // actually read them.
6578   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6579       (Definition->getParent()->isUnion() ||
6580        (Definition->isTrivial() &&
6581         isReadByLvalueToRvalueConversion(Definition->getParent())))) {
6582     return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6583                              Definition->getParent()->isUnion());
6584   }
6585 
6586   // Reserve space for the struct members.
6587   if (!Result.hasValue()) {
6588     if (!RD->isUnion())
6589       Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6590                        std::distance(RD->field_begin(), RD->field_end()));
6591     else
6592       // A union starts with no active member.
6593       Result = APValue((const FieldDecl*)nullptr);
6594   }
6595 
6596   if (RD->isInvalidDecl()) return false;
6597   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6598 
6599   // A scope for temporaries lifetime-extended by reference members.
6600   BlockScopeRAII LifetimeExtendedScope(Info);
6601 
6602   bool Success = true;
6603   unsigned BasesSeen = 0;
6604 #ifndef NDEBUG
6605   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
6606 #endif
6607   CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
6608   auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6609     // We might be initializing the same field again if this is an indirect
6610     // field initialization.
6611     if (FieldIt == RD->field_end() ||
6612         FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6613       assert(Indirect && "fields out of order?");
6614       return;
6615     }
6616 
6617     // Default-initialize any fields with no explicit initializer.
6618     for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6619       assert(FieldIt != RD->field_end() && "missing field?");
6620       if (!FieldIt->isUnnamedBitField())
6621         Success &= handleDefaultInitValue(
6622             FieldIt->getType(),
6623             Result.getStructField(FieldIt->getFieldIndex()));
6624     }
6625     ++FieldIt;
6626   };
6627   for (const auto *I : Definition->inits()) {
6628     LValue Subobject = This;
6629     LValue SubobjectParent = This;
6630     APValue *Value = &Result;
6631 
6632     // Determine the subobject to initialize.
6633     FieldDecl *FD = nullptr;
6634     if (I->isBaseInitializer()) {
6635       QualType BaseType(I->getBaseClass(), 0);
6636 #ifndef NDEBUG
6637       // Non-virtual base classes are initialized in the order in the class
6638       // definition. We have already checked for virtual base classes.
6639       assert(!BaseIt->isVirtual() && "virtual base for literal type");
6640       assert(Info.Ctx.hasSameUnqualifiedType(BaseIt->getType(), BaseType) &&
6641              "base class initializers not in expected order");
6642       ++BaseIt;
6643 #endif
6644       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6645                                   BaseType->getAsCXXRecordDecl(), &Layout))
6646         return false;
6647       Value = &Result.getStructBase(BasesSeen++);
6648     } else if ((FD = I->getMember())) {
6649       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6650         return false;
6651       if (RD->isUnion()) {
6652         Result = APValue(FD);
6653         Value = &Result.getUnionValue();
6654       } else {
6655         SkipToField(FD, false);
6656         Value = &Result.getStructField(FD->getFieldIndex());
6657       }
6658     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6659       // Walk the indirect field decl's chain to find the object to initialize,
6660       // and make sure we've initialized every step along it.
6661       auto IndirectFieldChain = IFD->chain();
6662       for (auto *C : IndirectFieldChain) {
6663         FD = cast<FieldDecl>(C);
6664         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6665         // Switch the union field if it differs. This happens if we had
6666         // preceding zero-initialization, and we're now initializing a union
6667         // subobject other than the first.
6668         // FIXME: In this case, the values of the other subobjects are
6669         // specified, since zero-initialization sets all padding bits to zero.
6670         if (!Value->hasValue() ||
6671             (Value->isUnion() && Value->getUnionField() != FD)) {
6672           if (CD->isUnion())
6673             *Value = APValue(FD);
6674           else
6675             // FIXME: This immediately starts the lifetime of all members of
6676             // an anonymous struct. It would be preferable to strictly start
6677             // member lifetime in initialization order.
6678             Success &=
6679                 handleDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
6680         }
6681         // Store Subobject as its parent before updating it for the last element
6682         // in the chain.
6683         if (C == IndirectFieldChain.back())
6684           SubobjectParent = Subobject;
6685         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6686           return false;
6687         if (CD->isUnion())
6688           Value = &Value->getUnionValue();
6689         else {
6690           if (C == IndirectFieldChain.front() && !RD->isUnion())
6691             SkipToField(FD, true);
6692           Value = &Value->getStructField(FD->getFieldIndex());
6693         }
6694       }
6695     } else {
6696       llvm_unreachable("unknown base initializer kind");
6697     }
6698 
6699     // Need to override This for implicit field initializers as in this case
6700     // This refers to innermost anonymous struct/union containing initializer,
6701     // not to currently constructed class.
6702     const Expr *Init = I->getInit();
6703     if (Init->isValueDependent()) {
6704       if (!EvaluateDependentExpr(Init, Info))
6705         return false;
6706     } else {
6707       ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6708                                     isa<CXXDefaultInitExpr>(Init));
6709       FullExpressionRAII InitScope(Info);
6710       if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6711           (FD && FD->isBitField() &&
6712            !truncateBitfieldValue(Info, Init, *Value, FD))) {
6713         // If we're checking for a potential constant expression, evaluate all
6714         // initializers even if some of them fail.
6715         if (!Info.noteFailure())
6716           return false;
6717         Success = false;
6718       }
6719     }
6720 
6721     // This is the point at which the dynamic type of the object becomes this
6722     // class type.
6723     if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6724       EvalObj.finishedConstructingBases();
6725   }
6726 
6727   // Default-initialize any remaining fields.
6728   if (!RD->isUnion()) {
6729     for (; FieldIt != RD->field_end(); ++FieldIt) {
6730       if (!FieldIt->isUnnamedBitField())
6731         Success &= handleDefaultInitValue(
6732             FieldIt->getType(),
6733             Result.getStructField(FieldIt->getFieldIndex()));
6734     }
6735   }
6736 
6737   EvalObj.finishedConstructingFields();
6738 
6739   return Success &&
6740          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6741          LifetimeExtendedScope.destroy();
6742 }
6743 
6744 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6745                                   ArrayRef<const Expr*> Args,
6746                                   const CXXConstructorDecl *Definition,
6747                                   EvalInfo &Info, APValue &Result) {
6748   CallScopeRAII CallScope(Info);
6749   CallRef Call = Info.CurrentCall->createCall(Definition);
6750   if (!EvaluateArgs(Args, Call, Info, Definition))
6751     return false;
6752 
6753   return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6754          CallScope.destroy();
6755 }
6756 
6757 static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange,
6758                                   const LValue &This, APValue &Value,
6759                                   QualType T) {
6760   // Objects can only be destroyed while they're within their lifetimes.
6761   // FIXME: We have no representation for whether an object of type nullptr_t
6762   // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6763   // as indeterminate instead?
6764   if (Value.isAbsent() && !T->isNullPtrType()) {
6765     APValue Printable;
6766     This.moveInto(Printable);
6767     Info.FFDiag(CallRange.getBegin(),
6768                 diag::note_constexpr_destroy_out_of_lifetime)
6769         << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6770     return false;
6771   }
6772 
6773   // Invent an expression for location purposes.
6774   // FIXME: We shouldn't need to do this.
6775   OpaqueValueExpr LocE(CallRange.getBegin(), Info.Ctx.IntTy, VK_PRValue);
6776 
6777   // For arrays, destroy elements right-to-left.
6778   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6779     uint64_t Size = CAT->getZExtSize();
6780     QualType ElemT = CAT->getElementType();
6781 
6782     if (!CheckArraySize(Info, CAT, CallRange.getBegin()))
6783       return false;
6784 
6785     LValue ElemLV = This;
6786     ElemLV.addArray(Info, &LocE, CAT);
6787     if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6788       return false;
6789 
6790     // Ensure that we have actual array elements available to destroy; the
6791     // destructors might mutate the value, so we can't run them on the array
6792     // filler.
6793     if (Size && Size > Value.getArrayInitializedElts())
6794       expandArray(Value, Value.getArraySize() - 1);
6795 
6796     // The size of the array might have been reduced by
6797     // a placement new.
6798     for (Size = Value.getArraySize(); Size != 0; --Size) {
6799       APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6800       if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6801           !HandleDestructionImpl(Info, CallRange, ElemLV, Elem, ElemT))
6802         return false;
6803     }
6804 
6805     // End the lifetime of this array now.
6806     Value = APValue();
6807     return true;
6808   }
6809 
6810   const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6811   if (!RD) {
6812     if (T.isDestructedType()) {
6813       Info.FFDiag(CallRange.getBegin(),
6814                   diag::note_constexpr_unsupported_destruction)
6815           << T;
6816       return false;
6817     }
6818 
6819     Value = APValue();
6820     return true;
6821   }
6822 
6823   if (RD->getNumVBases()) {
6824     Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_virtual_base) << RD;
6825     return false;
6826   }
6827 
6828   const CXXDestructorDecl *DD = RD->getDestructor();
6829   if (!DD && !RD->hasTrivialDestructor()) {
6830     Info.FFDiag(CallRange.getBegin());
6831     return false;
6832   }
6833 
6834   if (!DD || DD->isTrivial() ||
6835       (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6836     // A trivial destructor just ends the lifetime of the object. Check for
6837     // this case before checking for a body, because we might not bother
6838     // building a body for a trivial destructor. Note that it doesn't matter
6839     // whether the destructor is constexpr in this case; all trivial
6840     // destructors are constexpr.
6841     //
6842     // If an anonymous union would be destroyed, some enclosing destructor must
6843     // have been explicitly defined, and the anonymous union destruction should
6844     // have no effect.
6845     Value = APValue();
6846     return true;
6847   }
6848 
6849   if (!Info.CheckCallLimit(CallRange.getBegin()))
6850     return false;
6851 
6852   const FunctionDecl *Definition = nullptr;
6853   const Stmt *Body = DD->getBody(Definition);
6854 
6855   if (!CheckConstexprFunction(Info, CallRange.getBegin(), DD, Definition, Body))
6856     return false;
6857 
6858   CallStackFrame Frame(Info, CallRange, Definition, &This, /*CallExpr=*/nullptr,
6859                        CallRef());
6860 
6861   // We're now in the period of destruction of this object.
6862   unsigned BasesLeft = RD->getNumBases();
6863   EvalInfo::EvaluatingDestructorRAII EvalObj(
6864       Info,
6865       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6866   if (!EvalObj.DidInsert) {
6867     // C++2a [class.dtor]p19:
6868     //   the behavior is undefined if the destructor is invoked for an object
6869     //   whose lifetime has ended
6870     // (Note that formally the lifetime ends when the period of destruction
6871     // begins, even though certain uses of the object remain valid until the
6872     // period of destruction ends.)
6873     Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_double_destroy);
6874     return false;
6875   }
6876 
6877   // FIXME: Creating an APValue just to hold a nonexistent return value is
6878   // wasteful.
6879   APValue RetVal;
6880   StmtResult Ret = {RetVal, nullptr};
6881   if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6882     return false;
6883 
6884   // A union destructor does not implicitly destroy its members.
6885   if (RD->isUnion())
6886     return true;
6887 
6888   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6889 
6890   // We don't have a good way to iterate fields in reverse, so collect all the
6891   // fields first and then walk them backwards.
6892   SmallVector<FieldDecl*, 16> Fields(RD->fields());
6893   for (const FieldDecl *FD : llvm::reverse(Fields)) {
6894     if (FD->isUnnamedBitField())
6895       continue;
6896 
6897     LValue Subobject = This;
6898     if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6899       return false;
6900 
6901     APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6902     if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
6903                                FD->getType()))
6904       return false;
6905   }
6906 
6907   if (BasesLeft != 0)
6908     EvalObj.startedDestroyingBases();
6909 
6910   // Destroy base classes in reverse order.
6911   for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6912     --BasesLeft;
6913 
6914     QualType BaseType = Base.getType();
6915     LValue Subobject = This;
6916     if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
6917                                 BaseType->getAsCXXRecordDecl(), &Layout))
6918       return false;
6919 
6920     APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
6921     if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
6922                                BaseType))
6923       return false;
6924   }
6925   assert(BasesLeft == 0 && "NumBases was wrong?");
6926 
6927   // The period of destruction ends now. The object is gone.
6928   Value = APValue();
6929   return true;
6930 }
6931 
6932 namespace {
6933 struct DestroyObjectHandler {
6934   EvalInfo &Info;
6935   const Expr *E;
6936   const LValue &This;
6937   const AccessKinds AccessKind;
6938 
6939   typedef bool result_type;
6940   bool failed() { return false; }
6941   bool found(APValue &Subobj, QualType SubobjType) {
6942     return HandleDestructionImpl(Info, E->getSourceRange(), This, Subobj,
6943                                  SubobjType);
6944   }
6945   bool found(APSInt &Value, QualType SubobjType) {
6946     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6947     return false;
6948   }
6949   bool found(APFloat &Value, QualType SubobjType) {
6950     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6951     return false;
6952   }
6953 };
6954 }
6955 
6956 /// Perform a destructor or pseudo-destructor call on the given object, which
6957 /// might in general not be a complete object.
6958 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6959                               const LValue &This, QualType ThisType) {
6960   CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6961   DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6962   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6963 }
6964 
6965 /// Destroy and end the lifetime of the given complete object.
6966 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6967                               APValue::LValueBase LVBase, APValue &Value,
6968                               QualType T) {
6969   // If we've had an unmodeled side-effect, we can't rely on mutable state
6970   // (such as the object we're about to destroy) being correct.
6971   if (Info.EvalStatus.HasSideEffects)
6972     return false;
6973 
6974   LValue LV;
6975   LV.set({LVBase});
6976   return HandleDestructionImpl(Info, Loc, LV, Value, T);
6977 }
6978 
6979 /// Perform a call to 'operator new' or to `__builtin_operator_new'.
6980 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6981                                   LValue &Result) {
6982   if (Info.checkingPotentialConstantExpression() ||
6983       Info.SpeculativeEvaluationDepth)
6984     return false;
6985 
6986   // This is permitted only within a call to std::allocator<T>::allocate.
6987   auto Caller = Info.getStdAllocatorCaller("allocate");
6988   if (!Caller) {
6989     Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
6990                                      ? diag::note_constexpr_new_untyped
6991                                      : diag::note_constexpr_new);
6992     return false;
6993   }
6994 
6995   QualType ElemType = Caller.ElemType;
6996   if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6997     Info.FFDiag(E->getExprLoc(),
6998                 diag::note_constexpr_new_not_complete_object_type)
6999         << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
7000     return false;
7001   }
7002 
7003   APSInt ByteSize;
7004   if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
7005     return false;
7006   bool IsNothrow = false;
7007   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
7008     EvaluateIgnoredValue(Info, E->getArg(I));
7009     IsNothrow |= E->getType()->isNothrowT();
7010   }
7011 
7012   CharUnits ElemSize;
7013   if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
7014     return false;
7015   APInt Size, Remainder;
7016   APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
7017   APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
7018   if (Remainder != 0) {
7019     // This likely indicates a bug in the implementation of 'std::allocator'.
7020     Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
7021         << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
7022     return false;
7023   }
7024 
7025   if (!Info.CheckArraySize(E->getBeginLoc(), ByteSize.getActiveBits(),
7026                            Size.getZExtValue(), /*Diag=*/!IsNothrow)) {
7027     if (IsNothrow) {
7028       Result.setNull(Info.Ctx, E->getType());
7029       return true;
7030     }
7031     return false;
7032   }
7033 
7034   QualType AllocType = Info.Ctx.getConstantArrayType(
7035       ElemType, Size, nullptr, ArraySizeModifier::Normal, 0);
7036   APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
7037   *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
7038   Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
7039   return true;
7040 }
7041 
7042 static bool hasVirtualDestructor(QualType T) {
7043   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7044     if (CXXDestructorDecl *DD = RD->getDestructor())
7045       return DD->isVirtual();
7046   return false;
7047 }
7048 
7049 static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
7050   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7051     if (CXXDestructorDecl *DD = RD->getDestructor())
7052       return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
7053   return nullptr;
7054 }
7055 
7056 /// Check that the given object is a suitable pointer to a heap allocation that
7057 /// still exists and is of the right kind for the purpose of a deletion.
7058 ///
7059 /// On success, returns the heap allocation to deallocate. On failure, produces
7060 /// a diagnostic and returns std::nullopt.
7061 static std::optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
7062                                                  const LValue &Pointer,
7063                                                  DynAlloc::Kind DeallocKind) {
7064   auto PointerAsString = [&] {
7065     return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
7066   };
7067 
7068   DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
7069   if (!DA) {
7070     Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
7071         << PointerAsString();
7072     if (Pointer.Base)
7073       NoteLValueLocation(Info, Pointer.Base);
7074     return std::nullopt;
7075   }
7076 
7077   std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
7078   if (!Alloc) {
7079     Info.FFDiag(E, diag::note_constexpr_double_delete);
7080     return std::nullopt;
7081   }
7082 
7083   if (DeallocKind != (*Alloc)->getKind()) {
7084     QualType AllocType = Pointer.Base.getDynamicAllocType();
7085     Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
7086         << DeallocKind << (*Alloc)->getKind() << AllocType;
7087     NoteLValueLocation(Info, Pointer.Base);
7088     return std::nullopt;
7089   }
7090 
7091   bool Subobject = false;
7092   if (DeallocKind == DynAlloc::New) {
7093     Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
7094                 Pointer.Designator.isOnePastTheEnd();
7095   } else {
7096     Subobject = Pointer.Designator.Entries.size() != 1 ||
7097                 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
7098   }
7099   if (Subobject) {
7100     Info.FFDiag(E, diag::note_constexpr_delete_subobject)
7101         << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
7102     return std::nullopt;
7103   }
7104 
7105   return Alloc;
7106 }
7107 
7108 // Perform a call to 'operator delete' or '__builtin_operator_delete'.
7109 static bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
7110   if (Info.checkingPotentialConstantExpression() ||
7111       Info.SpeculativeEvaluationDepth)
7112     return false;
7113 
7114   // This is permitted only within a call to std::allocator<T>::deallocate.
7115   if (!Info.getStdAllocatorCaller("deallocate")) {
7116     Info.FFDiag(E->getExprLoc());
7117     return true;
7118   }
7119 
7120   LValue Pointer;
7121   if (!EvaluatePointer(E->getArg(0), Pointer, Info))
7122     return false;
7123   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
7124     EvaluateIgnoredValue(Info, E->getArg(I));
7125 
7126   if (Pointer.Designator.Invalid)
7127     return false;
7128 
7129   // Deleting a null pointer would have no effect, but it's not permitted by
7130   // std::allocator<T>::deallocate's contract.
7131   if (Pointer.isNullPointer()) {
7132     Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
7133     return true;
7134   }
7135 
7136   if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
7137     return false;
7138 
7139   Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
7140   return true;
7141 }
7142 
7143 //===----------------------------------------------------------------------===//
7144 // Generic Evaluation
7145 //===----------------------------------------------------------------------===//
7146 namespace {
7147 
7148 class BitCastBuffer {
7149   // FIXME: We're going to need bit-level granularity when we support
7150   // bit-fields.
7151   // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
7152   // we don't support a host or target where that is the case. Still, we should
7153   // use a more generic type in case we ever do.
7154   SmallVector<std::optional<unsigned char>, 32> Bytes;
7155 
7156   static_assert(std::numeric_limits<unsigned char>::digits >= 8,
7157                 "Need at least 8 bit unsigned char");
7158 
7159   bool TargetIsLittleEndian;
7160 
7161 public:
7162   BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
7163       : Bytes(Width.getQuantity()),
7164         TargetIsLittleEndian(TargetIsLittleEndian) {}
7165 
7166   [[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width,
7167                                 SmallVectorImpl<unsigned char> &Output) const {
7168     for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
7169       // If a byte of an integer is uninitialized, then the whole integer is
7170       // uninitialized.
7171       if (!Bytes[I.getQuantity()])
7172         return false;
7173       Output.push_back(*Bytes[I.getQuantity()]);
7174     }
7175     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7176       std::reverse(Output.begin(), Output.end());
7177     return true;
7178   }
7179 
7180   void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
7181     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7182       std::reverse(Input.begin(), Input.end());
7183 
7184     size_t Index = 0;
7185     for (unsigned char Byte : Input) {
7186       assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
7187       Bytes[Offset.getQuantity() + Index] = Byte;
7188       ++Index;
7189     }
7190   }
7191 
7192   size_t size() { return Bytes.size(); }
7193 };
7194 
7195 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
7196 /// target would represent the value at runtime.
7197 class APValueToBufferConverter {
7198   EvalInfo &Info;
7199   BitCastBuffer Buffer;
7200   const CastExpr *BCE;
7201 
7202   APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
7203                            const CastExpr *BCE)
7204       : Info(Info),
7205         Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
7206         BCE(BCE) {}
7207 
7208   bool visit(const APValue &Val, QualType Ty) {
7209     return visit(Val, Ty, CharUnits::fromQuantity(0));
7210   }
7211 
7212   // Write out Val with type Ty into Buffer starting at Offset.
7213   bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
7214     assert((size_t)Offset.getQuantity() <= Buffer.size());
7215 
7216     // As a special case, nullptr_t has an indeterminate value.
7217     if (Ty->isNullPtrType())
7218       return true;
7219 
7220     // Dig through Src to find the byte at SrcOffset.
7221     switch (Val.getKind()) {
7222     case APValue::Indeterminate:
7223     case APValue::None:
7224       return true;
7225 
7226     case APValue::Int:
7227       return visitInt(Val.getInt(), Ty, Offset);
7228     case APValue::Float:
7229       return visitFloat(Val.getFloat(), Ty, Offset);
7230     case APValue::Array:
7231       return visitArray(Val, Ty, Offset);
7232     case APValue::Struct:
7233       return visitRecord(Val, Ty, Offset);
7234     case APValue::Vector:
7235       return visitVector(Val, Ty, Offset);
7236 
7237     case APValue::ComplexInt:
7238     case APValue::ComplexFloat:
7239       return visitComplex(Val, Ty, Offset);
7240     case APValue::FixedPoint:
7241       // FIXME: We should support these.
7242 
7243     case APValue::Union:
7244     case APValue::MemberPointer:
7245     case APValue::AddrLabelDiff: {
7246       Info.FFDiag(BCE->getBeginLoc(),
7247                   diag::note_constexpr_bit_cast_unsupported_type)
7248           << Ty;
7249       return false;
7250     }
7251 
7252     case APValue::LValue:
7253       llvm_unreachable("LValue subobject in bit_cast?");
7254     }
7255     llvm_unreachable("Unhandled APValue::ValueKind");
7256   }
7257 
7258   bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
7259     const RecordDecl *RD = Ty->getAsRecordDecl();
7260     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7261 
7262     // Visit the base classes.
7263     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7264       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7265         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7266         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7267 
7268         if (!visitRecord(Val.getStructBase(I), BS.getType(),
7269                          Layout.getBaseClassOffset(BaseDecl) + Offset))
7270           return false;
7271       }
7272     }
7273 
7274     // Visit the fields.
7275     unsigned FieldIdx = 0;
7276     for (FieldDecl *FD : RD->fields()) {
7277       if (FD->isBitField()) {
7278         Info.FFDiag(BCE->getBeginLoc(),
7279                     diag::note_constexpr_bit_cast_unsupported_bitfield);
7280         return false;
7281       }
7282 
7283       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7284 
7285       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
7286              "only bit-fields can have sub-char alignment");
7287       CharUnits FieldOffset =
7288           Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
7289       QualType FieldTy = FD->getType();
7290       if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
7291         return false;
7292       ++FieldIdx;
7293     }
7294 
7295     return true;
7296   }
7297 
7298   bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
7299     const auto *CAT =
7300         dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
7301     if (!CAT)
7302       return false;
7303 
7304     CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
7305     unsigned NumInitializedElts = Val.getArrayInitializedElts();
7306     unsigned ArraySize = Val.getArraySize();
7307     // First, initialize the initialized elements.
7308     for (unsigned I = 0; I != NumInitializedElts; ++I) {
7309       const APValue &SubObj = Val.getArrayInitializedElt(I);
7310       if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
7311         return false;
7312     }
7313 
7314     // Next, initialize the rest of the array using the filler.
7315     if (Val.hasArrayFiller()) {
7316       const APValue &Filler = Val.getArrayFiller();
7317       for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
7318         if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
7319           return false;
7320       }
7321     }
7322 
7323     return true;
7324   }
7325 
7326   bool visitComplex(const APValue &Val, QualType Ty, CharUnits Offset) {
7327     const ComplexType *ComplexTy = Ty->castAs<ComplexType>();
7328     QualType EltTy = ComplexTy->getElementType();
7329     CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7330     bool IsInt = Val.isComplexInt();
7331 
7332     if (IsInt) {
7333       if (!visitInt(Val.getComplexIntReal(), EltTy,
7334                     Offset + (0 * EltSizeChars)))
7335         return false;
7336       if (!visitInt(Val.getComplexIntImag(), EltTy,
7337                     Offset + (1 * EltSizeChars)))
7338         return false;
7339     } else {
7340       if (!visitFloat(Val.getComplexFloatReal(), EltTy,
7341                       Offset + (0 * EltSizeChars)))
7342         return false;
7343       if (!visitFloat(Val.getComplexFloatImag(), EltTy,
7344                       Offset + (1 * EltSizeChars)))
7345         return false;
7346     }
7347 
7348     return true;
7349   }
7350 
7351   bool visitVector(const APValue &Val, QualType Ty, CharUnits Offset) {
7352     const VectorType *VTy = Ty->castAs<VectorType>();
7353     QualType EltTy = VTy->getElementType();
7354     unsigned NElts = VTy->getNumElements();
7355     unsigned EltSize =
7356         VTy->isExtVectorBoolType() ? 1 : Info.Ctx.getTypeSize(EltTy);
7357 
7358     if ((NElts * EltSize) % Info.Ctx.getCharWidth() != 0) {
7359       // The vector's size in bits is not a multiple of the target's byte size,
7360       // so its layout is unspecified. For now, we'll simply treat these cases
7361       // as unsupported (this should only be possible with OpenCL bool vectors
7362       // whose element count isn't a multiple of the byte size).
7363       Info.FFDiag(BCE->getBeginLoc(),
7364                   diag::note_constexpr_bit_cast_invalid_vector)
7365           << Ty.getCanonicalType() << EltSize << NElts
7366           << Info.Ctx.getCharWidth();
7367       return false;
7368     }
7369 
7370     if (EltTy->isRealFloatingType() && &Info.Ctx.getFloatTypeSemantics(EltTy) ==
7371                                            &APFloat::x87DoubleExtended()) {
7372       // The layout for x86_fp80 vectors seems to be handled very inconsistently
7373       // by both clang and LLVM, so for now we won't allow bit_casts involving
7374       // it in a constexpr context.
7375       Info.FFDiag(BCE->getBeginLoc(),
7376                   diag::note_constexpr_bit_cast_unsupported_type)
7377           << EltTy;
7378       return false;
7379     }
7380 
7381     if (VTy->isExtVectorBoolType()) {
7382       // Special handling for OpenCL bool vectors:
7383       // Since these vectors are stored as packed bits, but we can't write
7384       // individual bits to the BitCastBuffer, we'll buffer all of the elements
7385       // together into an appropriately sized APInt and write them all out at
7386       // once. Because we don't accept vectors where NElts * EltSize isn't a
7387       // multiple of the char size, there will be no padding space, so we don't
7388       // have to worry about writing data which should have been left
7389       // uninitialized.
7390       bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7391 
7392       llvm::APInt Res = llvm::APInt::getZero(NElts);
7393       for (unsigned I = 0; I < NElts; ++I) {
7394         const llvm::APSInt &EltAsInt = Val.getVectorElt(I).getInt();
7395         assert(EltAsInt.isUnsigned() && EltAsInt.getBitWidth() == 1 &&
7396                "bool vector element must be 1-bit unsigned integer!");
7397 
7398         Res.insertBits(EltAsInt, BigEndian ? (NElts - I - 1) : I);
7399       }
7400 
7401       SmallVector<uint8_t, 8> Bytes(NElts / 8);
7402       llvm::StoreIntToMemory(Res, &*Bytes.begin(), NElts / 8);
7403       Buffer.writeObject(Offset, Bytes);
7404     } else {
7405       // Iterate over each of the elements and write them out to the buffer at
7406       // the appropriate offset.
7407       CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7408       for (unsigned I = 0; I < NElts; ++I) {
7409         if (!visit(Val.getVectorElt(I), EltTy, Offset + I * EltSizeChars))
7410           return false;
7411       }
7412     }
7413 
7414     return true;
7415   }
7416 
7417   bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
7418     APSInt AdjustedVal = Val;
7419     unsigned Width = AdjustedVal.getBitWidth();
7420     if (Ty->isBooleanType()) {
7421       Width = Info.Ctx.getTypeSize(Ty);
7422       AdjustedVal = AdjustedVal.extend(Width);
7423     }
7424 
7425     SmallVector<uint8_t, 8> Bytes(Width / 8);
7426     llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
7427     Buffer.writeObject(Offset, Bytes);
7428     return true;
7429   }
7430 
7431   bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
7432     APSInt AsInt(Val.bitcastToAPInt());
7433     return visitInt(AsInt, Ty, Offset);
7434   }
7435 
7436 public:
7437   static std::optional<BitCastBuffer>
7438   convert(EvalInfo &Info, const APValue &Src, const CastExpr *BCE) {
7439     CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
7440     APValueToBufferConverter Converter(Info, DstSize, BCE);
7441     if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
7442       return std::nullopt;
7443     return Converter.Buffer;
7444   }
7445 };
7446 
7447 /// Write an BitCastBuffer into an APValue.
7448 class BufferToAPValueConverter {
7449   EvalInfo &Info;
7450   const BitCastBuffer &Buffer;
7451   const CastExpr *BCE;
7452 
7453   BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
7454                            const CastExpr *BCE)
7455       : Info(Info), Buffer(Buffer), BCE(BCE) {}
7456 
7457   // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
7458   // with an invalid type, so anything left is a deficiency on our part (FIXME).
7459   // Ideally this will be unreachable.
7460   std::nullopt_t unsupportedType(QualType Ty) {
7461     Info.FFDiag(BCE->getBeginLoc(),
7462                 diag::note_constexpr_bit_cast_unsupported_type)
7463         << Ty;
7464     return std::nullopt;
7465   }
7466 
7467   std::nullopt_t unrepresentableValue(QualType Ty, const APSInt &Val) {
7468     Info.FFDiag(BCE->getBeginLoc(),
7469                 diag::note_constexpr_bit_cast_unrepresentable_value)
7470         << Ty << toString(Val, /*Radix=*/10);
7471     return std::nullopt;
7472   }
7473 
7474   std::optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
7475                                const EnumType *EnumSugar = nullptr) {
7476     if (T->isNullPtrType()) {
7477       uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
7478       return APValue((Expr *)nullptr,
7479                      /*Offset=*/CharUnits::fromQuantity(NullValue),
7480                      APValue::NoLValuePath{}, /*IsNullPtr=*/true);
7481     }
7482 
7483     CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
7484 
7485     // Work around floating point types that contain unused padding bytes. This
7486     // is really just `long double` on x86, which is the only fundamental type
7487     // with padding bytes.
7488     if (T->isRealFloatingType()) {
7489       const llvm::fltSemantics &Semantics =
7490           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7491       unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
7492       assert(NumBits % 8 == 0);
7493       CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
7494       if (NumBytes != SizeOf)
7495         SizeOf = NumBytes;
7496     }
7497 
7498     SmallVector<uint8_t, 8> Bytes;
7499     if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
7500       // If this is std::byte or unsigned char, then its okay to store an
7501       // indeterminate value.
7502       bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
7503       bool IsUChar =
7504           !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
7505                          T->isSpecificBuiltinType(BuiltinType::Char_U));
7506       if (!IsStdByte && !IsUChar) {
7507         QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
7508         Info.FFDiag(BCE->getExprLoc(),
7509                     diag::note_constexpr_bit_cast_indet_dest)
7510             << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
7511         return std::nullopt;
7512       }
7513 
7514       return APValue::IndeterminateValue();
7515     }
7516 
7517     APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
7518     llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
7519 
7520     if (T->isIntegralOrEnumerationType()) {
7521       Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7522 
7523       unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
7524       if (IntWidth != Val.getBitWidth()) {
7525         APSInt Truncated = Val.trunc(IntWidth);
7526         if (Truncated.extend(Val.getBitWidth()) != Val)
7527           return unrepresentableValue(QualType(T, 0), Val);
7528         Val = Truncated;
7529       }
7530 
7531       return APValue(Val);
7532     }
7533 
7534     if (T->isRealFloatingType()) {
7535       const llvm::fltSemantics &Semantics =
7536           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7537       return APValue(APFloat(Semantics, Val));
7538     }
7539 
7540     return unsupportedType(QualType(T, 0));
7541   }
7542 
7543   std::optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7544     const RecordDecl *RD = RTy->getAsRecordDecl();
7545     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7546 
7547     unsigned NumBases = 0;
7548     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7549       NumBases = CXXRD->getNumBases();
7550 
7551     APValue ResultVal(APValue::UninitStruct(), NumBases,
7552                       std::distance(RD->field_begin(), RD->field_end()));
7553 
7554     // Visit the base classes.
7555     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7556       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7557         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7558         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7559 
7560         std::optional<APValue> SubObj = visitType(
7561             BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7562         if (!SubObj)
7563           return std::nullopt;
7564         ResultVal.getStructBase(I) = *SubObj;
7565       }
7566     }
7567 
7568     // Visit the fields.
7569     unsigned FieldIdx = 0;
7570     for (FieldDecl *FD : RD->fields()) {
7571       // FIXME: We don't currently support bit-fields. A lot of the logic for
7572       // this is in CodeGen, so we need to factor it around.
7573       if (FD->isBitField()) {
7574         Info.FFDiag(BCE->getBeginLoc(),
7575                     diag::note_constexpr_bit_cast_unsupported_bitfield);
7576         return std::nullopt;
7577       }
7578 
7579       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7580       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
7581 
7582       CharUnits FieldOffset =
7583           CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7584           Offset;
7585       QualType FieldTy = FD->getType();
7586       std::optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7587       if (!SubObj)
7588         return std::nullopt;
7589       ResultVal.getStructField(FieldIdx) = *SubObj;
7590       ++FieldIdx;
7591     }
7592 
7593     return ResultVal;
7594   }
7595 
7596   std::optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7597     QualType RepresentationType = Ty->getDecl()->getIntegerType();
7598     assert(!RepresentationType.isNull() &&
7599            "enum forward decl should be caught by Sema");
7600     const auto *AsBuiltin =
7601         RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7602     // Recurse into the underlying type. Treat std::byte transparently as
7603     // unsigned char.
7604     return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7605   }
7606 
7607   std::optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7608     size_t Size = Ty->getLimitedSize();
7609     CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7610 
7611     APValue ArrayValue(APValue::UninitArray(), Size, Size);
7612     for (size_t I = 0; I != Size; ++I) {
7613       std::optional<APValue> ElementValue =
7614           visitType(Ty->getElementType(), Offset + I * ElementWidth);
7615       if (!ElementValue)
7616         return std::nullopt;
7617       ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7618     }
7619 
7620     return ArrayValue;
7621   }
7622 
7623   std::optional<APValue> visit(const ComplexType *Ty, CharUnits Offset) {
7624     QualType ElementType = Ty->getElementType();
7625     CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(ElementType);
7626     bool IsInt = ElementType->isIntegerType();
7627 
7628     std::optional<APValue> Values[2];
7629     for (unsigned I = 0; I != 2; ++I) {
7630       Values[I] = visitType(Ty->getElementType(), Offset + I * ElementWidth);
7631       if (!Values[I])
7632         return std::nullopt;
7633     }
7634 
7635     if (IsInt)
7636       return APValue(Values[0]->getInt(), Values[1]->getInt());
7637     return APValue(Values[0]->getFloat(), Values[1]->getFloat());
7638   }
7639 
7640   std::optional<APValue> visit(const VectorType *VTy, CharUnits Offset) {
7641     QualType EltTy = VTy->getElementType();
7642     unsigned NElts = VTy->getNumElements();
7643     unsigned EltSize =
7644         VTy->isExtVectorBoolType() ? 1 : Info.Ctx.getTypeSize(EltTy);
7645 
7646     if ((NElts * EltSize) % Info.Ctx.getCharWidth() != 0) {
7647       // The vector's size in bits is not a multiple of the target's byte size,
7648       // so its layout is unspecified. For now, we'll simply treat these cases
7649       // as unsupported (this should only be possible with OpenCL bool vectors
7650       // whose element count isn't a multiple of the byte size).
7651       Info.FFDiag(BCE->getBeginLoc(),
7652                   diag::note_constexpr_bit_cast_invalid_vector)
7653           << QualType(VTy, 0) << EltSize << NElts << Info.Ctx.getCharWidth();
7654       return std::nullopt;
7655     }
7656 
7657     if (EltTy->isRealFloatingType() && &Info.Ctx.getFloatTypeSemantics(EltTy) ==
7658                                            &APFloat::x87DoubleExtended()) {
7659       // The layout for x86_fp80 vectors seems to be handled very inconsistently
7660       // by both clang and LLVM, so for now we won't allow bit_casts involving
7661       // it in a constexpr context.
7662       Info.FFDiag(BCE->getBeginLoc(),
7663                   diag::note_constexpr_bit_cast_unsupported_type)
7664           << EltTy;
7665       return std::nullopt;
7666     }
7667 
7668     SmallVector<APValue, 4> Elts;
7669     Elts.reserve(NElts);
7670     if (VTy->isExtVectorBoolType()) {
7671       // Special handling for OpenCL bool vectors:
7672       // Since these vectors are stored as packed bits, but we can't read
7673       // individual bits from the BitCastBuffer, we'll buffer all of the
7674       // elements together into an appropriately sized APInt and write them all
7675       // out at once. Because we don't accept vectors where NElts * EltSize
7676       // isn't a multiple of the char size, there will be no padding space, so
7677       // we don't have to worry about reading any padding data which didn't
7678       // actually need to be accessed.
7679       bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7680 
7681       SmallVector<uint8_t, 8> Bytes;
7682       Bytes.reserve(NElts / 8);
7683       if (!Buffer.readObject(Offset, CharUnits::fromQuantity(NElts / 8), Bytes))
7684         return std::nullopt;
7685 
7686       APSInt SValInt(NElts, true);
7687       llvm::LoadIntFromMemory(SValInt, &*Bytes.begin(), Bytes.size());
7688 
7689       for (unsigned I = 0; I < NElts; ++I) {
7690         llvm::APInt Elt =
7691             SValInt.extractBits(1, (BigEndian ? NElts - I - 1 : I) * EltSize);
7692         Elts.emplace_back(
7693             APSInt(std::move(Elt), !EltTy->isSignedIntegerType()));
7694       }
7695     } else {
7696       // Iterate over each of the elements and read them from the buffer at
7697       // the appropriate offset.
7698       CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7699       for (unsigned I = 0; I < NElts; ++I) {
7700         std::optional<APValue> EltValue =
7701             visitType(EltTy, Offset + I * EltSizeChars);
7702         if (!EltValue)
7703           return std::nullopt;
7704         Elts.push_back(std::move(*EltValue));
7705       }
7706     }
7707 
7708     return APValue(Elts.data(), Elts.size());
7709   }
7710 
7711   std::optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7712     return unsupportedType(QualType(Ty, 0));
7713   }
7714 
7715   std::optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7716     QualType Can = Ty.getCanonicalType();
7717 
7718     switch (Can->getTypeClass()) {
7719 #define TYPE(Class, Base)                                                      \
7720   case Type::Class:                                                            \
7721     return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7722 #define ABSTRACT_TYPE(Class, Base)
7723 #define NON_CANONICAL_TYPE(Class, Base)                                        \
7724   case Type::Class:                                                            \
7725     llvm_unreachable("non-canonical type should be impossible!");
7726 #define DEPENDENT_TYPE(Class, Base)                                            \
7727   case Type::Class:                                                            \
7728     llvm_unreachable(                                                          \
7729         "dependent types aren't supported in the constant evaluator!");
7730 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)                            \
7731   case Type::Class:                                                            \
7732     llvm_unreachable("either dependent or not canonical!");
7733 #include "clang/AST/TypeNodes.inc"
7734     }
7735     llvm_unreachable("Unhandled Type::TypeClass");
7736   }
7737 
7738 public:
7739   // Pull out a full value of type DstType.
7740   static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7741                                         const CastExpr *BCE) {
7742     BufferToAPValueConverter Converter(Info, Buffer, BCE);
7743     return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7744   }
7745 };
7746 
7747 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7748                                                  QualType Ty, EvalInfo *Info,
7749                                                  const ASTContext &Ctx,
7750                                                  bool CheckingDest) {
7751   Ty = Ty.getCanonicalType();
7752 
7753   auto diag = [&](int Reason) {
7754     if (Info)
7755       Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7756           << CheckingDest << (Reason == 4) << Reason;
7757     return false;
7758   };
7759   auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7760     if (Info)
7761       Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7762           << NoteTy << Construct << Ty;
7763     return false;
7764   };
7765 
7766   if (Ty->isUnionType())
7767     return diag(0);
7768   if (Ty->isPointerType())
7769     return diag(1);
7770   if (Ty->isMemberPointerType())
7771     return diag(2);
7772   if (Ty.isVolatileQualified())
7773     return diag(3);
7774 
7775   if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7776     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7777       for (CXXBaseSpecifier &BS : CXXRD->bases())
7778         if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7779                                                   CheckingDest))
7780           return note(1, BS.getType(), BS.getBeginLoc());
7781     }
7782     for (FieldDecl *FD : Record->fields()) {
7783       if (FD->getType()->isReferenceType())
7784         return diag(4);
7785       if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7786                                                 CheckingDest))
7787         return note(0, FD->getType(), FD->getBeginLoc());
7788     }
7789   }
7790 
7791   if (Ty->isArrayType() &&
7792       !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7793                                             Info, Ctx, CheckingDest))
7794     return false;
7795 
7796   return true;
7797 }
7798 
7799 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
7800                                              const ASTContext &Ctx,
7801                                              const CastExpr *BCE) {
7802   bool DestOK = checkBitCastConstexprEligibilityType(
7803       BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
7804   bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
7805                                 BCE->getBeginLoc(),
7806                                 BCE->getSubExpr()->getType(), Info, Ctx, false);
7807   return SourceOK;
7808 }
7809 
7810 static bool handleRValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7811                                         const APValue &SourceRValue,
7812                                         const CastExpr *BCE) {
7813   assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7814          "no host or target supports non 8-bit chars");
7815 
7816   if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
7817     return false;
7818 
7819   // Read out SourceValue into a char buffer.
7820   std::optional<BitCastBuffer> Buffer =
7821       APValueToBufferConverter::convert(Info, SourceRValue, BCE);
7822   if (!Buffer)
7823     return false;
7824 
7825   // Write out the buffer into a new APValue.
7826   std::optional<APValue> MaybeDestValue =
7827       BufferToAPValueConverter::convert(Info, *Buffer, BCE);
7828   if (!MaybeDestValue)
7829     return false;
7830 
7831   DestValue = std::move(*MaybeDestValue);
7832   return true;
7833 }
7834 
7835 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7836                                         APValue &SourceValue,
7837                                         const CastExpr *BCE) {
7838   assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7839          "no host or target supports non 8-bit chars");
7840   assert(SourceValue.isLValue() &&
7841          "LValueToRValueBitcast requires an lvalue operand!");
7842 
7843   LValue SourceLValue;
7844   APValue SourceRValue;
7845   SourceLValue.setFrom(Info.Ctx, SourceValue);
7846   if (!handleLValueToRValueConversion(
7847           Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
7848           SourceRValue, /*WantObjectRepresentation=*/true))
7849     return false;
7850 
7851   return handleRValueToRValueBitCast(Info, DestValue, SourceRValue, BCE);
7852 }
7853 
7854 template <class Derived>
7855 class ExprEvaluatorBase
7856   : public ConstStmtVisitor<Derived, bool> {
7857 private:
7858   Derived &getDerived() { return static_cast<Derived&>(*this); }
7859   bool DerivedSuccess(const APValue &V, const Expr *E) {
7860     return getDerived().Success(V, E);
7861   }
7862   bool DerivedZeroInitialization(const Expr *E) {
7863     return getDerived().ZeroInitialization(E);
7864   }
7865 
7866   // Check whether a conditional operator with a non-constant condition is a
7867   // potential constant expression. If neither arm is a potential constant
7868   // expression, then the conditional operator is not either.
7869   template<typename ConditionalOperator>
7870   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7871     assert(Info.checkingPotentialConstantExpression());
7872 
7873     // Speculatively evaluate both arms.
7874     SmallVector<PartialDiagnosticAt, 8> Diag;
7875     {
7876       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7877       StmtVisitorTy::Visit(E->getFalseExpr());
7878       if (Diag.empty())
7879         return;
7880     }
7881 
7882     {
7883       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7884       Diag.clear();
7885       StmtVisitorTy::Visit(E->getTrueExpr());
7886       if (Diag.empty())
7887         return;
7888     }
7889 
7890     Error(E, diag::note_constexpr_conditional_never_const);
7891   }
7892 
7893 
7894   template<typename ConditionalOperator>
7895   bool HandleConditionalOperator(const ConditionalOperator *E) {
7896     bool BoolResult;
7897     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7898       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7899         CheckPotentialConstantConditional(E);
7900         return false;
7901       }
7902       if (Info.noteFailure()) {
7903         StmtVisitorTy::Visit(E->getTrueExpr());
7904         StmtVisitorTy::Visit(E->getFalseExpr());
7905       }
7906       return false;
7907     }
7908 
7909     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
7910     return StmtVisitorTy::Visit(EvalExpr);
7911   }
7912 
7913 protected:
7914   EvalInfo &Info;
7915   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
7916   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
7917 
7918   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7919     return Info.CCEDiag(E, D);
7920   }
7921 
7922   bool ZeroInitialization(const Expr *E) { return Error(E); }
7923 
7924   bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
7925     unsigned BuiltinOp = E->getBuiltinCallee();
7926     return BuiltinOp != 0 &&
7927            Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp);
7928   }
7929 
7930 public:
7931   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
7932 
7933   EvalInfo &getEvalInfo() { return Info; }
7934 
7935   /// Report an evaluation error. This should only be called when an error is
7936   /// first discovered. When propagating an error, just return false.
7937   bool Error(const Expr *E, diag::kind D) {
7938     Info.FFDiag(E, D) << E->getSourceRange();
7939     return false;
7940   }
7941   bool Error(const Expr *E) {
7942     return Error(E, diag::note_invalid_subexpr_in_const_expr);
7943   }
7944 
7945   bool VisitStmt(const Stmt *) {
7946     llvm_unreachable("Expression evaluator should not be called on stmts");
7947   }
7948   bool VisitExpr(const Expr *E) {
7949     return Error(E);
7950   }
7951 
7952   bool VisitEmbedExpr(const EmbedExpr *E) {
7953     const auto It = E->begin();
7954     return StmtVisitorTy::Visit(*It);
7955   }
7956 
7957   bool VisitPredefinedExpr(const PredefinedExpr *E) {
7958     return StmtVisitorTy::Visit(E->getFunctionName());
7959   }
7960   bool VisitConstantExpr(const ConstantExpr *E) {
7961     if (E->hasAPValueResult())
7962       return DerivedSuccess(E->getAPValueResult(), E);
7963 
7964     return StmtVisitorTy::Visit(E->getSubExpr());
7965   }
7966 
7967   bool VisitParenExpr(const ParenExpr *E)
7968     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7969   bool VisitUnaryExtension(const UnaryOperator *E)
7970     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7971   bool VisitUnaryPlus(const UnaryOperator *E)
7972     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7973   bool VisitChooseExpr(const ChooseExpr *E)
7974     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
7975   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
7976     { return StmtVisitorTy::Visit(E->getResultExpr()); }
7977   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
7978     { return StmtVisitorTy::Visit(E->getReplacement()); }
7979   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7980     TempVersionRAII RAII(*Info.CurrentCall);
7981     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7982     return StmtVisitorTy::Visit(E->getExpr());
7983   }
7984   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7985     TempVersionRAII RAII(*Info.CurrentCall);
7986     // The initializer may not have been parsed yet, or might be erroneous.
7987     if (!E->getExpr())
7988       return Error(E);
7989     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7990     return StmtVisitorTy::Visit(E->getExpr());
7991   }
7992 
7993   bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7994     FullExpressionRAII Scope(Info);
7995     return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
7996   }
7997 
7998   // Temporaries are registered when created, so we don't care about
7999   // CXXBindTemporaryExpr.
8000   bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
8001     return StmtVisitorTy::Visit(E->getSubExpr());
8002   }
8003 
8004   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
8005     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
8006     return static_cast<Derived*>(this)->VisitCastExpr(E);
8007   }
8008   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
8009     if (!Info.Ctx.getLangOpts().CPlusPlus20)
8010       CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
8011     return static_cast<Derived*>(this)->VisitCastExpr(E);
8012   }
8013   bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
8014     return static_cast<Derived*>(this)->VisitCastExpr(E);
8015   }
8016 
8017   bool VisitBinaryOperator(const BinaryOperator *E) {
8018     switch (E->getOpcode()) {
8019     default:
8020       return Error(E);
8021 
8022     case BO_Comma:
8023       VisitIgnoredValue(E->getLHS());
8024       return StmtVisitorTy::Visit(E->getRHS());
8025 
8026     case BO_PtrMemD:
8027     case BO_PtrMemI: {
8028       LValue Obj;
8029       if (!HandleMemberPointerAccess(Info, E, Obj))
8030         return false;
8031       APValue Result;
8032       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
8033         return false;
8034       return DerivedSuccess(Result, E);
8035     }
8036     }
8037   }
8038 
8039   bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
8040     return StmtVisitorTy::Visit(E->getSemanticForm());
8041   }
8042 
8043   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
8044     // Evaluate and cache the common expression. We treat it as a temporary,
8045     // even though it's not quite the same thing.
8046     LValue CommonLV;
8047     if (!Evaluate(Info.CurrentCall->createTemporary(
8048                       E->getOpaqueValue(),
8049                       getStorageType(Info.Ctx, E->getOpaqueValue()),
8050                       ScopeKind::FullExpression, CommonLV),
8051                   Info, E->getCommon()))
8052       return false;
8053 
8054     return HandleConditionalOperator(E);
8055   }
8056 
8057   bool VisitConditionalOperator(const ConditionalOperator *E) {
8058     bool IsBcpCall = false;
8059     // If the condition (ignoring parens) is a __builtin_constant_p call,
8060     // the result is a constant expression if it can be folded without
8061     // side-effects. This is an important GNU extension. See GCC PR38377
8062     // for discussion.
8063     if (const CallExpr *CallCE =
8064           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
8065       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
8066         IsBcpCall = true;
8067 
8068     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
8069     // constant expression; we can't check whether it's potentially foldable.
8070     // FIXME: We should instead treat __builtin_constant_p as non-constant if
8071     // it would return 'false' in this mode.
8072     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
8073       return false;
8074 
8075     FoldConstant Fold(Info, IsBcpCall);
8076     if (!HandleConditionalOperator(E)) {
8077       Fold.keepDiagnostics();
8078       return false;
8079     }
8080 
8081     return true;
8082   }
8083 
8084   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
8085     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E);
8086         Value && !Value->isAbsent())
8087       return DerivedSuccess(*Value, E);
8088 
8089     const Expr *Source = E->getSourceExpr();
8090     if (!Source)
8091       return Error(E);
8092     if (Source == E) {
8093       assert(0 && "OpaqueValueExpr recursively refers to itself");
8094       return Error(E);
8095     }
8096     return StmtVisitorTy::Visit(Source);
8097   }
8098 
8099   bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
8100     for (const Expr *SemE : E->semantics()) {
8101       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
8102         // FIXME: We can't handle the case where an OpaqueValueExpr is also the
8103         // result expression: there could be two different LValues that would
8104         // refer to the same object in that case, and we can't model that.
8105         if (SemE == E->getResultExpr())
8106           return Error(E);
8107 
8108         // Unique OVEs get evaluated if and when we encounter them when
8109         // emitting the rest of the semantic form, rather than eagerly.
8110         if (OVE->isUnique())
8111           continue;
8112 
8113         LValue LV;
8114         if (!Evaluate(Info.CurrentCall->createTemporary(
8115                           OVE, getStorageType(Info.Ctx, OVE),
8116                           ScopeKind::FullExpression, LV),
8117                       Info, OVE->getSourceExpr()))
8118           return false;
8119       } else if (SemE == E->getResultExpr()) {
8120         if (!StmtVisitorTy::Visit(SemE))
8121           return false;
8122       } else {
8123         if (!EvaluateIgnoredValue(Info, SemE))
8124           return false;
8125       }
8126     }
8127     return true;
8128   }
8129 
8130   bool VisitCallExpr(const CallExpr *E) {
8131     APValue Result;
8132     if (!handleCallExpr(E, Result, nullptr))
8133       return false;
8134     return DerivedSuccess(Result, E);
8135   }
8136 
8137   bool handleCallExpr(const CallExpr *E, APValue &Result,
8138                      const LValue *ResultSlot) {
8139     CallScopeRAII CallScope(Info);
8140 
8141     const Expr *Callee = E->getCallee()->IgnoreParens();
8142     QualType CalleeType = Callee->getType();
8143 
8144     const FunctionDecl *FD = nullptr;
8145     LValue *This = nullptr, ThisVal;
8146     auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
8147     bool HasQualifier = false;
8148 
8149     CallRef Call;
8150 
8151     // Extract function decl and 'this' pointer from the callee.
8152     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
8153       const CXXMethodDecl *Member = nullptr;
8154       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
8155         // Explicit bound member calls, such as x.f() or p->g();
8156         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
8157           return false;
8158         Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
8159         if (!Member)
8160           return Error(Callee);
8161         This = &ThisVal;
8162         HasQualifier = ME->hasQualifier();
8163       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
8164         // Indirect bound member calls ('.*' or '->*').
8165         const ValueDecl *D =
8166             HandleMemberPointerAccess(Info, BE, ThisVal, false);
8167         if (!D)
8168           return false;
8169         Member = dyn_cast<CXXMethodDecl>(D);
8170         if (!Member)
8171           return Error(Callee);
8172         This = &ThisVal;
8173       } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
8174         if (!Info.getLangOpts().CPlusPlus20)
8175           Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
8176         return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
8177                HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
8178       } else
8179         return Error(Callee);
8180       FD = Member;
8181     } else if (CalleeType->isFunctionPointerType()) {
8182       LValue CalleeLV;
8183       if (!EvaluatePointer(Callee, CalleeLV, Info))
8184         return false;
8185 
8186       if (!CalleeLV.getLValueOffset().isZero())
8187         return Error(Callee);
8188       if (CalleeLV.isNullPointer()) {
8189         Info.FFDiag(Callee, diag::note_constexpr_null_callee)
8190             << const_cast<Expr *>(Callee);
8191         return false;
8192       }
8193       FD = dyn_cast_or_null<FunctionDecl>(
8194           CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
8195       if (!FD)
8196         return Error(Callee);
8197       // Don't call function pointers which have been cast to some other type.
8198       // Per DR (no number yet), the caller and callee can differ in noexcept.
8199       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
8200         CalleeType->getPointeeType(), FD->getType())) {
8201         return Error(E);
8202       }
8203 
8204       // For an (overloaded) assignment expression, evaluate the RHS before the
8205       // LHS.
8206       auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
8207       if (OCE && OCE->isAssignmentOp()) {
8208         assert(Args.size() == 2 && "wrong number of arguments in assignment");
8209         Call = Info.CurrentCall->createCall(FD);
8210         bool HasThis = false;
8211         if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
8212           HasThis = MD->isImplicitObjectMemberFunction();
8213         if (!EvaluateArgs(HasThis ? Args.slice(1) : Args, Call, Info, FD,
8214                           /*RightToLeft=*/true))
8215           return false;
8216       }
8217 
8218       // Overloaded operator calls to member functions are represented as normal
8219       // calls with '*this' as the first argument.
8220       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8221       if (MD &&
8222           (MD->isImplicitObjectMemberFunction() || (OCE && MD->isStatic()))) {
8223         // FIXME: When selecting an implicit conversion for an overloaded
8224         // operator delete, we sometimes try to evaluate calls to conversion
8225         // operators without a 'this' parameter!
8226         if (Args.empty())
8227           return Error(E);
8228 
8229         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
8230           return false;
8231 
8232         // If we are calling a static operator, the 'this' argument needs to be
8233         // ignored after being evaluated.
8234         if (MD->isInstance())
8235           This = &ThisVal;
8236 
8237         // If this is syntactically a simple assignment using a trivial
8238         // assignment operator, start the lifetimes of union members as needed,
8239         // per C++20 [class.union]5.
8240         if (Info.getLangOpts().CPlusPlus20 && OCE &&
8241             OCE->getOperator() == OO_Equal && MD->isTrivial() &&
8242             !MaybeHandleUnionActiveMemberChange(Info, Args[0], ThisVal))
8243           return false;
8244 
8245         Args = Args.slice(1);
8246       } else if (MD && MD->isLambdaStaticInvoker()) {
8247         // Map the static invoker for the lambda back to the call operator.
8248         // Conveniently, we don't have to slice out the 'this' argument (as is
8249         // being done for the non-static case), since a static member function
8250         // doesn't have an implicit argument passed in.
8251         const CXXRecordDecl *ClosureClass = MD->getParent();
8252         assert(
8253             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
8254             "Number of captures must be zero for conversion to function-ptr");
8255 
8256         const CXXMethodDecl *LambdaCallOp =
8257             ClosureClass->getLambdaCallOperator();
8258 
8259         // Set 'FD', the function that will be called below, to the call
8260         // operator.  If the closure object represents a generic lambda, find
8261         // the corresponding specialization of the call operator.
8262 
8263         if (ClosureClass->isGenericLambda()) {
8264           assert(MD->isFunctionTemplateSpecialization() &&
8265                  "A generic lambda's static-invoker function must be a "
8266                  "template specialization");
8267           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
8268           FunctionTemplateDecl *CallOpTemplate =
8269               LambdaCallOp->getDescribedFunctionTemplate();
8270           void *InsertPos = nullptr;
8271           FunctionDecl *CorrespondingCallOpSpecialization =
8272               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
8273           assert(CorrespondingCallOpSpecialization &&
8274                  "We must always have a function call operator specialization "
8275                  "that corresponds to our static invoker specialization");
8276           assert(isa<CXXMethodDecl>(CorrespondingCallOpSpecialization));
8277           FD = CorrespondingCallOpSpecialization;
8278         } else
8279           FD = LambdaCallOp;
8280       } else if (FD->isReplaceableGlobalAllocationFunction()) {
8281         if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
8282             FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
8283           LValue Ptr;
8284           if (!HandleOperatorNewCall(Info, E, Ptr))
8285             return false;
8286           Ptr.moveInto(Result);
8287           return CallScope.destroy();
8288         } else {
8289           return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
8290         }
8291       }
8292     } else
8293       return Error(E);
8294 
8295     // Evaluate the arguments now if we've not already done so.
8296     if (!Call) {
8297       Call = Info.CurrentCall->createCall(FD);
8298       if (!EvaluateArgs(Args, Call, Info, FD))
8299         return false;
8300     }
8301 
8302     SmallVector<QualType, 4> CovariantAdjustmentPath;
8303     if (This) {
8304       auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
8305       if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
8306         // Perform virtual dispatch, if necessary.
8307         FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
8308                                    CovariantAdjustmentPath);
8309         if (!FD)
8310           return false;
8311       } else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) {
8312         // Check that the 'this' pointer points to an object of the right type.
8313         // FIXME: If this is an assignment operator call, we may need to change
8314         // the active union member before we check this.
8315         if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
8316           return false;
8317       }
8318     }
8319 
8320     // Destructor calls are different enough that they have their own codepath.
8321     if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
8322       assert(This && "no 'this' pointer for destructor call");
8323       return HandleDestruction(Info, E, *This,
8324                                Info.Ctx.getRecordType(DD->getParent())) &&
8325              CallScope.destroy();
8326     }
8327 
8328     const FunctionDecl *Definition = nullptr;
8329     Stmt *Body = FD->getBody(Definition);
8330 
8331     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
8332         !HandleFunctionCall(E->getExprLoc(), Definition, This, E, Args, Call,
8333                             Body, Info, Result, ResultSlot))
8334       return false;
8335 
8336     if (!CovariantAdjustmentPath.empty() &&
8337         !HandleCovariantReturnAdjustment(Info, E, Result,
8338                                          CovariantAdjustmentPath))
8339       return false;
8340 
8341     return CallScope.destroy();
8342   }
8343 
8344   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8345     return StmtVisitorTy::Visit(E->getInitializer());
8346   }
8347   bool VisitInitListExpr(const InitListExpr *E) {
8348     if (E->getNumInits() == 0)
8349       return DerivedZeroInitialization(E);
8350     if (E->getNumInits() == 1)
8351       return StmtVisitorTy::Visit(E->getInit(0));
8352     return Error(E);
8353   }
8354   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
8355     return DerivedZeroInitialization(E);
8356   }
8357   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
8358     return DerivedZeroInitialization(E);
8359   }
8360   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
8361     return DerivedZeroInitialization(E);
8362   }
8363 
8364   /// A member expression where the object is a prvalue is itself a prvalue.
8365   bool VisitMemberExpr(const MemberExpr *E) {
8366     assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
8367            "missing temporary materialization conversion");
8368     assert(!E->isArrow() && "missing call to bound member function?");
8369 
8370     APValue Val;
8371     if (!Evaluate(Val, Info, E->getBase()))
8372       return false;
8373 
8374     QualType BaseTy = E->getBase()->getType();
8375 
8376     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
8377     if (!FD) return Error(E);
8378     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
8379     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8380            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8381 
8382     // Note: there is no lvalue base here. But this case should only ever
8383     // happen in C or in C++98, where we cannot be evaluating a constexpr
8384     // constructor, which is the only case the base matters.
8385     CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
8386     SubobjectDesignator Designator(BaseTy);
8387     Designator.addDeclUnchecked(FD);
8388 
8389     APValue Result;
8390     return extractSubobject(Info, E, Obj, Designator, Result) &&
8391            DerivedSuccess(Result, E);
8392   }
8393 
8394   bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
8395     APValue Val;
8396     if (!Evaluate(Val, Info, E->getBase()))
8397       return false;
8398 
8399     if (Val.isVector()) {
8400       SmallVector<uint32_t, 4> Indices;
8401       E->getEncodedElementAccess(Indices);
8402       if (Indices.size() == 1) {
8403         // Return scalar.
8404         return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
8405       } else {
8406         // Construct new APValue vector.
8407         SmallVector<APValue, 4> Elts;
8408         for (unsigned I = 0; I < Indices.size(); ++I) {
8409           Elts.push_back(Val.getVectorElt(Indices[I]));
8410         }
8411         APValue VecResult(Elts.data(), Indices.size());
8412         return DerivedSuccess(VecResult, E);
8413       }
8414     }
8415 
8416     return false;
8417   }
8418 
8419   bool VisitCastExpr(const CastExpr *E) {
8420     switch (E->getCastKind()) {
8421     default:
8422       break;
8423 
8424     case CK_AtomicToNonAtomic: {
8425       APValue AtomicVal;
8426       // This does not need to be done in place even for class/array types:
8427       // atomic-to-non-atomic conversion implies copying the object
8428       // representation.
8429       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
8430         return false;
8431       return DerivedSuccess(AtomicVal, E);
8432     }
8433 
8434     case CK_NoOp:
8435     case CK_UserDefinedConversion:
8436       return StmtVisitorTy::Visit(E->getSubExpr());
8437 
8438     case CK_LValueToRValue: {
8439       LValue LVal;
8440       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
8441         return false;
8442       APValue RVal;
8443       // Note, we use the subexpression's type in order to retain cv-qualifiers.
8444       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8445                                           LVal, RVal))
8446         return false;
8447       return DerivedSuccess(RVal, E);
8448     }
8449     case CK_LValueToRValueBitCast: {
8450       APValue DestValue, SourceValue;
8451       if (!Evaluate(SourceValue, Info, E->getSubExpr()))
8452         return false;
8453       if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
8454         return false;
8455       return DerivedSuccess(DestValue, E);
8456     }
8457 
8458     case CK_AddressSpaceConversion: {
8459       APValue Value;
8460       if (!Evaluate(Value, Info, E->getSubExpr()))
8461         return false;
8462       return DerivedSuccess(Value, E);
8463     }
8464     }
8465 
8466     return Error(E);
8467   }
8468 
8469   bool VisitUnaryPostInc(const UnaryOperator *UO) {
8470     return VisitUnaryPostIncDec(UO);
8471   }
8472   bool VisitUnaryPostDec(const UnaryOperator *UO) {
8473     return VisitUnaryPostIncDec(UO);
8474   }
8475   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
8476     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8477       return Error(UO);
8478 
8479     LValue LVal;
8480     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
8481       return false;
8482     APValue RVal;
8483     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
8484                       UO->isIncrementOp(), &RVal))
8485       return false;
8486     return DerivedSuccess(RVal, UO);
8487   }
8488 
8489   bool VisitStmtExpr(const StmtExpr *E) {
8490     // We will have checked the full-expressions inside the statement expression
8491     // when they were completed, and don't need to check them again now.
8492     llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
8493                                           false);
8494 
8495     const CompoundStmt *CS = E->getSubStmt();
8496     if (CS->body_empty())
8497       return true;
8498 
8499     BlockScopeRAII Scope(Info);
8500     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
8501                                            BE = CS->body_end();
8502          /**/; ++BI) {
8503       if (BI + 1 == BE) {
8504         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
8505         if (!FinalExpr) {
8506           Info.FFDiag((*BI)->getBeginLoc(),
8507                       diag::note_constexpr_stmt_expr_unsupported);
8508           return false;
8509         }
8510         return this->Visit(FinalExpr) && Scope.destroy();
8511       }
8512 
8513       APValue ReturnValue;
8514       StmtResult Result = { ReturnValue, nullptr };
8515       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
8516       if (ESR != ESR_Succeeded) {
8517         // FIXME: If the statement-expression terminated due to 'return',
8518         // 'break', or 'continue', it would be nice to propagate that to
8519         // the outer statement evaluation rather than bailing out.
8520         if (ESR != ESR_Failed)
8521           Info.FFDiag((*BI)->getBeginLoc(),
8522                       diag::note_constexpr_stmt_expr_unsupported);
8523         return false;
8524       }
8525     }
8526 
8527     llvm_unreachable("Return from function from the loop above.");
8528   }
8529 
8530   bool VisitPackIndexingExpr(const PackIndexingExpr *E) {
8531     return StmtVisitorTy::Visit(E->getSelectedExpr());
8532   }
8533 
8534   /// Visit a value which is evaluated, but whose value is ignored.
8535   void VisitIgnoredValue(const Expr *E) {
8536     EvaluateIgnoredValue(Info, E);
8537   }
8538 
8539   /// Potentially visit a MemberExpr's base expression.
8540   void VisitIgnoredBaseExpression(const Expr *E) {
8541     // While MSVC doesn't evaluate the base expression, it does diagnose the
8542     // presence of side-effecting behavior.
8543     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
8544       return;
8545     VisitIgnoredValue(E);
8546   }
8547 };
8548 
8549 } // namespace
8550 
8551 //===----------------------------------------------------------------------===//
8552 // Common base class for lvalue and temporary evaluation.
8553 //===----------------------------------------------------------------------===//
8554 namespace {
8555 template<class Derived>
8556 class LValueExprEvaluatorBase
8557   : public ExprEvaluatorBase<Derived> {
8558 protected:
8559   LValue &Result;
8560   bool InvalidBaseOK;
8561   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
8562   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
8563 
8564   bool Success(APValue::LValueBase B) {
8565     Result.set(B);
8566     return true;
8567   }
8568 
8569   bool evaluatePointer(const Expr *E, LValue &Result) {
8570     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
8571   }
8572 
8573 public:
8574   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
8575       : ExprEvaluatorBaseTy(Info), Result(Result),
8576         InvalidBaseOK(InvalidBaseOK) {}
8577 
8578   bool Success(const APValue &V, const Expr *E) {
8579     Result.setFrom(this->Info.Ctx, V);
8580     return true;
8581   }
8582 
8583   bool VisitMemberExpr(const MemberExpr *E) {
8584     // Handle non-static data members.
8585     QualType BaseTy;
8586     bool EvalOK;
8587     if (E->isArrow()) {
8588       EvalOK = evaluatePointer(E->getBase(), Result);
8589       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
8590     } else if (E->getBase()->isPRValue()) {
8591       assert(E->getBase()->getType()->isRecordType());
8592       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
8593       BaseTy = E->getBase()->getType();
8594     } else {
8595       EvalOK = this->Visit(E->getBase());
8596       BaseTy = E->getBase()->getType();
8597     }
8598     if (!EvalOK) {
8599       if (!InvalidBaseOK)
8600         return false;
8601       Result.setInvalid(E);
8602       return true;
8603     }
8604 
8605     const ValueDecl *MD = E->getMemberDecl();
8606     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
8607       assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8608              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8609       (void)BaseTy;
8610       if (!HandleLValueMember(this->Info, E, Result, FD))
8611         return false;
8612     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
8613       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
8614         return false;
8615     } else
8616       return this->Error(E);
8617 
8618     if (MD->getType()->isReferenceType()) {
8619       APValue RefValue;
8620       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
8621                                           RefValue))
8622         return false;
8623       return Success(RefValue, E);
8624     }
8625     return true;
8626   }
8627 
8628   bool VisitBinaryOperator(const BinaryOperator *E) {
8629     switch (E->getOpcode()) {
8630     default:
8631       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8632 
8633     case BO_PtrMemD:
8634     case BO_PtrMemI:
8635       return HandleMemberPointerAccess(this->Info, E, Result);
8636     }
8637   }
8638 
8639   bool VisitCastExpr(const CastExpr *E) {
8640     switch (E->getCastKind()) {
8641     default:
8642       return ExprEvaluatorBaseTy::VisitCastExpr(E);
8643 
8644     case CK_DerivedToBase:
8645     case CK_UncheckedDerivedToBase:
8646       if (!this->Visit(E->getSubExpr()))
8647         return false;
8648 
8649       // Now figure out the necessary offset to add to the base LV to get from
8650       // the derived class to the base class.
8651       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8652                                   Result);
8653     }
8654   }
8655 };
8656 }
8657 
8658 //===----------------------------------------------------------------------===//
8659 // LValue Evaluation
8660 //
8661 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8662 // function designators (in C), decl references to void objects (in C), and
8663 // temporaries (if building with -Wno-address-of-temporary).
8664 //
8665 // LValue evaluation produces values comprising a base expression of one of the
8666 // following types:
8667 // - Declarations
8668 //  * VarDecl
8669 //  * FunctionDecl
8670 // - Literals
8671 //  * CompoundLiteralExpr in C (and in global scope in C++)
8672 //  * StringLiteral
8673 //  * PredefinedExpr
8674 //  * ObjCStringLiteralExpr
8675 //  * ObjCEncodeExpr
8676 //  * AddrLabelExpr
8677 //  * BlockExpr
8678 //  * CallExpr for a MakeStringConstant builtin
8679 // - typeid(T) expressions, as TypeInfoLValues
8680 // - Locals and temporaries
8681 //  * MaterializeTemporaryExpr
8682 //  * Any Expr, with a CallIndex indicating the function in which the temporary
8683 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
8684 //    from the AST (FIXME).
8685 //  * A MaterializeTemporaryExpr that has static storage duration, with no
8686 //    CallIndex, for a lifetime-extended temporary.
8687 //  * The ConstantExpr that is currently being evaluated during evaluation of an
8688 //    immediate invocation.
8689 // plus an offset in bytes.
8690 //===----------------------------------------------------------------------===//
8691 namespace {
8692 class LValueExprEvaluator
8693   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8694 public:
8695   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8696     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8697 
8698   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8699   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8700 
8701   bool VisitCallExpr(const CallExpr *E);
8702   bool VisitDeclRefExpr(const DeclRefExpr *E);
8703   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8704   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8705   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8706   bool VisitMemberExpr(const MemberExpr *E);
8707   bool VisitStringLiteral(const StringLiteral *E) {
8708     return Success(APValue::LValueBase(
8709         E, 0, Info.getASTContext().getNextStringLiteralVersion()));
8710   }
8711   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8712   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8713   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8714   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8715   bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E);
8716   bool VisitUnaryDeref(const UnaryOperator *E);
8717   bool VisitUnaryReal(const UnaryOperator *E);
8718   bool VisitUnaryImag(const UnaryOperator *E);
8719   bool VisitUnaryPreInc(const UnaryOperator *UO) {
8720     return VisitUnaryPreIncDec(UO);
8721   }
8722   bool VisitUnaryPreDec(const UnaryOperator *UO) {
8723     return VisitUnaryPreIncDec(UO);
8724   }
8725   bool VisitBinAssign(const BinaryOperator *BO);
8726   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8727 
8728   bool VisitCastExpr(const CastExpr *E) {
8729     switch (E->getCastKind()) {
8730     default:
8731       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8732 
8733     case CK_LValueBitCast:
8734       this->CCEDiag(E, diag::note_constexpr_invalid_cast)
8735           << 2 << Info.Ctx.getLangOpts().CPlusPlus;
8736       if (!Visit(E->getSubExpr()))
8737         return false;
8738       Result.Designator.setInvalid();
8739       return true;
8740 
8741     case CK_BaseToDerived:
8742       if (!Visit(E->getSubExpr()))
8743         return false;
8744       return HandleBaseToDerivedCast(Info, E, Result);
8745 
8746     case CK_Dynamic:
8747       if (!Visit(E->getSubExpr()))
8748         return false;
8749       return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8750     }
8751   }
8752 };
8753 } // end anonymous namespace
8754 
8755 /// Get an lvalue to a field of a lambda's closure type.
8756 static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result,
8757                                 const CXXMethodDecl *MD, const FieldDecl *FD,
8758                                 bool LValueToRValueConversion) {
8759   // Static lambda function call operators can't have captures. We already
8760   // diagnosed this, so bail out here.
8761   if (MD->isStatic()) {
8762     assert(Info.CurrentCall->This == nullptr &&
8763            "This should not be set for a static call operator");
8764     return false;
8765   }
8766 
8767   // Start with 'Result' referring to the complete closure object...
8768   if (MD->isExplicitObjectMemberFunction()) {
8769     // Self may be passed by reference or by value.
8770     const ParmVarDecl *Self = MD->getParamDecl(0);
8771     if (Self->getType()->isReferenceType()) {
8772       APValue *RefValue = Info.getParamSlot(Info.CurrentCall->Arguments, Self);
8773       Result.setFrom(Info.Ctx, *RefValue);
8774     } else {
8775       const ParmVarDecl *VD = Info.CurrentCall->Arguments.getOrigParam(Self);
8776       CallStackFrame *Frame =
8777           Info.getCallFrameAndDepth(Info.CurrentCall->Arguments.CallIndex)
8778               .first;
8779       unsigned Version = Info.CurrentCall->Arguments.Version;
8780       Result.set({VD, Frame->Index, Version});
8781     }
8782   } else
8783     Result = *Info.CurrentCall->This;
8784 
8785   // ... then update it to refer to the field of the closure object
8786   // that represents the capture.
8787   if (!HandleLValueMember(Info, E, Result, FD))
8788     return false;
8789 
8790   // And if the field is of reference type (or if we captured '*this' by
8791   // reference), update 'Result' to refer to what
8792   // the field refers to.
8793   if (LValueToRValueConversion) {
8794     APValue RVal;
8795     if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, RVal))
8796       return false;
8797     Result.setFrom(Info.Ctx, RVal);
8798   }
8799   return true;
8800 }
8801 
8802 /// Evaluate an expression as an lvalue. This can be legitimately called on
8803 /// expressions which are not glvalues, in three cases:
8804 ///  * function designators in C, and
8805 ///  * "extern void" objects
8806 ///  * @selector() expressions in Objective-C
8807 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
8808                            bool InvalidBaseOK) {
8809   assert(!E->isValueDependent());
8810   assert(E->isGLValue() || E->getType()->isFunctionType() ||
8811          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E->IgnoreParens()));
8812   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8813 }
8814 
8815 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
8816   const NamedDecl *D = E->getDecl();
8817   if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl,
8818           UnnamedGlobalConstantDecl>(D))
8819     return Success(cast<ValueDecl>(D));
8820   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
8821     return VisitVarDecl(E, VD);
8822   if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
8823     return Visit(BD->getBinding());
8824   return Error(E);
8825 }
8826 
8827 
8828 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
8829 
8830   // If we are within a lambda's call operator, check whether the 'VD' referred
8831   // to within 'E' actually represents a lambda-capture that maps to a
8832   // data-member/field within the closure object, and if so, evaluate to the
8833   // field or what the field refers to.
8834   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
8835       isa<DeclRefExpr>(E) &&
8836       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
8837     // We don't always have a complete capture-map when checking or inferring if
8838     // the function call operator meets the requirements of a constexpr function
8839     // - but we don't need to evaluate the captures to determine constexprness
8840     // (dcl.constexpr C++17).
8841     if (Info.checkingPotentialConstantExpression())
8842       return false;
8843 
8844     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
8845       const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
8846       return HandleLambdaCapture(Info, E, Result, MD, FD,
8847                                  FD->getType()->isReferenceType());
8848     }
8849   }
8850 
8851   CallStackFrame *Frame = nullptr;
8852   unsigned Version = 0;
8853   if (VD->hasLocalStorage()) {
8854     // Only if a local variable was declared in the function currently being
8855     // evaluated, do we expect to be able to find its value in the current
8856     // frame. (Otherwise it was likely declared in an enclosing context and
8857     // could either have a valid evaluatable value (for e.g. a constexpr
8858     // variable) or be ill-formed (and trigger an appropriate evaluation
8859     // diagnostic)).
8860     CallStackFrame *CurrFrame = Info.CurrentCall;
8861     if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
8862       // Function parameters are stored in some caller's frame. (Usually the
8863       // immediate caller, but for an inherited constructor they may be more
8864       // distant.)
8865       if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
8866         if (CurrFrame->Arguments) {
8867           VD = CurrFrame->Arguments.getOrigParam(PVD);
8868           Frame =
8869               Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
8870           Version = CurrFrame->Arguments.Version;
8871         }
8872       } else {
8873         Frame = CurrFrame;
8874         Version = CurrFrame->getCurrentTemporaryVersion(VD);
8875       }
8876     }
8877   }
8878 
8879   if (!VD->getType()->isReferenceType()) {
8880     if (Frame) {
8881       Result.set({VD, Frame->Index, Version});
8882       return true;
8883     }
8884     return Success(VD);
8885   }
8886 
8887   if (!Info.getLangOpts().CPlusPlus11) {
8888     Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
8889         << VD << VD->getType();
8890     Info.Note(VD->getLocation(), diag::note_declared_at);
8891   }
8892 
8893   APValue *V;
8894   if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
8895     return false;
8896   if (!V->hasValue()) {
8897     // FIXME: Is it possible for V to be indeterminate here? If so, we should
8898     // adjust the diagnostic to say that.
8899     if (!Info.checkingPotentialConstantExpression())
8900       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
8901     return false;
8902   }
8903   return Success(*V, E);
8904 }
8905 
8906 bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {
8907   if (!IsConstantEvaluatedBuiltinCall(E))
8908     return ExprEvaluatorBaseTy::VisitCallExpr(E);
8909 
8910   switch (E->getBuiltinCallee()) {
8911   default:
8912     return false;
8913   case Builtin::BIas_const:
8914   case Builtin::BIforward:
8915   case Builtin::BIforward_like:
8916   case Builtin::BImove:
8917   case Builtin::BImove_if_noexcept:
8918     if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())
8919       return Visit(E->getArg(0));
8920     break;
8921   }
8922 
8923   return ExprEvaluatorBaseTy::VisitCallExpr(E);
8924 }
8925 
8926 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
8927     const MaterializeTemporaryExpr *E) {
8928   // Walk through the expression to find the materialized temporary itself.
8929   SmallVector<const Expr *, 2> CommaLHSs;
8930   SmallVector<SubobjectAdjustment, 2> Adjustments;
8931   const Expr *Inner =
8932       E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
8933 
8934   // If we passed any comma operators, evaluate their LHSs.
8935   for (const Expr *E : CommaLHSs)
8936     if (!EvaluateIgnoredValue(Info, E))
8937       return false;
8938 
8939   // A materialized temporary with static storage duration can appear within the
8940   // result of a constant expression evaluation, so we need to preserve its
8941   // value for use outside this evaluation.
8942   APValue *Value;
8943   if (E->getStorageDuration() == SD_Static) {
8944     if (Info.EvalMode == EvalInfo::EM_ConstantFold)
8945       return false;
8946     // FIXME: What about SD_Thread?
8947     Value = E->getOrCreateValue(true);
8948     *Value = APValue();
8949     Result.set(E);
8950   } else {
8951     Value = &Info.CurrentCall->createTemporary(
8952         E, Inner->getType(),
8953         E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
8954                                                      : ScopeKind::Block,
8955         Result);
8956   }
8957 
8958   QualType Type = Inner->getType();
8959 
8960   // Materialize the temporary itself.
8961   if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
8962     *Value = APValue();
8963     return false;
8964   }
8965 
8966   // Adjust our lvalue to refer to the desired subobject.
8967   for (unsigned I = Adjustments.size(); I != 0; /**/) {
8968     --I;
8969     switch (Adjustments[I].Kind) {
8970     case SubobjectAdjustment::DerivedToBaseAdjustment:
8971       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
8972                                 Type, Result))
8973         return false;
8974       Type = Adjustments[I].DerivedToBase.BasePath->getType();
8975       break;
8976 
8977     case SubobjectAdjustment::FieldAdjustment:
8978       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
8979         return false;
8980       Type = Adjustments[I].Field->getType();
8981       break;
8982 
8983     case SubobjectAdjustment::MemberPointerAdjustment:
8984       if (!HandleMemberPointerAccess(this->Info, Type, Result,
8985                                      Adjustments[I].Ptr.RHS))
8986         return false;
8987       Type = Adjustments[I].Ptr.MPT->getPointeeType();
8988       break;
8989     }
8990   }
8991 
8992   return true;
8993 }
8994 
8995 bool
8996 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8997   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
8998          "lvalue compound literal in c++?");
8999   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
9000   // only see this when folding in C, so there's no standard to follow here.
9001   return Success(E);
9002 }
9003 
9004 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
9005   TypeInfoLValue TypeInfo;
9006 
9007   if (!E->isPotentiallyEvaluated()) {
9008     if (E->isTypeOperand())
9009       TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
9010     else
9011       TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
9012   } else {
9013     if (!Info.Ctx.getLangOpts().CPlusPlus20) {
9014       Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
9015         << E->getExprOperand()->getType()
9016         << E->getExprOperand()->getSourceRange();
9017     }
9018 
9019     if (!Visit(E->getExprOperand()))
9020       return false;
9021 
9022     std::optional<DynamicType> DynType =
9023         ComputeDynamicType(Info, E, Result, AK_TypeId);
9024     if (!DynType)
9025       return false;
9026 
9027     TypeInfo =
9028         TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
9029   }
9030 
9031   return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
9032 }
9033 
9034 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
9035   return Success(E->getGuidDecl());
9036 }
9037 
9038 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
9039   // Handle static data members.
9040   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
9041     VisitIgnoredBaseExpression(E->getBase());
9042     return VisitVarDecl(E, VD);
9043   }
9044 
9045   // Handle static member functions.
9046   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
9047     if (MD->isStatic()) {
9048       VisitIgnoredBaseExpression(E->getBase());
9049       return Success(MD);
9050     }
9051   }
9052 
9053   // Handle non-static data members.
9054   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
9055 }
9056 
9057 bool LValueExprEvaluator::VisitExtVectorElementExpr(
9058     const ExtVectorElementExpr *E) {
9059   bool Success = true;
9060 
9061   APValue Val;
9062   if (!Evaluate(Val, Info, E->getBase())) {
9063     if (!Info.noteFailure())
9064       return false;
9065     Success = false;
9066   }
9067 
9068   SmallVector<uint32_t, 4> Indices;
9069   E->getEncodedElementAccess(Indices);
9070   // FIXME: support accessing more than one element
9071   if (Indices.size() > 1)
9072     return false;
9073 
9074   if (Success) {
9075     Result.setFrom(Info.Ctx, Val);
9076     const auto *VT = E->getBase()->getType()->castAs<VectorType>();
9077     HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9078                               VT->getNumElements(), Indices[0]);
9079   }
9080 
9081   return Success;
9082 }
9083 
9084 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
9085   if (E->getBase()->getType()->isSveVLSBuiltinType())
9086     return Error(E);
9087 
9088   APSInt Index;
9089   bool Success = true;
9090 
9091   if (const auto *VT = E->getBase()->getType()->getAs<VectorType>()) {
9092     APValue Val;
9093     if (!Evaluate(Val, Info, E->getBase())) {
9094       if (!Info.noteFailure())
9095         return false;
9096       Success = false;
9097     }
9098 
9099     if (!EvaluateInteger(E->getIdx(), Index, Info)) {
9100       if (!Info.noteFailure())
9101         return false;
9102       Success = false;
9103     }
9104 
9105     if (Success) {
9106       Result.setFrom(Info.Ctx, Val);
9107       HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9108                                 VT->getNumElements(), Index.getExtValue());
9109     }
9110 
9111     return Success;
9112   }
9113 
9114   // C++17's rules require us to evaluate the LHS first, regardless of which
9115   // side is the base.
9116   for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
9117     if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
9118                                 : !EvaluateInteger(SubExpr, Index, Info)) {
9119       if (!Info.noteFailure())
9120         return false;
9121       Success = false;
9122     }
9123   }
9124 
9125   return Success &&
9126          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
9127 }
9128 
9129 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
9130   return evaluatePointer(E->getSubExpr(), Result);
9131 }
9132 
9133 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9134   if (!Visit(E->getSubExpr()))
9135     return false;
9136   // __real is a no-op on scalar lvalues.
9137   if (E->getSubExpr()->getType()->isAnyComplexType())
9138     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
9139   return true;
9140 }
9141 
9142 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9143   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
9144          "lvalue __imag__ on scalar?");
9145   if (!Visit(E->getSubExpr()))
9146     return false;
9147   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
9148   return true;
9149 }
9150 
9151 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
9152   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9153     return Error(UO);
9154 
9155   if (!this->Visit(UO->getSubExpr()))
9156     return false;
9157 
9158   return handleIncDec(
9159       this->Info, UO, Result, UO->getSubExpr()->getType(),
9160       UO->isIncrementOp(), nullptr);
9161 }
9162 
9163 bool LValueExprEvaluator::VisitCompoundAssignOperator(
9164     const CompoundAssignOperator *CAO) {
9165   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9166     return Error(CAO);
9167 
9168   bool Success = true;
9169 
9170   // C++17 onwards require that we evaluate the RHS first.
9171   APValue RHS;
9172   if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
9173     if (!Info.noteFailure())
9174       return false;
9175     Success = false;
9176   }
9177 
9178   // The overall lvalue result is the result of evaluating the LHS.
9179   if (!this->Visit(CAO->getLHS()) || !Success)
9180     return false;
9181 
9182   return handleCompoundAssignment(
9183       this->Info, CAO,
9184       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
9185       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
9186 }
9187 
9188 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
9189   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9190     return Error(E);
9191 
9192   bool Success = true;
9193 
9194   // C++17 onwards require that we evaluate the RHS first.
9195   APValue NewVal;
9196   if (!Evaluate(NewVal, this->Info, E->getRHS())) {
9197     if (!Info.noteFailure())
9198       return false;
9199     Success = false;
9200   }
9201 
9202   if (!this->Visit(E->getLHS()) || !Success)
9203     return false;
9204 
9205   if (Info.getLangOpts().CPlusPlus20 &&
9206       !MaybeHandleUnionActiveMemberChange(Info, E->getLHS(), Result))
9207     return false;
9208 
9209   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
9210                           NewVal);
9211 }
9212 
9213 //===----------------------------------------------------------------------===//
9214 // Pointer Evaluation
9215 //===----------------------------------------------------------------------===//
9216 
9217 /// Attempts to compute the number of bytes available at the pointer
9218 /// returned by a function with the alloc_size attribute. Returns true if we
9219 /// were successful. Places an unsigned number into `Result`.
9220 ///
9221 /// This expects the given CallExpr to be a call to a function with an
9222 /// alloc_size attribute.
9223 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
9224                                             const CallExpr *Call,
9225                                             llvm::APInt &Result) {
9226   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
9227 
9228   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
9229   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
9230   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
9231   if (Call->getNumArgs() <= SizeArgNo)
9232     return false;
9233 
9234   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
9235     Expr::EvalResult ExprResult;
9236     if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
9237       return false;
9238     Into = ExprResult.Val.getInt();
9239     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
9240       return false;
9241     Into = Into.zext(BitsInSizeT);
9242     return true;
9243   };
9244 
9245   APSInt SizeOfElem;
9246   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
9247     return false;
9248 
9249   if (!AllocSize->getNumElemsParam().isValid()) {
9250     Result = std::move(SizeOfElem);
9251     return true;
9252   }
9253 
9254   APSInt NumberOfElems;
9255   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
9256   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
9257     return false;
9258 
9259   bool Overflow;
9260   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
9261   if (Overflow)
9262     return false;
9263 
9264   Result = std::move(BytesAvailable);
9265   return true;
9266 }
9267 
9268 /// Convenience function. LVal's base must be a call to an alloc_size
9269 /// function.
9270 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
9271                                             const LValue &LVal,
9272                                             llvm::APInt &Result) {
9273   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9274          "Can't get the size of a non alloc_size function");
9275   const auto *Base = LVal.getLValueBase().get<const Expr *>();
9276   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
9277   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
9278 }
9279 
9280 /// Attempts to evaluate the given LValueBase as the result of a call to
9281 /// a function with the alloc_size attribute. If it was possible to do so, this
9282 /// function will return true, make Result's Base point to said function call,
9283 /// and mark Result's Base as invalid.
9284 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
9285                                       LValue &Result) {
9286   if (Base.isNull())
9287     return false;
9288 
9289   // Because we do no form of static analysis, we only support const variables.
9290   //
9291   // Additionally, we can't support parameters, nor can we support static
9292   // variables (in the latter case, use-before-assign isn't UB; in the former,
9293   // we have no clue what they'll be assigned to).
9294   const auto *VD =
9295       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
9296   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
9297     return false;
9298 
9299   const Expr *Init = VD->getAnyInitializer();
9300   if (!Init || Init->getType().isNull())
9301     return false;
9302 
9303   const Expr *E = Init->IgnoreParens();
9304   if (!tryUnwrapAllocSizeCall(E))
9305     return false;
9306 
9307   // Store E instead of E unwrapped so that the type of the LValue's base is
9308   // what the user wanted.
9309   Result.setInvalid(E);
9310 
9311   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
9312   Result.addUnsizedArray(Info, E, Pointee);
9313   return true;
9314 }
9315 
9316 namespace {
9317 class PointerExprEvaluator
9318   : public ExprEvaluatorBase<PointerExprEvaluator> {
9319   LValue &Result;
9320   bool InvalidBaseOK;
9321 
9322   bool Success(const Expr *E) {
9323     Result.set(E);
9324     return true;
9325   }
9326 
9327   bool evaluateLValue(const Expr *E, LValue &Result) {
9328     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
9329   }
9330 
9331   bool evaluatePointer(const Expr *E, LValue &Result) {
9332     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
9333   }
9334 
9335   bool visitNonBuiltinCallExpr(const CallExpr *E);
9336 public:
9337 
9338   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
9339       : ExprEvaluatorBaseTy(info), Result(Result),
9340         InvalidBaseOK(InvalidBaseOK) {}
9341 
9342   bool Success(const APValue &V, const Expr *E) {
9343     Result.setFrom(Info.Ctx, V);
9344     return true;
9345   }
9346   bool ZeroInitialization(const Expr *E) {
9347     Result.setNull(Info.Ctx, E->getType());
9348     return true;
9349   }
9350 
9351   bool VisitBinaryOperator(const BinaryOperator *E);
9352   bool VisitCastExpr(const CastExpr* E);
9353   bool VisitUnaryAddrOf(const UnaryOperator *E);
9354   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
9355       { return Success(E); }
9356   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
9357     if (E->isExpressibleAsConstantInitializer())
9358       return Success(E);
9359     if (Info.noteFailure())
9360       EvaluateIgnoredValue(Info, E->getSubExpr());
9361     return Error(E);
9362   }
9363   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
9364       { return Success(E); }
9365   bool VisitCallExpr(const CallExpr *E);
9366   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
9367   bool VisitBlockExpr(const BlockExpr *E) {
9368     if (!E->getBlockDecl()->hasCaptures())
9369       return Success(E);
9370     return Error(E);
9371   }
9372   bool VisitCXXThisExpr(const CXXThisExpr *E) {
9373     auto DiagnoseInvalidUseOfThis = [&] {
9374       if (Info.getLangOpts().CPlusPlus11)
9375         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
9376       else
9377         Info.FFDiag(E);
9378     };
9379 
9380     // Can't look at 'this' when checking a potential constant expression.
9381     if (Info.checkingPotentialConstantExpression())
9382       return false;
9383 
9384     bool IsExplicitLambda =
9385         isLambdaCallWithExplicitObjectParameter(Info.CurrentCall->Callee);
9386     if (!IsExplicitLambda) {
9387       if (!Info.CurrentCall->This) {
9388         DiagnoseInvalidUseOfThis();
9389         return false;
9390       }
9391 
9392       Result = *Info.CurrentCall->This;
9393     }
9394 
9395     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
9396       // Ensure we actually have captured 'this'. If something was wrong with
9397       // 'this' capture, the error would have been previously reported.
9398       // Otherwise we can be inside of a default initialization of an object
9399       // declared by lambda's body, so no need to return false.
9400       if (!Info.CurrentCall->LambdaThisCaptureField) {
9401         if (IsExplicitLambda && !Info.CurrentCall->This) {
9402           DiagnoseInvalidUseOfThis();
9403           return false;
9404         }
9405 
9406         return true;
9407       }
9408 
9409       const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
9410       return HandleLambdaCapture(
9411           Info, E, Result, MD, Info.CurrentCall->LambdaThisCaptureField,
9412           Info.CurrentCall->LambdaThisCaptureField->getType()->isPointerType());
9413     }
9414     return true;
9415   }
9416 
9417   bool VisitCXXNewExpr(const CXXNewExpr *E);
9418 
9419   bool VisitSourceLocExpr(const SourceLocExpr *E) {
9420     assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
9421     APValue LValResult = E->EvaluateInContext(
9422         Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
9423     Result.setFrom(Info.Ctx, LValResult);
9424     return true;
9425   }
9426 
9427   bool VisitEmbedExpr(const EmbedExpr *E) {
9428     llvm::report_fatal_error("Not yet implemented for ExprConstant.cpp");
9429     return true;
9430   }
9431 
9432   bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
9433     std::string ResultStr = E->ComputeName(Info.Ctx);
9434 
9435     QualType CharTy = Info.Ctx.CharTy.withConst();
9436     APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
9437                ResultStr.size() + 1);
9438     QualType ArrayTy = Info.Ctx.getConstantArrayType(
9439         CharTy, Size, nullptr, ArraySizeModifier::Normal, 0);
9440 
9441     StringLiteral *SL =
9442         StringLiteral::Create(Info.Ctx, ResultStr, StringLiteralKind::Ordinary,
9443                               /*Pascal*/ false, ArrayTy, E->getLocation());
9444 
9445     evaluateLValue(SL, Result);
9446     Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
9447     return true;
9448   }
9449 
9450   // FIXME: Missing: @protocol, @selector
9451 };
9452 } // end anonymous namespace
9453 
9454 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
9455                             bool InvalidBaseOK) {
9456   assert(!E->isValueDependent());
9457   assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
9458   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
9459 }
9460 
9461 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9462   if (E->getOpcode() != BO_Add &&
9463       E->getOpcode() != BO_Sub)
9464     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9465 
9466   const Expr *PExp = E->getLHS();
9467   const Expr *IExp = E->getRHS();
9468   if (IExp->getType()->isPointerType())
9469     std::swap(PExp, IExp);
9470 
9471   bool EvalPtrOK = evaluatePointer(PExp, Result);
9472   if (!EvalPtrOK && !Info.noteFailure())
9473     return false;
9474 
9475   llvm::APSInt Offset;
9476   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
9477     return false;
9478 
9479   if (E->getOpcode() == BO_Sub)
9480     negateAsSigned(Offset);
9481 
9482   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
9483   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
9484 }
9485 
9486 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9487   return evaluateLValue(E->getSubExpr(), Result);
9488 }
9489 
9490 // Is the provided decl 'std::source_location::current'?
9491 static bool IsDeclSourceLocationCurrent(const FunctionDecl *FD) {
9492   if (!FD)
9493     return false;
9494   const IdentifierInfo *FnII = FD->getIdentifier();
9495   if (!FnII || !FnII->isStr("current"))
9496     return false;
9497 
9498   const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
9499   if (!RD)
9500     return false;
9501 
9502   const IdentifierInfo *ClassII = RD->getIdentifier();
9503   return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
9504 }
9505 
9506 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9507   const Expr *SubExpr = E->getSubExpr();
9508 
9509   switch (E->getCastKind()) {
9510   default:
9511     break;
9512   case CK_BitCast:
9513   case CK_CPointerToObjCPointerCast:
9514   case CK_BlockPointerToObjCPointerCast:
9515   case CK_AnyPointerToBlockPointerCast:
9516   case CK_AddressSpaceConversion:
9517     if (!Visit(SubExpr))
9518       return false;
9519     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
9520     // permitted in constant expressions in C++11. Bitcasts from cv void* are
9521     // also static_casts, but we disallow them as a resolution to DR1312.
9522     if (!E->getType()->isVoidPointerType()) {
9523       // In some circumstances, we permit casting from void* to cv1 T*, when the
9524       // actual pointee object is actually a cv2 T.
9525       bool HasValidResult = !Result.InvalidBase && !Result.Designator.Invalid &&
9526                             !Result.IsNullPtr;
9527       bool VoidPtrCastMaybeOK =
9528           Result.IsNullPtr ||
9529           (HasValidResult &&
9530            Info.Ctx.hasSimilarType(Result.Designator.getType(Info.Ctx),
9531                                    E->getType()->getPointeeType()));
9532       // 1. We'll allow it in std::allocator::allocate, and anything which that
9533       //    calls.
9534       // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
9535       //    <source_location> header. Fixed in GCC 12 and later (2022-04-??).
9536       //    We'll allow it in the body of std::source_location::current.  GCC's
9537       //    implementation had a parameter of type `void*`, and casts from
9538       //    that back to `const __impl*` in its body.
9539       if (VoidPtrCastMaybeOK &&
9540           (Info.getStdAllocatorCaller("allocate") ||
9541            IsDeclSourceLocationCurrent(Info.CurrentCall->Callee) ||
9542            Info.getLangOpts().CPlusPlus26)) {
9543         // Permitted.
9544       } else {
9545         if (SubExpr->getType()->isVoidPointerType() &&
9546             Info.getLangOpts().CPlusPlus) {
9547           if (HasValidResult)
9548             CCEDiag(E, diag::note_constexpr_invalid_void_star_cast)
9549                 << SubExpr->getType() << Info.getLangOpts().CPlusPlus26
9550                 << Result.Designator.getType(Info.Ctx).getCanonicalType()
9551                 << E->getType()->getPointeeType();
9552           else
9553             CCEDiag(E, diag::note_constexpr_invalid_cast)
9554                 << 3 << SubExpr->getType();
9555         } else
9556           CCEDiag(E, diag::note_constexpr_invalid_cast)
9557               << 2 << Info.Ctx.getLangOpts().CPlusPlus;
9558         Result.Designator.setInvalid();
9559       }
9560     }
9561     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
9562       ZeroInitialization(E);
9563     return true;
9564 
9565   case CK_DerivedToBase:
9566   case CK_UncheckedDerivedToBase:
9567     if (!evaluatePointer(E->getSubExpr(), Result))
9568       return false;
9569     if (!Result.Base && Result.Offset.isZero())
9570       return true;
9571 
9572     // Now figure out the necessary offset to add to the base LV to get from
9573     // the derived class to the base class.
9574     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
9575                                   castAs<PointerType>()->getPointeeType(),
9576                                 Result);
9577 
9578   case CK_BaseToDerived:
9579     if (!Visit(E->getSubExpr()))
9580       return false;
9581     if (!Result.Base && Result.Offset.isZero())
9582       return true;
9583     return HandleBaseToDerivedCast(Info, E, Result);
9584 
9585   case CK_Dynamic:
9586     if (!Visit(E->getSubExpr()))
9587       return false;
9588     return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
9589 
9590   case CK_NullToPointer:
9591     VisitIgnoredValue(E->getSubExpr());
9592     return ZeroInitialization(E);
9593 
9594   case CK_IntegralToPointer: {
9595     CCEDiag(E, diag::note_constexpr_invalid_cast)
9596         << 2 << Info.Ctx.getLangOpts().CPlusPlus;
9597 
9598     APValue Value;
9599     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
9600       break;
9601 
9602     if (Value.isInt()) {
9603       unsigned Size = Info.Ctx.getTypeSize(E->getType());
9604       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
9605       Result.Base = (Expr*)nullptr;
9606       Result.InvalidBase = false;
9607       Result.Offset = CharUnits::fromQuantity(N);
9608       Result.Designator.setInvalid();
9609       Result.IsNullPtr = false;
9610       return true;
9611     } else {
9612       // In rare instances, the value isn't an lvalue.
9613       // For example, when the value is the difference between the addresses of
9614       // two labels. We reject that as a constant expression because we can't
9615       // compute a valid offset to convert into a pointer.
9616       if (!Value.isLValue())
9617         return false;
9618 
9619       // Cast is of an lvalue, no need to change value.
9620       Result.setFrom(Info.Ctx, Value);
9621       return true;
9622     }
9623   }
9624 
9625   case CK_ArrayToPointerDecay: {
9626     if (SubExpr->isGLValue()) {
9627       if (!evaluateLValue(SubExpr, Result))
9628         return false;
9629     } else {
9630       APValue &Value = Info.CurrentCall->createTemporary(
9631           SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
9632       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
9633         return false;
9634     }
9635     // The result is a pointer to the first element of the array.
9636     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
9637     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
9638       Result.addArray(Info, E, CAT);
9639     else
9640       Result.addUnsizedArray(Info, E, AT->getElementType());
9641     return true;
9642   }
9643 
9644   case CK_FunctionToPointerDecay:
9645     return evaluateLValue(SubExpr, Result);
9646 
9647   case CK_LValueToRValue: {
9648     LValue LVal;
9649     if (!evaluateLValue(E->getSubExpr(), LVal))
9650       return false;
9651 
9652     APValue RVal;
9653     // Note, we use the subexpression's type in order to retain cv-qualifiers.
9654     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
9655                                         LVal, RVal))
9656       return InvalidBaseOK &&
9657              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
9658     return Success(RVal, E);
9659   }
9660   }
9661 
9662   return ExprEvaluatorBaseTy::VisitCastExpr(E);
9663 }
9664 
9665 static CharUnits GetAlignOfType(const ASTContext &Ctx, QualType T,
9666                                 UnaryExprOrTypeTrait ExprKind) {
9667   // C++ [expr.alignof]p3:
9668   //     When alignof is applied to a reference type, the result is the
9669   //     alignment of the referenced type.
9670   T = T.getNonReferenceType();
9671 
9672   if (T.getQualifiers().hasUnaligned())
9673     return CharUnits::One();
9674 
9675   const bool AlignOfReturnsPreferred =
9676       Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
9677 
9678   // __alignof is defined to return the preferred alignment.
9679   // Before 8, clang returned the preferred alignment for alignof and _Alignof
9680   // as well.
9681   if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
9682     return Ctx.toCharUnitsFromBits(Ctx.getPreferredTypeAlign(T.getTypePtr()));
9683   // alignof and _Alignof are defined to return the ABI alignment.
9684   else if (ExprKind == UETT_AlignOf)
9685     return Ctx.getTypeAlignInChars(T.getTypePtr());
9686   else
9687     llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
9688 }
9689 
9690 CharUnits GetAlignOfExpr(const ASTContext &Ctx, const Expr *E,
9691                          UnaryExprOrTypeTrait ExprKind) {
9692   E = E->IgnoreParens();
9693 
9694   // The kinds of expressions that we have special-case logic here for
9695   // should be kept up to date with the special checks for those
9696   // expressions in Sema.
9697 
9698   // alignof decl is always accepted, even if it doesn't make sense: we default
9699   // to 1 in those cases.
9700   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9701     return Ctx.getDeclAlign(DRE->getDecl(),
9702                             /*RefAsPointee*/ true);
9703 
9704   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
9705     return Ctx.getDeclAlign(ME->getMemberDecl(),
9706                             /*RefAsPointee*/ true);
9707 
9708   return GetAlignOfType(Ctx, E->getType(), ExprKind);
9709 }
9710 
9711 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
9712   if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
9713     return Info.Ctx.getDeclAlign(VD);
9714   if (const auto *E = Value.Base.dyn_cast<const Expr *>())
9715     return GetAlignOfExpr(Info.Ctx, E, UETT_AlignOf);
9716   return GetAlignOfType(Info.Ctx, Value.Base.getTypeInfoType(), UETT_AlignOf);
9717 }
9718 
9719 /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
9720 /// __builtin_is_aligned and __builtin_assume_aligned.
9721 static bool getAlignmentArgument(const Expr *E, QualType ForType,
9722                                  EvalInfo &Info, APSInt &Alignment) {
9723   if (!EvaluateInteger(E, Alignment, Info))
9724     return false;
9725   if (Alignment < 0 || !Alignment.isPowerOf2()) {
9726     Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
9727     return false;
9728   }
9729   unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
9730   APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
9731   if (APSInt::compareValues(Alignment, MaxValue) > 0) {
9732     Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
9733         << MaxValue << ForType << Alignment;
9734     return false;
9735   }
9736   // Ensure both alignment and source value have the same bit width so that we
9737   // don't assert when computing the resulting value.
9738   APSInt ExtAlignment =
9739       APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
9740   assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
9741          "Alignment should not be changed by ext/trunc");
9742   Alignment = ExtAlignment;
9743   assert(Alignment.getBitWidth() == SrcWidth);
9744   return true;
9745 }
9746 
9747 // To be clear: this happily visits unsupported builtins. Better name welcomed.
9748 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
9749   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
9750     return true;
9751 
9752   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
9753     return false;
9754 
9755   Result.setInvalid(E);
9756   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
9757   Result.addUnsizedArray(Info, E, PointeeTy);
9758   return true;
9759 }
9760 
9761 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
9762   if (!IsConstantEvaluatedBuiltinCall(E))
9763     return visitNonBuiltinCallExpr(E);
9764   return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
9765 }
9766 
9767 // Determine if T is a character type for which we guarantee that
9768 // sizeof(T) == 1.
9769 static bool isOneByteCharacterType(QualType T) {
9770   return T->isCharType() || T->isChar8Type();
9771 }
9772 
9773 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
9774                                                 unsigned BuiltinOp) {
9775   if (IsOpaqueConstantCall(E))
9776     return Success(E);
9777 
9778   switch (BuiltinOp) {
9779   case Builtin::BIaddressof:
9780   case Builtin::BI__addressof:
9781   case Builtin::BI__builtin_addressof:
9782     return evaluateLValue(E->getArg(0), Result);
9783   case Builtin::BI__builtin_assume_aligned: {
9784     // We need to be very careful here because: if the pointer does not have the
9785     // asserted alignment, then the behavior is undefined, and undefined
9786     // behavior is non-constant.
9787     if (!evaluatePointer(E->getArg(0), Result))
9788       return false;
9789 
9790     LValue OffsetResult(Result);
9791     APSInt Alignment;
9792     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9793                               Alignment))
9794       return false;
9795     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
9796 
9797     if (E->getNumArgs() > 2) {
9798       APSInt Offset;
9799       if (!EvaluateInteger(E->getArg(2), Offset, Info))
9800         return false;
9801 
9802       int64_t AdditionalOffset = -Offset.getZExtValue();
9803       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
9804     }
9805 
9806     // If there is a base object, then it must have the correct alignment.
9807     if (OffsetResult.Base) {
9808       CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
9809 
9810       if (BaseAlignment < Align) {
9811         Result.Designator.setInvalid();
9812         CCEDiag(E->getArg(0), diag::note_constexpr_baa_insufficient_alignment)
9813             << 0 << BaseAlignment.getQuantity() << Align.getQuantity();
9814         return false;
9815       }
9816     }
9817 
9818     // The offset must also have the correct alignment.
9819     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
9820       Result.Designator.setInvalid();
9821 
9822       (OffsetResult.Base
9823            ? CCEDiag(E->getArg(0),
9824                      diag::note_constexpr_baa_insufficient_alignment)
9825                  << 1
9826            : CCEDiag(E->getArg(0),
9827                      diag::note_constexpr_baa_value_insufficient_alignment))
9828           << OffsetResult.Offset.getQuantity() << Align.getQuantity();
9829       return false;
9830     }
9831 
9832     return true;
9833   }
9834   case Builtin::BI__builtin_align_up:
9835   case Builtin::BI__builtin_align_down: {
9836     if (!evaluatePointer(E->getArg(0), Result))
9837       return false;
9838     APSInt Alignment;
9839     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9840                               Alignment))
9841       return false;
9842     CharUnits BaseAlignment = getBaseAlignment(Info, Result);
9843     CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
9844     // For align_up/align_down, we can return the same value if the alignment
9845     // is known to be greater or equal to the requested value.
9846     if (PtrAlign.getQuantity() >= Alignment)
9847       return true;
9848 
9849     // The alignment could be greater than the minimum at run-time, so we cannot
9850     // infer much about the resulting pointer value. One case is possible:
9851     // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
9852     // can infer the correct index if the requested alignment is smaller than
9853     // the base alignment so we can perform the computation on the offset.
9854     if (BaseAlignment.getQuantity() >= Alignment) {
9855       assert(Alignment.getBitWidth() <= 64 &&
9856              "Cannot handle > 64-bit address-space");
9857       uint64_t Alignment64 = Alignment.getZExtValue();
9858       CharUnits NewOffset = CharUnits::fromQuantity(
9859           BuiltinOp == Builtin::BI__builtin_align_down
9860               ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
9861               : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
9862       Result.adjustOffset(NewOffset - Result.Offset);
9863       // TODO: diagnose out-of-bounds values/only allow for arrays?
9864       return true;
9865     }
9866     // Otherwise, we cannot constant-evaluate the result.
9867     Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
9868         << Alignment;
9869     return false;
9870   }
9871   case Builtin::BI__builtin_operator_new:
9872     return HandleOperatorNewCall(Info, E, Result);
9873   case Builtin::BI__builtin_launder:
9874     return evaluatePointer(E->getArg(0), Result);
9875   case Builtin::BIstrchr:
9876   case Builtin::BIwcschr:
9877   case Builtin::BImemchr:
9878   case Builtin::BIwmemchr:
9879     if (Info.getLangOpts().CPlusPlus11)
9880       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9881           << /*isConstexpr*/ 0 << /*isConstructor*/ 0
9882           << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
9883     else
9884       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9885     [[fallthrough]];
9886   case Builtin::BI__builtin_strchr:
9887   case Builtin::BI__builtin_wcschr:
9888   case Builtin::BI__builtin_memchr:
9889   case Builtin::BI__builtin_char_memchr:
9890   case Builtin::BI__builtin_wmemchr: {
9891     if (!Visit(E->getArg(0)))
9892       return false;
9893     APSInt Desired;
9894     if (!EvaluateInteger(E->getArg(1), Desired, Info))
9895       return false;
9896     uint64_t MaxLength = uint64_t(-1);
9897     if (BuiltinOp != Builtin::BIstrchr &&
9898         BuiltinOp != Builtin::BIwcschr &&
9899         BuiltinOp != Builtin::BI__builtin_strchr &&
9900         BuiltinOp != Builtin::BI__builtin_wcschr) {
9901       APSInt N;
9902       if (!EvaluateInteger(E->getArg(2), N, Info))
9903         return false;
9904       MaxLength = N.getZExtValue();
9905     }
9906     // We cannot find the value if there are no candidates to match against.
9907     if (MaxLength == 0u)
9908       return ZeroInitialization(E);
9909     if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9910         Result.Designator.Invalid)
9911       return false;
9912     QualType CharTy = Result.Designator.getType(Info.Ctx);
9913     bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
9914                      BuiltinOp == Builtin::BI__builtin_memchr;
9915     assert(IsRawByte ||
9916            Info.Ctx.hasSameUnqualifiedType(
9917                CharTy, E->getArg(0)->getType()->getPointeeType()));
9918     // Pointers to const void may point to objects of incomplete type.
9919     if (IsRawByte && CharTy->isIncompleteType()) {
9920       Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
9921       return false;
9922     }
9923     // Give up on byte-oriented matching against multibyte elements.
9924     // FIXME: We can compare the bytes in the correct order.
9925     if (IsRawByte && !isOneByteCharacterType(CharTy)) {
9926       Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
9927           << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str()
9928           << CharTy;
9929       return false;
9930     }
9931     // Figure out what value we're actually looking for (after converting to
9932     // the corresponding unsigned type if necessary).
9933     uint64_t DesiredVal;
9934     bool StopAtNull = false;
9935     switch (BuiltinOp) {
9936     case Builtin::BIstrchr:
9937     case Builtin::BI__builtin_strchr:
9938       // strchr compares directly to the passed integer, and therefore
9939       // always fails if given an int that is not a char.
9940       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
9941                                                   E->getArg(1)->getType(),
9942                                                   Desired),
9943                                Desired))
9944         return ZeroInitialization(E);
9945       StopAtNull = true;
9946       [[fallthrough]];
9947     case Builtin::BImemchr:
9948     case Builtin::BI__builtin_memchr:
9949     case Builtin::BI__builtin_char_memchr:
9950       // memchr compares by converting both sides to unsigned char. That's also
9951       // correct for strchr if we get this far (to cope with plain char being
9952       // unsigned in the strchr case).
9953       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
9954       break;
9955 
9956     case Builtin::BIwcschr:
9957     case Builtin::BI__builtin_wcschr:
9958       StopAtNull = true;
9959       [[fallthrough]];
9960     case Builtin::BIwmemchr:
9961     case Builtin::BI__builtin_wmemchr:
9962       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
9963       DesiredVal = Desired.getZExtValue();
9964       break;
9965     }
9966 
9967     for (; MaxLength; --MaxLength) {
9968       APValue Char;
9969       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
9970           !Char.isInt())
9971         return false;
9972       if (Char.getInt().getZExtValue() == DesiredVal)
9973         return true;
9974       if (StopAtNull && !Char.getInt())
9975         break;
9976       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
9977         return false;
9978     }
9979     // Not found: return nullptr.
9980     return ZeroInitialization(E);
9981   }
9982 
9983   case Builtin::BImemcpy:
9984   case Builtin::BImemmove:
9985   case Builtin::BIwmemcpy:
9986   case Builtin::BIwmemmove:
9987     if (Info.getLangOpts().CPlusPlus11)
9988       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9989           << /*isConstexpr*/ 0 << /*isConstructor*/ 0
9990           << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
9991     else
9992       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9993     [[fallthrough]];
9994   case Builtin::BI__builtin_memcpy:
9995   case Builtin::BI__builtin_memmove:
9996   case Builtin::BI__builtin_wmemcpy:
9997   case Builtin::BI__builtin_wmemmove: {
9998     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
9999                  BuiltinOp == Builtin::BIwmemmove ||
10000                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
10001                  BuiltinOp == Builtin::BI__builtin_wmemmove;
10002     bool Move = BuiltinOp == Builtin::BImemmove ||
10003                 BuiltinOp == Builtin::BIwmemmove ||
10004                 BuiltinOp == Builtin::BI__builtin_memmove ||
10005                 BuiltinOp == Builtin::BI__builtin_wmemmove;
10006 
10007     // The result of mem* is the first argument.
10008     if (!Visit(E->getArg(0)))
10009       return false;
10010     LValue Dest = Result;
10011 
10012     LValue Src;
10013     if (!EvaluatePointer(E->getArg(1), Src, Info))
10014       return false;
10015 
10016     APSInt N;
10017     if (!EvaluateInteger(E->getArg(2), N, Info))
10018       return false;
10019     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
10020 
10021     // If the size is zero, we treat this as always being a valid no-op.
10022     // (Even if one of the src and dest pointers is null.)
10023     if (!N)
10024       return true;
10025 
10026     // Otherwise, if either of the operands is null, we can't proceed. Don't
10027     // try to determine the type of the copied objects, because there aren't
10028     // any.
10029     if (!Src.Base || !Dest.Base) {
10030       APValue Val;
10031       (!Src.Base ? Src : Dest).moveInto(Val);
10032       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
10033           << Move << WChar << !!Src.Base
10034           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
10035       return false;
10036     }
10037     if (Src.Designator.Invalid || Dest.Designator.Invalid)
10038       return false;
10039 
10040     // We require that Src and Dest are both pointers to arrays of
10041     // trivially-copyable type. (For the wide version, the designator will be
10042     // invalid if the designated object is not a wchar_t.)
10043     QualType T = Dest.Designator.getType(Info.Ctx);
10044     QualType SrcT = Src.Designator.getType(Info.Ctx);
10045     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
10046       // FIXME: Consider using our bit_cast implementation to support this.
10047       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
10048       return false;
10049     }
10050     if (T->isIncompleteType()) {
10051       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
10052       return false;
10053     }
10054     if (!T.isTriviallyCopyableType(Info.Ctx)) {
10055       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
10056       return false;
10057     }
10058 
10059     // Figure out how many T's we're copying.
10060     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
10061     if (TSize == 0)
10062       return false;
10063     if (!WChar) {
10064       uint64_t Remainder;
10065       llvm::APInt OrigN = N;
10066       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
10067       if (Remainder) {
10068         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10069             << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
10070             << (unsigned)TSize;
10071         return false;
10072       }
10073     }
10074 
10075     // Check that the copying will remain within the arrays, just so that we
10076     // can give a more meaningful diagnostic. This implicitly also checks that
10077     // N fits into 64 bits.
10078     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
10079     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
10080     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
10081       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10082           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
10083           << toString(N, 10, /*Signed*/false);
10084       return false;
10085     }
10086     uint64_t NElems = N.getZExtValue();
10087     uint64_t NBytes = NElems * TSize;
10088 
10089     // Check for overlap.
10090     int Direction = 1;
10091     if (HasSameBase(Src, Dest)) {
10092       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
10093       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
10094       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
10095         // Dest is inside the source region.
10096         if (!Move) {
10097           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10098           return false;
10099         }
10100         // For memmove and friends, copy backwards.
10101         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
10102             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
10103           return false;
10104         Direction = -1;
10105       } else if (!Move && SrcOffset >= DestOffset &&
10106                  SrcOffset - DestOffset < NBytes) {
10107         // Src is inside the destination region for memcpy: invalid.
10108         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10109         return false;
10110       }
10111     }
10112 
10113     while (true) {
10114       APValue Val;
10115       // FIXME: Set WantObjectRepresentation to true if we're copying a
10116       // char-like type?
10117       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
10118           !handleAssignment(Info, E, Dest, T, Val))
10119         return false;
10120       // Do not iterate past the last element; if we're copying backwards, that
10121       // might take us off the start of the array.
10122       if (--NElems == 0)
10123         return true;
10124       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
10125           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
10126         return false;
10127     }
10128   }
10129 
10130   default:
10131     return false;
10132   }
10133 }
10134 
10135 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10136                                      APValue &Result, const InitListExpr *ILE,
10137                                      QualType AllocType);
10138 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10139                                           APValue &Result,
10140                                           const CXXConstructExpr *CCE,
10141                                           QualType AllocType);
10142 
10143 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
10144   if (!Info.getLangOpts().CPlusPlus20)
10145     Info.CCEDiag(E, diag::note_constexpr_new);
10146 
10147   // We cannot speculatively evaluate a delete expression.
10148   if (Info.SpeculativeEvaluationDepth)
10149     return false;
10150 
10151   FunctionDecl *OperatorNew = E->getOperatorNew();
10152   QualType AllocType = E->getAllocatedType();
10153   QualType TargetType = AllocType;
10154 
10155   bool IsNothrow = false;
10156   bool IsPlacement = false;
10157 
10158   if (E->getNumPlacementArgs() == 1 &&
10159       E->getPlacementArg(0)->getType()->isNothrowT()) {
10160     // The only new-placement list we support is of the form (std::nothrow).
10161     //
10162     // FIXME: There is no restriction on this, but it's not clear that any
10163     // other form makes any sense. We get here for cases such as:
10164     //
10165     //   new (std::align_val_t{N}) X(int)
10166     //
10167     // (which should presumably be valid only if N is a multiple of
10168     // alignof(int), and in any case can't be deallocated unless N is
10169     // alignof(X) and X has new-extended alignment).
10170     LValue Nothrow;
10171     if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
10172       return false;
10173     IsNothrow = true;
10174   } else if (OperatorNew->isReservedGlobalPlacementOperator()) {
10175     if (Info.CurrentCall->isStdFunction() || Info.getLangOpts().CPlusPlus26) {
10176       if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
10177         return false;
10178       if (Result.Designator.Invalid)
10179         return false;
10180       TargetType = E->getPlacementArg(0)->getType();
10181       IsPlacement = true;
10182     } else {
10183       Info.FFDiag(E, diag::note_constexpr_new_placement)
10184           << /*C++26 feature*/ 1 << E->getSourceRange();
10185       return false;
10186     }
10187   } else if (E->getNumPlacementArgs()) {
10188     Info.FFDiag(E, diag::note_constexpr_new_placement)
10189         << /*Unsupported*/ 0 << E->getSourceRange();
10190     return false;
10191   } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
10192     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
10193         << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
10194     return false;
10195   }
10196 
10197   const Expr *Init = E->getInitializer();
10198   const InitListExpr *ResizedArrayILE = nullptr;
10199   const CXXConstructExpr *ResizedArrayCCE = nullptr;
10200   bool ValueInit = false;
10201 
10202   if (std::optional<const Expr *> ArraySize = E->getArraySize()) {
10203     const Expr *Stripped = *ArraySize;
10204     for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
10205          Stripped = ICE->getSubExpr())
10206       if (ICE->getCastKind() != CK_NoOp &&
10207           ICE->getCastKind() != CK_IntegralCast)
10208         break;
10209 
10210     llvm::APSInt ArrayBound;
10211     if (!EvaluateInteger(Stripped, ArrayBound, Info))
10212       return false;
10213 
10214     // C++ [expr.new]p9:
10215     //   The expression is erroneous if:
10216     //   -- [...] its value before converting to size_t [or] applying the
10217     //      second standard conversion sequence is less than zero
10218     if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
10219       if (IsNothrow)
10220         return ZeroInitialization(E);
10221 
10222       Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
10223           << ArrayBound << (*ArraySize)->getSourceRange();
10224       return false;
10225     }
10226 
10227     //   -- its value is such that the size of the allocated object would
10228     //      exceed the implementation-defined limit
10229     if (!Info.CheckArraySize(ArraySize.value()->getExprLoc(),
10230                              ConstantArrayType::getNumAddressingBits(
10231                                  Info.Ctx, AllocType, ArrayBound),
10232                              ArrayBound.getZExtValue(), /*Diag=*/!IsNothrow)) {
10233       if (IsNothrow)
10234         return ZeroInitialization(E);
10235       return false;
10236     }
10237 
10238     //   -- the new-initializer is a braced-init-list and the number of
10239     //      array elements for which initializers are provided [...]
10240     //      exceeds the number of elements to initialize
10241     if (!Init) {
10242       // No initialization is performed.
10243     } else if (isa<CXXScalarValueInitExpr>(Init) ||
10244                isa<ImplicitValueInitExpr>(Init)) {
10245       ValueInit = true;
10246     } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
10247       ResizedArrayCCE = CCE;
10248     } else {
10249       auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
10250       assert(CAT && "unexpected type for array initializer");
10251 
10252       unsigned Bits =
10253           std::max(CAT->getSizeBitWidth(), ArrayBound.getBitWidth());
10254       llvm::APInt InitBound = CAT->getSize().zext(Bits);
10255       llvm::APInt AllocBound = ArrayBound.zext(Bits);
10256       if (InitBound.ugt(AllocBound)) {
10257         if (IsNothrow)
10258           return ZeroInitialization(E);
10259 
10260         Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
10261             << toString(AllocBound, 10, /*Signed=*/false)
10262             << toString(InitBound, 10, /*Signed=*/false)
10263             << (*ArraySize)->getSourceRange();
10264         return false;
10265       }
10266 
10267       // If the sizes differ, we must have an initializer list, and we need
10268       // special handling for this case when we initialize.
10269       if (InitBound != AllocBound)
10270         ResizedArrayILE = cast<InitListExpr>(Init);
10271     }
10272 
10273     AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
10274                                               ArraySizeModifier::Normal, 0);
10275   } else {
10276     assert(!AllocType->isArrayType() &&
10277            "array allocation with non-array new");
10278   }
10279 
10280   APValue *Val;
10281   if (IsPlacement) {
10282     AccessKinds AK = AK_Construct;
10283     struct FindObjectHandler {
10284       EvalInfo &Info;
10285       const Expr *E;
10286       QualType AllocType;
10287       const AccessKinds AccessKind;
10288       APValue *Value;
10289 
10290       typedef bool result_type;
10291       bool failed() { return false; }
10292       bool found(APValue &Subobj, QualType SubobjType) {
10293         // FIXME: Reject the cases where [basic.life]p8 would not permit the
10294         // old name of the object to be used to name the new object.
10295         unsigned SubobjectSize = 1;
10296         unsigned AllocSize = 1;
10297         if (auto *CAT = dyn_cast<ConstantArrayType>(AllocType))
10298           AllocSize = CAT->getZExtSize();
10299         if (auto *CAT = dyn_cast<ConstantArrayType>(SubobjType))
10300           SubobjectSize = CAT->getZExtSize();
10301         if (SubobjectSize < AllocSize ||
10302             !Info.Ctx.hasSimilarType(Info.Ctx.getBaseElementType(SubobjType),
10303                                      Info.Ctx.getBaseElementType(AllocType))) {
10304           Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type)
10305               << SubobjType << AllocType;
10306           return false;
10307         }
10308         Value = &Subobj;
10309         return true;
10310       }
10311       bool found(APSInt &Value, QualType SubobjType) {
10312         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10313         return false;
10314       }
10315       bool found(APFloat &Value, QualType SubobjType) {
10316         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10317         return false;
10318       }
10319     } Handler = {Info, E, AllocType, AK, nullptr};
10320 
10321     CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
10322     if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
10323       return false;
10324 
10325     Val = Handler.Value;
10326 
10327     // [basic.life]p1:
10328     //   The lifetime of an object o of type T ends when [...] the storage
10329     //   which the object occupies is [...] reused by an object that is not
10330     //   nested within o (6.6.2).
10331     *Val = APValue();
10332   } else {
10333     // Perform the allocation and obtain a pointer to the resulting object.
10334     Val = Info.createHeapAlloc(E, AllocType, Result);
10335     if (!Val)
10336       return false;
10337   }
10338 
10339   if (ValueInit) {
10340     ImplicitValueInitExpr VIE(AllocType);
10341     if (!EvaluateInPlace(*Val, Info, Result, &VIE))
10342       return false;
10343   } else if (ResizedArrayILE) {
10344     if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
10345                                   AllocType))
10346       return false;
10347   } else if (ResizedArrayCCE) {
10348     if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
10349                                        AllocType))
10350       return false;
10351   } else if (Init) {
10352     if (!EvaluateInPlace(*Val, Info, Result, Init))
10353       return false;
10354   } else if (!handleDefaultInitValue(AllocType, *Val)) {
10355     return false;
10356   }
10357 
10358   // Array new returns a pointer to the first element, not a pointer to the
10359   // array.
10360   if (auto *AT = AllocType->getAsArrayTypeUnsafe())
10361     Result.addArray(Info, E, cast<ConstantArrayType>(AT));
10362 
10363   return true;
10364 }
10365 //===----------------------------------------------------------------------===//
10366 // Member Pointer Evaluation
10367 //===----------------------------------------------------------------------===//
10368 
10369 namespace {
10370 class MemberPointerExprEvaluator
10371   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
10372   MemberPtr &Result;
10373 
10374   bool Success(const ValueDecl *D) {
10375     Result = MemberPtr(D);
10376     return true;
10377   }
10378 public:
10379 
10380   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
10381     : ExprEvaluatorBaseTy(Info), Result(Result) {}
10382 
10383   bool Success(const APValue &V, const Expr *E) {
10384     Result.setFrom(V);
10385     return true;
10386   }
10387   bool ZeroInitialization(const Expr *E) {
10388     return Success((const ValueDecl*)nullptr);
10389   }
10390 
10391   bool VisitCastExpr(const CastExpr *E);
10392   bool VisitUnaryAddrOf(const UnaryOperator *E);
10393 };
10394 } // end anonymous namespace
10395 
10396 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
10397                                   EvalInfo &Info) {
10398   assert(!E->isValueDependent());
10399   assert(E->isPRValue() && E->getType()->isMemberPointerType());
10400   return MemberPointerExprEvaluator(Info, Result).Visit(E);
10401 }
10402 
10403 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
10404   switch (E->getCastKind()) {
10405   default:
10406     return ExprEvaluatorBaseTy::VisitCastExpr(E);
10407 
10408   case CK_NullToMemberPointer:
10409     VisitIgnoredValue(E->getSubExpr());
10410     return ZeroInitialization(E);
10411 
10412   case CK_BaseToDerivedMemberPointer: {
10413     if (!Visit(E->getSubExpr()))
10414       return false;
10415     if (E->path_empty())
10416       return true;
10417     // Base-to-derived member pointer casts store the path in derived-to-base
10418     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
10419     // the wrong end of the derived->base arc, so stagger the path by one class.
10420     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
10421     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
10422          PathI != PathE; ++PathI) {
10423       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
10424       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
10425       if (!Result.castToDerived(Derived))
10426         return Error(E);
10427     }
10428     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
10429     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
10430       return Error(E);
10431     return true;
10432   }
10433 
10434   case CK_DerivedToBaseMemberPointer:
10435     if (!Visit(E->getSubExpr()))
10436       return false;
10437     for (CastExpr::path_const_iterator PathI = E->path_begin(),
10438          PathE = E->path_end(); PathI != PathE; ++PathI) {
10439       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
10440       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
10441       if (!Result.castToBase(Base))
10442         return Error(E);
10443     }
10444     return true;
10445   }
10446 }
10447 
10448 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
10449   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
10450   // member can be formed.
10451   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
10452 }
10453 
10454 //===----------------------------------------------------------------------===//
10455 // Record Evaluation
10456 //===----------------------------------------------------------------------===//
10457 
10458 namespace {
10459   class RecordExprEvaluator
10460   : public ExprEvaluatorBase<RecordExprEvaluator> {
10461     const LValue &This;
10462     APValue &Result;
10463   public:
10464 
10465     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
10466       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
10467 
10468     bool Success(const APValue &V, const Expr *E) {
10469       Result = V;
10470       return true;
10471     }
10472     bool ZeroInitialization(const Expr *E) {
10473       return ZeroInitialization(E, E->getType());
10474     }
10475     bool ZeroInitialization(const Expr *E, QualType T);
10476 
10477     bool VisitCallExpr(const CallExpr *E) {
10478       return handleCallExpr(E, Result, &This);
10479     }
10480     bool VisitCastExpr(const CastExpr *E);
10481     bool VisitInitListExpr(const InitListExpr *E);
10482     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10483       return VisitCXXConstructExpr(E, E->getType());
10484     }
10485     bool VisitLambdaExpr(const LambdaExpr *E);
10486     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
10487     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
10488     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
10489     bool VisitBinCmp(const BinaryOperator *E);
10490     bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
10491     bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
10492                                          ArrayRef<Expr *> Args);
10493   };
10494 }
10495 
10496 /// Perform zero-initialization on an object of non-union class type.
10497 /// C++11 [dcl.init]p5:
10498 ///  To zero-initialize an object or reference of type T means:
10499 ///    [...]
10500 ///    -- if T is a (possibly cv-qualified) non-union class type,
10501 ///       each non-static data member and each base-class subobject is
10502 ///       zero-initialized
10503 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
10504                                           const RecordDecl *RD,
10505                                           const LValue &This, APValue &Result) {
10506   assert(!RD->isUnion() && "Expected non-union class type");
10507   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
10508   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
10509                    std::distance(RD->field_begin(), RD->field_end()));
10510 
10511   if (RD->isInvalidDecl()) return false;
10512   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
10513 
10514   if (CD) {
10515     unsigned Index = 0;
10516     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
10517            End = CD->bases_end(); I != End; ++I, ++Index) {
10518       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
10519       LValue Subobject = This;
10520       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
10521         return false;
10522       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
10523                                          Result.getStructBase(Index)))
10524         return false;
10525     }
10526   }
10527 
10528   for (const auto *I : RD->fields()) {
10529     // -- if T is a reference type, no initialization is performed.
10530     if (I->isUnnamedBitField() || I->getType()->isReferenceType())
10531       continue;
10532 
10533     LValue Subobject = This;
10534     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
10535       return false;
10536 
10537     ImplicitValueInitExpr VIE(I->getType());
10538     if (!EvaluateInPlace(
10539           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
10540       return false;
10541   }
10542 
10543   return true;
10544 }
10545 
10546 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
10547   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
10548   if (RD->isInvalidDecl()) return false;
10549   if (RD->isUnion()) {
10550     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
10551     // object's first non-static named data member is zero-initialized
10552     RecordDecl::field_iterator I = RD->field_begin();
10553     while (I != RD->field_end() && (*I)->isUnnamedBitField())
10554       ++I;
10555     if (I == RD->field_end()) {
10556       Result = APValue((const FieldDecl*)nullptr);
10557       return true;
10558     }
10559 
10560     LValue Subobject = This;
10561     if (!HandleLValueMember(Info, E, Subobject, *I))
10562       return false;
10563     Result = APValue(*I);
10564     ImplicitValueInitExpr VIE(I->getType());
10565     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
10566   }
10567 
10568   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
10569     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
10570     return false;
10571   }
10572 
10573   return HandleClassZeroInitialization(Info, E, RD, This, Result);
10574 }
10575 
10576 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
10577   switch (E->getCastKind()) {
10578   default:
10579     return ExprEvaluatorBaseTy::VisitCastExpr(E);
10580 
10581   case CK_ConstructorConversion:
10582     return Visit(E->getSubExpr());
10583 
10584   case CK_DerivedToBase:
10585   case CK_UncheckedDerivedToBase: {
10586     APValue DerivedObject;
10587     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
10588       return false;
10589     if (!DerivedObject.isStruct())
10590       return Error(E->getSubExpr());
10591 
10592     // Derived-to-base rvalue conversion: just slice off the derived part.
10593     APValue *Value = &DerivedObject;
10594     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
10595     for (CastExpr::path_const_iterator PathI = E->path_begin(),
10596          PathE = E->path_end(); PathI != PathE; ++PathI) {
10597       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
10598       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
10599       Value = &Value->getStructBase(getBaseIndex(RD, Base));
10600       RD = Base;
10601     }
10602     Result = *Value;
10603     return true;
10604   }
10605   }
10606 }
10607 
10608 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10609   if (E->isTransparent())
10610     return Visit(E->getInit(0));
10611   return VisitCXXParenListOrInitListExpr(E, E->inits());
10612 }
10613 
10614 bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr(
10615     const Expr *ExprToVisit, ArrayRef<Expr *> Args) {
10616   const RecordDecl *RD =
10617       ExprToVisit->getType()->castAs<RecordType>()->getDecl();
10618   if (RD->isInvalidDecl()) return false;
10619   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
10620   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
10621 
10622   EvalInfo::EvaluatingConstructorRAII EvalObj(
10623       Info,
10624       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
10625       CXXRD && CXXRD->getNumBases());
10626 
10627   if (RD->isUnion()) {
10628     const FieldDecl *Field;
10629     if (auto *ILE = dyn_cast<InitListExpr>(ExprToVisit)) {
10630       Field = ILE->getInitializedFieldInUnion();
10631     } else if (auto *PLIE = dyn_cast<CXXParenListInitExpr>(ExprToVisit)) {
10632       Field = PLIE->getInitializedFieldInUnion();
10633     } else {
10634       llvm_unreachable(
10635           "Expression is neither an init list nor a C++ paren list");
10636     }
10637 
10638     Result = APValue(Field);
10639     if (!Field)
10640       return true;
10641 
10642     // If the initializer list for a union does not contain any elements, the
10643     // first element of the union is value-initialized.
10644     // FIXME: The element should be initialized from an initializer list.
10645     //        Is this difference ever observable for initializer lists which
10646     //        we don't build?
10647     ImplicitValueInitExpr VIE(Field->getType());
10648     const Expr *InitExpr = Args.empty() ? &VIE : Args[0];
10649 
10650     LValue Subobject = This;
10651     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
10652       return false;
10653 
10654     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10655     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10656                                   isa<CXXDefaultInitExpr>(InitExpr));
10657 
10658     if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
10659       if (Field->isBitField())
10660         return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
10661                                      Field);
10662       return true;
10663     }
10664 
10665     return false;
10666   }
10667 
10668   if (!Result.hasValue())
10669     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
10670                      std::distance(RD->field_begin(), RD->field_end()));
10671   unsigned ElementNo = 0;
10672   bool Success = true;
10673 
10674   // Initialize base classes.
10675   if (CXXRD && CXXRD->getNumBases()) {
10676     for (const auto &Base : CXXRD->bases()) {
10677       assert(ElementNo < Args.size() && "missing init for base class");
10678       const Expr *Init = Args[ElementNo];
10679 
10680       LValue Subobject = This;
10681       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
10682         return false;
10683 
10684       APValue &FieldVal = Result.getStructBase(ElementNo);
10685       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
10686         if (!Info.noteFailure())
10687           return false;
10688         Success = false;
10689       }
10690       ++ElementNo;
10691     }
10692 
10693     EvalObj.finishedConstructingBases();
10694   }
10695 
10696   // Initialize members.
10697   for (const auto *Field : RD->fields()) {
10698     // Anonymous bit-fields are not considered members of the class for
10699     // purposes of aggregate initialization.
10700     if (Field->isUnnamedBitField())
10701       continue;
10702 
10703     LValue Subobject = This;
10704 
10705     bool HaveInit = ElementNo < Args.size();
10706 
10707     // FIXME: Diagnostics here should point to the end of the initializer
10708     // list, not the start.
10709     if (!HandleLValueMember(Info, HaveInit ? Args[ElementNo] : ExprToVisit,
10710                             Subobject, Field, &Layout))
10711       return false;
10712 
10713     // Perform an implicit value-initialization for members beyond the end of
10714     // the initializer list.
10715     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
10716     const Expr *Init = HaveInit ? Args[ElementNo++] : &VIE;
10717 
10718     if (Field->getType()->isIncompleteArrayType()) {
10719       if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {
10720         if (!CAT->isZeroSize()) {
10721           // Bail out for now. This might sort of "work", but the rest of the
10722           // code isn't really prepared to handle it.
10723           Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array);
10724           return false;
10725         }
10726       }
10727     }
10728 
10729     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10730     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10731                                   isa<CXXDefaultInitExpr>(Init));
10732 
10733     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10734     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
10735         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
10736                                                        FieldVal, Field))) {
10737       if (!Info.noteFailure())
10738         return false;
10739       Success = false;
10740     }
10741   }
10742 
10743   EvalObj.finishedConstructingFields();
10744 
10745   return Success;
10746 }
10747 
10748 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10749                                                 QualType T) {
10750   // Note that E's type is not necessarily the type of our class here; we might
10751   // be initializing an array element instead.
10752   const CXXConstructorDecl *FD = E->getConstructor();
10753   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
10754 
10755   bool ZeroInit = E->requiresZeroInitialization();
10756   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
10757     // If we've already performed zero-initialization, we're already done.
10758     if (Result.hasValue())
10759       return true;
10760 
10761     if (ZeroInit)
10762       return ZeroInitialization(E, T);
10763 
10764     return handleDefaultInitValue(T, Result);
10765   }
10766 
10767   const FunctionDecl *Definition = nullptr;
10768   auto Body = FD->getBody(Definition);
10769 
10770   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10771     return false;
10772 
10773   // Avoid materializing a temporary for an elidable copy/move constructor.
10774   if (E->isElidable() && !ZeroInit) {
10775     // FIXME: This only handles the simplest case, where the source object
10776     //        is passed directly as the first argument to the constructor.
10777     //        This should also handle stepping though implicit casts and
10778     //        and conversion sequences which involve two steps, with a
10779     //        conversion operator followed by a converting constructor.
10780     const Expr *SrcObj = E->getArg(0);
10781     assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
10782     assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
10783     if (const MaterializeTemporaryExpr *ME =
10784             dyn_cast<MaterializeTemporaryExpr>(SrcObj))
10785       return Visit(ME->getSubExpr());
10786   }
10787 
10788   if (ZeroInit && !ZeroInitialization(E, T))
10789     return false;
10790 
10791   auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
10792   return HandleConstructorCall(E, This, Args,
10793                                cast<CXXConstructorDecl>(Definition), Info,
10794                                Result);
10795 }
10796 
10797 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
10798     const CXXInheritedCtorInitExpr *E) {
10799   if (!Info.CurrentCall) {
10800     assert(Info.checkingPotentialConstantExpression());
10801     return false;
10802   }
10803 
10804   const CXXConstructorDecl *FD = E->getConstructor();
10805   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
10806     return false;
10807 
10808   const FunctionDecl *Definition = nullptr;
10809   auto Body = FD->getBody(Definition);
10810 
10811   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10812     return false;
10813 
10814   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
10815                                cast<CXXConstructorDecl>(Definition), Info,
10816                                Result);
10817 }
10818 
10819 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
10820     const CXXStdInitializerListExpr *E) {
10821   const ConstantArrayType *ArrayType =
10822       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
10823 
10824   LValue Array;
10825   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
10826     return false;
10827 
10828   assert(ArrayType && "unexpected type for array initializer");
10829 
10830   // Get a pointer to the first element of the array.
10831   Array.addArray(Info, E, ArrayType);
10832 
10833   // FIXME: What if the initializer_list type has base classes, etc?
10834   Result = APValue(APValue::UninitStruct(), 0, 2);
10835   Array.moveInto(Result.getStructField(0));
10836 
10837   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
10838   RecordDecl::field_iterator Field = Record->field_begin();
10839   assert(Field != Record->field_end() &&
10840          Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10841                               ArrayType->getElementType()) &&
10842          "Expected std::initializer_list first field to be const E *");
10843   ++Field;
10844   assert(Field != Record->field_end() &&
10845          "Expected std::initializer_list to have two fields");
10846 
10847   if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) {
10848     // Length.
10849     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
10850   } else {
10851     // End pointer.
10852     assert(Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10853                                 ArrayType->getElementType()) &&
10854            "Expected std::initializer_list second field to be const E *");
10855     if (!HandleLValueArrayAdjustment(Info, E, Array,
10856                                      ArrayType->getElementType(),
10857                                      ArrayType->getZExtSize()))
10858       return false;
10859     Array.moveInto(Result.getStructField(1));
10860   }
10861 
10862   assert(++Field == Record->field_end() &&
10863          "Expected std::initializer_list to only have two fields");
10864 
10865   return true;
10866 }
10867 
10868 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
10869   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
10870   if (ClosureClass->isInvalidDecl())
10871     return false;
10872 
10873   const size_t NumFields =
10874       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
10875 
10876   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
10877                                             E->capture_init_end()) &&
10878          "The number of lambda capture initializers should equal the number of "
10879          "fields within the closure type");
10880 
10881   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
10882   // Iterate through all the lambda's closure object's fields and initialize
10883   // them.
10884   auto *CaptureInitIt = E->capture_init_begin();
10885   bool Success = true;
10886   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
10887   for (const auto *Field : ClosureClass->fields()) {
10888     assert(CaptureInitIt != E->capture_init_end());
10889     // Get the initializer for this field
10890     Expr *const CurFieldInit = *CaptureInitIt++;
10891 
10892     // If there is no initializer, either this is a VLA or an error has
10893     // occurred.
10894     if (!CurFieldInit)
10895       return Error(E);
10896 
10897     LValue Subobject = This;
10898 
10899     if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
10900       return false;
10901 
10902     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10903     if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
10904       if (!Info.keepEvaluatingAfterFailure())
10905         return false;
10906       Success = false;
10907     }
10908   }
10909   return Success;
10910 }
10911 
10912 static bool EvaluateRecord(const Expr *E, const LValue &This,
10913                            APValue &Result, EvalInfo &Info) {
10914   assert(!E->isValueDependent());
10915   assert(E->isPRValue() && E->getType()->isRecordType() &&
10916          "can't evaluate expression as a record rvalue");
10917   return RecordExprEvaluator(Info, This, Result).Visit(E);
10918 }
10919 
10920 //===----------------------------------------------------------------------===//
10921 // Temporary Evaluation
10922 //
10923 // Temporaries are represented in the AST as rvalues, but generally behave like
10924 // lvalues. The full-object of which the temporary is a subobject is implicitly
10925 // materialized so that a reference can bind to it.
10926 //===----------------------------------------------------------------------===//
10927 namespace {
10928 class TemporaryExprEvaluator
10929   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
10930 public:
10931   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
10932     LValueExprEvaluatorBaseTy(Info, Result, false) {}
10933 
10934   /// Visit an expression which constructs the value of this temporary.
10935   bool VisitConstructExpr(const Expr *E) {
10936     APValue &Value = Info.CurrentCall->createTemporary(
10937         E, E->getType(), ScopeKind::FullExpression, Result);
10938     return EvaluateInPlace(Value, Info, Result, E);
10939   }
10940 
10941   bool VisitCastExpr(const CastExpr *E) {
10942     switch (E->getCastKind()) {
10943     default:
10944       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
10945 
10946     case CK_ConstructorConversion:
10947       return VisitConstructExpr(E->getSubExpr());
10948     }
10949   }
10950   bool VisitInitListExpr(const InitListExpr *E) {
10951     return VisitConstructExpr(E);
10952   }
10953   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10954     return VisitConstructExpr(E);
10955   }
10956   bool VisitCallExpr(const CallExpr *E) {
10957     return VisitConstructExpr(E);
10958   }
10959   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
10960     return VisitConstructExpr(E);
10961   }
10962   bool VisitLambdaExpr(const LambdaExpr *E) {
10963     return VisitConstructExpr(E);
10964   }
10965 };
10966 } // end anonymous namespace
10967 
10968 /// Evaluate an expression of record type as a temporary.
10969 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
10970   assert(!E->isValueDependent());
10971   assert(E->isPRValue() && E->getType()->isRecordType());
10972   return TemporaryExprEvaluator(Info, Result).Visit(E);
10973 }
10974 
10975 //===----------------------------------------------------------------------===//
10976 // Vector Evaluation
10977 //===----------------------------------------------------------------------===//
10978 
10979 namespace {
10980   class VectorExprEvaluator
10981   : public ExprEvaluatorBase<VectorExprEvaluator> {
10982     APValue &Result;
10983   public:
10984 
10985     VectorExprEvaluator(EvalInfo &info, APValue &Result)
10986       : ExprEvaluatorBaseTy(info), Result(Result) {}
10987 
10988     bool Success(ArrayRef<APValue> V, const Expr *E) {
10989       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
10990       // FIXME: remove this APValue copy.
10991       Result = APValue(V.data(), V.size());
10992       return true;
10993     }
10994     bool Success(const APValue &V, const Expr *E) {
10995       assert(V.isVector());
10996       Result = V;
10997       return true;
10998     }
10999     bool ZeroInitialization(const Expr *E);
11000 
11001     bool VisitUnaryReal(const UnaryOperator *E)
11002       { return Visit(E->getSubExpr()); }
11003     bool VisitCastExpr(const CastExpr* E);
11004     bool VisitInitListExpr(const InitListExpr *E);
11005     bool VisitUnaryImag(const UnaryOperator *E);
11006     bool VisitBinaryOperator(const BinaryOperator *E);
11007     bool VisitUnaryOperator(const UnaryOperator *E);
11008     bool VisitConvertVectorExpr(const ConvertVectorExpr *E);
11009     bool VisitShuffleVectorExpr(const ShuffleVectorExpr *E);
11010 
11011     // FIXME: Missing: conditional operator (for GNU
11012     //                 conditional select), ExtVectorElementExpr
11013   };
11014 } // end anonymous namespace
11015 
11016 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
11017   assert(E->isPRValue() && E->getType()->isVectorType() &&
11018          "not a vector prvalue");
11019   return VectorExprEvaluator(Info, Result).Visit(E);
11020 }
11021 
11022 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
11023   const VectorType *VTy = E->getType()->castAs<VectorType>();
11024   unsigned NElts = VTy->getNumElements();
11025 
11026   const Expr *SE = E->getSubExpr();
11027   QualType SETy = SE->getType();
11028 
11029   switch (E->getCastKind()) {
11030   case CK_VectorSplat: {
11031     APValue Val = APValue();
11032     if (SETy->isIntegerType()) {
11033       APSInt IntResult;
11034       if (!EvaluateInteger(SE, IntResult, Info))
11035         return false;
11036       Val = APValue(std::move(IntResult));
11037     } else if (SETy->isRealFloatingType()) {
11038       APFloat FloatResult(0.0);
11039       if (!EvaluateFloat(SE, FloatResult, Info))
11040         return false;
11041       Val = APValue(std::move(FloatResult));
11042     } else {
11043       return Error(E);
11044     }
11045 
11046     // Splat and create vector APValue.
11047     SmallVector<APValue, 4> Elts(NElts, Val);
11048     return Success(Elts, E);
11049   }
11050   case CK_BitCast: {
11051     APValue SVal;
11052     if (!Evaluate(SVal, Info, SE))
11053       return false;
11054 
11055     if (!SVal.isInt() && !SVal.isFloat() && !SVal.isVector()) {
11056       // Give up if the input isn't an int, float, or vector.  For example, we
11057       // reject "(v4i16)(intptr_t)&a".
11058       Info.FFDiag(E, diag::note_constexpr_invalid_cast)
11059           << 2 << Info.Ctx.getLangOpts().CPlusPlus;
11060       return false;
11061     }
11062 
11063     if (!handleRValueToRValueBitCast(Info, Result, SVal, E))
11064       return false;
11065 
11066     return true;
11067   }
11068   case CK_HLSLVectorTruncation: {
11069     APValue Val;
11070     SmallVector<APValue, 4> Elements;
11071     if (!EvaluateVector(SE, Val, Info))
11072       return Error(E);
11073     for (unsigned I = 0; I < NElts; I++)
11074       Elements.push_back(Val.getVectorElt(I));
11075     return Success(Elements, E);
11076   }
11077   default:
11078     return ExprEvaluatorBaseTy::VisitCastExpr(E);
11079   }
11080 }
11081 
11082 bool
11083 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11084   const VectorType *VT = E->getType()->castAs<VectorType>();
11085   unsigned NumInits = E->getNumInits();
11086   unsigned NumElements = VT->getNumElements();
11087 
11088   QualType EltTy = VT->getElementType();
11089   SmallVector<APValue, 4> Elements;
11090 
11091   // The number of initializers can be less than the number of
11092   // vector elements. For OpenCL, this can be due to nested vector
11093   // initialization. For GCC compatibility, missing trailing elements
11094   // should be initialized with zeroes.
11095   unsigned CountInits = 0, CountElts = 0;
11096   while (CountElts < NumElements) {
11097     // Handle nested vector initialization.
11098     if (CountInits < NumInits
11099         && E->getInit(CountInits)->getType()->isVectorType()) {
11100       APValue v;
11101       if (!EvaluateVector(E->getInit(CountInits), v, Info))
11102         return Error(E);
11103       unsigned vlen = v.getVectorLength();
11104       for (unsigned j = 0; j < vlen; j++)
11105         Elements.push_back(v.getVectorElt(j));
11106       CountElts += vlen;
11107     } else if (EltTy->isIntegerType()) {
11108       llvm::APSInt sInt(32);
11109       if (CountInits < NumInits) {
11110         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
11111           return false;
11112       } else // trailing integer zero.
11113         sInt = Info.Ctx.MakeIntValue(0, EltTy);
11114       Elements.push_back(APValue(sInt));
11115       CountElts++;
11116     } else {
11117       llvm::APFloat f(0.0);
11118       if (CountInits < NumInits) {
11119         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
11120           return false;
11121       } else // trailing float zero.
11122         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
11123       Elements.push_back(APValue(f));
11124       CountElts++;
11125     }
11126     CountInits++;
11127   }
11128   return Success(Elements, E);
11129 }
11130 
11131 bool
11132 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
11133   const auto *VT = E->getType()->castAs<VectorType>();
11134   QualType EltTy = VT->getElementType();
11135   APValue ZeroElement;
11136   if (EltTy->isIntegerType())
11137     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
11138   else
11139     ZeroElement =
11140         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
11141 
11142   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
11143   return Success(Elements, E);
11144 }
11145 
11146 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
11147   VisitIgnoredValue(E->getSubExpr());
11148   return ZeroInitialization(E);
11149 }
11150 
11151 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11152   BinaryOperatorKind Op = E->getOpcode();
11153   assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
11154          "Operation not supported on vector types");
11155 
11156   if (Op == BO_Comma)
11157     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11158 
11159   Expr *LHS = E->getLHS();
11160   Expr *RHS = E->getRHS();
11161 
11162   assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
11163          "Must both be vector types");
11164   // Checking JUST the types are the same would be fine, except shifts don't
11165   // need to have their types be the same (since you always shift by an int).
11166   assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
11167              E->getType()->castAs<VectorType>()->getNumElements() &&
11168          RHS->getType()->castAs<VectorType>()->getNumElements() ==
11169              E->getType()->castAs<VectorType>()->getNumElements() &&
11170          "All operands must be the same size.");
11171 
11172   APValue LHSValue;
11173   APValue RHSValue;
11174   bool LHSOK = Evaluate(LHSValue, Info, LHS);
11175   if (!LHSOK && !Info.noteFailure())
11176     return false;
11177   if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
11178     return false;
11179 
11180   if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
11181     return false;
11182 
11183   return Success(LHSValue, E);
11184 }
11185 
11186 static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
11187                                                         QualType ResultTy,
11188                                                         UnaryOperatorKind Op,
11189                                                         APValue Elt) {
11190   switch (Op) {
11191   case UO_Plus:
11192     // Nothing to do here.
11193     return Elt;
11194   case UO_Minus:
11195     if (Elt.getKind() == APValue::Int) {
11196       Elt.getInt().negate();
11197     } else {
11198       assert(Elt.getKind() == APValue::Float &&
11199              "Vector can only be int or float type");
11200       Elt.getFloat().changeSign();
11201     }
11202     return Elt;
11203   case UO_Not:
11204     // This is only valid for integral types anyway, so we don't have to handle
11205     // float here.
11206     assert(Elt.getKind() == APValue::Int &&
11207            "Vector operator ~ can only be int");
11208     Elt.getInt().flipAllBits();
11209     return Elt;
11210   case UO_LNot: {
11211     if (Elt.getKind() == APValue::Int) {
11212       Elt.getInt() = !Elt.getInt();
11213       // operator ! on vectors returns -1 for 'truth', so negate it.
11214       Elt.getInt().negate();
11215       return Elt;
11216     }
11217     assert(Elt.getKind() == APValue::Float &&
11218            "Vector can only be int or float type");
11219     // Float types result in an int of the same size, but -1 for true, or 0 for
11220     // false.
11221     APSInt EltResult{Ctx.getIntWidth(ResultTy),
11222                      ResultTy->isUnsignedIntegerType()};
11223     if (Elt.getFloat().isZero())
11224       EltResult.setAllBits();
11225     else
11226       EltResult.clearAllBits();
11227 
11228     return APValue{EltResult};
11229   }
11230   default:
11231     // FIXME: Implement the rest of the unary operators.
11232     return std::nullopt;
11233   }
11234 }
11235 
11236 bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11237   Expr *SubExpr = E->getSubExpr();
11238   const auto *VD = SubExpr->getType()->castAs<VectorType>();
11239   // This result element type differs in the case of negating a floating point
11240   // vector, since the result type is the a vector of the equivilant sized
11241   // integer.
11242   const QualType ResultEltTy = VD->getElementType();
11243   UnaryOperatorKind Op = E->getOpcode();
11244 
11245   APValue SubExprValue;
11246   if (!Evaluate(SubExprValue, Info, SubExpr))
11247     return false;
11248 
11249   // FIXME: This vector evaluator someday needs to be changed to be LValue
11250   // aware/keep LValue information around, rather than dealing with just vector
11251   // types directly. Until then, we cannot handle cases where the operand to
11252   // these unary operators is an LValue. The only case I've been able to see
11253   // cause this is operator++ assigning to a member expression (only valid in
11254   // altivec compilations) in C mode, so this shouldn't limit us too much.
11255   if (SubExprValue.isLValue())
11256     return false;
11257 
11258   assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
11259          "Vector length doesn't match type?");
11260 
11261   SmallVector<APValue, 4> ResultElements;
11262   for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
11263     std::optional<APValue> Elt = handleVectorUnaryOperator(
11264         Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
11265     if (!Elt)
11266       return false;
11267     ResultElements.push_back(*Elt);
11268   }
11269   return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11270 }
11271 
11272 static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO,
11273                                     const Expr *E, QualType SourceTy,
11274                                     QualType DestTy, APValue const &Original,
11275                                     APValue &Result) {
11276   if (SourceTy->isIntegerType()) {
11277     if (DestTy->isRealFloatingType()) {
11278       Result = APValue(APFloat(0.0));
11279       return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
11280                                   DestTy, Result.getFloat());
11281     }
11282     if (DestTy->isIntegerType()) {
11283       Result = APValue(
11284           HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
11285       return true;
11286     }
11287   } else if (SourceTy->isRealFloatingType()) {
11288     if (DestTy->isRealFloatingType()) {
11289       Result = Original;
11290       return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
11291                                     Result.getFloat());
11292     }
11293     if (DestTy->isIntegerType()) {
11294       Result = APValue(APSInt());
11295       return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
11296                                   DestTy, Result.getInt());
11297     }
11298   }
11299 
11300   Info.FFDiag(E, diag::err_convertvector_constexpr_unsupported_vector_cast)
11301       << SourceTy << DestTy;
11302   return false;
11303 }
11304 
11305 bool VectorExprEvaluator::VisitConvertVectorExpr(const ConvertVectorExpr *E) {
11306   APValue Source;
11307   QualType SourceVecType = E->getSrcExpr()->getType();
11308   if (!EvaluateAsRValue(Info, E->getSrcExpr(), Source))
11309     return false;
11310 
11311   QualType DestTy = E->getType()->castAs<VectorType>()->getElementType();
11312   QualType SourceTy = SourceVecType->castAs<VectorType>()->getElementType();
11313 
11314   const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11315 
11316   auto SourceLen = Source.getVectorLength();
11317   SmallVector<APValue, 4> ResultElements;
11318   ResultElements.reserve(SourceLen);
11319   for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11320     APValue Elt;
11321     if (!handleVectorElementCast(Info, FPO, E, SourceTy, DestTy,
11322                                  Source.getVectorElt(EltNum), Elt))
11323       return false;
11324     ResultElements.push_back(std::move(Elt));
11325   }
11326 
11327   return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11328 }
11329 
11330 static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E,
11331                                 QualType ElemType, APValue const &VecVal1,
11332                                 APValue const &VecVal2, unsigned EltNum,
11333                                 APValue &Result) {
11334   unsigned const TotalElementsInInputVector1 = VecVal1.getVectorLength();
11335   unsigned const TotalElementsInInputVector2 = VecVal2.getVectorLength();
11336 
11337   APSInt IndexVal = E->getShuffleMaskIdx(Info.Ctx, EltNum);
11338   int64_t index = IndexVal.getExtValue();
11339   // The spec says that -1 should be treated as undef for optimizations,
11340   // but in constexpr we'd have to produce an APValue::Indeterminate,
11341   // which is prohibited from being a top-level constant value. Emit a
11342   // diagnostic instead.
11343   if (index == -1) {
11344     Info.FFDiag(
11345         E, diag::err_shufflevector_minus_one_is_undefined_behavior_constexpr)
11346         << EltNum;
11347     return false;
11348   }
11349 
11350   if (index < 0 ||
11351       index >= TotalElementsInInputVector1 + TotalElementsInInputVector2)
11352     llvm_unreachable("Out of bounds shuffle index");
11353 
11354   if (index >= TotalElementsInInputVector1)
11355     Result = VecVal2.getVectorElt(index - TotalElementsInInputVector1);
11356   else
11357     Result = VecVal1.getVectorElt(index);
11358   return true;
11359 }
11360 
11361 bool VectorExprEvaluator::VisitShuffleVectorExpr(const ShuffleVectorExpr *E) {
11362   APValue VecVal1;
11363   const Expr *Vec1 = E->getExpr(0);
11364   if (!EvaluateAsRValue(Info, Vec1, VecVal1))
11365     return false;
11366   APValue VecVal2;
11367   const Expr *Vec2 = E->getExpr(1);
11368   if (!EvaluateAsRValue(Info, Vec2, VecVal2))
11369     return false;
11370 
11371   VectorType const *DestVecTy = E->getType()->castAs<VectorType>();
11372   QualType DestElTy = DestVecTy->getElementType();
11373 
11374   auto TotalElementsInOutputVector = DestVecTy->getNumElements();
11375 
11376   SmallVector<APValue, 4> ResultElements;
11377   ResultElements.reserve(TotalElementsInOutputVector);
11378   for (unsigned EltNum = 0; EltNum < TotalElementsInOutputVector; ++EltNum) {
11379     APValue Elt;
11380     if (!handleVectorShuffle(Info, E, DestElTy, VecVal1, VecVal2, EltNum, Elt))
11381       return false;
11382     ResultElements.push_back(std::move(Elt));
11383   }
11384 
11385   return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11386 }
11387 
11388 //===----------------------------------------------------------------------===//
11389 // Array Evaluation
11390 //===----------------------------------------------------------------------===//
11391 
11392 namespace {
11393   class ArrayExprEvaluator
11394   : public ExprEvaluatorBase<ArrayExprEvaluator> {
11395     const LValue &This;
11396     APValue &Result;
11397   public:
11398 
11399     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
11400       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
11401 
11402     bool Success(const APValue &V, const Expr *E) {
11403       assert(V.isArray() && "expected array");
11404       Result = V;
11405       return true;
11406     }
11407 
11408     bool ZeroInitialization(const Expr *E) {
11409       const ConstantArrayType *CAT =
11410           Info.Ctx.getAsConstantArrayType(E->getType());
11411       if (!CAT) {
11412         if (E->getType()->isIncompleteArrayType()) {
11413           // We can be asked to zero-initialize a flexible array member; this
11414           // is represented as an ImplicitValueInitExpr of incomplete array
11415           // type. In this case, the array has zero elements.
11416           Result = APValue(APValue::UninitArray(), 0, 0);
11417           return true;
11418         }
11419         // FIXME: We could handle VLAs here.
11420         return Error(E);
11421       }
11422 
11423       Result = APValue(APValue::UninitArray(), 0, CAT->getZExtSize());
11424       if (!Result.hasArrayFiller())
11425         return true;
11426 
11427       // Zero-initialize all elements.
11428       LValue Subobject = This;
11429       Subobject.addArray(Info, E, CAT);
11430       ImplicitValueInitExpr VIE(CAT->getElementType());
11431       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
11432     }
11433 
11434     bool VisitCallExpr(const CallExpr *E) {
11435       return handleCallExpr(E, Result, &This);
11436     }
11437     bool VisitInitListExpr(const InitListExpr *E,
11438                            QualType AllocType = QualType());
11439     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
11440     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
11441     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
11442                                const LValue &Subobject,
11443                                APValue *Value, QualType Type);
11444     bool VisitStringLiteral(const StringLiteral *E,
11445                             QualType AllocType = QualType()) {
11446       expandStringLiteral(Info, E, Result, AllocType);
11447       return true;
11448     }
11449     bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
11450     bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
11451                                          ArrayRef<Expr *> Args,
11452                                          const Expr *ArrayFiller,
11453                                          QualType AllocType = QualType());
11454   };
11455 } // end anonymous namespace
11456 
11457 static bool EvaluateArray(const Expr *E, const LValue &This,
11458                           APValue &Result, EvalInfo &Info) {
11459   assert(!E->isValueDependent());
11460   assert(E->isPRValue() && E->getType()->isArrayType() &&
11461          "not an array prvalue");
11462   return ArrayExprEvaluator(Info, This, Result).Visit(E);
11463 }
11464 
11465 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
11466                                      APValue &Result, const InitListExpr *ILE,
11467                                      QualType AllocType) {
11468   assert(!ILE->isValueDependent());
11469   assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
11470          "not an array prvalue");
11471   return ArrayExprEvaluator(Info, This, Result)
11472       .VisitInitListExpr(ILE, AllocType);
11473 }
11474 
11475 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
11476                                           APValue &Result,
11477                                           const CXXConstructExpr *CCE,
11478                                           QualType AllocType) {
11479   assert(!CCE->isValueDependent());
11480   assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
11481          "not an array prvalue");
11482   return ArrayExprEvaluator(Info, This, Result)
11483       .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
11484 }
11485 
11486 // Return true iff the given array filler may depend on the element index.
11487 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
11488   // For now, just allow non-class value-initialization and initialization
11489   // lists comprised of them.
11490   if (isa<ImplicitValueInitExpr>(FillerExpr))
11491     return false;
11492   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
11493     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
11494       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
11495         return true;
11496     }
11497 
11498     if (ILE->hasArrayFiller() &&
11499         MaybeElementDependentArrayFiller(ILE->getArrayFiller()))
11500       return true;
11501 
11502     return false;
11503   }
11504   return true;
11505 }
11506 
11507 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
11508                                            QualType AllocType) {
11509   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
11510       AllocType.isNull() ? E->getType() : AllocType);
11511   if (!CAT)
11512     return Error(E);
11513 
11514   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
11515   // an appropriately-typed string literal enclosed in braces.
11516   if (E->isStringLiteralInit()) {
11517     auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
11518     // FIXME: Support ObjCEncodeExpr here once we support it in
11519     // ArrayExprEvaluator generally.
11520     if (!SL)
11521       return Error(E);
11522     return VisitStringLiteral(SL, AllocType);
11523   }
11524   // Any other transparent list init will need proper handling of the
11525   // AllocType; we can't just recurse to the inner initializer.
11526   assert(!E->isTransparent() &&
11527          "transparent array list initialization is not string literal init?");
11528 
11529   return VisitCXXParenListOrInitListExpr(E, E->inits(), E->getArrayFiller(),
11530                                          AllocType);
11531 }
11532 
11533 bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr(
11534     const Expr *ExprToVisit, ArrayRef<Expr *> Args, const Expr *ArrayFiller,
11535     QualType AllocType) {
11536   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
11537       AllocType.isNull() ? ExprToVisit->getType() : AllocType);
11538 
11539   bool Success = true;
11540 
11541   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
11542          "zero-initialized array shouldn't have any initialized elts");
11543   APValue Filler;
11544   if (Result.isArray() && Result.hasArrayFiller())
11545     Filler = Result.getArrayFiller();
11546 
11547   unsigned NumEltsToInit = Args.size();
11548   unsigned NumElts = CAT->getZExtSize();
11549 
11550   // If the initializer might depend on the array index, run it for each
11551   // array element.
11552   if (NumEltsToInit != NumElts &&
11553       MaybeElementDependentArrayFiller(ArrayFiller)) {
11554     NumEltsToInit = NumElts;
11555   } else {
11556     for (auto *Init : Args) {
11557       if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts()))
11558         NumEltsToInit += EmbedS->getDataElementCount() - 1;
11559     }
11560     if (NumEltsToInit > NumElts)
11561       NumEltsToInit = NumElts;
11562   }
11563 
11564   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
11565                           << NumEltsToInit << ".\n");
11566 
11567   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
11568 
11569   // If the array was previously zero-initialized, preserve the
11570   // zero-initialized values.
11571   if (Filler.hasValue()) {
11572     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
11573       Result.getArrayInitializedElt(I) = Filler;
11574     if (Result.hasArrayFiller())
11575       Result.getArrayFiller() = Filler;
11576   }
11577 
11578   LValue Subobject = This;
11579   Subobject.addArray(Info, ExprToVisit, CAT);
11580   auto Eval = [&](const Expr *Init, unsigned ArrayIndex) {
11581     if (Init->isValueDependent())
11582       return EvaluateDependentExpr(Init, Info);
11583 
11584     if (!EvaluateInPlace(Result.getArrayInitializedElt(ArrayIndex), Info,
11585                          Subobject, Init) ||
11586         !HandleLValueArrayAdjustment(Info, Init, Subobject,
11587                                      CAT->getElementType(), 1)) {
11588       if (!Info.noteFailure())
11589         return false;
11590       Success = false;
11591     }
11592     return true;
11593   };
11594   unsigned ArrayIndex = 0;
11595   QualType DestTy = CAT->getElementType();
11596   APSInt Value(Info.Ctx.getTypeSize(DestTy), DestTy->isUnsignedIntegerType());
11597   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
11598     const Expr *Init = Index < Args.size() ? Args[Index] : ArrayFiller;
11599     if (ArrayIndex >= NumEltsToInit)
11600       break;
11601     if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {
11602       StringLiteral *SL = EmbedS->getDataStringLiteral();
11603       for (unsigned I = EmbedS->getStartingElementPos(),
11604                     N = EmbedS->getDataElementCount();
11605            I != EmbedS->getStartingElementPos() + N; ++I) {
11606         Value = SL->getCodeUnit(I);
11607         if (DestTy->isIntegerType()) {
11608           Result.getArrayInitializedElt(ArrayIndex) = APValue(Value);
11609         } else {
11610           assert(DestTy->isFloatingType() && "unexpected type");
11611           const FPOptions FPO =
11612               Init->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11613           APFloat FValue(0.0);
11614           if (!HandleIntToFloatCast(Info, Init, FPO, EmbedS->getType(), Value,
11615                                     DestTy, FValue))
11616             return false;
11617           Result.getArrayInitializedElt(ArrayIndex) = APValue(FValue);
11618         }
11619         ArrayIndex++;
11620       }
11621     } else {
11622       if (!Eval(Init, ArrayIndex))
11623         return false;
11624       ++ArrayIndex;
11625     }
11626   }
11627 
11628   if (!Result.hasArrayFiller())
11629     return Success;
11630 
11631   // If we get here, we have a trivial filler, which we can just evaluate
11632   // once and splat over the rest of the array elements.
11633   assert(ArrayFiller && "no array filler for incomplete init list");
11634   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
11635                          ArrayFiller) &&
11636          Success;
11637 }
11638 
11639 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
11640   LValue CommonLV;
11641   if (E->getCommonExpr() &&
11642       !Evaluate(Info.CurrentCall->createTemporary(
11643                     E->getCommonExpr(),
11644                     getStorageType(Info.Ctx, E->getCommonExpr()),
11645                     ScopeKind::FullExpression, CommonLV),
11646                 Info, E->getCommonExpr()->getSourceExpr()))
11647     return false;
11648 
11649   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
11650 
11651   uint64_t Elements = CAT->getZExtSize();
11652   Result = APValue(APValue::UninitArray(), Elements, Elements);
11653 
11654   LValue Subobject = This;
11655   Subobject.addArray(Info, E, CAT);
11656 
11657   bool Success = true;
11658   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
11659     // C++ [class.temporary]/5
11660     // There are four contexts in which temporaries are destroyed at a different
11661     // point than the end of the full-expression. [...] The second context is
11662     // when a copy constructor is called to copy an element of an array while
11663     // the entire array is copied [...]. In either case, if the constructor has
11664     // one or more default arguments, the destruction of every temporary created
11665     // in a default argument is sequenced before the construction of the next
11666     // array element, if any.
11667     FullExpressionRAII Scope(Info);
11668 
11669     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
11670                          Info, Subobject, E->getSubExpr()) ||
11671         !HandleLValueArrayAdjustment(Info, E, Subobject,
11672                                      CAT->getElementType(), 1)) {
11673       if (!Info.noteFailure())
11674         return false;
11675       Success = false;
11676     }
11677 
11678     // Make sure we run the destructors too.
11679     Scope.destroy();
11680   }
11681 
11682   return Success;
11683 }
11684 
11685 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
11686   return VisitCXXConstructExpr(E, This, &Result, E->getType());
11687 }
11688 
11689 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
11690                                                const LValue &Subobject,
11691                                                APValue *Value,
11692                                                QualType Type) {
11693   bool HadZeroInit = Value->hasValue();
11694 
11695   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
11696     unsigned FinalSize = CAT->getZExtSize();
11697 
11698     // Preserve the array filler if we had prior zero-initialization.
11699     APValue Filler =
11700       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
11701                                              : APValue();
11702 
11703     *Value = APValue(APValue::UninitArray(), 0, FinalSize);
11704     if (FinalSize == 0)
11705       return true;
11706 
11707     bool HasTrivialConstructor = CheckTrivialDefaultConstructor(
11708         Info, E->getExprLoc(), E->getConstructor(),
11709         E->requiresZeroInitialization());
11710     LValue ArrayElt = Subobject;
11711     ArrayElt.addArray(Info, E, CAT);
11712     // We do the whole initialization in two passes, first for just one element,
11713     // then for the whole array. It's possible we may find out we can't do const
11714     // init in the first pass, in which case we avoid allocating a potentially
11715     // large array. We don't do more passes because expanding array requires
11716     // copying the data, which is wasteful.
11717     for (const unsigned N : {1u, FinalSize}) {
11718       unsigned OldElts = Value->getArrayInitializedElts();
11719       if (OldElts == N)
11720         break;
11721 
11722       // Expand the array to appropriate size.
11723       APValue NewValue(APValue::UninitArray(), N, FinalSize);
11724       for (unsigned I = 0; I < OldElts; ++I)
11725         NewValue.getArrayInitializedElt(I).swap(
11726             Value->getArrayInitializedElt(I));
11727       Value->swap(NewValue);
11728 
11729       if (HadZeroInit)
11730         for (unsigned I = OldElts; I < N; ++I)
11731           Value->getArrayInitializedElt(I) = Filler;
11732 
11733       if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) {
11734         // If we have a trivial constructor, only evaluate it once and copy
11735         // the result into all the array elements.
11736         APValue &FirstResult = Value->getArrayInitializedElt(0);
11737         for (unsigned I = OldElts; I < FinalSize; ++I)
11738           Value->getArrayInitializedElt(I) = FirstResult;
11739       } else {
11740         for (unsigned I = OldElts; I < N; ++I) {
11741           if (!VisitCXXConstructExpr(E, ArrayElt,
11742                                      &Value->getArrayInitializedElt(I),
11743                                      CAT->getElementType()) ||
11744               !HandleLValueArrayAdjustment(Info, E, ArrayElt,
11745                                            CAT->getElementType(), 1))
11746             return false;
11747           // When checking for const initilization any diagnostic is considered
11748           // an error.
11749           if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
11750               !Info.keepEvaluatingAfterFailure())
11751             return false;
11752         }
11753       }
11754     }
11755 
11756     return true;
11757   }
11758 
11759   if (!Type->isRecordType())
11760     return Error(E);
11761 
11762   return RecordExprEvaluator(Info, Subobject, *Value)
11763              .VisitCXXConstructExpr(E, Type);
11764 }
11765 
11766 bool ArrayExprEvaluator::VisitCXXParenListInitExpr(
11767     const CXXParenListInitExpr *E) {
11768   assert(E->getType()->isConstantArrayType() &&
11769          "Expression result is not a constant array type");
11770 
11771   return VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),
11772                                          E->getArrayFiller());
11773 }
11774 
11775 //===----------------------------------------------------------------------===//
11776 // Integer Evaluation
11777 //
11778 // As a GNU extension, we support casting pointers to sufficiently-wide integer
11779 // types and back in constant folding. Integer values are thus represented
11780 // either as an integer-valued APValue, or as an lvalue-valued APValue.
11781 //===----------------------------------------------------------------------===//
11782 
11783 namespace {
11784 class IntExprEvaluator
11785         : public ExprEvaluatorBase<IntExprEvaluator> {
11786   APValue &Result;
11787 public:
11788   IntExprEvaluator(EvalInfo &info, APValue &result)
11789       : ExprEvaluatorBaseTy(info), Result(result) {}
11790 
11791   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
11792     assert(E->getType()->isIntegralOrEnumerationType() &&
11793            "Invalid evaluation result.");
11794     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
11795            "Invalid evaluation result.");
11796     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11797            "Invalid evaluation result.");
11798     Result = APValue(SI);
11799     return true;
11800   }
11801   bool Success(const llvm::APSInt &SI, const Expr *E) {
11802     return Success(SI, E, Result);
11803   }
11804 
11805   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
11806     assert(E->getType()->isIntegralOrEnumerationType() &&
11807            "Invalid evaluation result.");
11808     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11809            "Invalid evaluation result.");
11810     Result = APValue(APSInt(I));
11811     Result.getInt().setIsUnsigned(
11812                             E->getType()->isUnsignedIntegerOrEnumerationType());
11813     return true;
11814   }
11815   bool Success(const llvm::APInt &I, const Expr *E) {
11816     return Success(I, E, Result);
11817   }
11818 
11819   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
11820     assert(E->getType()->isIntegralOrEnumerationType() &&
11821            "Invalid evaluation result.");
11822     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
11823     return true;
11824   }
11825   bool Success(uint64_t Value, const Expr *E) {
11826     return Success(Value, E, Result);
11827   }
11828 
11829   bool Success(CharUnits Size, const Expr *E) {
11830     return Success(Size.getQuantity(), E);
11831   }
11832 
11833   bool Success(const APValue &V, const Expr *E) {
11834     if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
11835       Result = V;
11836       return true;
11837     }
11838     return Success(V.getInt(), E);
11839   }
11840 
11841   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
11842 
11843   friend std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &,
11844                                                              const CallExpr *);
11845 
11846   //===--------------------------------------------------------------------===//
11847   //                            Visitor Methods
11848   //===--------------------------------------------------------------------===//
11849 
11850   bool VisitIntegerLiteral(const IntegerLiteral *E) {
11851     return Success(E->getValue(), E);
11852   }
11853   bool VisitCharacterLiteral(const CharacterLiteral *E) {
11854     return Success(E->getValue(), E);
11855   }
11856 
11857   bool CheckReferencedDecl(const Expr *E, const Decl *D);
11858   bool VisitDeclRefExpr(const DeclRefExpr *E) {
11859     if (CheckReferencedDecl(E, E->getDecl()))
11860       return true;
11861 
11862     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
11863   }
11864   bool VisitMemberExpr(const MemberExpr *E) {
11865     if (CheckReferencedDecl(E, E->getMemberDecl())) {
11866       VisitIgnoredBaseExpression(E->getBase());
11867       return true;
11868     }
11869 
11870     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
11871   }
11872 
11873   bool VisitCallExpr(const CallExpr *E);
11874   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
11875   bool VisitBinaryOperator(const BinaryOperator *E);
11876   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
11877   bool VisitUnaryOperator(const UnaryOperator *E);
11878 
11879   bool VisitCastExpr(const CastExpr* E);
11880   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
11881 
11882   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
11883     return Success(E->getValue(), E);
11884   }
11885 
11886   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
11887     return Success(E->getValue(), E);
11888   }
11889 
11890   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
11891     if (Info.ArrayInitIndex == uint64_t(-1)) {
11892       // We were asked to evaluate this subexpression independent of the
11893       // enclosing ArrayInitLoopExpr. We can't do that.
11894       Info.FFDiag(E);
11895       return false;
11896     }
11897     return Success(Info.ArrayInitIndex, E);
11898   }
11899 
11900   // Note, GNU defines __null as an integer, not a pointer.
11901   bool VisitGNUNullExpr(const GNUNullExpr *E) {
11902     return ZeroInitialization(E);
11903   }
11904 
11905   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
11906     return Success(E->getValue(), E);
11907   }
11908 
11909   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
11910     return Success(E->getValue(), E);
11911   }
11912 
11913   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
11914     return Success(E->getValue(), E);
11915   }
11916 
11917   bool VisitOpenACCAsteriskSizeExpr(const OpenACCAsteriskSizeExpr *E) {
11918     // This should not be evaluated during constant expr evaluation, as it
11919     // should always be in an unevaluated context (the args list of a 'gang' or
11920     // 'tile' clause).
11921     return Error(E);
11922   }
11923 
11924   bool VisitUnaryReal(const UnaryOperator *E);
11925   bool VisitUnaryImag(const UnaryOperator *E);
11926 
11927   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
11928   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
11929   bool VisitSourceLocExpr(const SourceLocExpr *E);
11930   bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
11931   bool VisitRequiresExpr(const RequiresExpr *E);
11932   // FIXME: Missing: array subscript of vector, member of vector
11933 };
11934 
11935 class FixedPointExprEvaluator
11936     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
11937   APValue &Result;
11938 
11939  public:
11940   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
11941       : ExprEvaluatorBaseTy(info), Result(result) {}
11942 
11943   bool Success(const llvm::APInt &I, const Expr *E) {
11944     return Success(
11945         APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
11946   }
11947 
11948   bool Success(uint64_t Value, const Expr *E) {
11949     return Success(
11950         APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
11951   }
11952 
11953   bool Success(const APValue &V, const Expr *E) {
11954     return Success(V.getFixedPoint(), E);
11955   }
11956 
11957   bool Success(const APFixedPoint &V, const Expr *E) {
11958     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
11959     assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11960            "Invalid evaluation result.");
11961     Result = APValue(V);
11962     return true;
11963   }
11964 
11965   bool ZeroInitialization(const Expr *E) {
11966     return Success(0, E);
11967   }
11968 
11969   //===--------------------------------------------------------------------===//
11970   //                            Visitor Methods
11971   //===--------------------------------------------------------------------===//
11972 
11973   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
11974     return Success(E->getValue(), E);
11975   }
11976 
11977   bool VisitCastExpr(const CastExpr *E);
11978   bool VisitUnaryOperator(const UnaryOperator *E);
11979   bool VisitBinaryOperator(const BinaryOperator *E);
11980 };
11981 } // end anonymous namespace
11982 
11983 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
11984 /// produce either the integer value or a pointer.
11985 ///
11986 /// GCC has a heinous extension which folds casts between pointer types and
11987 /// pointer-sized integral types. We support this by allowing the evaluation of
11988 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
11989 /// Some simple arithmetic on such values is supported (they are treated much
11990 /// like char*).
11991 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
11992                                     EvalInfo &Info) {
11993   assert(!E->isValueDependent());
11994   assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
11995   return IntExprEvaluator(Info, Result).Visit(E);
11996 }
11997 
11998 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
11999   assert(!E->isValueDependent());
12000   APValue Val;
12001   if (!EvaluateIntegerOrLValue(E, Val, Info))
12002     return false;
12003   if (!Val.isInt()) {
12004     // FIXME: It would be better to produce the diagnostic for casting
12005     //        a pointer to an integer.
12006     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12007     return false;
12008   }
12009   Result = Val.getInt();
12010   return true;
12011 }
12012 
12013 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
12014   APValue Evaluated = E->EvaluateInContext(
12015       Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
12016   return Success(Evaluated, E);
12017 }
12018 
12019 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
12020                                EvalInfo &Info) {
12021   assert(!E->isValueDependent());
12022   if (E->getType()->isFixedPointType()) {
12023     APValue Val;
12024     if (!FixedPointExprEvaluator(Info, Val).Visit(E))
12025       return false;
12026     if (!Val.isFixedPoint())
12027       return false;
12028 
12029     Result = Val.getFixedPoint();
12030     return true;
12031   }
12032   return false;
12033 }
12034 
12035 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
12036                                         EvalInfo &Info) {
12037   assert(!E->isValueDependent());
12038   if (E->getType()->isIntegerType()) {
12039     auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
12040     APSInt Val;
12041     if (!EvaluateInteger(E, Val, Info))
12042       return false;
12043     Result = APFixedPoint(Val, FXSema);
12044     return true;
12045   } else if (E->getType()->isFixedPointType()) {
12046     return EvaluateFixedPoint(E, Result, Info);
12047   }
12048   return false;
12049 }
12050 
12051 /// Check whether the given declaration can be directly converted to an integral
12052 /// rvalue. If not, no diagnostic is produced; there are other things we can
12053 /// try.
12054 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
12055   // Enums are integer constant exprs.
12056   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
12057     // Check for signedness/width mismatches between E type and ECD value.
12058     bool SameSign = (ECD->getInitVal().isSigned()
12059                      == E->getType()->isSignedIntegerOrEnumerationType());
12060     bool SameWidth = (ECD->getInitVal().getBitWidth()
12061                       == Info.Ctx.getIntWidth(E->getType()));
12062     if (SameSign && SameWidth)
12063       return Success(ECD->getInitVal(), E);
12064     else {
12065       // Get rid of mismatch (otherwise Success assertions will fail)
12066       // by computing a new value matching the type of E.
12067       llvm::APSInt Val = ECD->getInitVal();
12068       if (!SameSign)
12069         Val.setIsSigned(!ECD->getInitVal().isSigned());
12070       if (!SameWidth)
12071         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
12072       return Success(Val, E);
12073     }
12074   }
12075   return false;
12076 }
12077 
12078 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
12079 /// as GCC.
12080 GCCTypeClass EvaluateBuiltinClassifyType(QualType T,
12081                                          const LangOptions &LangOpts) {
12082   assert(!T->isDependentType() && "unexpected dependent type");
12083 
12084   QualType CanTy = T.getCanonicalType();
12085 
12086   switch (CanTy->getTypeClass()) {
12087 #define TYPE(ID, BASE)
12088 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
12089 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
12090 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
12091 #include "clang/AST/TypeNodes.inc"
12092   case Type::Auto:
12093   case Type::DeducedTemplateSpecialization:
12094       llvm_unreachable("unexpected non-canonical or dependent type");
12095 
12096   case Type::Builtin:
12097       switch (cast<BuiltinType>(CanTy)->getKind()) {
12098 #define BUILTIN_TYPE(ID, SINGLETON_ID)
12099 #define SIGNED_TYPE(ID, SINGLETON_ID) \
12100     case BuiltinType::ID: return GCCTypeClass::Integer;
12101 #define FLOATING_TYPE(ID, SINGLETON_ID) \
12102     case BuiltinType::ID: return GCCTypeClass::RealFloat;
12103 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
12104     case BuiltinType::ID: break;
12105 #include "clang/AST/BuiltinTypes.def"
12106     case BuiltinType::Void:
12107       return GCCTypeClass::Void;
12108 
12109     case BuiltinType::Bool:
12110       return GCCTypeClass::Bool;
12111 
12112     case BuiltinType::Char_U:
12113     case BuiltinType::UChar:
12114     case BuiltinType::WChar_U:
12115     case BuiltinType::Char8:
12116     case BuiltinType::Char16:
12117     case BuiltinType::Char32:
12118     case BuiltinType::UShort:
12119     case BuiltinType::UInt:
12120     case BuiltinType::ULong:
12121     case BuiltinType::ULongLong:
12122     case BuiltinType::UInt128:
12123       return GCCTypeClass::Integer;
12124 
12125     case BuiltinType::UShortAccum:
12126     case BuiltinType::UAccum:
12127     case BuiltinType::ULongAccum:
12128     case BuiltinType::UShortFract:
12129     case BuiltinType::UFract:
12130     case BuiltinType::ULongFract:
12131     case BuiltinType::SatUShortAccum:
12132     case BuiltinType::SatUAccum:
12133     case BuiltinType::SatULongAccum:
12134     case BuiltinType::SatUShortFract:
12135     case BuiltinType::SatUFract:
12136     case BuiltinType::SatULongFract:
12137       return GCCTypeClass::None;
12138 
12139     case BuiltinType::NullPtr:
12140 
12141     case BuiltinType::ObjCId:
12142     case BuiltinType::ObjCClass:
12143     case BuiltinType::ObjCSel:
12144 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
12145     case BuiltinType::Id:
12146 #include "clang/Basic/OpenCLImageTypes.def"
12147 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
12148     case BuiltinType::Id:
12149 #include "clang/Basic/OpenCLExtensionTypes.def"
12150     case BuiltinType::OCLSampler:
12151     case BuiltinType::OCLEvent:
12152     case BuiltinType::OCLClkEvent:
12153     case BuiltinType::OCLQueue:
12154     case BuiltinType::OCLReserveID:
12155 #define SVE_TYPE(Name, Id, SingletonId) \
12156     case BuiltinType::Id:
12157 #include "clang/Basic/AArch64SVEACLETypes.def"
12158 #define PPC_VECTOR_TYPE(Name, Id, Size) \
12159     case BuiltinType::Id:
12160 #include "clang/Basic/PPCTypes.def"
12161 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
12162 #include "clang/Basic/RISCVVTypes.def"
12163 #define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
12164 #include "clang/Basic/WebAssemblyReferenceTypes.def"
12165 #define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
12166 #include "clang/Basic/AMDGPUTypes.def"
12167 #define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
12168 #include "clang/Basic/HLSLIntangibleTypes.def"
12169       return GCCTypeClass::None;
12170 
12171     case BuiltinType::Dependent:
12172       llvm_unreachable("unexpected dependent type");
12173     };
12174     llvm_unreachable("unexpected placeholder type");
12175 
12176   case Type::Enum:
12177     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
12178 
12179   case Type::Pointer:
12180   case Type::ConstantArray:
12181   case Type::VariableArray:
12182   case Type::IncompleteArray:
12183   case Type::FunctionNoProto:
12184   case Type::FunctionProto:
12185   case Type::ArrayParameter:
12186     return GCCTypeClass::Pointer;
12187 
12188   case Type::MemberPointer:
12189     return CanTy->isMemberDataPointerType()
12190                ? GCCTypeClass::PointerToDataMember
12191                : GCCTypeClass::PointerToMemberFunction;
12192 
12193   case Type::Complex:
12194     return GCCTypeClass::Complex;
12195 
12196   case Type::Record:
12197     return CanTy->isUnionType() ? GCCTypeClass::Union
12198                                 : GCCTypeClass::ClassOrStruct;
12199 
12200   case Type::Atomic:
12201     // GCC classifies _Atomic T the same as T.
12202     return EvaluateBuiltinClassifyType(
12203         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
12204 
12205   case Type::Vector:
12206   case Type::ExtVector:
12207     return GCCTypeClass::Vector;
12208 
12209   case Type::BlockPointer:
12210   case Type::ConstantMatrix:
12211   case Type::ObjCObject:
12212   case Type::ObjCInterface:
12213   case Type::ObjCObjectPointer:
12214   case Type::Pipe:
12215   case Type::HLSLAttributedResource:
12216     // Classify all other types that don't fit into the regular
12217     // classification the same way.
12218     return GCCTypeClass::None;
12219 
12220   case Type::BitInt:
12221     return GCCTypeClass::BitInt;
12222 
12223   case Type::LValueReference:
12224   case Type::RValueReference:
12225     llvm_unreachable("invalid type for expression");
12226   }
12227 
12228   llvm_unreachable("unexpected type class");
12229 }
12230 
12231 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
12232 /// as GCC.
12233 static GCCTypeClass
12234 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
12235   // If no argument was supplied, default to None. This isn't
12236   // ideal, however it is what gcc does.
12237   if (E->getNumArgs() == 0)
12238     return GCCTypeClass::None;
12239 
12240   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
12241   // being an ICE, but still folds it to a constant using the type of the first
12242   // argument.
12243   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
12244 }
12245 
12246 /// EvaluateBuiltinConstantPForLValue - Determine the result of
12247 /// __builtin_constant_p when applied to the given pointer.
12248 ///
12249 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
12250 /// or it points to the first character of a string literal.
12251 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
12252   APValue::LValueBase Base = LV.getLValueBase();
12253   if (Base.isNull()) {
12254     // A null base is acceptable.
12255     return true;
12256   } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
12257     if (!isa<StringLiteral>(E))
12258       return false;
12259     return LV.getLValueOffset().isZero();
12260   } else if (Base.is<TypeInfoLValue>()) {
12261     // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
12262     // evaluate to true.
12263     return true;
12264   } else {
12265     // Any other base is not constant enough for GCC.
12266     return false;
12267   }
12268 }
12269 
12270 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
12271 /// GCC as we can manage.
12272 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
12273   // This evaluation is not permitted to have side-effects, so evaluate it in
12274   // a speculative evaluation context.
12275   SpeculativeEvaluationRAII SpeculativeEval(Info);
12276 
12277   // Constant-folding is always enabled for the operand of __builtin_constant_p
12278   // (even when the enclosing evaluation context otherwise requires a strict
12279   // language-specific constant expression).
12280   FoldConstant Fold(Info, true);
12281 
12282   QualType ArgType = Arg->getType();
12283 
12284   // __builtin_constant_p always has one operand. The rules which gcc follows
12285   // are not precisely documented, but are as follows:
12286   //
12287   //  - If the operand is of integral, floating, complex or enumeration type,
12288   //    and can be folded to a known value of that type, it returns 1.
12289   //  - If the operand can be folded to a pointer to the first character
12290   //    of a string literal (or such a pointer cast to an integral type)
12291   //    or to a null pointer or an integer cast to a pointer, it returns 1.
12292   //
12293   // Otherwise, it returns 0.
12294   //
12295   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
12296   // its support for this did not work prior to GCC 9 and is not yet well
12297   // understood.
12298   if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
12299       ArgType->isAnyComplexType() || ArgType->isPointerType() ||
12300       ArgType->isNullPtrType()) {
12301     APValue V;
12302     if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
12303       Fold.keepDiagnostics();
12304       return false;
12305     }
12306 
12307     // For a pointer (possibly cast to integer), there are special rules.
12308     if (V.getKind() == APValue::LValue)
12309       return EvaluateBuiltinConstantPForLValue(V);
12310 
12311     // Otherwise, any constant value is good enough.
12312     return V.hasValue();
12313   }
12314 
12315   // Anything else isn't considered to be sufficiently constant.
12316   return false;
12317 }
12318 
12319 /// Retrieves the "underlying object type" of the given expression,
12320 /// as used by __builtin_object_size.
12321 static QualType getObjectType(APValue::LValueBase B) {
12322   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
12323     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
12324       return VD->getType();
12325   } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
12326     if (isa<CompoundLiteralExpr>(E))
12327       return E->getType();
12328   } else if (B.is<TypeInfoLValue>()) {
12329     return B.getTypeInfoType();
12330   } else if (B.is<DynamicAllocLValue>()) {
12331     return B.getDynamicAllocType();
12332   }
12333 
12334   return QualType();
12335 }
12336 
12337 /// A more selective version of E->IgnoreParenCasts for
12338 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
12339 /// to change the type of E.
12340 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
12341 ///
12342 /// Always returns an RValue with a pointer representation.
12343 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
12344   assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
12345 
12346   const Expr *NoParens = E->IgnoreParens();
12347   const auto *Cast = dyn_cast<CastExpr>(NoParens);
12348   if (Cast == nullptr)
12349     return NoParens;
12350 
12351   // We only conservatively allow a few kinds of casts, because this code is
12352   // inherently a simple solution that seeks to support the common case.
12353   auto CastKind = Cast->getCastKind();
12354   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
12355       CastKind != CK_AddressSpaceConversion)
12356     return NoParens;
12357 
12358   const auto *SubExpr = Cast->getSubExpr();
12359   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
12360     return NoParens;
12361   return ignorePointerCastsAndParens(SubExpr);
12362 }
12363 
12364 /// Checks to see if the given LValue's Designator is at the end of the LValue's
12365 /// record layout. e.g.
12366 ///   struct { struct { int a, b; } fst, snd; } obj;
12367 ///   obj.fst   // no
12368 ///   obj.snd   // yes
12369 ///   obj.fst.a // no
12370 ///   obj.fst.b // no
12371 ///   obj.snd.a // no
12372 ///   obj.snd.b // yes
12373 ///
12374 /// Please note: this function is specialized for how __builtin_object_size
12375 /// views "objects".
12376 ///
12377 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
12378 /// correct result, it will always return true.
12379 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
12380   assert(!LVal.Designator.Invalid);
12381 
12382   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
12383     const RecordDecl *Parent = FD->getParent();
12384     Invalid = Parent->isInvalidDecl();
12385     if (Invalid || Parent->isUnion())
12386       return true;
12387     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
12388     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
12389   };
12390 
12391   auto &Base = LVal.getLValueBase();
12392   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
12393     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
12394       bool Invalid;
12395       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
12396         return Invalid;
12397     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
12398       for (auto *FD : IFD->chain()) {
12399         bool Invalid;
12400         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
12401           return Invalid;
12402       }
12403     }
12404   }
12405 
12406   unsigned I = 0;
12407   QualType BaseType = getType(Base);
12408   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
12409     // If we don't know the array bound, conservatively assume we're looking at
12410     // the final array element.
12411     ++I;
12412     if (BaseType->isIncompleteArrayType())
12413       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
12414     else
12415       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
12416   }
12417 
12418   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
12419     const auto &Entry = LVal.Designator.Entries[I];
12420     if (BaseType->isArrayType()) {
12421       // Because __builtin_object_size treats arrays as objects, we can ignore
12422       // the index iff this is the last array in the Designator.
12423       if (I + 1 == E)
12424         return true;
12425       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
12426       uint64_t Index = Entry.getAsArrayIndex();
12427       if (Index + 1 != CAT->getZExtSize())
12428         return false;
12429       BaseType = CAT->getElementType();
12430     } else if (BaseType->isAnyComplexType()) {
12431       const auto *CT = BaseType->castAs<ComplexType>();
12432       uint64_t Index = Entry.getAsArrayIndex();
12433       if (Index != 1)
12434         return false;
12435       BaseType = CT->getElementType();
12436     } else if (auto *FD = getAsField(Entry)) {
12437       bool Invalid;
12438       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
12439         return Invalid;
12440       BaseType = FD->getType();
12441     } else {
12442       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
12443       return false;
12444     }
12445   }
12446   return true;
12447 }
12448 
12449 /// Tests to see if the LValue has a user-specified designator (that isn't
12450 /// necessarily valid). Note that this always returns 'true' if the LValue has
12451 /// an unsized array as its first designator entry, because there's currently no
12452 /// way to tell if the user typed *foo or foo[0].
12453 static bool refersToCompleteObject(const LValue &LVal) {
12454   if (LVal.Designator.Invalid)
12455     return false;
12456 
12457   if (!LVal.Designator.Entries.empty())
12458     return LVal.Designator.isMostDerivedAnUnsizedArray();
12459 
12460   if (!LVal.InvalidBase)
12461     return true;
12462 
12463   // If `E` is a MemberExpr, then the first part of the designator is hiding in
12464   // the LValueBase.
12465   const auto *E = LVal.Base.dyn_cast<const Expr *>();
12466   return !E || !isa<MemberExpr>(E);
12467 }
12468 
12469 /// Attempts to detect a user writing into a piece of memory that's impossible
12470 /// to figure out the size of by just using types.
12471 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
12472   const SubobjectDesignator &Designator = LVal.Designator;
12473   // Notes:
12474   // - Users can only write off of the end when we have an invalid base. Invalid
12475   //   bases imply we don't know where the memory came from.
12476   // - We used to be a bit more aggressive here; we'd only be conservative if
12477   //   the array at the end was flexible, or if it had 0 or 1 elements. This
12478   //   broke some common standard library extensions (PR30346), but was
12479   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
12480   //   with some sort of list. OTOH, it seems that GCC is always
12481   //   conservative with the last element in structs (if it's an array), so our
12482   //   current behavior is more compatible than an explicit list approach would
12483   //   be.
12484   auto isFlexibleArrayMember = [&] {
12485     using FAMKind = LangOptions::StrictFlexArraysLevelKind;
12486     FAMKind StrictFlexArraysLevel =
12487         Ctx.getLangOpts().getStrictFlexArraysLevel();
12488 
12489     if (Designator.isMostDerivedAnUnsizedArray())
12490       return true;
12491 
12492     if (StrictFlexArraysLevel == FAMKind::Default)
12493       return true;
12494 
12495     if (Designator.getMostDerivedArraySize() == 0 &&
12496         StrictFlexArraysLevel != FAMKind::IncompleteOnly)
12497       return true;
12498 
12499     if (Designator.getMostDerivedArraySize() == 1 &&
12500         StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete)
12501       return true;
12502 
12503     return false;
12504   };
12505 
12506   return LVal.InvalidBase &&
12507          Designator.Entries.size() == Designator.MostDerivedPathLength &&
12508          Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() &&
12509          isDesignatorAtObjectEnd(Ctx, LVal);
12510 }
12511 
12512 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
12513 /// Fails if the conversion would cause loss of precision.
12514 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
12515                                             CharUnits &Result) {
12516   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
12517   if (Int.ugt(CharUnitsMax))
12518     return false;
12519   Result = CharUnits::fromQuantity(Int.getZExtValue());
12520   return true;
12521 }
12522 
12523 /// If we're evaluating the object size of an instance of a struct that
12524 /// contains a flexible array member, add the size of the initializer.
12525 static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T,
12526                                            const LValue &LV, CharUnits &Size) {
12527   if (!T.isNull() && T->isStructureType() &&
12528       T->getAsStructureType()->getDecl()->hasFlexibleArrayMember())
12529     if (const auto *V = LV.getLValueBase().dyn_cast<const ValueDecl *>())
12530       if (const auto *VD = dyn_cast<VarDecl>(V))
12531         if (VD->hasInit())
12532           Size += VD->getFlexibleArrayInitChars(Info.Ctx);
12533 }
12534 
12535 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
12536 /// determine how many bytes exist from the beginning of the object to either
12537 /// the end of the current subobject, or the end of the object itself, depending
12538 /// on what the LValue looks like + the value of Type.
12539 ///
12540 /// If this returns false, the value of Result is undefined.
12541 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
12542                                unsigned Type, const LValue &LVal,
12543                                CharUnits &EndOffset) {
12544   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
12545 
12546   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
12547     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
12548       return false;
12549     return HandleSizeof(Info, ExprLoc, Ty, Result);
12550   };
12551 
12552   // We want to evaluate the size of the entire object. This is a valid fallback
12553   // for when Type=1 and the designator is invalid, because we're asked for an
12554   // upper-bound.
12555   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
12556     // Type=3 wants a lower bound, so we can't fall back to this.
12557     if (Type == 3 && !DetermineForCompleteObject)
12558       return false;
12559 
12560     llvm::APInt APEndOffset;
12561     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
12562         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
12563       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
12564 
12565     if (LVal.InvalidBase)
12566       return false;
12567 
12568     QualType BaseTy = getObjectType(LVal.getLValueBase());
12569     const bool Ret = CheckedHandleSizeof(BaseTy, EndOffset);
12570     addFlexibleArrayMemberInitSize(Info, BaseTy, LVal, EndOffset);
12571     return Ret;
12572   }
12573 
12574   // We want to evaluate the size of a subobject.
12575   const SubobjectDesignator &Designator = LVal.Designator;
12576 
12577   // The following is a moderately common idiom in C:
12578   //
12579   // struct Foo { int a; char c[1]; };
12580   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
12581   // strcpy(&F->c[0], Bar);
12582   //
12583   // In order to not break too much legacy code, we need to support it.
12584   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
12585     // If we can resolve this to an alloc_size call, we can hand that back,
12586     // because we know for certain how many bytes there are to write to.
12587     llvm::APInt APEndOffset;
12588     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
12589         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
12590       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
12591 
12592     // If we cannot determine the size of the initial allocation, then we can't
12593     // given an accurate upper-bound. However, we are still able to give
12594     // conservative lower-bounds for Type=3.
12595     if (Type == 1)
12596       return false;
12597   }
12598 
12599   CharUnits BytesPerElem;
12600   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
12601     return false;
12602 
12603   // According to the GCC documentation, we want the size of the subobject
12604   // denoted by the pointer. But that's not quite right -- what we actually
12605   // want is the size of the immediately-enclosing array, if there is one.
12606   int64_t ElemsRemaining;
12607   if (Designator.MostDerivedIsArrayElement &&
12608       Designator.Entries.size() == Designator.MostDerivedPathLength) {
12609     uint64_t ArraySize = Designator.getMostDerivedArraySize();
12610     uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
12611     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
12612   } else {
12613     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
12614   }
12615 
12616   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
12617   return true;
12618 }
12619 
12620 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
12621 /// returns true and stores the result in @p Size.
12622 ///
12623 /// If @p WasError is non-null, this will report whether the failure to evaluate
12624 /// is to be treated as an Error in IntExprEvaluator.
12625 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
12626                                          EvalInfo &Info, uint64_t &Size) {
12627   // Determine the denoted object.
12628   LValue LVal;
12629   {
12630     // The operand of __builtin_object_size is never evaluated for side-effects.
12631     // If there are any, but we can determine the pointed-to object anyway, then
12632     // ignore the side-effects.
12633     SpeculativeEvaluationRAII SpeculativeEval(Info);
12634     IgnoreSideEffectsRAII Fold(Info);
12635 
12636     if (E->isGLValue()) {
12637       // It's possible for us to be given GLValues if we're called via
12638       // Expr::tryEvaluateObjectSize.
12639       APValue RVal;
12640       if (!EvaluateAsRValue(Info, E, RVal))
12641         return false;
12642       LVal.setFrom(Info.Ctx, RVal);
12643     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
12644                                 /*InvalidBaseOK=*/true))
12645       return false;
12646   }
12647 
12648   // If we point to before the start of the object, there are no accessible
12649   // bytes.
12650   if (LVal.getLValueOffset().isNegative()) {
12651     Size = 0;
12652     return true;
12653   }
12654 
12655   CharUnits EndOffset;
12656   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
12657     return false;
12658 
12659   // If we've fallen outside of the end offset, just pretend there's nothing to
12660   // write to/read from.
12661   if (EndOffset <= LVal.getLValueOffset())
12662     Size = 0;
12663   else
12664     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
12665   return true;
12666 }
12667 
12668 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
12669   if (!IsConstantEvaluatedBuiltinCall(E))
12670     return ExprEvaluatorBaseTy::VisitCallExpr(E);
12671   return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
12672 }
12673 
12674 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
12675                                      APValue &Val, APSInt &Alignment) {
12676   QualType SrcTy = E->getArg(0)->getType();
12677   if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
12678     return false;
12679   // Even though we are evaluating integer expressions we could get a pointer
12680   // argument for the __builtin_is_aligned() case.
12681   if (SrcTy->isPointerType()) {
12682     LValue Ptr;
12683     if (!EvaluatePointer(E->getArg(0), Ptr, Info))
12684       return false;
12685     Ptr.moveInto(Val);
12686   } else if (!SrcTy->isIntegralOrEnumerationType()) {
12687     Info.FFDiag(E->getArg(0));
12688     return false;
12689   } else {
12690     APSInt SrcInt;
12691     if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
12692       return false;
12693     assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
12694            "Bit widths must be the same");
12695     Val = APValue(SrcInt);
12696   }
12697   assert(Val.hasValue());
12698   return true;
12699 }
12700 
12701 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
12702                                             unsigned BuiltinOp) {
12703   switch (BuiltinOp) {
12704   default:
12705     return false;
12706 
12707   case Builtin::BI__builtin_dynamic_object_size:
12708   case Builtin::BI__builtin_object_size: {
12709     // The type was checked when we built the expression.
12710     unsigned Type =
12711         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
12712     assert(Type <= 3 && "unexpected type");
12713 
12714     uint64_t Size;
12715     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
12716       return Success(Size, E);
12717 
12718     if (E->getArg(0)->HasSideEffects(Info.Ctx))
12719       return Success((Type & 2) ? 0 : -1, E);
12720 
12721     // Expression had no side effects, but we couldn't statically determine the
12722     // size of the referenced object.
12723     switch (Info.EvalMode) {
12724     case EvalInfo::EM_ConstantExpression:
12725     case EvalInfo::EM_ConstantFold:
12726     case EvalInfo::EM_IgnoreSideEffects:
12727       // Leave it to IR generation.
12728       return Error(E);
12729     case EvalInfo::EM_ConstantExpressionUnevaluated:
12730       // Reduce it to a constant now.
12731       return Success((Type & 2) ? 0 : -1, E);
12732     }
12733 
12734     llvm_unreachable("unexpected EvalMode");
12735   }
12736 
12737   case Builtin::BI__builtin_os_log_format_buffer_size: {
12738     analyze_os_log::OSLogBufferLayout Layout;
12739     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
12740     return Success(Layout.size().getQuantity(), E);
12741   }
12742 
12743   case Builtin::BI__builtin_is_aligned: {
12744     APValue Src;
12745     APSInt Alignment;
12746     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
12747       return false;
12748     if (Src.isLValue()) {
12749       // If we evaluated a pointer, check the minimum known alignment.
12750       LValue Ptr;
12751       Ptr.setFrom(Info.Ctx, Src);
12752       CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
12753       CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
12754       // We can return true if the known alignment at the computed offset is
12755       // greater than the requested alignment.
12756       assert(PtrAlign.isPowerOfTwo());
12757       assert(Alignment.isPowerOf2());
12758       if (PtrAlign.getQuantity() >= Alignment)
12759         return Success(1, E);
12760       // If the alignment is not known to be sufficient, some cases could still
12761       // be aligned at run time. However, if the requested alignment is less or
12762       // equal to the base alignment and the offset is not aligned, we know that
12763       // the run-time value can never be aligned.
12764       if (BaseAlignment.getQuantity() >= Alignment &&
12765           PtrAlign.getQuantity() < Alignment)
12766         return Success(0, E);
12767       // Otherwise we can't infer whether the value is sufficiently aligned.
12768       // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
12769       //  in cases where we can't fully evaluate the pointer.
12770       Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
12771           << Alignment;
12772       return false;
12773     }
12774     assert(Src.isInt());
12775     return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
12776   }
12777   case Builtin::BI__builtin_align_up: {
12778     APValue Src;
12779     APSInt Alignment;
12780     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
12781       return false;
12782     if (!Src.isInt())
12783       return Error(E);
12784     APSInt AlignedVal =
12785         APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
12786                Src.getInt().isUnsigned());
12787     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
12788     return Success(AlignedVal, E);
12789   }
12790   case Builtin::BI__builtin_align_down: {
12791     APValue Src;
12792     APSInt Alignment;
12793     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
12794       return false;
12795     if (!Src.isInt())
12796       return Error(E);
12797     APSInt AlignedVal =
12798         APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
12799     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
12800     return Success(AlignedVal, E);
12801   }
12802 
12803   case Builtin::BI__builtin_bitreverse8:
12804   case Builtin::BI__builtin_bitreverse16:
12805   case Builtin::BI__builtin_bitreverse32:
12806   case Builtin::BI__builtin_bitreverse64: {
12807     APSInt Val;
12808     if (!EvaluateInteger(E->getArg(0), Val, Info))
12809       return false;
12810 
12811     return Success(Val.reverseBits(), E);
12812   }
12813 
12814   case Builtin::BI__builtin_bswap16:
12815   case Builtin::BI__builtin_bswap32:
12816   case Builtin::BI__builtin_bswap64: {
12817     APSInt Val;
12818     if (!EvaluateInteger(E->getArg(0), Val, Info))
12819       return false;
12820 
12821     return Success(Val.byteSwap(), E);
12822   }
12823 
12824   case Builtin::BI__builtin_classify_type:
12825     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
12826 
12827   case Builtin::BI__builtin_clrsb:
12828   case Builtin::BI__builtin_clrsbl:
12829   case Builtin::BI__builtin_clrsbll: {
12830     APSInt Val;
12831     if (!EvaluateInteger(E->getArg(0), Val, Info))
12832       return false;
12833 
12834     return Success(Val.getBitWidth() - Val.getSignificantBits(), E);
12835   }
12836 
12837   case Builtin::BI__builtin_clz:
12838   case Builtin::BI__builtin_clzl:
12839   case Builtin::BI__builtin_clzll:
12840   case Builtin::BI__builtin_clzs:
12841   case Builtin::BI__builtin_clzg:
12842   case Builtin::BI__lzcnt16: // Microsoft variants of count leading-zeroes
12843   case Builtin::BI__lzcnt:
12844   case Builtin::BI__lzcnt64: {
12845     APSInt Val;
12846     if (!EvaluateInteger(E->getArg(0), Val, Info))
12847       return false;
12848 
12849     std::optional<APSInt> Fallback;
12850     if (BuiltinOp == Builtin::BI__builtin_clzg && E->getNumArgs() > 1) {
12851       APSInt FallbackTemp;
12852       if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
12853         return false;
12854       Fallback = FallbackTemp;
12855     }
12856 
12857     if (!Val) {
12858       if (Fallback)
12859         return Success(*Fallback, E);
12860 
12861       // When the argument is 0, the result of GCC builtins is undefined,
12862       // whereas for Microsoft intrinsics, the result is the bit-width of the
12863       // argument.
12864       bool ZeroIsUndefined = BuiltinOp != Builtin::BI__lzcnt16 &&
12865                              BuiltinOp != Builtin::BI__lzcnt &&
12866                              BuiltinOp != Builtin::BI__lzcnt64;
12867 
12868       if (ZeroIsUndefined)
12869         return Error(E);
12870     }
12871 
12872     return Success(Val.countl_zero(), E);
12873   }
12874 
12875   case Builtin::BI__builtin_constant_p: {
12876     const Expr *Arg = E->getArg(0);
12877     if (EvaluateBuiltinConstantP(Info, Arg))
12878       return Success(true, E);
12879     if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
12880       // Outside a constant context, eagerly evaluate to false in the presence
12881       // of side-effects in order to avoid -Wunsequenced false-positives in
12882       // a branch on __builtin_constant_p(expr).
12883       return Success(false, E);
12884     }
12885     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12886     return false;
12887   }
12888 
12889   case Builtin::BI__noop:
12890     // __noop always evaluates successfully and returns 0.
12891     return Success(0, E);
12892 
12893   case Builtin::BI__builtin_is_constant_evaluated: {
12894     const auto *Callee = Info.CurrentCall->getCallee();
12895     if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
12896         (Info.CallStackDepth == 1 ||
12897          (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
12898           Callee->getIdentifier() &&
12899           Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
12900       // FIXME: Find a better way to avoid duplicated diagnostics.
12901       if (Info.EvalStatus.Diag)
12902         Info.report((Info.CallStackDepth == 1)
12903                         ? E->getExprLoc()
12904                         : Info.CurrentCall->getCallRange().getBegin(),
12905                     diag::warn_is_constant_evaluated_always_true_constexpr)
12906             << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
12907                                          : "std::is_constant_evaluated");
12908     }
12909 
12910     return Success(Info.InConstantContext, E);
12911   }
12912 
12913   case Builtin::BI__builtin_is_within_lifetime:
12914     if (auto result = EvaluateBuiltinIsWithinLifetime(*this, E))
12915       return Success(*result, E);
12916     return false;
12917 
12918   case Builtin::BI__builtin_ctz:
12919   case Builtin::BI__builtin_ctzl:
12920   case Builtin::BI__builtin_ctzll:
12921   case Builtin::BI__builtin_ctzs:
12922   case Builtin::BI__builtin_ctzg: {
12923     APSInt Val;
12924     if (!EvaluateInteger(E->getArg(0), Val, Info))
12925       return false;
12926 
12927     std::optional<APSInt> Fallback;
12928     if (BuiltinOp == Builtin::BI__builtin_ctzg && E->getNumArgs() > 1) {
12929       APSInt FallbackTemp;
12930       if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
12931         return false;
12932       Fallback = FallbackTemp;
12933     }
12934 
12935     if (!Val) {
12936       if (Fallback)
12937         return Success(*Fallback, E);
12938 
12939       return Error(E);
12940     }
12941 
12942     return Success(Val.countr_zero(), E);
12943   }
12944 
12945   case Builtin::BI__builtin_eh_return_data_regno: {
12946     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
12947     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
12948     return Success(Operand, E);
12949   }
12950 
12951   case Builtin::BI__builtin_expect:
12952   case Builtin::BI__builtin_expect_with_probability:
12953     return Visit(E->getArg(0));
12954 
12955   case Builtin::BI__builtin_ptrauth_string_discriminator: {
12956     const auto *Literal =
12957         cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts());
12958     uint64_t Result = getPointerAuthStableSipHash(Literal->getString());
12959     return Success(Result, E);
12960   }
12961 
12962   case Builtin::BI__builtin_ffs:
12963   case Builtin::BI__builtin_ffsl:
12964   case Builtin::BI__builtin_ffsll: {
12965     APSInt Val;
12966     if (!EvaluateInteger(E->getArg(0), Val, Info))
12967       return false;
12968 
12969     unsigned N = Val.countr_zero();
12970     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
12971   }
12972 
12973   case Builtin::BI__builtin_fpclassify: {
12974     APFloat Val(0.0);
12975     if (!EvaluateFloat(E->getArg(5), Val, Info))
12976       return false;
12977     unsigned Arg;
12978     switch (Val.getCategory()) {
12979     case APFloat::fcNaN: Arg = 0; break;
12980     case APFloat::fcInfinity: Arg = 1; break;
12981     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
12982     case APFloat::fcZero: Arg = 4; break;
12983     }
12984     return Visit(E->getArg(Arg));
12985   }
12986 
12987   case Builtin::BI__builtin_isinf_sign: {
12988     APFloat Val(0.0);
12989     return EvaluateFloat(E->getArg(0), Val, Info) &&
12990            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
12991   }
12992 
12993   case Builtin::BI__builtin_isinf: {
12994     APFloat Val(0.0);
12995     return EvaluateFloat(E->getArg(0), Val, Info) &&
12996            Success(Val.isInfinity() ? 1 : 0, E);
12997   }
12998 
12999   case Builtin::BI__builtin_isfinite: {
13000     APFloat Val(0.0);
13001     return EvaluateFloat(E->getArg(0), Val, Info) &&
13002            Success(Val.isFinite() ? 1 : 0, E);
13003   }
13004 
13005   case Builtin::BI__builtin_isnan: {
13006     APFloat Val(0.0);
13007     return EvaluateFloat(E->getArg(0), Val, Info) &&
13008            Success(Val.isNaN() ? 1 : 0, E);
13009   }
13010 
13011   case Builtin::BI__builtin_isnormal: {
13012     APFloat Val(0.0);
13013     return EvaluateFloat(E->getArg(0), Val, Info) &&
13014            Success(Val.isNormal() ? 1 : 0, E);
13015   }
13016 
13017   case Builtin::BI__builtin_issubnormal: {
13018     APFloat Val(0.0);
13019     return EvaluateFloat(E->getArg(0), Val, Info) &&
13020            Success(Val.isDenormal() ? 1 : 0, E);
13021   }
13022 
13023   case Builtin::BI__builtin_iszero: {
13024     APFloat Val(0.0);
13025     return EvaluateFloat(E->getArg(0), Val, Info) &&
13026            Success(Val.isZero() ? 1 : 0, E);
13027   }
13028 
13029   case Builtin::BI__builtin_signbit:
13030   case Builtin::BI__builtin_signbitf:
13031   case Builtin::BI__builtin_signbitl: {
13032     APFloat Val(0.0);
13033     return EvaluateFloat(E->getArg(0), Val, Info) &&
13034            Success(Val.isNegative() ? 1 : 0, E);
13035   }
13036 
13037   case Builtin::BI__builtin_isgreater:
13038   case Builtin::BI__builtin_isgreaterequal:
13039   case Builtin::BI__builtin_isless:
13040   case Builtin::BI__builtin_islessequal:
13041   case Builtin::BI__builtin_islessgreater:
13042   case Builtin::BI__builtin_isunordered: {
13043     APFloat LHS(0.0);
13044     APFloat RHS(0.0);
13045     if (!EvaluateFloat(E->getArg(0), LHS, Info) ||
13046         !EvaluateFloat(E->getArg(1), RHS, Info))
13047       return false;
13048 
13049     return Success(
13050         [&] {
13051           switch (BuiltinOp) {
13052           case Builtin::BI__builtin_isgreater:
13053             return LHS > RHS;
13054           case Builtin::BI__builtin_isgreaterequal:
13055             return LHS >= RHS;
13056           case Builtin::BI__builtin_isless:
13057             return LHS < RHS;
13058           case Builtin::BI__builtin_islessequal:
13059             return LHS <= RHS;
13060           case Builtin::BI__builtin_islessgreater: {
13061             APFloat::cmpResult cmp = LHS.compare(RHS);
13062             return cmp == APFloat::cmpResult::cmpLessThan ||
13063                    cmp == APFloat::cmpResult::cmpGreaterThan;
13064           }
13065           case Builtin::BI__builtin_isunordered:
13066             return LHS.compare(RHS) == APFloat::cmpResult::cmpUnordered;
13067           default:
13068             llvm_unreachable("Unexpected builtin ID: Should be a floating "
13069                              "point comparison function");
13070           }
13071         }()
13072             ? 1
13073             : 0,
13074         E);
13075   }
13076 
13077   case Builtin::BI__builtin_issignaling: {
13078     APFloat Val(0.0);
13079     return EvaluateFloat(E->getArg(0), Val, Info) &&
13080            Success(Val.isSignaling() ? 1 : 0, E);
13081   }
13082 
13083   case Builtin::BI__builtin_isfpclass: {
13084     APSInt MaskVal;
13085     if (!EvaluateInteger(E->getArg(1), MaskVal, Info))
13086       return false;
13087     unsigned Test = static_cast<llvm::FPClassTest>(MaskVal.getZExtValue());
13088     APFloat Val(0.0);
13089     return EvaluateFloat(E->getArg(0), Val, Info) &&
13090            Success((Val.classify() & Test) ? 1 : 0, E);
13091   }
13092 
13093   case Builtin::BI__builtin_parity:
13094   case Builtin::BI__builtin_parityl:
13095   case Builtin::BI__builtin_parityll: {
13096     APSInt Val;
13097     if (!EvaluateInteger(E->getArg(0), Val, Info))
13098       return false;
13099 
13100     return Success(Val.popcount() % 2, E);
13101   }
13102 
13103   case Builtin::BI__builtin_abs:
13104   case Builtin::BI__builtin_labs:
13105   case Builtin::BI__builtin_llabs: {
13106     APSInt Val;
13107     if (!EvaluateInteger(E->getArg(0), Val, Info))
13108       return false;
13109     if (Val == APSInt(APInt::getSignedMinValue(Val.getBitWidth()),
13110                       /*IsUnsigned=*/false))
13111       return false;
13112     if (Val.isNegative())
13113       Val.negate();
13114     return Success(Val, E);
13115   }
13116 
13117   case Builtin::BI__builtin_popcount:
13118   case Builtin::BI__builtin_popcountl:
13119   case Builtin::BI__builtin_popcountll:
13120   case Builtin::BI__builtin_popcountg:
13121   case Builtin::BI__popcnt16: // Microsoft variants of popcount
13122   case Builtin::BI__popcnt:
13123   case Builtin::BI__popcnt64: {
13124     APSInt Val;
13125     if (!EvaluateInteger(E->getArg(0), Val, Info))
13126       return false;
13127 
13128     return Success(Val.popcount(), E);
13129   }
13130 
13131   case Builtin::BI__builtin_rotateleft8:
13132   case Builtin::BI__builtin_rotateleft16:
13133   case Builtin::BI__builtin_rotateleft32:
13134   case Builtin::BI__builtin_rotateleft64:
13135   case Builtin::BI_rotl8: // Microsoft variants of rotate right
13136   case Builtin::BI_rotl16:
13137   case Builtin::BI_rotl:
13138   case Builtin::BI_lrotl:
13139   case Builtin::BI_rotl64: {
13140     APSInt Val, Amt;
13141     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
13142         !EvaluateInteger(E->getArg(1), Amt, Info))
13143       return false;
13144 
13145     return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
13146   }
13147 
13148   case Builtin::BI__builtin_rotateright8:
13149   case Builtin::BI__builtin_rotateright16:
13150   case Builtin::BI__builtin_rotateright32:
13151   case Builtin::BI__builtin_rotateright64:
13152   case Builtin::BI_rotr8: // Microsoft variants of rotate right
13153   case Builtin::BI_rotr16:
13154   case Builtin::BI_rotr:
13155   case Builtin::BI_lrotr:
13156   case Builtin::BI_rotr64: {
13157     APSInt Val, Amt;
13158     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
13159         !EvaluateInteger(E->getArg(1), Amt, Info))
13160       return false;
13161 
13162     return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
13163   }
13164 
13165   case Builtin::BIstrlen:
13166   case Builtin::BIwcslen:
13167     // A call to strlen is not a constant expression.
13168     if (Info.getLangOpts().CPlusPlus11)
13169       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
13170           << /*isConstexpr*/ 0 << /*isConstructor*/ 0
13171           << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
13172     else
13173       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
13174     [[fallthrough]];
13175   case Builtin::BI__builtin_strlen:
13176   case Builtin::BI__builtin_wcslen: {
13177     // As an extension, we support __builtin_strlen() as a constant expression,
13178     // and support folding strlen() to a constant.
13179     uint64_t StrLen;
13180     if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
13181       return Success(StrLen, E);
13182     return false;
13183   }
13184 
13185   case Builtin::BIstrcmp:
13186   case Builtin::BIwcscmp:
13187   case Builtin::BIstrncmp:
13188   case Builtin::BIwcsncmp:
13189   case Builtin::BImemcmp:
13190   case Builtin::BIbcmp:
13191   case Builtin::BIwmemcmp:
13192     // A call to strlen is not a constant expression.
13193     if (Info.getLangOpts().CPlusPlus11)
13194       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
13195           << /*isConstexpr*/ 0 << /*isConstructor*/ 0
13196           << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
13197     else
13198       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
13199     [[fallthrough]];
13200   case Builtin::BI__builtin_strcmp:
13201   case Builtin::BI__builtin_wcscmp:
13202   case Builtin::BI__builtin_strncmp:
13203   case Builtin::BI__builtin_wcsncmp:
13204   case Builtin::BI__builtin_memcmp:
13205   case Builtin::BI__builtin_bcmp:
13206   case Builtin::BI__builtin_wmemcmp: {
13207     LValue String1, String2;
13208     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
13209         !EvaluatePointer(E->getArg(1), String2, Info))
13210       return false;
13211 
13212     uint64_t MaxLength = uint64_t(-1);
13213     if (BuiltinOp != Builtin::BIstrcmp &&
13214         BuiltinOp != Builtin::BIwcscmp &&
13215         BuiltinOp != Builtin::BI__builtin_strcmp &&
13216         BuiltinOp != Builtin::BI__builtin_wcscmp) {
13217       APSInt N;
13218       if (!EvaluateInteger(E->getArg(2), N, Info))
13219         return false;
13220       MaxLength = N.getZExtValue();
13221     }
13222 
13223     // Empty substrings compare equal by definition.
13224     if (MaxLength == 0u)
13225       return Success(0, E);
13226 
13227     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
13228         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
13229         String1.Designator.Invalid || String2.Designator.Invalid)
13230       return false;
13231 
13232     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
13233     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
13234 
13235     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
13236                      BuiltinOp == Builtin::BIbcmp ||
13237                      BuiltinOp == Builtin::BI__builtin_memcmp ||
13238                      BuiltinOp == Builtin::BI__builtin_bcmp;
13239 
13240     assert(IsRawByte ||
13241            (Info.Ctx.hasSameUnqualifiedType(
13242                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
13243             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
13244 
13245     // For memcmp, allow comparing any arrays of '[[un]signed] char' or
13246     // 'char8_t', but no other types.
13247     if (IsRawByte &&
13248         !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
13249       // FIXME: Consider using our bit_cast implementation to support this.
13250       Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
13251           << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str()
13252           << CharTy1 << CharTy2;
13253       return false;
13254     }
13255 
13256     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
13257       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
13258              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
13259              Char1.isInt() && Char2.isInt();
13260     };
13261     const auto &AdvanceElems = [&] {
13262       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
13263              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
13264     };
13265 
13266     bool StopAtNull =
13267         (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
13268          BuiltinOp != Builtin::BIwmemcmp &&
13269          BuiltinOp != Builtin::BI__builtin_memcmp &&
13270          BuiltinOp != Builtin::BI__builtin_bcmp &&
13271          BuiltinOp != Builtin::BI__builtin_wmemcmp);
13272     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
13273                   BuiltinOp == Builtin::BIwcsncmp ||
13274                   BuiltinOp == Builtin::BIwmemcmp ||
13275                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
13276                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
13277                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
13278 
13279     for (; MaxLength; --MaxLength) {
13280       APValue Char1, Char2;
13281       if (!ReadCurElems(Char1, Char2))
13282         return false;
13283       if (Char1.getInt().ne(Char2.getInt())) {
13284         if (IsWide) // wmemcmp compares with wchar_t signedness.
13285           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
13286         // memcmp always compares unsigned chars.
13287         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
13288       }
13289       if (StopAtNull && !Char1.getInt())
13290         return Success(0, E);
13291       assert(!(StopAtNull && !Char2.getInt()));
13292       if (!AdvanceElems())
13293         return false;
13294     }
13295     // We hit the strncmp / memcmp limit.
13296     return Success(0, E);
13297   }
13298 
13299   case Builtin::BI__atomic_always_lock_free:
13300   case Builtin::BI__atomic_is_lock_free:
13301   case Builtin::BI__c11_atomic_is_lock_free: {
13302     APSInt SizeVal;
13303     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
13304       return false;
13305 
13306     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
13307     // of two less than or equal to the maximum inline atomic width, we know it
13308     // is lock-free.  If the size isn't a power of two, or greater than the
13309     // maximum alignment where we promote atomics, we know it is not lock-free
13310     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
13311     // the answer can only be determined at runtime; for example, 16-byte
13312     // atomics have lock-free implementations on some, but not all,
13313     // x86-64 processors.
13314 
13315     // Check power-of-two.
13316     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
13317     if (Size.isPowerOfTwo()) {
13318       // Check against inlining width.
13319       unsigned InlineWidthBits =
13320           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
13321       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
13322         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
13323             Size == CharUnits::One())
13324           return Success(1, E);
13325 
13326         // If the pointer argument can be evaluated to a compile-time constant
13327         // integer (or nullptr), check if that value is appropriately aligned.
13328         const Expr *PtrArg = E->getArg(1);
13329         Expr::EvalResult ExprResult;
13330         APSInt IntResult;
13331         if (PtrArg->EvaluateAsRValue(ExprResult, Info.Ctx) &&
13332             ExprResult.Val.toIntegralConstant(IntResult, PtrArg->getType(),
13333                                               Info.Ctx) &&
13334             IntResult.isAligned(Size.getAsAlign()))
13335           return Success(1, E);
13336 
13337         // Otherwise, check if the type's alignment against Size.
13338         if (auto *ICE = dyn_cast<ImplicitCastExpr>(PtrArg)) {
13339           // Drop the potential implicit-cast to 'const volatile void*', getting
13340           // the underlying type.
13341           if (ICE->getCastKind() == CK_BitCast)
13342             PtrArg = ICE->getSubExpr();
13343         }
13344 
13345         if (auto PtrTy = PtrArg->getType()->getAs<PointerType>()) {
13346           QualType PointeeType = PtrTy->getPointeeType();
13347           if (!PointeeType->isIncompleteType() &&
13348               Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
13349             // OK, we will inline operations on this object.
13350             return Success(1, E);
13351           }
13352         }
13353       }
13354     }
13355 
13356     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
13357         Success(0, E) : Error(E);
13358   }
13359   case Builtin::BI__builtin_addcb:
13360   case Builtin::BI__builtin_addcs:
13361   case Builtin::BI__builtin_addc:
13362   case Builtin::BI__builtin_addcl:
13363   case Builtin::BI__builtin_addcll:
13364   case Builtin::BI__builtin_subcb:
13365   case Builtin::BI__builtin_subcs:
13366   case Builtin::BI__builtin_subc:
13367   case Builtin::BI__builtin_subcl:
13368   case Builtin::BI__builtin_subcll: {
13369     LValue CarryOutLValue;
13370     APSInt LHS, RHS, CarryIn, CarryOut, Result;
13371     QualType ResultType = E->getArg(0)->getType();
13372     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
13373         !EvaluateInteger(E->getArg(1), RHS, Info) ||
13374         !EvaluateInteger(E->getArg(2), CarryIn, Info) ||
13375         !EvaluatePointer(E->getArg(3), CarryOutLValue, Info))
13376       return false;
13377     // Copy the number of bits and sign.
13378     Result = LHS;
13379     CarryOut = LHS;
13380 
13381     bool FirstOverflowed = false;
13382     bool SecondOverflowed = false;
13383     switch (BuiltinOp) {
13384     default:
13385       llvm_unreachable("Invalid value for BuiltinOp");
13386     case Builtin::BI__builtin_addcb:
13387     case Builtin::BI__builtin_addcs:
13388     case Builtin::BI__builtin_addc:
13389     case Builtin::BI__builtin_addcl:
13390     case Builtin::BI__builtin_addcll:
13391       Result =
13392           LHS.uadd_ov(RHS, FirstOverflowed).uadd_ov(CarryIn, SecondOverflowed);
13393       break;
13394     case Builtin::BI__builtin_subcb:
13395     case Builtin::BI__builtin_subcs:
13396     case Builtin::BI__builtin_subc:
13397     case Builtin::BI__builtin_subcl:
13398     case Builtin::BI__builtin_subcll:
13399       Result =
13400           LHS.usub_ov(RHS, FirstOverflowed).usub_ov(CarryIn, SecondOverflowed);
13401       break;
13402     }
13403 
13404     // It is possible for both overflows to happen but CGBuiltin uses an OR so
13405     // this is consistent.
13406     CarryOut = (uint64_t)(FirstOverflowed | SecondOverflowed);
13407     APValue APV{CarryOut};
13408     if (!handleAssignment(Info, E, CarryOutLValue, ResultType, APV))
13409       return false;
13410     return Success(Result, E);
13411   }
13412   case Builtin::BI__builtin_add_overflow:
13413   case Builtin::BI__builtin_sub_overflow:
13414   case Builtin::BI__builtin_mul_overflow:
13415   case Builtin::BI__builtin_sadd_overflow:
13416   case Builtin::BI__builtin_uadd_overflow:
13417   case Builtin::BI__builtin_uaddl_overflow:
13418   case Builtin::BI__builtin_uaddll_overflow:
13419   case Builtin::BI__builtin_usub_overflow:
13420   case Builtin::BI__builtin_usubl_overflow:
13421   case Builtin::BI__builtin_usubll_overflow:
13422   case Builtin::BI__builtin_umul_overflow:
13423   case Builtin::BI__builtin_umull_overflow:
13424   case Builtin::BI__builtin_umulll_overflow:
13425   case Builtin::BI__builtin_saddl_overflow:
13426   case Builtin::BI__builtin_saddll_overflow:
13427   case Builtin::BI__builtin_ssub_overflow:
13428   case Builtin::BI__builtin_ssubl_overflow:
13429   case Builtin::BI__builtin_ssubll_overflow:
13430   case Builtin::BI__builtin_smul_overflow:
13431   case Builtin::BI__builtin_smull_overflow:
13432   case Builtin::BI__builtin_smulll_overflow: {
13433     LValue ResultLValue;
13434     APSInt LHS, RHS;
13435 
13436     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
13437     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
13438         !EvaluateInteger(E->getArg(1), RHS, Info) ||
13439         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
13440       return false;
13441 
13442     APSInt Result;
13443     bool DidOverflow = false;
13444 
13445     // If the types don't have to match, enlarge all 3 to the largest of them.
13446     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
13447         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
13448         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
13449       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
13450                       ResultType->isSignedIntegerOrEnumerationType();
13451       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
13452                       ResultType->isSignedIntegerOrEnumerationType();
13453       uint64_t LHSSize = LHS.getBitWidth();
13454       uint64_t RHSSize = RHS.getBitWidth();
13455       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
13456       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
13457 
13458       // Add an additional bit if the signedness isn't uniformly agreed to. We
13459       // could do this ONLY if there is a signed and an unsigned that both have
13460       // MaxBits, but the code to check that is pretty nasty.  The issue will be
13461       // caught in the shrink-to-result later anyway.
13462       if (IsSigned && !AllSigned)
13463         ++MaxBits;
13464 
13465       LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
13466       RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
13467       Result = APSInt(MaxBits, !IsSigned);
13468     }
13469 
13470     // Find largest int.
13471     switch (BuiltinOp) {
13472     default:
13473       llvm_unreachable("Invalid value for BuiltinOp");
13474     case Builtin::BI__builtin_add_overflow:
13475     case Builtin::BI__builtin_sadd_overflow:
13476     case Builtin::BI__builtin_saddl_overflow:
13477     case Builtin::BI__builtin_saddll_overflow:
13478     case Builtin::BI__builtin_uadd_overflow:
13479     case Builtin::BI__builtin_uaddl_overflow:
13480     case Builtin::BI__builtin_uaddll_overflow:
13481       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
13482                               : LHS.uadd_ov(RHS, DidOverflow);
13483       break;
13484     case Builtin::BI__builtin_sub_overflow:
13485     case Builtin::BI__builtin_ssub_overflow:
13486     case Builtin::BI__builtin_ssubl_overflow:
13487     case Builtin::BI__builtin_ssubll_overflow:
13488     case Builtin::BI__builtin_usub_overflow:
13489     case Builtin::BI__builtin_usubl_overflow:
13490     case Builtin::BI__builtin_usubll_overflow:
13491       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
13492                               : LHS.usub_ov(RHS, DidOverflow);
13493       break;
13494     case Builtin::BI__builtin_mul_overflow:
13495     case Builtin::BI__builtin_smul_overflow:
13496     case Builtin::BI__builtin_smull_overflow:
13497     case Builtin::BI__builtin_smulll_overflow:
13498     case Builtin::BI__builtin_umul_overflow:
13499     case Builtin::BI__builtin_umull_overflow:
13500     case Builtin::BI__builtin_umulll_overflow:
13501       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
13502                               : LHS.umul_ov(RHS, DidOverflow);
13503       break;
13504     }
13505 
13506     // In the case where multiple sizes are allowed, truncate and see if
13507     // the values are the same.
13508     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
13509         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
13510         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
13511       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
13512       // since it will give us the behavior of a TruncOrSelf in the case where
13513       // its parameter <= its size.  We previously set Result to be at least the
13514       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
13515       // will work exactly like TruncOrSelf.
13516       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
13517       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
13518 
13519       if (!APSInt::isSameValue(Temp, Result))
13520         DidOverflow = true;
13521       Result = Temp;
13522     }
13523 
13524     APValue APV{Result};
13525     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
13526       return false;
13527     return Success(DidOverflow, E);
13528   }
13529 
13530   case Builtin::BI__builtin_reduce_add:
13531   case Builtin::BI__builtin_reduce_mul:
13532   case Builtin::BI__builtin_reduce_and:
13533   case Builtin::BI__builtin_reduce_or:
13534   case Builtin::BI__builtin_reduce_xor: {
13535     APValue Source;
13536     if (!EvaluateAsRValue(Info, E->getArg(0), Source))
13537       return false;
13538 
13539     unsigned SourceLen = Source.getVectorLength();
13540     APSInt Reduced = Source.getVectorElt(0).getInt();
13541     for (unsigned EltNum = 1; EltNum < SourceLen; ++EltNum) {
13542       switch (BuiltinOp) {
13543       default:
13544         return false;
13545       case Builtin::BI__builtin_reduce_add: {
13546         if (!CheckedIntArithmetic(
13547                 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
13548                 Reduced.getBitWidth() + 1, std::plus<APSInt>(), Reduced))
13549           return false;
13550         break;
13551       }
13552       case Builtin::BI__builtin_reduce_mul: {
13553         if (!CheckedIntArithmetic(
13554                 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
13555                 Reduced.getBitWidth() * 2, std::multiplies<APSInt>(), Reduced))
13556           return false;
13557         break;
13558       }
13559       case Builtin::BI__builtin_reduce_and: {
13560         Reduced &= Source.getVectorElt(EltNum).getInt();
13561         break;
13562       }
13563       case Builtin::BI__builtin_reduce_or: {
13564         Reduced |= Source.getVectorElt(EltNum).getInt();
13565         break;
13566       }
13567       case Builtin::BI__builtin_reduce_xor: {
13568         Reduced ^= Source.getVectorElt(EltNum).getInt();
13569         break;
13570       }
13571       }
13572     }
13573 
13574     return Success(Reduced, E);
13575   }
13576 
13577   case clang::X86::BI__builtin_ia32_addcarryx_u32:
13578   case clang::X86::BI__builtin_ia32_addcarryx_u64:
13579   case clang::X86::BI__builtin_ia32_subborrow_u32:
13580   case clang::X86::BI__builtin_ia32_subborrow_u64: {
13581     LValue ResultLValue;
13582     APSInt CarryIn, LHS, RHS;
13583     QualType ResultType = E->getArg(3)->getType()->getPointeeType();
13584     if (!EvaluateInteger(E->getArg(0), CarryIn, Info) ||
13585         !EvaluateInteger(E->getArg(1), LHS, Info) ||
13586         !EvaluateInteger(E->getArg(2), RHS, Info) ||
13587         !EvaluatePointer(E->getArg(3), ResultLValue, Info))
13588       return false;
13589 
13590     bool IsAdd = BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u32 ||
13591                  BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u64;
13592 
13593     unsigned BitWidth = LHS.getBitWidth();
13594     unsigned CarryInBit = CarryIn.ugt(0) ? 1 : 0;
13595     APInt ExResult =
13596         IsAdd
13597             ? (LHS.zext(BitWidth + 1) + (RHS.zext(BitWidth + 1) + CarryInBit))
13598             : (LHS.zext(BitWidth + 1) - (RHS.zext(BitWidth + 1) + CarryInBit));
13599 
13600     APInt Result = ExResult.extractBits(BitWidth, 0);
13601     uint64_t CarryOut = ExResult.extractBitsAsZExtValue(1, BitWidth);
13602 
13603     APValue APV{APSInt(Result, /*isUnsigned=*/true)};
13604     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
13605       return false;
13606     return Success(CarryOut, E);
13607   }
13608 
13609   case clang::X86::BI__builtin_ia32_bextr_u32:
13610   case clang::X86::BI__builtin_ia32_bextr_u64:
13611   case clang::X86::BI__builtin_ia32_bextri_u32:
13612   case clang::X86::BI__builtin_ia32_bextri_u64: {
13613     APSInt Val, Idx;
13614     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
13615         !EvaluateInteger(E->getArg(1), Idx, Info))
13616       return false;
13617 
13618     unsigned BitWidth = Val.getBitWidth();
13619     uint64_t Shift = Idx.extractBitsAsZExtValue(8, 0);
13620     uint64_t Length = Idx.extractBitsAsZExtValue(8, 8);
13621     Length = Length > BitWidth ? BitWidth : Length;
13622 
13623     // Handle out of bounds cases.
13624     if (Length == 0 || Shift >= BitWidth)
13625       return Success(0, E);
13626 
13627     uint64_t Result = Val.getZExtValue() >> Shift;
13628     Result &= llvm::maskTrailingOnes<uint64_t>(Length);
13629     return Success(Result, E);
13630   }
13631 
13632   case clang::X86::BI__builtin_ia32_bzhi_si:
13633   case clang::X86::BI__builtin_ia32_bzhi_di: {
13634     APSInt Val, Idx;
13635     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
13636         !EvaluateInteger(E->getArg(1), Idx, Info))
13637       return false;
13638 
13639     unsigned BitWidth = Val.getBitWidth();
13640     unsigned Index = Idx.extractBitsAsZExtValue(8, 0);
13641     if (Index < BitWidth)
13642       Val.clearHighBits(BitWidth - Index);
13643     return Success(Val, E);
13644   }
13645 
13646   case clang::X86::BI__builtin_ia32_lzcnt_u16:
13647   case clang::X86::BI__builtin_ia32_lzcnt_u32:
13648   case clang::X86::BI__builtin_ia32_lzcnt_u64: {
13649     APSInt Val;
13650     if (!EvaluateInteger(E->getArg(0), Val, Info))
13651       return false;
13652     return Success(Val.countLeadingZeros(), E);
13653   }
13654 
13655   case clang::X86::BI__builtin_ia32_tzcnt_u16:
13656   case clang::X86::BI__builtin_ia32_tzcnt_u32:
13657   case clang::X86::BI__builtin_ia32_tzcnt_u64: {
13658     APSInt Val;
13659     if (!EvaluateInteger(E->getArg(0), Val, Info))
13660       return false;
13661     return Success(Val.countTrailingZeros(), E);
13662   }
13663 
13664   case clang::X86::BI__builtin_ia32_pdep_si:
13665   case clang::X86::BI__builtin_ia32_pdep_di: {
13666     APSInt Val, Msk;
13667     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
13668         !EvaluateInteger(E->getArg(1), Msk, Info))
13669       return false;
13670 
13671     unsigned BitWidth = Val.getBitWidth();
13672     APInt Result = APInt::getZero(BitWidth);
13673     for (unsigned I = 0, P = 0; I != BitWidth; ++I)
13674       if (Msk[I])
13675         Result.setBitVal(I, Val[P++]);
13676     return Success(Result, E);
13677   }
13678 
13679   case clang::X86::BI__builtin_ia32_pext_si:
13680   case clang::X86::BI__builtin_ia32_pext_di: {
13681     APSInt Val, Msk;
13682     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
13683         !EvaluateInteger(E->getArg(1), Msk, Info))
13684       return false;
13685 
13686     unsigned BitWidth = Val.getBitWidth();
13687     APInt Result = APInt::getZero(BitWidth);
13688     for (unsigned I = 0, P = 0; I != BitWidth; ++I)
13689       if (Msk[I])
13690         Result.setBitVal(P++, Val[I]);
13691     return Success(Result, E);
13692   }
13693   }
13694 }
13695 
13696 /// Determine whether this is a pointer past the end of the complete
13697 /// object referred to by the lvalue.
13698 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
13699                                             const LValue &LV) {
13700   // A null pointer can be viewed as being "past the end" but we don't
13701   // choose to look at it that way here.
13702   if (!LV.getLValueBase())
13703     return false;
13704 
13705   // If the designator is valid and refers to a subobject, we're not pointing
13706   // past the end.
13707   if (!LV.getLValueDesignator().Invalid &&
13708       !LV.getLValueDesignator().isOnePastTheEnd())
13709     return false;
13710 
13711   // A pointer to an incomplete type might be past-the-end if the type's size is
13712   // zero.  We cannot tell because the type is incomplete.
13713   QualType Ty = getType(LV.getLValueBase());
13714   if (Ty->isIncompleteType())
13715     return true;
13716 
13717   // Can't be past the end of an invalid object.
13718   if (LV.getLValueDesignator().Invalid)
13719     return false;
13720 
13721   // We're a past-the-end pointer if we point to the byte after the object,
13722   // no matter what our type or path is.
13723   auto Size = Ctx.getTypeSizeInChars(Ty);
13724   return LV.getLValueOffset() == Size;
13725 }
13726 
13727 namespace {
13728 
13729 /// Data recursive integer evaluator of certain binary operators.
13730 ///
13731 /// We use a data recursive algorithm for binary operators so that we are able
13732 /// to handle extreme cases of chained binary operators without causing stack
13733 /// overflow.
13734 class DataRecursiveIntBinOpEvaluator {
13735   struct EvalResult {
13736     APValue Val;
13737     bool Failed = false;
13738 
13739     EvalResult() = default;
13740 
13741     void swap(EvalResult &RHS) {
13742       Val.swap(RHS.Val);
13743       Failed = RHS.Failed;
13744       RHS.Failed = false;
13745     }
13746   };
13747 
13748   struct Job {
13749     const Expr *E;
13750     EvalResult LHSResult; // meaningful only for binary operator expression.
13751     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
13752 
13753     Job() = default;
13754     Job(Job &&) = default;
13755 
13756     void startSpeculativeEval(EvalInfo &Info) {
13757       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
13758     }
13759 
13760   private:
13761     SpeculativeEvaluationRAII SpecEvalRAII;
13762   };
13763 
13764   SmallVector<Job, 16> Queue;
13765 
13766   IntExprEvaluator &IntEval;
13767   EvalInfo &Info;
13768   APValue &FinalResult;
13769 
13770 public:
13771   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
13772     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
13773 
13774   /// True if \param E is a binary operator that we are going to handle
13775   /// data recursively.
13776   /// We handle binary operators that are comma, logical, or that have operands
13777   /// with integral or enumeration type.
13778   static bool shouldEnqueue(const BinaryOperator *E) {
13779     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
13780            (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() &&
13781             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
13782             E->getRHS()->getType()->isIntegralOrEnumerationType());
13783   }
13784 
13785   bool Traverse(const BinaryOperator *E) {
13786     enqueue(E);
13787     EvalResult PrevResult;
13788     while (!Queue.empty())
13789       process(PrevResult);
13790 
13791     if (PrevResult.Failed) return false;
13792 
13793     FinalResult.swap(PrevResult.Val);
13794     return true;
13795   }
13796 
13797 private:
13798   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
13799     return IntEval.Success(Value, E, Result);
13800   }
13801   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
13802     return IntEval.Success(Value, E, Result);
13803   }
13804   bool Error(const Expr *E) {
13805     return IntEval.Error(E);
13806   }
13807   bool Error(const Expr *E, diag::kind D) {
13808     return IntEval.Error(E, D);
13809   }
13810 
13811   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
13812     return Info.CCEDiag(E, D);
13813   }
13814 
13815   // Returns true if visiting the RHS is necessary, false otherwise.
13816   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
13817                          bool &SuppressRHSDiags);
13818 
13819   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
13820                   const BinaryOperator *E, APValue &Result);
13821 
13822   void EvaluateExpr(const Expr *E, EvalResult &Result) {
13823     Result.Failed = !Evaluate(Result.Val, Info, E);
13824     if (Result.Failed)
13825       Result.Val = APValue();
13826   }
13827 
13828   void process(EvalResult &Result);
13829 
13830   void enqueue(const Expr *E) {
13831     E = E->IgnoreParens();
13832     Queue.resize(Queue.size()+1);
13833     Queue.back().E = E;
13834     Queue.back().Kind = Job::AnyExprKind;
13835   }
13836 };
13837 
13838 }
13839 
13840 bool DataRecursiveIntBinOpEvaluator::
13841        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
13842                          bool &SuppressRHSDiags) {
13843   if (E->getOpcode() == BO_Comma) {
13844     // Ignore LHS but note if we could not evaluate it.
13845     if (LHSResult.Failed)
13846       return Info.noteSideEffect();
13847     return true;
13848   }
13849 
13850   if (E->isLogicalOp()) {
13851     bool LHSAsBool;
13852     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
13853       // We were able to evaluate the LHS, see if we can get away with not
13854       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
13855       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
13856         Success(LHSAsBool, E, LHSResult.Val);
13857         return false; // Ignore RHS
13858       }
13859     } else {
13860       LHSResult.Failed = true;
13861 
13862       // Since we weren't able to evaluate the left hand side, it
13863       // might have had side effects.
13864       if (!Info.noteSideEffect())
13865         return false;
13866 
13867       // We can't evaluate the LHS; however, sometimes the result
13868       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
13869       // Don't ignore RHS and suppress diagnostics from this arm.
13870       SuppressRHSDiags = true;
13871     }
13872 
13873     return true;
13874   }
13875 
13876   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
13877          E->getRHS()->getType()->isIntegralOrEnumerationType());
13878 
13879   if (LHSResult.Failed && !Info.noteFailure())
13880     return false; // Ignore RHS;
13881 
13882   return true;
13883 }
13884 
13885 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
13886                                     bool IsSub) {
13887   // Compute the new offset in the appropriate width, wrapping at 64 bits.
13888   // FIXME: When compiling for a 32-bit target, we should use 32-bit
13889   // offsets.
13890   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
13891   CharUnits &Offset = LVal.getLValueOffset();
13892   uint64_t Offset64 = Offset.getQuantity();
13893   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
13894   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
13895                                          : Offset64 + Index64);
13896 }
13897 
13898 bool DataRecursiveIntBinOpEvaluator::
13899        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
13900                   const BinaryOperator *E, APValue &Result) {
13901   if (E->getOpcode() == BO_Comma) {
13902     if (RHSResult.Failed)
13903       return false;
13904     Result = RHSResult.Val;
13905     return true;
13906   }
13907 
13908   if (E->isLogicalOp()) {
13909     bool lhsResult, rhsResult;
13910     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
13911     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
13912 
13913     if (LHSIsOK) {
13914       if (RHSIsOK) {
13915         if (E->getOpcode() == BO_LOr)
13916           return Success(lhsResult || rhsResult, E, Result);
13917         else
13918           return Success(lhsResult && rhsResult, E, Result);
13919       }
13920     } else {
13921       if (RHSIsOK) {
13922         // We can't evaluate the LHS; however, sometimes the result
13923         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
13924         if (rhsResult == (E->getOpcode() == BO_LOr))
13925           return Success(rhsResult, E, Result);
13926       }
13927     }
13928 
13929     return false;
13930   }
13931 
13932   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
13933          E->getRHS()->getType()->isIntegralOrEnumerationType());
13934 
13935   if (LHSResult.Failed || RHSResult.Failed)
13936     return false;
13937 
13938   const APValue &LHSVal = LHSResult.Val;
13939   const APValue &RHSVal = RHSResult.Val;
13940 
13941   // Handle cases like (unsigned long)&a + 4.
13942   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
13943     Result = LHSVal;
13944     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
13945     return true;
13946   }
13947 
13948   // Handle cases like 4 + (unsigned long)&a
13949   if (E->getOpcode() == BO_Add &&
13950       RHSVal.isLValue() && LHSVal.isInt()) {
13951     Result = RHSVal;
13952     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
13953     return true;
13954   }
13955 
13956   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
13957     // Handle (intptr_t)&&A - (intptr_t)&&B.
13958     if (!LHSVal.getLValueOffset().isZero() ||
13959         !RHSVal.getLValueOffset().isZero())
13960       return false;
13961     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
13962     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
13963     if (!LHSExpr || !RHSExpr)
13964       return false;
13965     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
13966     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
13967     if (!LHSAddrExpr || !RHSAddrExpr)
13968       return false;
13969     // Make sure both labels come from the same function.
13970     if (LHSAddrExpr->getLabel()->getDeclContext() !=
13971         RHSAddrExpr->getLabel()->getDeclContext())
13972       return false;
13973     Result = APValue(LHSAddrExpr, RHSAddrExpr);
13974     return true;
13975   }
13976 
13977   // All the remaining cases expect both operands to be an integer
13978   if (!LHSVal.isInt() || !RHSVal.isInt())
13979     return Error(E);
13980 
13981   // Set up the width and signedness manually, in case it can't be deduced
13982   // from the operation we're performing.
13983   // FIXME: Don't do this in the cases where we can deduce it.
13984   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
13985                E->getType()->isUnsignedIntegerOrEnumerationType());
13986   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
13987                          RHSVal.getInt(), Value))
13988     return false;
13989   return Success(Value, E, Result);
13990 }
13991 
13992 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
13993   Job &job = Queue.back();
13994 
13995   switch (job.Kind) {
13996     case Job::AnyExprKind: {
13997       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
13998         if (shouldEnqueue(Bop)) {
13999           job.Kind = Job::BinOpKind;
14000           enqueue(Bop->getLHS());
14001           return;
14002         }
14003       }
14004 
14005       EvaluateExpr(job.E, Result);
14006       Queue.pop_back();
14007       return;
14008     }
14009 
14010     case Job::BinOpKind: {
14011       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
14012       bool SuppressRHSDiags = false;
14013       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
14014         Queue.pop_back();
14015         return;
14016       }
14017       if (SuppressRHSDiags)
14018         job.startSpeculativeEval(Info);
14019       job.LHSResult.swap(Result);
14020       job.Kind = Job::BinOpVisitedLHSKind;
14021       enqueue(Bop->getRHS());
14022       return;
14023     }
14024 
14025     case Job::BinOpVisitedLHSKind: {
14026       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
14027       EvalResult RHS;
14028       RHS.swap(Result);
14029       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
14030       Queue.pop_back();
14031       return;
14032     }
14033   }
14034 
14035   llvm_unreachable("Invalid Job::Kind!");
14036 }
14037 
14038 namespace {
14039 enum class CmpResult {
14040   Unequal,
14041   Less,
14042   Equal,
14043   Greater,
14044   Unordered,
14045 };
14046 }
14047 
14048 template <class SuccessCB, class AfterCB>
14049 static bool
14050 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
14051                                  SuccessCB &&Success, AfterCB &&DoAfter) {
14052   assert(!E->isValueDependent());
14053   assert(E->isComparisonOp() && "expected comparison operator");
14054   assert((E->getOpcode() == BO_Cmp ||
14055           E->getType()->isIntegralOrEnumerationType()) &&
14056          "unsupported binary expression evaluation");
14057   auto Error = [&](const Expr *E) {
14058     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
14059     return false;
14060   };
14061 
14062   bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
14063   bool IsEquality = E->isEqualityOp();
14064 
14065   QualType LHSTy = E->getLHS()->getType();
14066   QualType RHSTy = E->getRHS()->getType();
14067 
14068   if (LHSTy->isIntegralOrEnumerationType() &&
14069       RHSTy->isIntegralOrEnumerationType()) {
14070     APSInt LHS, RHS;
14071     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
14072     if (!LHSOK && !Info.noteFailure())
14073       return false;
14074     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
14075       return false;
14076     if (LHS < RHS)
14077       return Success(CmpResult::Less, E);
14078     if (LHS > RHS)
14079       return Success(CmpResult::Greater, E);
14080     return Success(CmpResult::Equal, E);
14081   }
14082 
14083   if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
14084     APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
14085     APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
14086 
14087     bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
14088     if (!LHSOK && !Info.noteFailure())
14089       return false;
14090     if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
14091       return false;
14092     if (LHSFX < RHSFX)
14093       return Success(CmpResult::Less, E);
14094     if (LHSFX > RHSFX)
14095       return Success(CmpResult::Greater, E);
14096     return Success(CmpResult::Equal, E);
14097   }
14098 
14099   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
14100     ComplexValue LHS, RHS;
14101     bool LHSOK;
14102     if (E->isAssignmentOp()) {
14103       LValue LV;
14104       EvaluateLValue(E->getLHS(), LV, Info);
14105       LHSOK = false;
14106     } else if (LHSTy->isRealFloatingType()) {
14107       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
14108       if (LHSOK) {
14109         LHS.makeComplexFloat();
14110         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
14111       }
14112     } else {
14113       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
14114     }
14115     if (!LHSOK && !Info.noteFailure())
14116       return false;
14117 
14118     if (E->getRHS()->getType()->isRealFloatingType()) {
14119       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
14120         return false;
14121       RHS.makeComplexFloat();
14122       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
14123     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
14124       return false;
14125 
14126     if (LHS.isComplexFloat()) {
14127       APFloat::cmpResult CR_r =
14128         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
14129       APFloat::cmpResult CR_i =
14130         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
14131       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
14132       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
14133     } else {
14134       assert(IsEquality && "invalid complex comparison");
14135       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
14136                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
14137       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
14138     }
14139   }
14140 
14141   if (LHSTy->isRealFloatingType() &&
14142       RHSTy->isRealFloatingType()) {
14143     APFloat RHS(0.0), LHS(0.0);
14144 
14145     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
14146     if (!LHSOK && !Info.noteFailure())
14147       return false;
14148 
14149     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
14150       return false;
14151 
14152     assert(E->isComparisonOp() && "Invalid binary operator!");
14153     llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
14154     if (!Info.InConstantContext &&
14155         APFloatCmpResult == APFloat::cmpUnordered &&
14156         E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
14157       // Note: Compares may raise invalid in some cases involving NaN or sNaN.
14158       Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
14159       return false;
14160     }
14161     auto GetCmpRes = [&]() {
14162       switch (APFloatCmpResult) {
14163       case APFloat::cmpEqual:
14164         return CmpResult::Equal;
14165       case APFloat::cmpLessThan:
14166         return CmpResult::Less;
14167       case APFloat::cmpGreaterThan:
14168         return CmpResult::Greater;
14169       case APFloat::cmpUnordered:
14170         return CmpResult::Unordered;
14171       }
14172       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
14173     };
14174     return Success(GetCmpRes(), E);
14175   }
14176 
14177   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
14178     LValue LHSValue, RHSValue;
14179 
14180     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
14181     if (!LHSOK && !Info.noteFailure())
14182       return false;
14183 
14184     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
14185       return false;
14186 
14187     // Reject differing bases from the normal codepath; we special-case
14188     // comparisons to null.
14189     if (!HasSameBase(LHSValue, RHSValue)) {
14190       auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {
14191         std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
14192         std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
14193         Info.FFDiag(E, DiagID)
14194             << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS);
14195         return false;
14196       };
14197       // Inequalities and subtractions between unrelated pointers have
14198       // unspecified or undefined behavior.
14199       if (!IsEquality)
14200         return DiagComparison(
14201             diag::note_constexpr_pointer_comparison_unspecified);
14202       // A constant address may compare equal to the address of a symbol.
14203       // The one exception is that address of an object cannot compare equal
14204       // to a null pointer constant.
14205       // TODO: Should we restrict this to actual null pointers, and exclude the
14206       // case of zero cast to pointer type?
14207       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
14208           (!RHSValue.Base && !RHSValue.Offset.isZero()))
14209         return DiagComparison(diag::note_constexpr_pointer_constant_comparison,
14210                               !RHSValue.Base);
14211       // C++2c [intro.object]/10:
14212       //   Two objects [...] may have the same address if [...] they are both
14213       //   potentially non-unique objects.
14214       // C++2c [intro.object]/9:
14215       //   An object is potentially non-unique if it is a string literal object,
14216       //   the backing array of an initializer list, or a subobject thereof.
14217       //
14218       // This makes the comparison result unspecified, so it's not a constant
14219       // expression.
14220       //
14221       // TODO: Do we need to handle the initializer list case here?
14222       if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
14223         return DiagComparison(diag::note_constexpr_literal_comparison);
14224       if (IsOpaqueConstantCall(LHSValue) || IsOpaqueConstantCall(RHSValue))
14225         return DiagComparison(diag::note_constexpr_opaque_call_comparison,
14226                               !IsOpaqueConstantCall(LHSValue));
14227       // We can't tell whether weak symbols will end up pointing to the same
14228       // object.
14229       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
14230         return DiagComparison(diag::note_constexpr_pointer_weak_comparison,
14231                               !IsWeakLValue(LHSValue));
14232       // We can't compare the address of the start of one object with the
14233       // past-the-end address of another object, per C++ DR1652.
14234       if (LHSValue.Base && LHSValue.Offset.isZero() &&
14235           isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue))
14236         return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
14237                               true);
14238       if (RHSValue.Base && RHSValue.Offset.isZero() &&
14239            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))
14240         return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
14241                               false);
14242       // We can't tell whether an object is at the same address as another
14243       // zero sized object.
14244       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
14245           (LHSValue.Base && isZeroSized(RHSValue)))
14246         return DiagComparison(
14247             diag::note_constexpr_pointer_comparison_zero_sized);
14248       return Success(CmpResult::Unequal, E);
14249     }
14250 
14251     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
14252     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
14253 
14254     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
14255     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
14256 
14257     // C++11 [expr.rel]p2:
14258     // - If two pointers point to non-static data members of the same object,
14259     //   or to subobjects or array elements fo such members, recursively, the
14260     //   pointer to the later declared member compares greater provided the
14261     //   two members have the same access control and provided their class is
14262     //   not a union.
14263     //   [...]
14264     // - Otherwise pointer comparisons are unspecified.
14265     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
14266       bool WasArrayIndex;
14267       unsigned Mismatch = FindDesignatorMismatch(
14268           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
14269       // At the point where the designators diverge, the comparison has a
14270       // specified value if:
14271       //  - we are comparing array indices
14272       //  - we are comparing fields of a union, or fields with the same access
14273       // Otherwise, the result is unspecified and thus the comparison is not a
14274       // constant expression.
14275       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
14276           Mismatch < RHSDesignator.Entries.size()) {
14277         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
14278         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
14279         if (!LF && !RF)
14280           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
14281         else if (!LF)
14282           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
14283               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
14284               << RF->getParent() << RF;
14285         else if (!RF)
14286           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
14287               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
14288               << LF->getParent() << LF;
14289         else if (!LF->getParent()->isUnion() &&
14290                  LF->getAccess() != RF->getAccess())
14291           Info.CCEDiag(E,
14292                        diag::note_constexpr_pointer_comparison_differing_access)
14293               << LF << LF->getAccess() << RF << RF->getAccess()
14294               << LF->getParent();
14295       }
14296     }
14297 
14298     // The comparison here must be unsigned, and performed with the same
14299     // width as the pointer.
14300     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
14301     uint64_t CompareLHS = LHSOffset.getQuantity();
14302     uint64_t CompareRHS = RHSOffset.getQuantity();
14303     assert(PtrSize <= 64 && "Unexpected pointer width");
14304     uint64_t Mask = ~0ULL >> (64 - PtrSize);
14305     CompareLHS &= Mask;
14306     CompareRHS &= Mask;
14307 
14308     // If there is a base and this is a relational operator, we can only
14309     // compare pointers within the object in question; otherwise, the result
14310     // depends on where the object is located in memory.
14311     if (!LHSValue.Base.isNull() && IsRelational) {
14312       QualType BaseTy = getType(LHSValue.Base);
14313       if (BaseTy->isIncompleteType())
14314         return Error(E);
14315       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
14316       uint64_t OffsetLimit = Size.getQuantity();
14317       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
14318         return Error(E);
14319     }
14320 
14321     if (CompareLHS < CompareRHS)
14322       return Success(CmpResult::Less, E);
14323     if (CompareLHS > CompareRHS)
14324       return Success(CmpResult::Greater, E);
14325     return Success(CmpResult::Equal, E);
14326   }
14327 
14328   if (LHSTy->isMemberPointerType()) {
14329     assert(IsEquality && "unexpected member pointer operation");
14330     assert(RHSTy->isMemberPointerType() && "invalid comparison");
14331 
14332     MemberPtr LHSValue, RHSValue;
14333 
14334     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
14335     if (!LHSOK && !Info.noteFailure())
14336       return false;
14337 
14338     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
14339       return false;
14340 
14341     // If either operand is a pointer to a weak function, the comparison is not
14342     // constant.
14343     if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) {
14344       Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
14345           << LHSValue.getDecl();
14346       return false;
14347     }
14348     if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) {
14349       Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
14350           << RHSValue.getDecl();
14351       return false;
14352     }
14353 
14354     // C++11 [expr.eq]p2:
14355     //   If both operands are null, they compare equal. Otherwise if only one is
14356     //   null, they compare unequal.
14357     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
14358       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
14359       return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
14360     }
14361 
14362     //   Otherwise if either is a pointer to a virtual member function, the
14363     //   result is unspecified.
14364     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
14365       if (MD->isVirtual())
14366         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
14367     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
14368       if (MD->isVirtual())
14369         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
14370 
14371     //   Otherwise they compare equal if and only if they would refer to the
14372     //   same member of the same most derived object or the same subobject if
14373     //   they were dereferenced with a hypothetical object of the associated
14374     //   class type.
14375     bool Equal = LHSValue == RHSValue;
14376     return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
14377   }
14378 
14379   if (LHSTy->isNullPtrType()) {
14380     assert(E->isComparisonOp() && "unexpected nullptr operation");
14381     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
14382     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
14383     // are compared, the result is true of the operator is <=, >= or ==, and
14384     // false otherwise.
14385     LValue Res;
14386     if (!EvaluatePointer(E->getLHS(), Res, Info) ||
14387         !EvaluatePointer(E->getRHS(), Res, Info))
14388       return false;
14389     return Success(CmpResult::Equal, E);
14390   }
14391 
14392   return DoAfter();
14393 }
14394 
14395 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
14396   if (!CheckLiteralType(Info, E))
14397     return false;
14398 
14399   auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
14400     ComparisonCategoryResult CCR;
14401     switch (CR) {
14402     case CmpResult::Unequal:
14403       llvm_unreachable("should never produce Unequal for three-way comparison");
14404     case CmpResult::Less:
14405       CCR = ComparisonCategoryResult::Less;
14406       break;
14407     case CmpResult::Equal:
14408       CCR = ComparisonCategoryResult::Equal;
14409       break;
14410     case CmpResult::Greater:
14411       CCR = ComparisonCategoryResult::Greater;
14412       break;
14413     case CmpResult::Unordered:
14414       CCR = ComparisonCategoryResult::Unordered;
14415       break;
14416     }
14417     // Evaluation succeeded. Lookup the information for the comparison category
14418     // type and fetch the VarDecl for the result.
14419     const ComparisonCategoryInfo &CmpInfo =
14420         Info.Ctx.CompCategories.getInfoForType(E->getType());
14421     const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
14422     // Check and evaluate the result as a constant expression.
14423     LValue LV;
14424     LV.set(VD);
14425     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
14426       return false;
14427     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
14428                                    ConstantExprKind::Normal);
14429   };
14430   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
14431     return ExprEvaluatorBaseTy::VisitBinCmp(E);
14432   });
14433 }
14434 
14435 bool RecordExprEvaluator::VisitCXXParenListInitExpr(
14436     const CXXParenListInitExpr *E) {
14437   return VisitCXXParenListOrInitListExpr(E, E->getInitExprs());
14438 }
14439 
14440 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14441   // We don't support assignment in C. C++ assignments don't get here because
14442   // assignment is an lvalue in C++.
14443   if (E->isAssignmentOp()) {
14444     Error(E);
14445     if (!Info.noteFailure())
14446       return false;
14447   }
14448 
14449   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
14450     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
14451 
14452   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
14453           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
14454          "DataRecursiveIntBinOpEvaluator should have handled integral types");
14455 
14456   if (E->isComparisonOp()) {
14457     // Evaluate builtin binary comparisons by evaluating them as three-way
14458     // comparisons and then translating the result.
14459     auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
14460       assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
14461              "should only produce Unequal for equality comparisons");
14462       bool IsEqual   = CR == CmpResult::Equal,
14463            IsLess    = CR == CmpResult::Less,
14464            IsGreater = CR == CmpResult::Greater;
14465       auto Op = E->getOpcode();
14466       switch (Op) {
14467       default:
14468         llvm_unreachable("unsupported binary operator");
14469       case BO_EQ:
14470       case BO_NE:
14471         return Success(IsEqual == (Op == BO_EQ), E);
14472       case BO_LT:
14473         return Success(IsLess, E);
14474       case BO_GT:
14475         return Success(IsGreater, E);
14476       case BO_LE:
14477         return Success(IsEqual || IsLess, E);
14478       case BO_GE:
14479         return Success(IsEqual || IsGreater, E);
14480       }
14481     };
14482     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
14483       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14484     });
14485   }
14486 
14487   QualType LHSTy = E->getLHS()->getType();
14488   QualType RHSTy = E->getRHS()->getType();
14489 
14490   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
14491       E->getOpcode() == BO_Sub) {
14492     LValue LHSValue, RHSValue;
14493 
14494     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
14495     if (!LHSOK && !Info.noteFailure())
14496       return false;
14497 
14498     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
14499       return false;
14500 
14501     // Reject differing bases from the normal codepath; we special-case
14502     // comparisons to null.
14503     if (!HasSameBase(LHSValue, RHSValue)) {
14504       // Handle &&A - &&B.
14505       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
14506         return Error(E);
14507       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
14508       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
14509       if (!LHSExpr || !RHSExpr)
14510         return Error(E);
14511       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
14512       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
14513       if (!LHSAddrExpr || !RHSAddrExpr)
14514         return Error(E);
14515       // Make sure both labels come from the same function.
14516       if (LHSAddrExpr->getLabel()->getDeclContext() !=
14517           RHSAddrExpr->getLabel()->getDeclContext())
14518         return Error(E);
14519       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
14520     }
14521     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
14522     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
14523 
14524     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
14525     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
14526 
14527     // C++11 [expr.add]p6:
14528     //   Unless both pointers point to elements of the same array object, or
14529     //   one past the last element of the array object, the behavior is
14530     //   undefined.
14531     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
14532         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
14533                                 RHSDesignator))
14534       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
14535 
14536     QualType Type = E->getLHS()->getType();
14537     QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
14538 
14539     CharUnits ElementSize;
14540     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
14541       return false;
14542 
14543     // As an extension, a type may have zero size (empty struct or union in
14544     // C, array of zero length). Pointer subtraction in such cases has
14545     // undefined behavior, so is not constant.
14546     if (ElementSize.isZero()) {
14547       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
14548           << ElementType;
14549       return false;
14550     }
14551 
14552     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
14553     // and produce incorrect results when it overflows. Such behavior
14554     // appears to be non-conforming, but is common, so perhaps we should
14555     // assume the standard intended for such cases to be undefined behavior
14556     // and check for them.
14557 
14558     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
14559     // overflow in the final conversion to ptrdiff_t.
14560     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
14561     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
14562     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
14563                     false);
14564     APSInt TrueResult = (LHS - RHS) / ElemSize;
14565     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
14566 
14567     if (Result.extend(65) != TrueResult &&
14568         !HandleOverflow(Info, E, TrueResult, E->getType()))
14569       return false;
14570     return Success(Result, E);
14571   }
14572 
14573   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14574 }
14575 
14576 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
14577 /// a result as the expression's type.
14578 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
14579                                     const UnaryExprOrTypeTraitExpr *E) {
14580   switch(E->getKind()) {
14581   case UETT_PreferredAlignOf:
14582   case UETT_AlignOf: {
14583     if (E->isArgumentType())
14584       return Success(
14585           GetAlignOfType(Info.Ctx, E->getArgumentType(), E->getKind()), E);
14586     else
14587       return Success(
14588           GetAlignOfExpr(Info.Ctx, E->getArgumentExpr(), E->getKind()), E);
14589   }
14590 
14591   case UETT_PtrAuthTypeDiscriminator: {
14592     if (E->getArgumentType()->isDependentType())
14593       return false;
14594     return Success(
14595         Info.Ctx.getPointerAuthTypeDiscriminator(E->getArgumentType()), E);
14596   }
14597   case UETT_VecStep: {
14598     QualType Ty = E->getTypeOfArgument();
14599 
14600     if (Ty->isVectorType()) {
14601       unsigned n = Ty->castAs<VectorType>()->getNumElements();
14602 
14603       // The vec_step built-in functions that take a 3-component
14604       // vector return 4. (OpenCL 1.1 spec 6.11.12)
14605       if (n == 3)
14606         n = 4;
14607 
14608       return Success(n, E);
14609     } else
14610       return Success(1, E);
14611   }
14612 
14613   case UETT_DataSizeOf:
14614   case UETT_SizeOf: {
14615     QualType SrcTy = E->getTypeOfArgument();
14616     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
14617     //   the result is the size of the referenced type."
14618     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
14619       SrcTy = Ref->getPointeeType();
14620 
14621     CharUnits Sizeof;
14622     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof,
14623                       E->getKind() == UETT_DataSizeOf ? SizeOfType::DataSizeOf
14624                                                       : SizeOfType::SizeOf)) {
14625       return false;
14626     }
14627     return Success(Sizeof, E);
14628   }
14629   case UETT_OpenMPRequiredSimdAlign:
14630     assert(E->isArgumentType());
14631     return Success(
14632         Info.Ctx.toCharUnitsFromBits(
14633                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
14634             .getQuantity(),
14635         E);
14636   case UETT_VectorElements: {
14637     QualType Ty = E->getTypeOfArgument();
14638     // If the vector has a fixed size, we can determine the number of elements
14639     // at compile time.
14640     if (const auto *VT = Ty->getAs<VectorType>())
14641       return Success(VT->getNumElements(), E);
14642 
14643     assert(Ty->isSizelessVectorType());
14644     if (Info.InConstantContext)
14645       Info.CCEDiag(E, diag::note_constexpr_non_const_vectorelements)
14646           << E->getSourceRange();
14647 
14648     return false;
14649   }
14650   }
14651 
14652   llvm_unreachable("unknown expr/type trait");
14653 }
14654 
14655 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
14656   CharUnits Result;
14657   unsigned n = OOE->getNumComponents();
14658   if (n == 0)
14659     return Error(OOE);
14660   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
14661   for (unsigned i = 0; i != n; ++i) {
14662     OffsetOfNode ON = OOE->getComponent(i);
14663     switch (ON.getKind()) {
14664     case OffsetOfNode::Array: {
14665       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
14666       APSInt IdxResult;
14667       if (!EvaluateInteger(Idx, IdxResult, Info))
14668         return false;
14669       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
14670       if (!AT)
14671         return Error(OOE);
14672       CurrentType = AT->getElementType();
14673       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
14674       Result += IdxResult.getSExtValue() * ElementSize;
14675       break;
14676     }
14677 
14678     case OffsetOfNode::Field: {
14679       FieldDecl *MemberDecl = ON.getField();
14680       const RecordType *RT = CurrentType->getAs<RecordType>();
14681       if (!RT)
14682         return Error(OOE);
14683       RecordDecl *RD = RT->getDecl();
14684       if (RD->isInvalidDecl()) return false;
14685       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
14686       unsigned i = MemberDecl->getFieldIndex();
14687       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
14688       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
14689       CurrentType = MemberDecl->getType().getNonReferenceType();
14690       break;
14691     }
14692 
14693     case OffsetOfNode::Identifier:
14694       llvm_unreachable("dependent __builtin_offsetof");
14695 
14696     case OffsetOfNode::Base: {
14697       CXXBaseSpecifier *BaseSpec = ON.getBase();
14698       if (BaseSpec->isVirtual())
14699         return Error(OOE);
14700 
14701       // Find the layout of the class whose base we are looking into.
14702       const RecordType *RT = CurrentType->getAs<RecordType>();
14703       if (!RT)
14704         return Error(OOE);
14705       RecordDecl *RD = RT->getDecl();
14706       if (RD->isInvalidDecl()) return false;
14707       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
14708 
14709       // Find the base class itself.
14710       CurrentType = BaseSpec->getType();
14711       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
14712       if (!BaseRT)
14713         return Error(OOE);
14714 
14715       // Add the offset to the base.
14716       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
14717       break;
14718     }
14719     }
14720   }
14721   return Success(Result, OOE);
14722 }
14723 
14724 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14725   switch (E->getOpcode()) {
14726   default:
14727     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
14728     // See C99 6.6p3.
14729     return Error(E);
14730   case UO_Extension:
14731     // FIXME: Should extension allow i-c-e extension expressions in its scope?
14732     // If so, we could clear the diagnostic ID.
14733     return Visit(E->getSubExpr());
14734   case UO_Plus:
14735     // The result is just the value.
14736     return Visit(E->getSubExpr());
14737   case UO_Minus: {
14738     if (!Visit(E->getSubExpr()))
14739       return false;
14740     if (!Result.isInt()) return Error(E);
14741     const APSInt &Value = Result.getInt();
14742     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
14743       if (Info.checkingForUndefinedBehavior())
14744         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
14745                                          diag::warn_integer_constant_overflow)
14746             << toString(Value, 10, Value.isSigned(), /*formatAsCLiteral=*/false,
14747                         /*UpperCase=*/true, /*InsertSeparators=*/true)
14748             << E->getType() << E->getSourceRange();
14749 
14750       if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
14751                           E->getType()))
14752         return false;
14753     }
14754     return Success(-Value, E);
14755   }
14756   case UO_Not: {
14757     if (!Visit(E->getSubExpr()))
14758       return false;
14759     if (!Result.isInt()) return Error(E);
14760     return Success(~Result.getInt(), E);
14761   }
14762   case UO_LNot: {
14763     bool bres;
14764     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
14765       return false;
14766     return Success(!bres, E);
14767   }
14768   }
14769 }
14770 
14771 /// HandleCast - This is used to evaluate implicit or explicit casts where the
14772 /// result type is integer.
14773 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
14774   const Expr *SubExpr = E->getSubExpr();
14775   QualType DestType = E->getType();
14776   QualType SrcType = SubExpr->getType();
14777 
14778   switch (E->getCastKind()) {
14779   case CK_BaseToDerived:
14780   case CK_DerivedToBase:
14781   case CK_UncheckedDerivedToBase:
14782   case CK_Dynamic:
14783   case CK_ToUnion:
14784   case CK_ArrayToPointerDecay:
14785   case CK_FunctionToPointerDecay:
14786   case CK_NullToPointer:
14787   case CK_NullToMemberPointer:
14788   case CK_BaseToDerivedMemberPointer:
14789   case CK_DerivedToBaseMemberPointer:
14790   case CK_ReinterpretMemberPointer:
14791   case CK_ConstructorConversion:
14792   case CK_IntegralToPointer:
14793   case CK_ToVoid:
14794   case CK_VectorSplat:
14795   case CK_IntegralToFloating:
14796   case CK_FloatingCast:
14797   case CK_CPointerToObjCPointerCast:
14798   case CK_BlockPointerToObjCPointerCast:
14799   case CK_AnyPointerToBlockPointerCast:
14800   case CK_ObjCObjectLValueCast:
14801   case CK_FloatingRealToComplex:
14802   case CK_FloatingComplexToReal:
14803   case CK_FloatingComplexCast:
14804   case CK_FloatingComplexToIntegralComplex:
14805   case CK_IntegralRealToComplex:
14806   case CK_IntegralComplexCast:
14807   case CK_IntegralComplexToFloatingComplex:
14808   case CK_BuiltinFnToFnPtr:
14809   case CK_ZeroToOCLOpaqueType:
14810   case CK_NonAtomicToAtomic:
14811   case CK_AddressSpaceConversion:
14812   case CK_IntToOCLSampler:
14813   case CK_FloatingToFixedPoint:
14814   case CK_FixedPointToFloating:
14815   case CK_FixedPointCast:
14816   case CK_IntegralToFixedPoint:
14817   case CK_MatrixCast:
14818     llvm_unreachable("invalid cast kind for integral value");
14819 
14820   case CK_BitCast:
14821   case CK_Dependent:
14822   case CK_LValueBitCast:
14823   case CK_ARCProduceObject:
14824   case CK_ARCConsumeObject:
14825   case CK_ARCReclaimReturnedObject:
14826   case CK_ARCExtendBlockObject:
14827   case CK_CopyAndAutoreleaseBlockObject:
14828     return Error(E);
14829 
14830   case CK_UserDefinedConversion:
14831   case CK_LValueToRValue:
14832   case CK_AtomicToNonAtomic:
14833   case CK_NoOp:
14834   case CK_LValueToRValueBitCast:
14835   case CK_HLSLArrayRValue:
14836     return ExprEvaluatorBaseTy::VisitCastExpr(E);
14837 
14838   case CK_MemberPointerToBoolean:
14839   case CK_PointerToBoolean:
14840   case CK_IntegralToBoolean:
14841   case CK_FloatingToBoolean:
14842   case CK_BooleanToSignedIntegral:
14843   case CK_FloatingComplexToBoolean:
14844   case CK_IntegralComplexToBoolean: {
14845     bool BoolResult;
14846     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
14847       return false;
14848     uint64_t IntResult = BoolResult;
14849     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
14850       IntResult = (uint64_t)-1;
14851     return Success(IntResult, E);
14852   }
14853 
14854   case CK_FixedPointToIntegral: {
14855     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
14856     if (!EvaluateFixedPoint(SubExpr, Src, Info))
14857       return false;
14858     bool Overflowed;
14859     llvm::APSInt Result = Src.convertToInt(
14860         Info.Ctx.getIntWidth(DestType),
14861         DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
14862     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
14863       return false;
14864     return Success(Result, E);
14865   }
14866 
14867   case CK_FixedPointToBoolean: {
14868     // Unsigned padding does not affect this.
14869     APValue Val;
14870     if (!Evaluate(Val, Info, SubExpr))
14871       return false;
14872     return Success(Val.getFixedPoint().getBoolValue(), E);
14873   }
14874 
14875   case CK_IntegralCast: {
14876     if (!Visit(SubExpr))
14877       return false;
14878 
14879     if (!Result.isInt()) {
14880       // Allow casts of address-of-label differences if they are no-ops
14881       // or narrowing.  (The narrowing case isn't actually guaranteed to
14882       // be constant-evaluatable except in some narrow cases which are hard
14883       // to detect here.  We let it through on the assumption the user knows
14884       // what they are doing.)
14885       if (Result.isAddrLabelDiff())
14886         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
14887       // Only allow casts of lvalues if they are lossless.
14888       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
14889     }
14890 
14891     if (Info.Ctx.getLangOpts().CPlusPlus && Info.InConstantContext &&
14892         Info.EvalMode == EvalInfo::EM_ConstantExpression &&
14893         DestType->isEnumeralType()) {
14894 
14895       bool ConstexprVar = true;
14896 
14897       // We know if we are here that we are in a context that we might require
14898       // a constant expression or a context that requires a constant
14899       // value. But if we are initializing a value we don't know if it is a
14900       // constexpr variable or not. We can check the EvaluatingDecl to determine
14901       // if it constexpr or not. If not then we don't want to emit a diagnostic.
14902       if (const auto *VD = dyn_cast_or_null<VarDecl>(
14903               Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
14904         ConstexprVar = VD->isConstexpr();
14905 
14906       const EnumType *ET = dyn_cast<EnumType>(DestType.getCanonicalType());
14907       const EnumDecl *ED = ET->getDecl();
14908       // Check that the value is within the range of the enumeration values.
14909       //
14910       // This corressponds to [expr.static.cast]p10 which says:
14911       // A value of integral or enumeration type can be explicitly converted
14912       // to a complete enumeration type ... If the enumeration type does not
14913       // have a fixed underlying type, the value is unchanged if the original
14914       // value is within the range of the enumeration values ([dcl.enum]), and
14915       // otherwise, the behavior is undefined.
14916       //
14917       // This was resolved as part of DR2338 which has CD5 status.
14918       if (!ED->isFixed()) {
14919         llvm::APInt Min;
14920         llvm::APInt Max;
14921 
14922         ED->getValueRange(Max, Min);
14923         --Max;
14924 
14925         if (ED->getNumNegativeBits() && ConstexprVar &&
14926             (Max.slt(Result.getInt().getSExtValue()) ||
14927              Min.sgt(Result.getInt().getSExtValue())))
14928           Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
14929               << llvm::toString(Result.getInt(), 10) << Min.getSExtValue()
14930               << Max.getSExtValue() << ED;
14931         else if (!ED->getNumNegativeBits() && ConstexprVar &&
14932                  Max.ult(Result.getInt().getZExtValue()))
14933           Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
14934               << llvm::toString(Result.getInt(), 10) << Min.getZExtValue()
14935               << Max.getZExtValue() << ED;
14936       }
14937     }
14938 
14939     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
14940                                       Result.getInt()), E);
14941   }
14942 
14943   case CK_PointerToIntegral: {
14944     CCEDiag(E, diag::note_constexpr_invalid_cast)
14945         << 2 << Info.Ctx.getLangOpts().CPlusPlus << E->getSourceRange();
14946 
14947     LValue LV;
14948     if (!EvaluatePointer(SubExpr, LV, Info))
14949       return false;
14950 
14951     if (LV.getLValueBase()) {
14952       // Only allow based lvalue casts if they are lossless.
14953       // FIXME: Allow a larger integer size than the pointer size, and allow
14954       // narrowing back down to pointer width in subsequent integral casts.
14955       // FIXME: Check integer type's active bits, not its type size.
14956       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
14957         return Error(E);
14958 
14959       LV.Designator.setInvalid();
14960       LV.moveInto(Result);
14961       return true;
14962     }
14963 
14964     APSInt AsInt;
14965     APValue V;
14966     LV.moveInto(V);
14967     if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
14968       llvm_unreachable("Can't cast this!");
14969 
14970     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
14971   }
14972 
14973   case CK_IntegralComplexToReal: {
14974     ComplexValue C;
14975     if (!EvaluateComplex(SubExpr, C, Info))
14976       return false;
14977     return Success(C.getComplexIntReal(), E);
14978   }
14979 
14980   case CK_FloatingToIntegral: {
14981     APFloat F(0.0);
14982     if (!EvaluateFloat(SubExpr, F, Info))
14983       return false;
14984 
14985     APSInt Value;
14986     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
14987       return false;
14988     return Success(Value, E);
14989   }
14990   case CK_HLSLVectorTruncation: {
14991     APValue Val;
14992     if (!EvaluateVector(SubExpr, Val, Info))
14993       return Error(E);
14994     return Success(Val.getVectorElt(0), E);
14995   }
14996   }
14997 
14998   llvm_unreachable("unknown cast resulting in integral value");
14999 }
15000 
15001 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
15002   if (E->getSubExpr()->getType()->isAnyComplexType()) {
15003     ComplexValue LV;
15004     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
15005       return false;
15006     if (!LV.isComplexInt())
15007       return Error(E);
15008     return Success(LV.getComplexIntReal(), E);
15009   }
15010 
15011   return Visit(E->getSubExpr());
15012 }
15013 
15014 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
15015   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
15016     ComplexValue LV;
15017     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
15018       return false;
15019     if (!LV.isComplexInt())
15020       return Error(E);
15021     return Success(LV.getComplexIntImag(), E);
15022   }
15023 
15024   VisitIgnoredValue(E->getSubExpr());
15025   return Success(0, E);
15026 }
15027 
15028 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
15029   return Success(E->getPackLength(), E);
15030 }
15031 
15032 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
15033   return Success(E->getValue(), E);
15034 }
15035 
15036 bool IntExprEvaluator::VisitConceptSpecializationExpr(
15037        const ConceptSpecializationExpr *E) {
15038   return Success(E->isSatisfied(), E);
15039 }
15040 
15041 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
15042   return Success(E->isSatisfied(), E);
15043 }
15044 
15045 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
15046   switch (E->getOpcode()) {
15047     default:
15048       // Invalid unary operators
15049       return Error(E);
15050     case UO_Plus:
15051       // The result is just the value.
15052       return Visit(E->getSubExpr());
15053     case UO_Minus: {
15054       if (!Visit(E->getSubExpr())) return false;
15055       if (!Result.isFixedPoint())
15056         return Error(E);
15057       bool Overflowed;
15058       APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
15059       if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
15060         return false;
15061       return Success(Negated, E);
15062     }
15063     case UO_LNot: {
15064       bool bres;
15065       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
15066         return false;
15067       return Success(!bres, E);
15068     }
15069   }
15070 }
15071 
15072 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
15073   const Expr *SubExpr = E->getSubExpr();
15074   QualType DestType = E->getType();
15075   assert(DestType->isFixedPointType() &&
15076          "Expected destination type to be a fixed point type");
15077   auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
15078 
15079   switch (E->getCastKind()) {
15080   case CK_FixedPointCast: {
15081     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
15082     if (!EvaluateFixedPoint(SubExpr, Src, Info))
15083       return false;
15084     bool Overflowed;
15085     APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
15086     if (Overflowed) {
15087       if (Info.checkingForUndefinedBehavior())
15088         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
15089                                          diag::warn_fixedpoint_constant_overflow)
15090           << Result.toString() << E->getType();
15091       if (!HandleOverflow(Info, E, Result, E->getType()))
15092         return false;
15093     }
15094     return Success(Result, E);
15095   }
15096   case CK_IntegralToFixedPoint: {
15097     APSInt Src;
15098     if (!EvaluateInteger(SubExpr, Src, Info))
15099       return false;
15100 
15101     bool Overflowed;
15102     APFixedPoint IntResult = APFixedPoint::getFromIntValue(
15103         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
15104 
15105     if (Overflowed) {
15106       if (Info.checkingForUndefinedBehavior())
15107         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
15108                                          diag::warn_fixedpoint_constant_overflow)
15109           << IntResult.toString() << E->getType();
15110       if (!HandleOverflow(Info, E, IntResult, E->getType()))
15111         return false;
15112     }
15113 
15114     return Success(IntResult, E);
15115   }
15116   case CK_FloatingToFixedPoint: {
15117     APFloat Src(0.0);
15118     if (!EvaluateFloat(SubExpr, Src, Info))
15119       return false;
15120 
15121     bool Overflowed;
15122     APFixedPoint Result = APFixedPoint::getFromFloatValue(
15123         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
15124 
15125     if (Overflowed) {
15126       if (Info.checkingForUndefinedBehavior())
15127         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
15128                                          diag::warn_fixedpoint_constant_overflow)
15129           << Result.toString() << E->getType();
15130       if (!HandleOverflow(Info, E, Result, E->getType()))
15131         return false;
15132     }
15133 
15134     return Success(Result, E);
15135   }
15136   case CK_NoOp:
15137   case CK_LValueToRValue:
15138     return ExprEvaluatorBaseTy::VisitCastExpr(E);
15139   default:
15140     return Error(E);
15141   }
15142 }
15143 
15144 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
15145   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
15146     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
15147 
15148   const Expr *LHS = E->getLHS();
15149   const Expr *RHS = E->getRHS();
15150   FixedPointSemantics ResultFXSema =
15151       Info.Ctx.getFixedPointSemantics(E->getType());
15152 
15153   APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
15154   if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
15155     return false;
15156   APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
15157   if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
15158     return false;
15159 
15160   bool OpOverflow = false, ConversionOverflow = false;
15161   APFixedPoint Result(LHSFX.getSemantics());
15162   switch (E->getOpcode()) {
15163   case BO_Add: {
15164     Result = LHSFX.add(RHSFX, &OpOverflow)
15165                   .convert(ResultFXSema, &ConversionOverflow);
15166     break;
15167   }
15168   case BO_Sub: {
15169     Result = LHSFX.sub(RHSFX, &OpOverflow)
15170                   .convert(ResultFXSema, &ConversionOverflow);
15171     break;
15172   }
15173   case BO_Mul: {
15174     Result = LHSFX.mul(RHSFX, &OpOverflow)
15175                   .convert(ResultFXSema, &ConversionOverflow);
15176     break;
15177   }
15178   case BO_Div: {
15179     if (RHSFX.getValue() == 0) {
15180       Info.FFDiag(E, diag::note_expr_divide_by_zero);
15181       return false;
15182     }
15183     Result = LHSFX.div(RHSFX, &OpOverflow)
15184                   .convert(ResultFXSema, &ConversionOverflow);
15185     break;
15186   }
15187   case BO_Shl:
15188   case BO_Shr: {
15189     FixedPointSemantics LHSSema = LHSFX.getSemantics();
15190     llvm::APSInt RHSVal = RHSFX.getValue();
15191 
15192     unsigned ShiftBW =
15193         LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
15194     unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
15195     // Embedded-C 4.1.6.2.2:
15196     //   The right operand must be nonnegative and less than the total number
15197     //   of (nonpadding) bits of the fixed-point operand ...
15198     if (RHSVal.isNegative())
15199       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
15200     else if (Amt != RHSVal)
15201       Info.CCEDiag(E, diag::note_constexpr_large_shift)
15202           << RHSVal << E->getType() << ShiftBW;
15203 
15204     if (E->getOpcode() == BO_Shl)
15205       Result = LHSFX.shl(Amt, &OpOverflow);
15206     else
15207       Result = LHSFX.shr(Amt, &OpOverflow);
15208     break;
15209   }
15210   default:
15211     return false;
15212   }
15213   if (OpOverflow || ConversionOverflow) {
15214     if (Info.checkingForUndefinedBehavior())
15215       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
15216                                        diag::warn_fixedpoint_constant_overflow)
15217         << Result.toString() << E->getType();
15218     if (!HandleOverflow(Info, E, Result, E->getType()))
15219       return false;
15220   }
15221   return Success(Result, E);
15222 }
15223 
15224 //===----------------------------------------------------------------------===//
15225 // Float Evaluation
15226 //===----------------------------------------------------------------------===//
15227 
15228 namespace {
15229 class FloatExprEvaluator
15230   : public ExprEvaluatorBase<FloatExprEvaluator> {
15231   APFloat &Result;
15232 public:
15233   FloatExprEvaluator(EvalInfo &info, APFloat &result)
15234     : ExprEvaluatorBaseTy(info), Result(result) {}
15235 
15236   bool Success(const APValue &V, const Expr *e) {
15237     Result = V.getFloat();
15238     return true;
15239   }
15240 
15241   bool ZeroInitialization(const Expr *E) {
15242     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
15243     return true;
15244   }
15245 
15246   bool VisitCallExpr(const CallExpr *E);
15247 
15248   bool VisitUnaryOperator(const UnaryOperator *E);
15249   bool VisitBinaryOperator(const BinaryOperator *E);
15250   bool VisitFloatingLiteral(const FloatingLiteral *E);
15251   bool VisitCastExpr(const CastExpr *E);
15252 
15253   bool VisitUnaryReal(const UnaryOperator *E);
15254   bool VisitUnaryImag(const UnaryOperator *E);
15255 
15256   // FIXME: Missing: array subscript of vector, member of vector
15257 };
15258 } // end anonymous namespace
15259 
15260 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
15261   assert(!E->isValueDependent());
15262   assert(E->isPRValue() && E->getType()->isRealFloatingType());
15263   return FloatExprEvaluator(Info, Result).Visit(E);
15264 }
15265 
15266 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
15267                                   QualType ResultTy,
15268                                   const Expr *Arg,
15269                                   bool SNaN,
15270                                   llvm::APFloat &Result) {
15271   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
15272   if (!S) return false;
15273 
15274   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
15275 
15276   llvm::APInt fill;
15277 
15278   // Treat empty strings as if they were zero.
15279   if (S->getString().empty())
15280     fill = llvm::APInt(32, 0);
15281   else if (S->getString().getAsInteger(0, fill))
15282     return false;
15283 
15284   if (Context.getTargetInfo().isNan2008()) {
15285     if (SNaN)
15286       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
15287     else
15288       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
15289   } else {
15290     // Prior to IEEE 754-2008, architectures were allowed to choose whether
15291     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
15292     // a different encoding to what became a standard in 2008, and for pre-
15293     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
15294     // sNaN. This is now known as "legacy NaN" encoding.
15295     if (SNaN)
15296       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
15297     else
15298       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
15299   }
15300 
15301   return true;
15302 }
15303 
15304 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
15305   if (!IsConstantEvaluatedBuiltinCall(E))
15306     return ExprEvaluatorBaseTy::VisitCallExpr(E);
15307 
15308   switch (E->getBuiltinCallee()) {
15309   default:
15310     return false;
15311 
15312   case Builtin::BI__builtin_huge_val:
15313   case Builtin::BI__builtin_huge_valf:
15314   case Builtin::BI__builtin_huge_vall:
15315   case Builtin::BI__builtin_huge_valf16:
15316   case Builtin::BI__builtin_huge_valf128:
15317   case Builtin::BI__builtin_inf:
15318   case Builtin::BI__builtin_inff:
15319   case Builtin::BI__builtin_infl:
15320   case Builtin::BI__builtin_inff16:
15321   case Builtin::BI__builtin_inff128: {
15322     const llvm::fltSemantics &Sem =
15323       Info.Ctx.getFloatTypeSemantics(E->getType());
15324     Result = llvm::APFloat::getInf(Sem);
15325     return true;
15326   }
15327 
15328   case Builtin::BI__builtin_nans:
15329   case Builtin::BI__builtin_nansf:
15330   case Builtin::BI__builtin_nansl:
15331   case Builtin::BI__builtin_nansf16:
15332   case Builtin::BI__builtin_nansf128:
15333     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
15334                                true, Result))
15335       return Error(E);
15336     return true;
15337 
15338   case Builtin::BI__builtin_nan:
15339   case Builtin::BI__builtin_nanf:
15340   case Builtin::BI__builtin_nanl:
15341   case Builtin::BI__builtin_nanf16:
15342   case Builtin::BI__builtin_nanf128:
15343     // If this is __builtin_nan() turn this into a nan, otherwise we
15344     // can't constant fold it.
15345     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
15346                                false, Result))
15347       return Error(E);
15348     return true;
15349 
15350   case Builtin::BI__builtin_fabs:
15351   case Builtin::BI__builtin_fabsf:
15352   case Builtin::BI__builtin_fabsl:
15353   case Builtin::BI__builtin_fabsf128:
15354     // The C standard says "fabs raises no floating-point exceptions,
15355     // even if x is a signaling NaN. The returned value is independent of
15356     // the current rounding direction mode."  Therefore constant folding can
15357     // proceed without regard to the floating point settings.
15358     // Reference, WG14 N2478 F.10.4.3
15359     if (!EvaluateFloat(E->getArg(0), Result, Info))
15360       return false;
15361 
15362     if (Result.isNegative())
15363       Result.changeSign();
15364     return true;
15365 
15366   case Builtin::BI__arithmetic_fence:
15367     return EvaluateFloat(E->getArg(0), Result, Info);
15368 
15369   // FIXME: Builtin::BI__builtin_powi
15370   // FIXME: Builtin::BI__builtin_powif
15371   // FIXME: Builtin::BI__builtin_powil
15372 
15373   case Builtin::BI__builtin_copysign:
15374   case Builtin::BI__builtin_copysignf:
15375   case Builtin::BI__builtin_copysignl:
15376   case Builtin::BI__builtin_copysignf128: {
15377     APFloat RHS(0.);
15378     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
15379         !EvaluateFloat(E->getArg(1), RHS, Info))
15380       return false;
15381     Result.copySign(RHS);
15382     return true;
15383   }
15384 
15385   case Builtin::BI__builtin_fmax:
15386   case Builtin::BI__builtin_fmaxf:
15387   case Builtin::BI__builtin_fmaxl:
15388   case Builtin::BI__builtin_fmaxf16:
15389   case Builtin::BI__builtin_fmaxf128: {
15390     // TODO: Handle sNaN.
15391     APFloat RHS(0.);
15392     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
15393         !EvaluateFloat(E->getArg(1), RHS, Info))
15394       return false;
15395     // When comparing zeroes, return +0.0 if one of the zeroes is positive.
15396     if (Result.isZero() && RHS.isZero() && Result.isNegative())
15397       Result = RHS;
15398     else if (Result.isNaN() || RHS > Result)
15399       Result = RHS;
15400     return true;
15401   }
15402 
15403   case Builtin::BI__builtin_fmin:
15404   case Builtin::BI__builtin_fminf:
15405   case Builtin::BI__builtin_fminl:
15406   case Builtin::BI__builtin_fminf16:
15407   case Builtin::BI__builtin_fminf128: {
15408     // TODO: Handle sNaN.
15409     APFloat RHS(0.);
15410     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
15411         !EvaluateFloat(E->getArg(1), RHS, Info))
15412       return false;
15413     // When comparing zeroes, return -0.0 if one of the zeroes is negative.
15414     if (Result.isZero() && RHS.isZero() && RHS.isNegative())
15415       Result = RHS;
15416     else if (Result.isNaN() || RHS < Result)
15417       Result = RHS;
15418     return true;
15419   }
15420 
15421   case Builtin::BI__builtin_fmaximum_num:
15422   case Builtin::BI__builtin_fmaximum_numf:
15423   case Builtin::BI__builtin_fmaximum_numl:
15424   case Builtin::BI__builtin_fmaximum_numf16:
15425   case Builtin::BI__builtin_fmaximum_numf128: {
15426     APFloat RHS(0.);
15427     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
15428         !EvaluateFloat(E->getArg(1), RHS, Info))
15429       return false;
15430     Result = maximumnum(Result, RHS);
15431     return true;
15432   }
15433 
15434   case Builtin::BI__builtin_fminimum_num:
15435   case Builtin::BI__builtin_fminimum_numf:
15436   case Builtin::BI__builtin_fminimum_numl:
15437   case Builtin::BI__builtin_fminimum_numf16:
15438   case Builtin::BI__builtin_fminimum_numf128: {
15439     APFloat RHS(0.);
15440     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
15441         !EvaluateFloat(E->getArg(1), RHS, Info))
15442       return false;
15443     Result = minimumnum(Result, RHS);
15444     return true;
15445   }
15446   }
15447 }
15448 
15449 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
15450   if (E->getSubExpr()->getType()->isAnyComplexType()) {
15451     ComplexValue CV;
15452     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
15453       return false;
15454     Result = CV.FloatReal;
15455     return true;
15456   }
15457 
15458   return Visit(E->getSubExpr());
15459 }
15460 
15461 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
15462   if (E->getSubExpr()->getType()->isAnyComplexType()) {
15463     ComplexValue CV;
15464     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
15465       return false;
15466     Result = CV.FloatImag;
15467     return true;
15468   }
15469 
15470   VisitIgnoredValue(E->getSubExpr());
15471   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
15472   Result = llvm::APFloat::getZero(Sem);
15473   return true;
15474 }
15475 
15476 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
15477   switch (E->getOpcode()) {
15478   default: return Error(E);
15479   case UO_Plus:
15480     return EvaluateFloat(E->getSubExpr(), Result, Info);
15481   case UO_Minus:
15482     // In C standard, WG14 N2478 F.3 p4
15483     // "the unary - raises no floating point exceptions,
15484     // even if the operand is signalling."
15485     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
15486       return false;
15487     Result.changeSign();
15488     return true;
15489   }
15490 }
15491 
15492 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
15493   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
15494     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
15495 
15496   APFloat RHS(0.0);
15497   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
15498   if (!LHSOK && !Info.noteFailure())
15499     return false;
15500   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
15501          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
15502 }
15503 
15504 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
15505   Result = E->getValue();
15506   return true;
15507 }
15508 
15509 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
15510   const Expr* SubExpr = E->getSubExpr();
15511 
15512   switch (E->getCastKind()) {
15513   default:
15514     return ExprEvaluatorBaseTy::VisitCastExpr(E);
15515 
15516   case CK_IntegralToFloating: {
15517     APSInt IntResult;
15518     const FPOptions FPO = E->getFPFeaturesInEffect(
15519                                   Info.Ctx.getLangOpts());
15520     return EvaluateInteger(SubExpr, IntResult, Info) &&
15521            HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
15522                                 IntResult, E->getType(), Result);
15523   }
15524 
15525   case CK_FixedPointToFloating: {
15526     APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
15527     if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
15528       return false;
15529     Result =
15530         FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
15531     return true;
15532   }
15533 
15534   case CK_FloatingCast: {
15535     if (!Visit(SubExpr))
15536       return false;
15537     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
15538                                   Result);
15539   }
15540 
15541   case CK_FloatingComplexToReal: {
15542     ComplexValue V;
15543     if (!EvaluateComplex(SubExpr, V, Info))
15544       return false;
15545     Result = V.getComplexFloatReal();
15546     return true;
15547   }
15548   case CK_HLSLVectorTruncation: {
15549     APValue Val;
15550     if (!EvaluateVector(SubExpr, Val, Info))
15551       return Error(E);
15552     return Success(Val.getVectorElt(0), E);
15553   }
15554   }
15555 }
15556 
15557 //===----------------------------------------------------------------------===//
15558 // Complex Evaluation (for float and integer)
15559 //===----------------------------------------------------------------------===//
15560 
15561 namespace {
15562 class ComplexExprEvaluator
15563   : public ExprEvaluatorBase<ComplexExprEvaluator> {
15564   ComplexValue &Result;
15565 
15566 public:
15567   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
15568     : ExprEvaluatorBaseTy(info), Result(Result) {}
15569 
15570   bool Success(const APValue &V, const Expr *e) {
15571     Result.setFrom(V);
15572     return true;
15573   }
15574 
15575   bool ZeroInitialization(const Expr *E);
15576 
15577   //===--------------------------------------------------------------------===//
15578   //                            Visitor Methods
15579   //===--------------------------------------------------------------------===//
15580 
15581   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
15582   bool VisitCastExpr(const CastExpr *E);
15583   bool VisitBinaryOperator(const BinaryOperator *E);
15584   bool VisitUnaryOperator(const UnaryOperator *E);
15585   bool VisitInitListExpr(const InitListExpr *E);
15586   bool VisitCallExpr(const CallExpr *E);
15587 };
15588 } // end anonymous namespace
15589 
15590 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
15591                             EvalInfo &Info) {
15592   assert(!E->isValueDependent());
15593   assert(E->isPRValue() && E->getType()->isAnyComplexType());
15594   return ComplexExprEvaluator(Info, Result).Visit(E);
15595 }
15596 
15597 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
15598   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
15599   if (ElemTy->isRealFloatingType()) {
15600     Result.makeComplexFloat();
15601     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
15602     Result.FloatReal = Zero;
15603     Result.FloatImag = Zero;
15604   } else {
15605     Result.makeComplexInt();
15606     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
15607     Result.IntReal = Zero;
15608     Result.IntImag = Zero;
15609   }
15610   return true;
15611 }
15612 
15613 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
15614   const Expr* SubExpr = E->getSubExpr();
15615 
15616   if (SubExpr->getType()->isRealFloatingType()) {
15617     Result.makeComplexFloat();
15618     APFloat &Imag = Result.FloatImag;
15619     if (!EvaluateFloat(SubExpr, Imag, Info))
15620       return false;
15621 
15622     Result.FloatReal = APFloat(Imag.getSemantics());
15623     return true;
15624   } else {
15625     assert(SubExpr->getType()->isIntegerType() &&
15626            "Unexpected imaginary literal.");
15627 
15628     Result.makeComplexInt();
15629     APSInt &Imag = Result.IntImag;
15630     if (!EvaluateInteger(SubExpr, Imag, Info))
15631       return false;
15632 
15633     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
15634     return true;
15635   }
15636 }
15637 
15638 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
15639 
15640   switch (E->getCastKind()) {
15641   case CK_BitCast:
15642   case CK_BaseToDerived:
15643   case CK_DerivedToBase:
15644   case CK_UncheckedDerivedToBase:
15645   case CK_Dynamic:
15646   case CK_ToUnion:
15647   case CK_ArrayToPointerDecay:
15648   case CK_FunctionToPointerDecay:
15649   case CK_NullToPointer:
15650   case CK_NullToMemberPointer:
15651   case CK_BaseToDerivedMemberPointer:
15652   case CK_DerivedToBaseMemberPointer:
15653   case CK_MemberPointerToBoolean:
15654   case CK_ReinterpretMemberPointer:
15655   case CK_ConstructorConversion:
15656   case CK_IntegralToPointer:
15657   case CK_PointerToIntegral:
15658   case CK_PointerToBoolean:
15659   case CK_ToVoid:
15660   case CK_VectorSplat:
15661   case CK_IntegralCast:
15662   case CK_BooleanToSignedIntegral:
15663   case CK_IntegralToBoolean:
15664   case CK_IntegralToFloating:
15665   case CK_FloatingToIntegral:
15666   case CK_FloatingToBoolean:
15667   case CK_FloatingCast:
15668   case CK_CPointerToObjCPointerCast:
15669   case CK_BlockPointerToObjCPointerCast:
15670   case CK_AnyPointerToBlockPointerCast:
15671   case CK_ObjCObjectLValueCast:
15672   case CK_FloatingComplexToReal:
15673   case CK_FloatingComplexToBoolean:
15674   case CK_IntegralComplexToReal:
15675   case CK_IntegralComplexToBoolean:
15676   case CK_ARCProduceObject:
15677   case CK_ARCConsumeObject:
15678   case CK_ARCReclaimReturnedObject:
15679   case CK_ARCExtendBlockObject:
15680   case CK_CopyAndAutoreleaseBlockObject:
15681   case CK_BuiltinFnToFnPtr:
15682   case CK_ZeroToOCLOpaqueType:
15683   case CK_NonAtomicToAtomic:
15684   case CK_AddressSpaceConversion:
15685   case CK_IntToOCLSampler:
15686   case CK_FloatingToFixedPoint:
15687   case CK_FixedPointToFloating:
15688   case CK_FixedPointCast:
15689   case CK_FixedPointToBoolean:
15690   case CK_FixedPointToIntegral:
15691   case CK_IntegralToFixedPoint:
15692   case CK_MatrixCast:
15693   case CK_HLSLVectorTruncation:
15694     llvm_unreachable("invalid cast kind for complex value");
15695 
15696   case CK_LValueToRValue:
15697   case CK_AtomicToNonAtomic:
15698   case CK_NoOp:
15699   case CK_LValueToRValueBitCast:
15700   case CK_HLSLArrayRValue:
15701     return ExprEvaluatorBaseTy::VisitCastExpr(E);
15702 
15703   case CK_Dependent:
15704   case CK_LValueBitCast:
15705   case CK_UserDefinedConversion:
15706     return Error(E);
15707 
15708   case CK_FloatingRealToComplex: {
15709     APFloat &Real = Result.FloatReal;
15710     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
15711       return false;
15712 
15713     Result.makeComplexFloat();
15714     Result.FloatImag = APFloat(Real.getSemantics());
15715     return true;
15716   }
15717 
15718   case CK_FloatingComplexCast: {
15719     if (!Visit(E->getSubExpr()))
15720       return false;
15721 
15722     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
15723     QualType From
15724       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
15725 
15726     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
15727            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
15728   }
15729 
15730   case CK_FloatingComplexToIntegralComplex: {
15731     if (!Visit(E->getSubExpr()))
15732       return false;
15733 
15734     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
15735     QualType From
15736       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
15737     Result.makeComplexInt();
15738     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
15739                                 To, Result.IntReal) &&
15740            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
15741                                 To, Result.IntImag);
15742   }
15743 
15744   case CK_IntegralRealToComplex: {
15745     APSInt &Real = Result.IntReal;
15746     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
15747       return false;
15748 
15749     Result.makeComplexInt();
15750     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
15751     return true;
15752   }
15753 
15754   case CK_IntegralComplexCast: {
15755     if (!Visit(E->getSubExpr()))
15756       return false;
15757 
15758     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
15759     QualType From
15760       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
15761 
15762     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
15763     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
15764     return true;
15765   }
15766 
15767   case CK_IntegralComplexToFloatingComplex: {
15768     if (!Visit(E->getSubExpr()))
15769       return false;
15770 
15771     const FPOptions FPO = E->getFPFeaturesInEffect(
15772                                   Info.Ctx.getLangOpts());
15773     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
15774     QualType From
15775       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
15776     Result.makeComplexFloat();
15777     return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
15778                                 To, Result.FloatReal) &&
15779            HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
15780                                 To, Result.FloatImag);
15781   }
15782   }
15783 
15784   llvm_unreachable("unknown cast resulting in complex value");
15785 }
15786 
15787 void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D,
15788                              APFloat &ResR, APFloat &ResI) {
15789   // This is an implementation of complex multiplication according to the
15790   // constraints laid out in C11 Annex G. The implementation uses the
15791   // following naming scheme:
15792   //   (a + ib) * (c + id)
15793 
15794   APFloat AC = A * C;
15795   APFloat BD = B * D;
15796   APFloat AD = A * D;
15797   APFloat BC = B * C;
15798   ResR = AC - BD;
15799   ResI = AD + BC;
15800   if (ResR.isNaN() && ResI.isNaN()) {
15801     bool Recalc = false;
15802     if (A.isInfinity() || B.isInfinity()) {
15803       A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
15804                             A);
15805       B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
15806                             B);
15807       if (C.isNaN())
15808         C = APFloat::copySign(APFloat(C.getSemantics()), C);
15809       if (D.isNaN())
15810         D = APFloat::copySign(APFloat(D.getSemantics()), D);
15811       Recalc = true;
15812     }
15813     if (C.isInfinity() || D.isInfinity()) {
15814       C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
15815                             C);
15816       D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
15817                             D);
15818       if (A.isNaN())
15819         A = APFloat::copySign(APFloat(A.getSemantics()), A);
15820       if (B.isNaN())
15821         B = APFloat::copySign(APFloat(B.getSemantics()), B);
15822       Recalc = true;
15823     }
15824     if (!Recalc && (AC.isInfinity() || BD.isInfinity() || AD.isInfinity() ||
15825                     BC.isInfinity())) {
15826       if (A.isNaN())
15827         A = APFloat::copySign(APFloat(A.getSemantics()), A);
15828       if (B.isNaN())
15829         B = APFloat::copySign(APFloat(B.getSemantics()), B);
15830       if (C.isNaN())
15831         C = APFloat::copySign(APFloat(C.getSemantics()), C);
15832       if (D.isNaN())
15833         D = APFloat::copySign(APFloat(D.getSemantics()), D);
15834       Recalc = true;
15835     }
15836     if (Recalc) {
15837       ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
15838       ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
15839     }
15840   }
15841 }
15842 
15843 void HandleComplexComplexDiv(APFloat A, APFloat B, APFloat C, APFloat D,
15844                              APFloat &ResR, APFloat &ResI) {
15845   // This is an implementation of complex division according to the
15846   // constraints laid out in C11 Annex G. The implementation uses the
15847   // following naming scheme:
15848   //   (a + ib) / (c + id)
15849 
15850   int DenomLogB = 0;
15851   APFloat MaxCD = maxnum(abs(C), abs(D));
15852   if (MaxCD.isFinite()) {
15853     DenomLogB = ilogb(MaxCD);
15854     C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
15855     D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
15856   }
15857   APFloat Denom = C * C + D * D;
15858   ResR =
15859       scalbn((A * C + B * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
15860   ResI =
15861       scalbn((B * C - A * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
15862   if (ResR.isNaN() && ResI.isNaN()) {
15863     if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
15864       ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
15865       ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
15866     } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
15867                D.isFinite()) {
15868       A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
15869                             A);
15870       B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
15871                             B);
15872       ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
15873       ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
15874     } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
15875       C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
15876                             C);
15877       D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
15878                             D);
15879       ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
15880       ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
15881     }
15882   }
15883 }
15884 
15885 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
15886   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
15887     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
15888 
15889   // Track whether the LHS or RHS is real at the type system level. When this is
15890   // the case we can simplify our evaluation strategy.
15891   bool LHSReal = false, RHSReal = false;
15892 
15893   bool LHSOK;
15894   if (E->getLHS()->getType()->isRealFloatingType()) {
15895     LHSReal = true;
15896     APFloat &Real = Result.FloatReal;
15897     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
15898     if (LHSOK) {
15899       Result.makeComplexFloat();
15900       Result.FloatImag = APFloat(Real.getSemantics());
15901     }
15902   } else {
15903     LHSOK = Visit(E->getLHS());
15904   }
15905   if (!LHSOK && !Info.noteFailure())
15906     return false;
15907 
15908   ComplexValue RHS;
15909   if (E->getRHS()->getType()->isRealFloatingType()) {
15910     RHSReal = true;
15911     APFloat &Real = RHS.FloatReal;
15912     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
15913       return false;
15914     RHS.makeComplexFloat();
15915     RHS.FloatImag = APFloat(Real.getSemantics());
15916   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
15917     return false;
15918 
15919   assert(!(LHSReal && RHSReal) &&
15920          "Cannot have both operands of a complex operation be real.");
15921   switch (E->getOpcode()) {
15922   default: return Error(E);
15923   case BO_Add:
15924     if (Result.isComplexFloat()) {
15925       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
15926                                        APFloat::rmNearestTiesToEven);
15927       if (LHSReal)
15928         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
15929       else if (!RHSReal)
15930         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
15931                                          APFloat::rmNearestTiesToEven);
15932     } else {
15933       Result.getComplexIntReal() += RHS.getComplexIntReal();
15934       Result.getComplexIntImag() += RHS.getComplexIntImag();
15935     }
15936     break;
15937   case BO_Sub:
15938     if (Result.isComplexFloat()) {
15939       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
15940                                             APFloat::rmNearestTiesToEven);
15941       if (LHSReal) {
15942         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
15943         Result.getComplexFloatImag().changeSign();
15944       } else if (!RHSReal) {
15945         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
15946                                               APFloat::rmNearestTiesToEven);
15947       }
15948     } else {
15949       Result.getComplexIntReal() -= RHS.getComplexIntReal();
15950       Result.getComplexIntImag() -= RHS.getComplexIntImag();
15951     }
15952     break;
15953   case BO_Mul:
15954     if (Result.isComplexFloat()) {
15955       // This is an implementation of complex multiplication according to the
15956       // constraints laid out in C11 Annex G. The implementation uses the
15957       // following naming scheme:
15958       //   (a + ib) * (c + id)
15959       ComplexValue LHS = Result;
15960       APFloat &A = LHS.getComplexFloatReal();
15961       APFloat &B = LHS.getComplexFloatImag();
15962       APFloat &C = RHS.getComplexFloatReal();
15963       APFloat &D = RHS.getComplexFloatImag();
15964       APFloat &ResR = Result.getComplexFloatReal();
15965       APFloat &ResI = Result.getComplexFloatImag();
15966       if (LHSReal) {
15967         assert(!RHSReal && "Cannot have two real operands for a complex op!");
15968         ResR = A;
15969         ResI = A;
15970         // ResR = A * C;
15971         // ResI = A * D;
15972         if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, C) ||
15973             !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, D))
15974           return false;
15975       } else if (RHSReal) {
15976         // ResR = C * A;
15977         // ResI = C * B;
15978         ResR = C;
15979         ResI = C;
15980         if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, A) ||
15981             !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, B))
15982           return false;
15983       } else {
15984         HandleComplexComplexMul(A, B, C, D, ResR, ResI);
15985       }
15986     } else {
15987       ComplexValue LHS = Result;
15988       Result.getComplexIntReal() =
15989         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
15990          LHS.getComplexIntImag() * RHS.getComplexIntImag());
15991       Result.getComplexIntImag() =
15992         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
15993          LHS.getComplexIntImag() * RHS.getComplexIntReal());
15994     }
15995     break;
15996   case BO_Div:
15997     if (Result.isComplexFloat()) {
15998       // This is an implementation of complex division according to the
15999       // constraints laid out in C11 Annex G. The implementation uses the
16000       // following naming scheme:
16001       //   (a + ib) / (c + id)
16002       ComplexValue LHS = Result;
16003       APFloat &A = LHS.getComplexFloatReal();
16004       APFloat &B = LHS.getComplexFloatImag();
16005       APFloat &C = RHS.getComplexFloatReal();
16006       APFloat &D = RHS.getComplexFloatImag();
16007       APFloat &ResR = Result.getComplexFloatReal();
16008       APFloat &ResI = Result.getComplexFloatImag();
16009       if (RHSReal) {
16010         ResR = A;
16011         ResI = B;
16012         // ResR = A / C;
16013         // ResI = B / C;
16014         if (!handleFloatFloatBinOp(Info, E, ResR, BO_Div, C) ||
16015             !handleFloatFloatBinOp(Info, E, ResI, BO_Div, C))
16016           return false;
16017       } else {
16018         if (LHSReal) {
16019           // No real optimizations we can do here, stub out with zero.
16020           B = APFloat::getZero(A.getSemantics());
16021         }
16022         HandleComplexComplexDiv(A, B, C, D, ResR, ResI);
16023       }
16024     } else {
16025       ComplexValue LHS = Result;
16026       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
16027         RHS.getComplexIntImag() * RHS.getComplexIntImag();
16028       if (Den.isZero())
16029         return Error(E, diag::note_expr_divide_by_zero);
16030 
16031       Result.getComplexIntReal() =
16032         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
16033          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
16034       Result.getComplexIntImag() =
16035         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
16036          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
16037     }
16038     break;
16039   }
16040 
16041   return true;
16042 }
16043 
16044 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
16045   // Get the operand value into 'Result'.
16046   if (!Visit(E->getSubExpr()))
16047     return false;
16048 
16049   switch (E->getOpcode()) {
16050   default:
16051     return Error(E);
16052   case UO_Extension:
16053     return true;
16054   case UO_Plus:
16055     // The result is always just the subexpr.
16056     return true;
16057   case UO_Minus:
16058     if (Result.isComplexFloat()) {
16059       Result.getComplexFloatReal().changeSign();
16060       Result.getComplexFloatImag().changeSign();
16061     }
16062     else {
16063       Result.getComplexIntReal() = -Result.getComplexIntReal();
16064       Result.getComplexIntImag() = -Result.getComplexIntImag();
16065     }
16066     return true;
16067   case UO_Not:
16068     if (Result.isComplexFloat())
16069       Result.getComplexFloatImag().changeSign();
16070     else
16071       Result.getComplexIntImag() = -Result.getComplexIntImag();
16072     return true;
16073   }
16074 }
16075 
16076 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
16077   if (E->getNumInits() == 2) {
16078     if (E->getType()->isComplexType()) {
16079       Result.makeComplexFloat();
16080       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
16081         return false;
16082       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
16083         return false;
16084     } else {
16085       Result.makeComplexInt();
16086       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
16087         return false;
16088       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
16089         return false;
16090     }
16091     return true;
16092   }
16093   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
16094 }
16095 
16096 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
16097   if (!IsConstantEvaluatedBuiltinCall(E))
16098     return ExprEvaluatorBaseTy::VisitCallExpr(E);
16099 
16100   switch (E->getBuiltinCallee()) {
16101   case Builtin::BI__builtin_complex:
16102     Result.makeComplexFloat();
16103     if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
16104       return false;
16105     if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
16106       return false;
16107     return true;
16108 
16109   default:
16110     return false;
16111   }
16112 }
16113 
16114 //===----------------------------------------------------------------------===//
16115 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
16116 // implicit conversion.
16117 //===----------------------------------------------------------------------===//
16118 
16119 namespace {
16120 class AtomicExprEvaluator :
16121     public ExprEvaluatorBase<AtomicExprEvaluator> {
16122   const LValue *This;
16123   APValue &Result;
16124 public:
16125   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
16126       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
16127 
16128   bool Success(const APValue &V, const Expr *E) {
16129     Result = V;
16130     return true;
16131   }
16132 
16133   bool ZeroInitialization(const Expr *E) {
16134     ImplicitValueInitExpr VIE(
16135         E->getType()->castAs<AtomicType>()->getValueType());
16136     // For atomic-qualified class (and array) types in C++, initialize the
16137     // _Atomic-wrapped subobject directly, in-place.
16138     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
16139                 : Evaluate(Result, Info, &VIE);
16140   }
16141 
16142   bool VisitCastExpr(const CastExpr *E) {
16143     switch (E->getCastKind()) {
16144     default:
16145       return ExprEvaluatorBaseTy::VisitCastExpr(E);
16146     case CK_NullToPointer:
16147       VisitIgnoredValue(E->getSubExpr());
16148       return ZeroInitialization(E);
16149     case CK_NonAtomicToAtomic:
16150       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
16151                   : Evaluate(Result, Info, E->getSubExpr());
16152     }
16153   }
16154 };
16155 } // end anonymous namespace
16156 
16157 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
16158                            EvalInfo &Info) {
16159   assert(!E->isValueDependent());
16160   assert(E->isPRValue() && E->getType()->isAtomicType());
16161   return AtomicExprEvaluator(Info, This, Result).Visit(E);
16162 }
16163 
16164 //===----------------------------------------------------------------------===//
16165 // Void expression evaluation, primarily for a cast to void on the LHS of a
16166 // comma operator
16167 //===----------------------------------------------------------------------===//
16168 
16169 namespace {
16170 class VoidExprEvaluator
16171   : public ExprEvaluatorBase<VoidExprEvaluator> {
16172 public:
16173   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
16174 
16175   bool Success(const APValue &V, const Expr *e) { return true; }
16176 
16177   bool ZeroInitialization(const Expr *E) { return true; }
16178 
16179   bool VisitCastExpr(const CastExpr *E) {
16180     switch (E->getCastKind()) {
16181     default:
16182       return ExprEvaluatorBaseTy::VisitCastExpr(E);
16183     case CK_ToVoid:
16184       VisitIgnoredValue(E->getSubExpr());
16185       return true;
16186     }
16187   }
16188 
16189   bool VisitCallExpr(const CallExpr *E) {
16190     if (!IsConstantEvaluatedBuiltinCall(E))
16191       return ExprEvaluatorBaseTy::VisitCallExpr(E);
16192 
16193     switch (E->getBuiltinCallee()) {
16194     case Builtin::BI__assume:
16195     case Builtin::BI__builtin_assume:
16196       // The argument is not evaluated!
16197       return true;
16198 
16199     case Builtin::BI__builtin_operator_delete:
16200       return HandleOperatorDeleteCall(Info, E);
16201 
16202     default:
16203       return false;
16204     }
16205   }
16206 
16207   bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
16208 };
16209 } // end anonymous namespace
16210 
16211 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
16212   // We cannot speculatively evaluate a delete expression.
16213   if (Info.SpeculativeEvaluationDepth)
16214     return false;
16215 
16216   FunctionDecl *OperatorDelete = E->getOperatorDelete();
16217   if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
16218     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
16219         << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
16220     return false;
16221   }
16222 
16223   const Expr *Arg = E->getArgument();
16224 
16225   LValue Pointer;
16226   if (!EvaluatePointer(Arg, Pointer, Info))
16227     return false;
16228   if (Pointer.Designator.Invalid)
16229     return false;
16230 
16231   // Deleting a null pointer has no effect.
16232   if (Pointer.isNullPointer()) {
16233     // This is the only case where we need to produce an extension warning:
16234     // the only other way we can succeed is if we find a dynamic allocation,
16235     // and we will have warned when we allocated it in that case.
16236     if (!Info.getLangOpts().CPlusPlus20)
16237       Info.CCEDiag(E, diag::note_constexpr_new);
16238     return true;
16239   }
16240 
16241   std::optional<DynAlloc *> Alloc = CheckDeleteKind(
16242       Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
16243   if (!Alloc)
16244     return false;
16245   QualType AllocType = Pointer.Base.getDynamicAllocType();
16246 
16247   // For the non-array case, the designator must be empty if the static type
16248   // does not have a virtual destructor.
16249   if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
16250       !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
16251     Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
16252         << Arg->getType()->getPointeeType() << AllocType;
16253     return false;
16254   }
16255 
16256   // For a class type with a virtual destructor, the selected operator delete
16257   // is the one looked up when building the destructor.
16258   if (!E->isArrayForm() && !E->isGlobalDelete()) {
16259     const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
16260     if (VirtualDelete &&
16261         !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
16262       Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
16263           << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
16264       return false;
16265     }
16266   }
16267 
16268   if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
16269                          (*Alloc)->Value, AllocType))
16270     return false;
16271 
16272   if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
16273     // The element was already erased. This means the destructor call also
16274     // deleted the object.
16275     // FIXME: This probably results in undefined behavior before we get this
16276     // far, and should be diagnosed elsewhere first.
16277     Info.FFDiag(E, diag::note_constexpr_double_delete);
16278     return false;
16279   }
16280 
16281   return true;
16282 }
16283 
16284 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
16285   assert(!E->isValueDependent());
16286   assert(E->isPRValue() && E->getType()->isVoidType());
16287   return VoidExprEvaluator(Info).Visit(E);
16288 }
16289 
16290 //===----------------------------------------------------------------------===//
16291 // Top level Expr::EvaluateAsRValue method.
16292 //===----------------------------------------------------------------------===//
16293 
16294 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
16295   assert(!E->isValueDependent());
16296   // In C, function designators are not lvalues, but we evaluate them as if they
16297   // are.
16298   QualType T = E->getType();
16299   if (E->isGLValue() || T->isFunctionType()) {
16300     LValue LV;
16301     if (!EvaluateLValue(E, LV, Info))
16302       return false;
16303     LV.moveInto(Result);
16304   } else if (T->isVectorType()) {
16305     if (!EvaluateVector(E, Result, Info))
16306       return false;
16307   } else if (T->isIntegralOrEnumerationType()) {
16308     if (!IntExprEvaluator(Info, Result).Visit(E))
16309       return false;
16310   } else if (T->hasPointerRepresentation()) {
16311     LValue LV;
16312     if (!EvaluatePointer(E, LV, Info))
16313       return false;
16314     LV.moveInto(Result);
16315   } else if (T->isRealFloatingType()) {
16316     llvm::APFloat F(0.0);
16317     if (!EvaluateFloat(E, F, Info))
16318       return false;
16319     Result = APValue(F);
16320   } else if (T->isAnyComplexType()) {
16321     ComplexValue C;
16322     if (!EvaluateComplex(E, C, Info))
16323       return false;
16324     C.moveInto(Result);
16325   } else if (T->isFixedPointType()) {
16326     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
16327   } else if (T->isMemberPointerType()) {
16328     MemberPtr P;
16329     if (!EvaluateMemberPointer(E, P, Info))
16330       return false;
16331     P.moveInto(Result);
16332     return true;
16333   } else if (T->isArrayType()) {
16334     LValue LV;
16335     APValue &Value =
16336         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
16337     if (!EvaluateArray(E, LV, Value, Info))
16338       return false;
16339     Result = Value;
16340   } else if (T->isRecordType()) {
16341     LValue LV;
16342     APValue &Value =
16343         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
16344     if (!EvaluateRecord(E, LV, Value, Info))
16345       return false;
16346     Result = Value;
16347   } else if (T->isVoidType()) {
16348     if (!Info.getLangOpts().CPlusPlus11)
16349       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
16350         << E->getType();
16351     if (!EvaluateVoid(E, Info))
16352       return false;
16353   } else if (T->isAtomicType()) {
16354     QualType Unqual = T.getAtomicUnqualifiedType();
16355     if (Unqual->isArrayType() || Unqual->isRecordType()) {
16356       LValue LV;
16357       APValue &Value = Info.CurrentCall->createTemporary(
16358           E, Unqual, ScopeKind::FullExpression, LV);
16359       if (!EvaluateAtomic(E, &LV, Value, Info))
16360         return false;
16361       Result = Value;
16362     } else {
16363       if (!EvaluateAtomic(E, nullptr, Result, Info))
16364         return false;
16365     }
16366   } else if (Info.getLangOpts().CPlusPlus11) {
16367     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
16368     return false;
16369   } else {
16370     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
16371     return false;
16372   }
16373 
16374   return true;
16375 }
16376 
16377 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
16378 /// cases, the in-place evaluation is essential, since later initializers for
16379 /// an object can indirectly refer to subobjects which were initialized earlier.
16380 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
16381                             const Expr *E, bool AllowNonLiteralTypes) {
16382   assert(!E->isValueDependent());
16383 
16384   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
16385     return false;
16386 
16387   if (E->isPRValue()) {
16388     // Evaluate arrays and record types in-place, so that later initializers can
16389     // refer to earlier-initialized members of the object.
16390     QualType T = E->getType();
16391     if (T->isArrayType())
16392       return EvaluateArray(E, This, Result, Info);
16393     else if (T->isRecordType())
16394       return EvaluateRecord(E, This, Result, Info);
16395     else if (T->isAtomicType()) {
16396       QualType Unqual = T.getAtomicUnqualifiedType();
16397       if (Unqual->isArrayType() || Unqual->isRecordType())
16398         return EvaluateAtomic(E, &This, Result, Info);
16399     }
16400   }
16401 
16402   // For any other type, in-place evaluation is unimportant.
16403   return Evaluate(Result, Info, E);
16404 }
16405 
16406 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
16407 /// lvalue-to-rvalue cast if it is an lvalue.
16408 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
16409   assert(!E->isValueDependent());
16410 
16411   if (E->getType().isNull())
16412     return false;
16413 
16414   if (!CheckLiteralType(Info, E))
16415     return false;
16416 
16417   if (Info.EnableNewConstInterp) {
16418     if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
16419       return false;
16420     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
16421                                    ConstantExprKind::Normal);
16422   }
16423 
16424   if (!::Evaluate(Result, Info, E))
16425     return false;
16426 
16427   // Implicit lvalue-to-rvalue cast.
16428   if (E->isGLValue()) {
16429     LValue LV;
16430     LV.setFrom(Info.Ctx, Result);
16431     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
16432       return false;
16433   }
16434 
16435   // Check this core constant expression is a constant expression.
16436   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
16437                                  ConstantExprKind::Normal) &&
16438          CheckMemoryLeaks(Info);
16439 }
16440 
16441 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
16442                                  const ASTContext &Ctx, bool &IsConst) {
16443   // Fast-path evaluations of integer literals, since we sometimes see files
16444   // containing vast quantities of these.
16445   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
16446     Result.Val = APValue(APSInt(L->getValue(),
16447                                 L->getType()->isUnsignedIntegerType()));
16448     IsConst = true;
16449     return true;
16450   }
16451 
16452   if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Exp)) {
16453     Result.Val = APValue(APSInt(APInt(1, L->getValue())));
16454     IsConst = true;
16455     return true;
16456   }
16457 
16458   if (const auto *CE = dyn_cast<ConstantExpr>(Exp)) {
16459     if (CE->hasAPValueResult()) {
16460       APValue APV = CE->getAPValueResult();
16461       if (!APV.isLValue()) {
16462         Result.Val = std::move(APV);
16463         IsConst = true;
16464         return true;
16465       }
16466     }
16467 
16468     // The SubExpr is usually just an IntegerLiteral.
16469     return FastEvaluateAsRValue(CE->getSubExpr(), Result, Ctx, IsConst);
16470   }
16471 
16472   // This case should be rare, but we need to check it before we check on
16473   // the type below.
16474   if (Exp->getType().isNull()) {
16475     IsConst = false;
16476     return true;
16477   }
16478 
16479   return false;
16480 }
16481 
16482 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
16483                                       Expr::SideEffectsKind SEK) {
16484   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
16485          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
16486 }
16487 
16488 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
16489                              const ASTContext &Ctx, EvalInfo &Info) {
16490   assert(!E->isValueDependent());
16491   bool IsConst;
16492   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
16493     return IsConst;
16494 
16495   return EvaluateAsRValue(Info, E, Result.Val);
16496 }
16497 
16498 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
16499                           const ASTContext &Ctx,
16500                           Expr::SideEffectsKind AllowSideEffects,
16501                           EvalInfo &Info) {
16502   assert(!E->isValueDependent());
16503   if (!E->getType()->isIntegralOrEnumerationType())
16504     return false;
16505 
16506   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
16507       !ExprResult.Val.isInt() ||
16508       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
16509     return false;
16510 
16511   return true;
16512 }
16513 
16514 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
16515                                  const ASTContext &Ctx,
16516                                  Expr::SideEffectsKind AllowSideEffects,
16517                                  EvalInfo &Info) {
16518   assert(!E->isValueDependent());
16519   if (!E->getType()->isFixedPointType())
16520     return false;
16521 
16522   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
16523     return false;
16524 
16525   if (!ExprResult.Val.isFixedPoint() ||
16526       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
16527     return false;
16528 
16529   return true;
16530 }
16531 
16532 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
16533 /// any crazy technique (that has nothing to do with language standards) that
16534 /// we want to.  If this function returns true, it returns the folded constant
16535 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
16536 /// will be applied to the result.
16537 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
16538                             bool InConstantContext) const {
16539   assert(!isValueDependent() &&
16540          "Expression evaluator can't be called on a dependent expression.");
16541   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue");
16542   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
16543   Info.InConstantContext = InConstantContext;
16544   return ::EvaluateAsRValue(this, Result, Ctx, Info);
16545 }
16546 
16547 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
16548                                       bool InConstantContext) const {
16549   assert(!isValueDependent() &&
16550          "Expression evaluator can't be called on a dependent expression.");
16551   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition");
16552   EvalResult Scratch;
16553   return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
16554          HandleConversionToBool(Scratch.Val, Result);
16555 }
16556 
16557 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
16558                          SideEffectsKind AllowSideEffects,
16559                          bool InConstantContext) const {
16560   assert(!isValueDependent() &&
16561          "Expression evaluator can't be called on a dependent expression.");
16562   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt");
16563   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
16564   Info.InConstantContext = InConstantContext;
16565   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
16566 }
16567 
16568 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
16569                                 SideEffectsKind AllowSideEffects,
16570                                 bool InConstantContext) const {
16571   assert(!isValueDependent() &&
16572          "Expression evaluator can't be called on a dependent expression.");
16573   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint");
16574   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
16575   Info.InConstantContext = InConstantContext;
16576   return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
16577 }
16578 
16579 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
16580                            SideEffectsKind AllowSideEffects,
16581                            bool InConstantContext) const {
16582   assert(!isValueDependent() &&
16583          "Expression evaluator can't be called on a dependent expression.");
16584 
16585   if (!getType()->isRealFloatingType())
16586     return false;
16587 
16588   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat");
16589   EvalResult ExprResult;
16590   if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
16591       !ExprResult.Val.isFloat() ||
16592       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
16593     return false;
16594 
16595   Result = ExprResult.Val.getFloat();
16596   return true;
16597 }
16598 
16599 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
16600                             bool InConstantContext) const {
16601   assert(!isValueDependent() &&
16602          "Expression evaluator can't be called on a dependent expression.");
16603 
16604   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue");
16605   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
16606   Info.InConstantContext = InConstantContext;
16607   LValue LV;
16608   CheckedTemporaries CheckedTemps;
16609   if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
16610       Result.HasSideEffects ||
16611       !CheckLValueConstantExpression(Info, getExprLoc(),
16612                                      Ctx.getLValueReferenceType(getType()), LV,
16613                                      ConstantExprKind::Normal, CheckedTemps))
16614     return false;
16615 
16616   LV.moveInto(Result.Val);
16617   return true;
16618 }
16619 
16620 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base,
16621                                 APValue DestroyedValue, QualType Type,
16622                                 SourceLocation Loc, Expr::EvalStatus &EStatus,
16623                                 bool IsConstantDestruction) {
16624   EvalInfo Info(Ctx, EStatus,
16625                 IsConstantDestruction ? EvalInfo::EM_ConstantExpression
16626                                       : EvalInfo::EM_ConstantFold);
16627   Info.setEvaluatingDecl(Base, DestroyedValue,
16628                          EvalInfo::EvaluatingDeclKind::Dtor);
16629   Info.InConstantContext = IsConstantDestruction;
16630 
16631   LValue LVal;
16632   LVal.set(Base);
16633 
16634   if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
16635       EStatus.HasSideEffects)
16636     return false;
16637 
16638   if (!Info.discardCleanups())
16639     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
16640 
16641   return true;
16642 }
16643 
16644 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx,
16645                                   ConstantExprKind Kind) const {
16646   assert(!isValueDependent() &&
16647          "Expression evaluator can't be called on a dependent expression.");
16648   bool IsConst;
16649   if (FastEvaluateAsRValue(this, Result, Ctx, IsConst) && Result.Val.hasValue())
16650     return true;
16651 
16652   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr");
16653   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
16654   EvalInfo Info(Ctx, Result, EM);
16655   Info.InConstantContext = true;
16656 
16657   if (Info.EnableNewConstInterp) {
16658     if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val, Kind))
16659       return false;
16660     return CheckConstantExpression(Info, getExprLoc(),
16661                                    getStorageType(Ctx, this), Result.Val, Kind);
16662   }
16663 
16664   // The type of the object we're initializing is 'const T' for a class NTTP.
16665   QualType T = getType();
16666   if (Kind == ConstantExprKind::ClassTemplateArgument)
16667     T.addConst();
16668 
16669   // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
16670   // represent the result of the evaluation. CheckConstantExpression ensures
16671   // this doesn't escape.
16672   MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
16673   APValue::LValueBase Base(&BaseMTE);
16674   Info.setEvaluatingDecl(Base, Result.Val);
16675 
16676   if (Info.EnableNewConstInterp) {
16677     if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, this, Result.Val))
16678       return false;
16679   } else {
16680     LValue LVal;
16681     LVal.set(Base);
16682     // C++23 [intro.execution]/p5
16683     // A full-expression is [...] a constant-expression
16684     // So we need to make sure temporary objects are destroyed after having
16685     // evaluating the expression (per C++23 [class.temporary]/p4).
16686     FullExpressionRAII Scope(Info);
16687     if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
16688         Result.HasSideEffects || !Scope.destroy())
16689       return false;
16690 
16691     if (!Info.discardCleanups())
16692       llvm_unreachable("Unhandled cleanup; missing full expression marker?");
16693   }
16694 
16695   if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
16696                                Result.Val, Kind))
16697     return false;
16698   if (!CheckMemoryLeaks(Info))
16699     return false;
16700 
16701   // If this is a class template argument, it's required to have constant
16702   // destruction too.
16703   if (Kind == ConstantExprKind::ClassTemplateArgument &&
16704       (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result,
16705                             true) ||
16706        Result.HasSideEffects)) {
16707     // FIXME: Prefix a note to indicate that the problem is lack of constant
16708     // destruction.
16709     return false;
16710   }
16711 
16712   return true;
16713 }
16714 
16715 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
16716                                  const VarDecl *VD,
16717                                  SmallVectorImpl<PartialDiagnosticAt> &Notes,
16718                                  bool IsConstantInitialization) const {
16719   assert(!isValueDependent() &&
16720          "Expression evaluator can't be called on a dependent expression.");
16721 
16722   llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] {
16723     std::string Name;
16724     llvm::raw_string_ostream OS(Name);
16725     VD->printQualifiedName(OS);
16726     return Name;
16727   });
16728 
16729   Expr::EvalStatus EStatus;
16730   EStatus.Diag = &Notes;
16731 
16732   EvalInfo Info(Ctx, EStatus,
16733                 (IsConstantInitialization &&
16734                  (Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23))
16735                     ? EvalInfo::EM_ConstantExpression
16736                     : EvalInfo::EM_ConstantFold);
16737   Info.setEvaluatingDecl(VD, Value);
16738   Info.InConstantContext = IsConstantInitialization;
16739 
16740   SourceLocation DeclLoc = VD->getLocation();
16741   QualType DeclTy = VD->getType();
16742 
16743   if (Info.EnableNewConstInterp) {
16744     auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
16745     if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
16746       return false;
16747 
16748     return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
16749                                    ConstantExprKind::Normal);
16750   } else {
16751     LValue LVal;
16752     LVal.set(VD);
16753 
16754     {
16755       // C++23 [intro.execution]/p5
16756       // A full-expression is ... an init-declarator ([dcl.decl]) or a
16757       // mem-initializer.
16758       // So we need to make sure temporary objects are destroyed after having
16759       // evaluated the expression (per C++23 [class.temporary]/p4).
16760       //
16761       // FIXME: Otherwise this may break test/Modules/pr68702.cpp because the
16762       // serialization code calls ParmVarDecl::getDefaultArg() which strips the
16763       // outermost FullExpr, such as ExprWithCleanups.
16764       FullExpressionRAII Scope(Info);
16765       if (!EvaluateInPlace(Value, Info, LVal, this,
16766                            /*AllowNonLiteralTypes=*/true) ||
16767           EStatus.HasSideEffects)
16768         return false;
16769     }
16770 
16771     // At this point, any lifetime-extended temporaries are completely
16772     // initialized.
16773     Info.performLifetimeExtension();
16774 
16775     if (!Info.discardCleanups())
16776       llvm_unreachable("Unhandled cleanup; missing full expression marker?");
16777   }
16778 
16779   return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
16780                                  ConstantExprKind::Normal) &&
16781          CheckMemoryLeaks(Info);
16782 }
16783 
16784 bool VarDecl::evaluateDestruction(
16785     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
16786   Expr::EvalStatus EStatus;
16787   EStatus.Diag = &Notes;
16788 
16789   // Only treat the destruction as constant destruction if we formally have
16790   // constant initialization (or are usable in a constant expression).
16791   bool IsConstantDestruction = hasConstantInitialization();
16792 
16793   // Make a copy of the value for the destructor to mutate, if we know it.
16794   // Otherwise, treat the value as default-initialized; if the destructor works
16795   // anyway, then the destruction is constant (and must be essentially empty).
16796   APValue DestroyedValue;
16797   if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
16798     DestroyedValue = *getEvaluatedValue();
16799   else if (!handleDefaultInitValue(getType(), DestroyedValue))
16800     return false;
16801 
16802   if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
16803                            getType(), getLocation(), EStatus,
16804                            IsConstantDestruction) ||
16805       EStatus.HasSideEffects)
16806     return false;
16807 
16808   ensureEvaluatedStmt()->HasConstantDestruction = true;
16809   return true;
16810 }
16811 
16812 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
16813 /// constant folded, but discard the result.
16814 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
16815   assert(!isValueDependent() &&
16816          "Expression evaluator can't be called on a dependent expression.");
16817 
16818   EvalResult Result;
16819   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
16820          !hasUnacceptableSideEffect(Result, SEK);
16821 }
16822 
16823 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
16824                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
16825   assert(!isValueDependent() &&
16826          "Expression evaluator can't be called on a dependent expression.");
16827 
16828   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt");
16829   EvalResult EVResult;
16830   EVResult.Diag = Diag;
16831   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
16832   Info.InConstantContext = true;
16833 
16834   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
16835   (void)Result;
16836   assert(Result && "Could not evaluate expression");
16837   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
16838 
16839   return EVResult.Val.getInt();
16840 }
16841 
16842 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
16843     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
16844   assert(!isValueDependent() &&
16845          "Expression evaluator can't be called on a dependent expression.");
16846 
16847   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow");
16848   EvalResult EVResult;
16849   EVResult.Diag = Diag;
16850   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
16851   Info.InConstantContext = true;
16852   Info.CheckingForUndefinedBehavior = true;
16853 
16854   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
16855   (void)Result;
16856   assert(Result && "Could not evaluate expression");
16857   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
16858 
16859   return EVResult.Val.getInt();
16860 }
16861 
16862 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
16863   assert(!isValueDependent() &&
16864          "Expression evaluator can't be called on a dependent expression.");
16865 
16866   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow");
16867   bool IsConst;
16868   EvalResult EVResult;
16869   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
16870     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
16871     Info.CheckingForUndefinedBehavior = true;
16872     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
16873   }
16874 }
16875 
16876 bool Expr::EvalResult::isGlobalLValue() const {
16877   assert(Val.isLValue());
16878   return IsGlobalLValue(Val.getLValueBase());
16879 }
16880 
16881 /// isIntegerConstantExpr - this recursive routine will test if an expression is
16882 /// an integer constant expression.
16883 
16884 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
16885 /// comma, etc
16886 
16887 // CheckICE - This function does the fundamental ICE checking: the returned
16888 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
16889 // and a (possibly null) SourceLocation indicating the location of the problem.
16890 //
16891 // Note that to reduce code duplication, this helper does no evaluation
16892 // itself; the caller checks whether the expression is evaluatable, and
16893 // in the rare cases where CheckICE actually cares about the evaluated
16894 // value, it calls into Evaluate.
16895 
16896 namespace {
16897 
16898 enum ICEKind {
16899   /// This expression is an ICE.
16900   IK_ICE,
16901   /// This expression is not an ICE, but if it isn't evaluated, it's
16902   /// a legal subexpression for an ICE. This return value is used to handle
16903   /// the comma operator in C99 mode, and non-constant subexpressions.
16904   IK_ICEIfUnevaluated,
16905   /// This expression is not an ICE, and is not a legal subexpression for one.
16906   IK_NotICE
16907 };
16908 
16909 struct ICEDiag {
16910   ICEKind Kind;
16911   SourceLocation Loc;
16912 
16913   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
16914 };
16915 
16916 }
16917 
16918 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
16919 
16920 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
16921 
16922 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
16923   Expr::EvalResult EVResult;
16924   Expr::EvalStatus Status;
16925   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
16926 
16927   Info.InConstantContext = true;
16928   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
16929       !EVResult.Val.isInt())
16930     return ICEDiag(IK_NotICE, E->getBeginLoc());
16931 
16932   return NoDiag();
16933 }
16934 
16935 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
16936   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
16937   if (!E->getType()->isIntegralOrEnumerationType())
16938     return ICEDiag(IK_NotICE, E->getBeginLoc());
16939 
16940   switch (E->getStmtClass()) {
16941 #define ABSTRACT_STMT(Node)
16942 #define STMT(Node, Base) case Expr::Node##Class:
16943 #define EXPR(Node, Base)
16944 #include "clang/AST/StmtNodes.inc"
16945   case Expr::PredefinedExprClass:
16946   case Expr::FloatingLiteralClass:
16947   case Expr::ImaginaryLiteralClass:
16948   case Expr::StringLiteralClass:
16949   case Expr::ArraySubscriptExprClass:
16950   case Expr::MatrixSubscriptExprClass:
16951   case Expr::ArraySectionExprClass:
16952   case Expr::OMPArrayShapingExprClass:
16953   case Expr::OMPIteratorExprClass:
16954   case Expr::MemberExprClass:
16955   case Expr::CompoundAssignOperatorClass:
16956   case Expr::CompoundLiteralExprClass:
16957   case Expr::ExtVectorElementExprClass:
16958   case Expr::DesignatedInitExprClass:
16959   case Expr::ArrayInitLoopExprClass:
16960   case Expr::ArrayInitIndexExprClass:
16961   case Expr::NoInitExprClass:
16962   case Expr::DesignatedInitUpdateExprClass:
16963   case Expr::ImplicitValueInitExprClass:
16964   case Expr::ParenListExprClass:
16965   case Expr::VAArgExprClass:
16966   case Expr::AddrLabelExprClass:
16967   case Expr::StmtExprClass:
16968   case Expr::CXXMemberCallExprClass:
16969   case Expr::CUDAKernelCallExprClass:
16970   case Expr::CXXAddrspaceCastExprClass:
16971   case Expr::CXXDynamicCastExprClass:
16972   case Expr::CXXTypeidExprClass:
16973   case Expr::CXXUuidofExprClass:
16974   case Expr::MSPropertyRefExprClass:
16975   case Expr::MSPropertySubscriptExprClass:
16976   case Expr::CXXNullPtrLiteralExprClass:
16977   case Expr::UserDefinedLiteralClass:
16978   case Expr::CXXThisExprClass:
16979   case Expr::CXXThrowExprClass:
16980   case Expr::CXXNewExprClass:
16981   case Expr::CXXDeleteExprClass:
16982   case Expr::CXXPseudoDestructorExprClass:
16983   case Expr::UnresolvedLookupExprClass:
16984   case Expr::TypoExprClass:
16985   case Expr::RecoveryExprClass:
16986   case Expr::DependentScopeDeclRefExprClass:
16987   case Expr::CXXConstructExprClass:
16988   case Expr::CXXInheritedCtorInitExprClass:
16989   case Expr::CXXStdInitializerListExprClass:
16990   case Expr::CXXBindTemporaryExprClass:
16991   case Expr::ExprWithCleanupsClass:
16992   case Expr::CXXTemporaryObjectExprClass:
16993   case Expr::CXXUnresolvedConstructExprClass:
16994   case Expr::CXXDependentScopeMemberExprClass:
16995   case Expr::UnresolvedMemberExprClass:
16996   case Expr::ObjCStringLiteralClass:
16997   case Expr::ObjCBoxedExprClass:
16998   case Expr::ObjCArrayLiteralClass:
16999   case Expr::ObjCDictionaryLiteralClass:
17000   case Expr::ObjCEncodeExprClass:
17001   case Expr::ObjCMessageExprClass:
17002   case Expr::ObjCSelectorExprClass:
17003   case Expr::ObjCProtocolExprClass:
17004   case Expr::ObjCIvarRefExprClass:
17005   case Expr::ObjCPropertyRefExprClass:
17006   case Expr::ObjCSubscriptRefExprClass:
17007   case Expr::ObjCIsaExprClass:
17008   case Expr::ObjCAvailabilityCheckExprClass:
17009   case Expr::ShuffleVectorExprClass:
17010   case Expr::ConvertVectorExprClass:
17011   case Expr::BlockExprClass:
17012   case Expr::NoStmtClass:
17013   case Expr::OpaqueValueExprClass:
17014   case Expr::PackExpansionExprClass:
17015   case Expr::SubstNonTypeTemplateParmPackExprClass:
17016   case Expr::FunctionParmPackExprClass:
17017   case Expr::AsTypeExprClass:
17018   case Expr::ObjCIndirectCopyRestoreExprClass:
17019   case Expr::MaterializeTemporaryExprClass:
17020   case Expr::PseudoObjectExprClass:
17021   case Expr::AtomicExprClass:
17022   case Expr::LambdaExprClass:
17023   case Expr::CXXFoldExprClass:
17024   case Expr::CoawaitExprClass:
17025   case Expr::DependentCoawaitExprClass:
17026   case Expr::CoyieldExprClass:
17027   case Expr::SYCLUniqueStableNameExprClass:
17028   case Expr::CXXParenListInitExprClass:
17029   case Expr::HLSLOutArgExprClass:
17030     return ICEDiag(IK_NotICE, E->getBeginLoc());
17031 
17032   case Expr::InitListExprClass: {
17033     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
17034     // form "T x = { a };" is equivalent to "T x = a;".
17035     // Unless we're initializing a reference, T is a scalar as it is known to be
17036     // of integral or enumeration type.
17037     if (E->isPRValue())
17038       if (cast<InitListExpr>(E)->getNumInits() == 1)
17039         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
17040     return ICEDiag(IK_NotICE, E->getBeginLoc());
17041   }
17042 
17043   case Expr::SizeOfPackExprClass:
17044   case Expr::GNUNullExprClass:
17045   case Expr::SourceLocExprClass:
17046   case Expr::EmbedExprClass:
17047   case Expr::OpenACCAsteriskSizeExprClass:
17048     return NoDiag();
17049 
17050   case Expr::PackIndexingExprClass:
17051     return CheckICE(cast<PackIndexingExpr>(E)->getSelectedExpr(), Ctx);
17052 
17053   case Expr::SubstNonTypeTemplateParmExprClass:
17054     return
17055       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
17056 
17057   case Expr::ConstantExprClass:
17058     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
17059 
17060   case Expr::ParenExprClass:
17061     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
17062   case Expr::GenericSelectionExprClass:
17063     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
17064   case Expr::IntegerLiteralClass:
17065   case Expr::FixedPointLiteralClass:
17066   case Expr::CharacterLiteralClass:
17067   case Expr::ObjCBoolLiteralExprClass:
17068   case Expr::CXXBoolLiteralExprClass:
17069   case Expr::CXXScalarValueInitExprClass:
17070   case Expr::TypeTraitExprClass:
17071   case Expr::ConceptSpecializationExprClass:
17072   case Expr::RequiresExprClass:
17073   case Expr::ArrayTypeTraitExprClass:
17074   case Expr::ExpressionTraitExprClass:
17075   case Expr::CXXNoexceptExprClass:
17076     return NoDiag();
17077   case Expr::CallExprClass:
17078   case Expr::CXXOperatorCallExprClass: {
17079     // C99 6.6/3 allows function calls within unevaluated subexpressions of
17080     // constant expressions, but they can never be ICEs because an ICE cannot
17081     // contain an operand of (pointer to) function type.
17082     const CallExpr *CE = cast<CallExpr>(E);
17083     if (CE->getBuiltinCallee())
17084       return CheckEvalInICE(E, Ctx);
17085     return ICEDiag(IK_NotICE, E->getBeginLoc());
17086   }
17087   case Expr::CXXRewrittenBinaryOperatorClass:
17088     return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
17089                     Ctx);
17090   case Expr::DeclRefExprClass: {
17091     const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
17092     if (isa<EnumConstantDecl>(D))
17093       return NoDiag();
17094 
17095     // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
17096     // integer variables in constant expressions:
17097     //
17098     // C++ 7.1.5.1p2
17099     //   A variable of non-volatile const-qualified integral or enumeration
17100     //   type initialized by an ICE can be used in ICEs.
17101     //
17102     // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
17103     // that mode, use of reference variables should not be allowed.
17104     const VarDecl *VD = dyn_cast<VarDecl>(D);
17105     if (VD && VD->isUsableInConstantExpressions(Ctx) &&
17106         !VD->getType()->isReferenceType())
17107       return NoDiag();
17108 
17109     return ICEDiag(IK_NotICE, E->getBeginLoc());
17110   }
17111   case Expr::UnaryOperatorClass: {
17112     const UnaryOperator *Exp = cast<UnaryOperator>(E);
17113     switch (Exp->getOpcode()) {
17114     case UO_PostInc:
17115     case UO_PostDec:
17116     case UO_PreInc:
17117     case UO_PreDec:
17118     case UO_AddrOf:
17119     case UO_Deref:
17120     case UO_Coawait:
17121       // C99 6.6/3 allows increment and decrement within unevaluated
17122       // subexpressions of constant expressions, but they can never be ICEs
17123       // because an ICE cannot contain an lvalue operand.
17124       return ICEDiag(IK_NotICE, E->getBeginLoc());
17125     case UO_Extension:
17126     case UO_LNot:
17127     case UO_Plus:
17128     case UO_Minus:
17129     case UO_Not:
17130     case UO_Real:
17131     case UO_Imag:
17132       return CheckICE(Exp->getSubExpr(), Ctx);
17133     }
17134     llvm_unreachable("invalid unary operator class");
17135   }
17136   case Expr::OffsetOfExprClass: {
17137     // Note that per C99, offsetof must be an ICE. And AFAIK, using
17138     // EvaluateAsRValue matches the proposed gcc behavior for cases like
17139     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
17140     // compliance: we should warn earlier for offsetof expressions with
17141     // array subscripts that aren't ICEs, and if the array subscripts
17142     // are ICEs, the value of the offsetof must be an integer constant.
17143     return CheckEvalInICE(E, Ctx);
17144   }
17145   case Expr::UnaryExprOrTypeTraitExprClass: {
17146     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
17147     if ((Exp->getKind() ==  UETT_SizeOf) &&
17148         Exp->getTypeOfArgument()->isVariableArrayType())
17149       return ICEDiag(IK_NotICE, E->getBeginLoc());
17150     return NoDiag();
17151   }
17152   case Expr::BinaryOperatorClass: {
17153     const BinaryOperator *Exp = cast<BinaryOperator>(E);
17154     switch (Exp->getOpcode()) {
17155     case BO_PtrMemD:
17156     case BO_PtrMemI:
17157     case BO_Assign:
17158     case BO_MulAssign:
17159     case BO_DivAssign:
17160     case BO_RemAssign:
17161     case BO_AddAssign:
17162     case BO_SubAssign:
17163     case BO_ShlAssign:
17164     case BO_ShrAssign:
17165     case BO_AndAssign:
17166     case BO_XorAssign:
17167     case BO_OrAssign:
17168       // C99 6.6/3 allows assignments within unevaluated subexpressions of
17169       // constant expressions, but they can never be ICEs because an ICE cannot
17170       // contain an lvalue operand.
17171       return ICEDiag(IK_NotICE, E->getBeginLoc());
17172 
17173     case BO_Mul:
17174     case BO_Div:
17175     case BO_Rem:
17176     case BO_Add:
17177     case BO_Sub:
17178     case BO_Shl:
17179     case BO_Shr:
17180     case BO_LT:
17181     case BO_GT:
17182     case BO_LE:
17183     case BO_GE:
17184     case BO_EQ:
17185     case BO_NE:
17186     case BO_And:
17187     case BO_Xor:
17188     case BO_Or:
17189     case BO_Comma:
17190     case BO_Cmp: {
17191       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
17192       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
17193       if (Exp->getOpcode() == BO_Div ||
17194           Exp->getOpcode() == BO_Rem) {
17195         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
17196         // we don't evaluate one.
17197         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
17198           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
17199           if (REval == 0)
17200             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
17201           if (REval.isSigned() && REval.isAllOnes()) {
17202             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
17203             if (LEval.isMinSignedValue())
17204               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
17205           }
17206         }
17207       }
17208       if (Exp->getOpcode() == BO_Comma) {
17209         if (Ctx.getLangOpts().C99) {
17210           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
17211           // if it isn't evaluated.
17212           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
17213             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
17214         } else {
17215           // In both C89 and C++, commas in ICEs are illegal.
17216           return ICEDiag(IK_NotICE, E->getBeginLoc());
17217         }
17218       }
17219       return Worst(LHSResult, RHSResult);
17220     }
17221     case BO_LAnd:
17222     case BO_LOr: {
17223       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
17224       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
17225       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
17226         // Rare case where the RHS has a comma "side-effect"; we need
17227         // to actually check the condition to see whether the side
17228         // with the comma is evaluated.
17229         if ((Exp->getOpcode() == BO_LAnd) !=
17230             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
17231           return RHSResult;
17232         return NoDiag();
17233       }
17234 
17235       return Worst(LHSResult, RHSResult);
17236     }
17237     }
17238     llvm_unreachable("invalid binary operator kind");
17239   }
17240   case Expr::ImplicitCastExprClass:
17241   case Expr::CStyleCastExprClass:
17242   case Expr::CXXFunctionalCastExprClass:
17243   case Expr::CXXStaticCastExprClass:
17244   case Expr::CXXReinterpretCastExprClass:
17245   case Expr::CXXConstCastExprClass:
17246   case Expr::ObjCBridgedCastExprClass: {
17247     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
17248     if (isa<ExplicitCastExpr>(E)) {
17249       if (const FloatingLiteral *FL
17250             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
17251         unsigned DestWidth = Ctx.getIntWidth(E->getType());
17252         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
17253         APSInt IgnoredVal(DestWidth, !DestSigned);
17254         bool Ignored;
17255         // If the value does not fit in the destination type, the behavior is
17256         // undefined, so we are not required to treat it as a constant
17257         // expression.
17258         if (FL->getValue().convertToInteger(IgnoredVal,
17259                                             llvm::APFloat::rmTowardZero,
17260                                             &Ignored) & APFloat::opInvalidOp)
17261           return ICEDiag(IK_NotICE, E->getBeginLoc());
17262         return NoDiag();
17263       }
17264     }
17265     switch (cast<CastExpr>(E)->getCastKind()) {
17266     case CK_LValueToRValue:
17267     case CK_AtomicToNonAtomic:
17268     case CK_NonAtomicToAtomic:
17269     case CK_NoOp:
17270     case CK_IntegralToBoolean:
17271     case CK_IntegralCast:
17272       return CheckICE(SubExpr, Ctx);
17273     default:
17274       return ICEDiag(IK_NotICE, E->getBeginLoc());
17275     }
17276   }
17277   case Expr::BinaryConditionalOperatorClass: {
17278     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
17279     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
17280     if (CommonResult.Kind == IK_NotICE) return CommonResult;
17281     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
17282     if (FalseResult.Kind == IK_NotICE) return FalseResult;
17283     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
17284     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
17285         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
17286     return FalseResult;
17287   }
17288   case Expr::ConditionalOperatorClass: {
17289     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
17290     // If the condition (ignoring parens) is a __builtin_constant_p call,
17291     // then only the true side is actually considered in an integer constant
17292     // expression, and it is fully evaluated.  This is an important GNU
17293     // extension.  See GCC PR38377 for discussion.
17294     if (const CallExpr *CallCE
17295         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
17296       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
17297         return CheckEvalInICE(E, Ctx);
17298     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
17299     if (CondResult.Kind == IK_NotICE)
17300       return CondResult;
17301 
17302     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
17303     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
17304 
17305     if (TrueResult.Kind == IK_NotICE)
17306       return TrueResult;
17307     if (FalseResult.Kind == IK_NotICE)
17308       return FalseResult;
17309     if (CondResult.Kind == IK_ICEIfUnevaluated)
17310       return CondResult;
17311     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
17312       return NoDiag();
17313     // Rare case where the diagnostics depend on which side is evaluated
17314     // Note that if we get here, CondResult is 0, and at least one of
17315     // TrueResult and FalseResult is non-zero.
17316     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
17317       return FalseResult;
17318     return TrueResult;
17319   }
17320   case Expr::CXXDefaultArgExprClass:
17321     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
17322   case Expr::CXXDefaultInitExprClass:
17323     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
17324   case Expr::ChooseExprClass: {
17325     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
17326   }
17327   case Expr::BuiltinBitCastExprClass: {
17328     if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
17329       return ICEDiag(IK_NotICE, E->getBeginLoc());
17330     return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
17331   }
17332   }
17333 
17334   llvm_unreachable("Invalid StmtClass!");
17335 }
17336 
17337 /// Evaluate an expression as a C++11 integral constant expression.
17338 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
17339                                                     const Expr *E,
17340                                                     llvm::APSInt *Value,
17341                                                     SourceLocation *Loc) {
17342   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
17343     if (Loc) *Loc = E->getExprLoc();
17344     return false;
17345   }
17346 
17347   APValue Result;
17348   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
17349     return false;
17350 
17351   if (!Result.isInt()) {
17352     if (Loc) *Loc = E->getExprLoc();
17353     return false;
17354   }
17355 
17356   if (Value) *Value = Result.getInt();
17357   return true;
17358 }
17359 
17360 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
17361                                  SourceLocation *Loc) const {
17362   assert(!isValueDependent() &&
17363          "Expression evaluator can't be called on a dependent expression.");
17364 
17365   ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr");
17366 
17367   if (Ctx.getLangOpts().CPlusPlus11)
17368     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
17369 
17370   ICEDiag D = CheckICE(this, Ctx);
17371   if (D.Kind != IK_ICE) {
17372     if (Loc) *Loc = D.Loc;
17373     return false;
17374   }
17375   return true;
17376 }
17377 
17378 std::optional<llvm::APSInt>
17379 Expr::getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc) const {
17380   if (isValueDependent()) {
17381     // Expression evaluator can't succeed on a dependent expression.
17382     return std::nullopt;
17383   }
17384 
17385   APSInt Value;
17386 
17387   if (Ctx.getLangOpts().CPlusPlus11) {
17388     if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc))
17389       return Value;
17390     return std::nullopt;
17391   }
17392 
17393   if (!isIntegerConstantExpr(Ctx, Loc))
17394     return std::nullopt;
17395 
17396   // The only possible side-effects here are due to UB discovered in the
17397   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
17398   // required to treat the expression as an ICE, so we produce the folded
17399   // value.
17400   EvalResult ExprResult;
17401   Expr::EvalStatus Status;
17402   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
17403   Info.InConstantContext = true;
17404 
17405   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
17406     llvm_unreachable("ICE cannot be evaluated!");
17407 
17408   return ExprResult.Val.getInt();
17409 }
17410 
17411 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
17412   assert(!isValueDependent() &&
17413          "Expression evaluator can't be called on a dependent expression.");
17414 
17415   return CheckICE(this, Ctx).Kind == IK_ICE;
17416 }
17417 
17418 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
17419                                SourceLocation *Loc) const {
17420   assert(!isValueDependent() &&
17421          "Expression evaluator can't be called on a dependent expression.");
17422 
17423   // We support this checking in C++98 mode in order to diagnose compatibility
17424   // issues.
17425   assert(Ctx.getLangOpts().CPlusPlus);
17426 
17427   // Build evaluation settings.
17428   Expr::EvalStatus Status;
17429   SmallVector<PartialDiagnosticAt, 8> Diags;
17430   Status.Diag = &Diags;
17431   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
17432 
17433   APValue Scratch;
17434   bool IsConstExpr =
17435       ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
17436       // FIXME: We don't produce a diagnostic for this, but the callers that
17437       // call us on arbitrary full-expressions should generally not care.
17438       Info.discardCleanups() && !Status.HasSideEffects;
17439 
17440   if (!Diags.empty()) {
17441     IsConstExpr = false;
17442     if (Loc) *Loc = Diags[0].first;
17443   } else if (!IsConstExpr) {
17444     // FIXME: This shouldn't happen.
17445     if (Loc) *Loc = getExprLoc();
17446   }
17447 
17448   return IsConstExpr;
17449 }
17450 
17451 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
17452                                     const FunctionDecl *Callee,
17453                                     ArrayRef<const Expr*> Args,
17454                                     const Expr *This) const {
17455   assert(!isValueDependent() &&
17456          "Expression evaluator can't be called on a dependent expression.");
17457 
17458   llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] {
17459     std::string Name;
17460     llvm::raw_string_ostream OS(Name);
17461     Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(),
17462                                  /*Qualified=*/true);
17463     return Name;
17464   });
17465 
17466   Expr::EvalStatus Status;
17467   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
17468   Info.InConstantContext = true;
17469 
17470   LValue ThisVal;
17471   const LValue *ThisPtr = nullptr;
17472   if (This) {
17473 #ifndef NDEBUG
17474     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
17475     assert(MD && "Don't provide `this` for non-methods.");
17476     assert(MD->isImplicitObjectMemberFunction() &&
17477            "Don't provide `this` for methods without an implicit object.");
17478 #endif
17479     if (!This->isValueDependent() &&
17480         EvaluateObjectArgument(Info, This, ThisVal) &&
17481         !Info.EvalStatus.HasSideEffects)
17482       ThisPtr = &ThisVal;
17483 
17484     // Ignore any side-effects from a failed evaluation. This is safe because
17485     // they can't interfere with any other argument evaluation.
17486     Info.EvalStatus.HasSideEffects = false;
17487   }
17488 
17489   CallRef Call = Info.CurrentCall->createCall(Callee);
17490   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
17491        I != E; ++I) {
17492     unsigned Idx = I - Args.begin();
17493     if (Idx >= Callee->getNumParams())
17494       break;
17495     const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
17496     if ((*I)->isValueDependent() ||
17497         !EvaluateCallArg(PVD, *I, Call, Info) ||
17498         Info.EvalStatus.HasSideEffects) {
17499       // If evaluation fails, throw away the argument entirely.
17500       if (APValue *Slot = Info.getParamSlot(Call, PVD))
17501         *Slot = APValue();
17502     }
17503 
17504     // Ignore any side-effects from a failed evaluation. This is safe because
17505     // they can't interfere with any other argument evaluation.
17506     Info.EvalStatus.HasSideEffects = false;
17507   }
17508 
17509   // Parameter cleanups happen in the caller and are not part of this
17510   // evaluation.
17511   Info.discardCleanups();
17512   Info.EvalStatus.HasSideEffects = false;
17513 
17514   // Build fake call to Callee.
17515   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, This,
17516                        Call);
17517   // FIXME: Missing ExprWithCleanups in enable_if conditions?
17518   FullExpressionRAII Scope(Info);
17519   return Evaluate(Value, Info, this) && Scope.destroy() &&
17520          !Info.EvalStatus.HasSideEffects;
17521 }
17522 
17523 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
17524                                    SmallVectorImpl<
17525                                      PartialDiagnosticAt> &Diags) {
17526   // FIXME: It would be useful to check constexpr function templates, but at the
17527   // moment the constant expression evaluator cannot cope with the non-rigorous
17528   // ASTs which we build for dependent expressions.
17529   if (FD->isDependentContext())
17530     return true;
17531 
17532   llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] {
17533     std::string Name;
17534     llvm::raw_string_ostream OS(Name);
17535     FD->getNameForDiagnostic(OS, FD->getASTContext().getPrintingPolicy(),
17536                              /*Qualified=*/true);
17537     return Name;
17538   });
17539 
17540   Expr::EvalStatus Status;
17541   Status.Diag = &Diags;
17542 
17543   EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
17544   Info.InConstantContext = true;
17545   Info.CheckingPotentialConstantExpression = true;
17546 
17547   // The constexpr VM attempts to compile all methods to bytecode here.
17548   if (Info.EnableNewConstInterp) {
17549     Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
17550     return Diags.empty();
17551   }
17552 
17553   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
17554   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
17555 
17556   // Fabricate an arbitrary expression on the stack and pretend that it
17557   // is a temporary being used as the 'this' pointer.
17558   LValue This;
17559   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
17560   This.set({&VIE, Info.CurrentCall->Index});
17561 
17562   ArrayRef<const Expr*> Args;
17563 
17564   APValue Scratch;
17565   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
17566     // Evaluate the call as a constant initializer, to allow the construction
17567     // of objects of non-literal types.
17568     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
17569     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
17570   } else {
17571     SourceLocation Loc = FD->getLocation();
17572     HandleFunctionCall(
17573         Loc, FD, (MD && MD->isImplicitObjectMemberFunction()) ? &This : nullptr,
17574         &VIE, Args, CallRef(), FD->getBody(), Info, Scratch,
17575         /*ResultSlot=*/nullptr);
17576   }
17577 
17578   return Diags.empty();
17579 }
17580 
17581 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
17582                                               const FunctionDecl *FD,
17583                                               SmallVectorImpl<
17584                                                 PartialDiagnosticAt> &Diags) {
17585   assert(!E->isValueDependent() &&
17586          "Expression evaluator can't be called on a dependent expression.");
17587 
17588   Expr::EvalStatus Status;
17589   Status.Diag = &Diags;
17590 
17591   EvalInfo Info(FD->getASTContext(), Status,
17592                 EvalInfo::EM_ConstantExpressionUnevaluated);
17593   Info.InConstantContext = true;
17594   Info.CheckingPotentialConstantExpression = true;
17595 
17596   // Fabricate a call stack frame to give the arguments a plausible cover story.
17597   CallStackFrame Frame(Info, SourceLocation(), FD, /*This=*/nullptr,
17598                        /*CallExpr=*/nullptr, CallRef());
17599 
17600   APValue ResultScratch;
17601   Evaluate(ResultScratch, Info, E);
17602   return Diags.empty();
17603 }
17604 
17605 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
17606                                  unsigned Type) const {
17607   if (!getType()->isPointerType())
17608     return false;
17609 
17610   Expr::EvalStatus Status;
17611   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
17612   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
17613 }
17614 
17615 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
17616                                   EvalInfo &Info, std::string *StringResult) {
17617   if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
17618     return false;
17619 
17620   LValue String;
17621 
17622   if (!EvaluatePointer(E, String, Info))
17623     return false;
17624 
17625   QualType CharTy = E->getType()->getPointeeType();
17626 
17627   // Fast path: if it's a string literal, search the string value.
17628   if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
17629           String.getLValueBase().dyn_cast<const Expr *>())) {
17630     StringRef Str = S->getBytes();
17631     int64_t Off = String.Offset.getQuantity();
17632     if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
17633         S->getCharByteWidth() == 1 &&
17634         // FIXME: Add fast-path for wchar_t too.
17635         Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
17636       Str = Str.substr(Off);
17637 
17638       StringRef::size_type Pos = Str.find(0);
17639       if (Pos != StringRef::npos)
17640         Str = Str.substr(0, Pos);
17641 
17642       Result = Str.size();
17643       if (StringResult)
17644         *StringResult = Str;
17645       return true;
17646     }
17647 
17648     // Fall through to slow path.
17649   }
17650 
17651   // Slow path: scan the bytes of the string looking for the terminating 0.
17652   for (uint64_t Strlen = 0; /**/; ++Strlen) {
17653     APValue Char;
17654     if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
17655         !Char.isInt())
17656       return false;
17657     if (!Char.getInt()) {
17658       Result = Strlen;
17659       return true;
17660     } else if (StringResult)
17661       StringResult->push_back(Char.getInt().getExtValue());
17662     if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
17663       return false;
17664   }
17665 }
17666 
17667 std::optional<std::string> Expr::tryEvaluateString(ASTContext &Ctx) const {
17668   Expr::EvalStatus Status;
17669   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
17670   uint64_t Result;
17671   std::string StringResult;
17672 
17673   if (EvaluateBuiltinStrLen(this, Result, Info, &StringResult))
17674     return StringResult;
17675   return {};
17676 }
17677 
17678 bool Expr::EvaluateCharRangeAsString(std::string &Result,
17679                                      const Expr *SizeExpression,
17680                                      const Expr *PtrExpression, ASTContext &Ctx,
17681                                      EvalResult &Status) const {
17682   LValue String;
17683   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
17684   Info.InConstantContext = true;
17685 
17686   FullExpressionRAII Scope(Info);
17687   APSInt SizeValue;
17688   if (!::EvaluateInteger(SizeExpression, SizeValue, Info))
17689     return false;
17690 
17691   uint64_t Size = SizeValue.getZExtValue();
17692 
17693   if (!::EvaluatePointer(PtrExpression, String, Info))
17694     return false;
17695 
17696   QualType CharTy = PtrExpression->getType()->getPointeeType();
17697   for (uint64_t I = 0; I < Size; ++I) {
17698     APValue Char;
17699     if (!handleLValueToRValueConversion(Info, PtrExpression, CharTy, String,
17700                                         Char))
17701       return false;
17702 
17703     APSInt C = Char.getInt();
17704     Result.push_back(static_cast<char>(C.getExtValue()));
17705     if (!HandleLValueArrayAdjustment(Info, PtrExpression, String, CharTy, 1))
17706       return false;
17707   }
17708   if (!Scope.destroy())
17709     return false;
17710 
17711   if (!CheckMemoryLeaks(Info))
17712     return false;
17713 
17714   return true;
17715 }
17716 
17717 bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
17718   Expr::EvalStatus Status;
17719   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
17720   return EvaluateBuiltinStrLen(this, Result, Info);
17721 }
17722 
17723 namespace {
17724 struct IsWithinLifetimeHandler {
17725   EvalInfo &Info;
17726   static constexpr AccessKinds AccessKind = AccessKinds::AK_IsWithinLifetime;
17727   using result_type = std::optional<bool>;
17728   std::optional<bool> failed() { return std::nullopt; }
17729   template <typename T>
17730   std::optional<bool> found(T &Subobj, QualType SubobjType) {
17731     return true;
17732   }
17733 };
17734 
17735 std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &IEE,
17736                                                     const CallExpr *E) {
17737   EvalInfo &Info = IEE.Info;
17738   // Sometimes this is called during some sorts of constant folding / early
17739   // evaluation. These are meant for non-constant expressions and are not
17740   // necessary since this consteval builtin will never be evaluated at runtime.
17741   // Just fail to evaluate when not in a constant context.
17742   if (!Info.InConstantContext)
17743     return std::nullopt;
17744   assert(E->getBuiltinCallee() == Builtin::BI__builtin_is_within_lifetime);
17745   const Expr *Arg = E->getArg(0);
17746   if (Arg->isValueDependent())
17747     return std::nullopt;
17748   LValue Val;
17749   if (!EvaluatePointer(Arg, Val, Info))
17750     return std::nullopt;
17751 
17752   auto Error = [&](int Diag) {
17753     bool CalledFromStd = false;
17754     const auto *Callee = Info.CurrentCall->getCallee();
17755     if (Callee && Callee->isInStdNamespace()) {
17756       const IdentifierInfo *Identifier = Callee->getIdentifier();
17757       CalledFromStd = Identifier && Identifier->isStr("is_within_lifetime");
17758     }
17759     Info.CCEDiag(CalledFromStd ? Info.CurrentCall->getCallRange().getBegin()
17760                                : E->getExprLoc(),
17761                  diag::err_invalid_is_within_lifetime)
17762         << (CalledFromStd ? "std::is_within_lifetime"
17763                           : "__builtin_is_within_lifetime")
17764         << Diag;
17765     return std::nullopt;
17766   };
17767   // C++2c [meta.const.eval]p4:
17768   //   During the evaluation of an expression E as a core constant expression, a
17769   //   call to this function is ill-formed unless p points to an object that is
17770   //   usable in constant expressions or whose complete object's lifetime began
17771   //   within E.
17772 
17773   // Make sure it points to an object
17774   // nullptr does not point to an object
17775   if (Val.isNullPointer() || Val.getLValueBase().isNull())
17776     return Error(0);
17777   QualType T = Val.getLValueBase().getType();
17778   assert(!T->isFunctionType() &&
17779          "Pointers to functions should have been typed as function pointers "
17780          "which would have been rejected earlier");
17781   assert(T->isObjectType());
17782   // Hypothetical array element is not an object
17783   if (Val.getLValueDesignator().isOnePastTheEnd())
17784     return Error(1);
17785   assert(Val.getLValueDesignator().isValidSubobject() &&
17786          "Unchecked case for valid subobject");
17787   // All other ill-formed values should have failed EvaluatePointer, so the
17788   // object should be a pointer to an object that is usable in a constant
17789   // expression or whose complete lifetime began within the expression
17790   CompleteObject CO =
17791       findCompleteObject(Info, E, AccessKinds::AK_IsWithinLifetime, Val, T);
17792   // The lifetime hasn't begun yet if we are still evaluating the
17793   // initializer ([basic.life]p(1.2))
17794   if (Info.EvaluatingDeclValue && CO.Value == Info.EvaluatingDeclValue)
17795     return Error(2);
17796 
17797   if (!CO)
17798     return false;
17799   IsWithinLifetimeHandler handler{Info};
17800   return findSubobject(Info, E, CO, Val.getLValueDesignator(), handler);
17801 }
17802 } // namespace
17803