1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Expr constant evaluator.
10 //
11 // Constant expression evaluation produces four main results:
12 //
13 //  * A success/failure flag indicating whether constant folding was successful.
14 //    This is the 'bool' return value used by most of the code in this file. A
15 //    'false' return value indicates that constant folding has failed, and any
16 //    appropriate diagnostic has already been produced.
17 //
18 //  * An evaluated result, valid only if constant folding has not failed.
19 //
20 //  * A flag indicating if evaluation encountered (unevaluated) side-effects.
21 //    These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
22 //    where it is possible to determine the evaluated result regardless.
23 //
24 //  * A set of notes indicating why the evaluation was not a constant expression
25 //    (under the C++11 / C++1y rules only, at the moment), or, if folding failed
26 //    too, why the expression could not be folded.
27 //
28 // If we are checking for a potential constant expression, failure to constant
29 // fold a potential constant sub-expression will be indicated by a 'false'
30 // return value (the expression could not be folded) and no diagnostic (the
31 // expression is not necessarily non-constant).
32 //
33 //===----------------------------------------------------------------------===//
34 
35 #include "Interp/Context.h"
36 #include "Interp/Frame.h"
37 #include "Interp/State.h"
38 #include "clang/AST/APValue.h"
39 #include "clang/AST/ASTContext.h"
40 #include "clang/AST/ASTDiagnostic.h"
41 #include "clang/AST/ASTLambda.h"
42 #include "clang/AST/Attr.h"
43 #include "clang/AST/CXXInheritance.h"
44 #include "clang/AST/CharUnits.h"
45 #include "clang/AST/CurrentSourceLocExprScope.h"
46 #include "clang/AST/Expr.h"
47 #include "clang/AST/OSLog.h"
48 #include "clang/AST/OptionalDiagnostic.h"
49 #include "clang/AST/RecordLayout.h"
50 #include "clang/AST/StmtVisitor.h"
51 #include "clang/AST/TypeLoc.h"
52 #include "clang/Basic/Builtins.h"
53 #include "clang/Basic/TargetInfo.h"
54 #include "llvm/ADT/APFixedPoint.h"
55 #include "llvm/ADT/Optional.h"
56 #include "llvm/ADT/SmallBitVector.h"
57 #include "llvm/Support/Debug.h"
58 #include "llvm/Support/SaveAndRestore.h"
59 #include "llvm/Support/raw_ostream.h"
60 #include <cstring>
61 #include <functional>
62 
63 #define DEBUG_TYPE "exprconstant"
64 
65 using namespace clang;
66 using llvm::APFixedPoint;
67 using llvm::APInt;
68 using llvm::APSInt;
69 using llvm::APFloat;
70 using llvm::FixedPointSemantics;
71 using llvm::Optional;
72 
73 namespace {
74   struct LValue;
75   class CallStackFrame;
76   class EvalInfo;
77 
78   using SourceLocExprScopeGuard =
79       CurrentSourceLocExprScope::SourceLocExprScopeGuard;
80 
81   static QualType getType(APValue::LValueBase B) {
82     return B.getType();
83   }
84 
85   /// Get an LValue path entry, which is known to not be an array index, as a
86   /// field declaration.
87   static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
88     return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
89   }
90   /// Get an LValue path entry, which is known to not be an array index, as a
91   /// base class declaration.
92   static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
93     return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
94   }
95   /// Determine whether this LValue path entry for a base class names a virtual
96   /// base class.
97   static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
98     return E.getAsBaseOrMember().getInt();
99   }
100 
101   /// Given an expression, determine the type used to store the result of
102   /// evaluating that expression.
103   static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
104     if (E->isPRValue())
105       return E->getType();
106     return Ctx.getLValueReferenceType(E->getType());
107   }
108 
109   /// Given a CallExpr, try to get the alloc_size attribute. May return null.
110   static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
111     if (const FunctionDecl *DirectCallee = CE->getDirectCallee())
112       return DirectCallee->getAttr<AllocSizeAttr>();
113     if (const Decl *IndirectCallee = CE->getCalleeDecl())
114       return IndirectCallee->getAttr<AllocSizeAttr>();
115     return nullptr;
116   }
117 
118   /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
119   /// This will look through a single cast.
120   ///
121   /// Returns null if we couldn't unwrap a function with alloc_size.
122   static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
123     if (!E->getType()->isPointerType())
124       return nullptr;
125 
126     E = E->IgnoreParens();
127     // If we're doing a variable assignment from e.g. malloc(N), there will
128     // probably be a cast of some kind. In exotic cases, we might also see a
129     // top-level ExprWithCleanups. Ignore them either way.
130     if (const auto *FE = dyn_cast<FullExpr>(E))
131       E = FE->getSubExpr()->IgnoreParens();
132 
133     if (const auto *Cast = dyn_cast<CastExpr>(E))
134       E = Cast->getSubExpr()->IgnoreParens();
135 
136     if (const auto *CE = dyn_cast<CallExpr>(E))
137       return getAllocSizeAttr(CE) ? CE : nullptr;
138     return nullptr;
139   }
140 
141   /// Determines whether or not the given Base contains a call to a function
142   /// with the alloc_size attribute.
143   static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
144     const auto *E = Base.dyn_cast<const Expr *>();
145     return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
146   }
147 
148   /// Determines whether the given kind of constant expression is only ever
149   /// used for name mangling. If so, it's permitted to reference things that we
150   /// can't generate code for (in particular, dllimported functions).
151   static bool isForManglingOnly(ConstantExprKind Kind) {
152     switch (Kind) {
153     case ConstantExprKind::Normal:
154     case ConstantExprKind::ClassTemplateArgument:
155     case ConstantExprKind::ImmediateInvocation:
156       // Note that non-type template arguments of class type are emitted as
157       // template parameter objects.
158       return false;
159 
160     case ConstantExprKind::NonClassTemplateArgument:
161       return true;
162     }
163     llvm_unreachable("unknown ConstantExprKind");
164   }
165 
166   static bool isTemplateArgument(ConstantExprKind Kind) {
167     switch (Kind) {
168     case ConstantExprKind::Normal:
169     case ConstantExprKind::ImmediateInvocation:
170       return false;
171 
172     case ConstantExprKind::ClassTemplateArgument:
173     case ConstantExprKind::NonClassTemplateArgument:
174       return true;
175     }
176     llvm_unreachable("unknown ConstantExprKind");
177   }
178 
179   /// The bound to claim that an array of unknown bound has.
180   /// The value in MostDerivedArraySize is undefined in this case. So, set it
181   /// to an arbitrary value that's likely to loudly break things if it's used.
182   static const uint64_t AssumedSizeForUnsizedArray =
183       std::numeric_limits<uint64_t>::max() / 2;
184 
185   /// Determines if an LValue with the given LValueBase will have an unsized
186   /// array in its designator.
187   /// Find the path length and type of the most-derived subobject in the given
188   /// path, and find the size of the containing array, if any.
189   static unsigned
190   findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
191                            ArrayRef<APValue::LValuePathEntry> Path,
192                            uint64_t &ArraySize, QualType &Type, bool &IsArray,
193                            bool &FirstEntryIsUnsizedArray) {
194     // This only accepts LValueBases from APValues, and APValues don't support
195     // arrays that lack size info.
196     assert(!isBaseAnAllocSizeCall(Base) &&
197            "Unsized arrays shouldn't appear here");
198     unsigned MostDerivedLength = 0;
199     Type = getType(Base);
200 
201     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
202       if (Type->isArrayType()) {
203         const ArrayType *AT = Ctx.getAsArrayType(Type);
204         Type = AT->getElementType();
205         MostDerivedLength = I + 1;
206         IsArray = true;
207 
208         if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
209           ArraySize = CAT->getSize().getZExtValue();
210         } else {
211           assert(I == 0 && "unexpected unsized array designator");
212           FirstEntryIsUnsizedArray = true;
213           ArraySize = AssumedSizeForUnsizedArray;
214         }
215       } else if (Type->isAnyComplexType()) {
216         const ComplexType *CT = Type->castAs<ComplexType>();
217         Type = CT->getElementType();
218         ArraySize = 2;
219         MostDerivedLength = I + 1;
220         IsArray = true;
221       } else if (const FieldDecl *FD = getAsField(Path[I])) {
222         Type = FD->getType();
223         ArraySize = 0;
224         MostDerivedLength = I + 1;
225         IsArray = false;
226       } else {
227         // Path[I] describes a base class.
228         ArraySize = 0;
229         IsArray = false;
230       }
231     }
232     return MostDerivedLength;
233   }
234 
235   /// A path from a glvalue to a subobject of that glvalue.
236   struct SubobjectDesignator {
237     /// True if the subobject was named in a manner not supported by C++11. Such
238     /// lvalues can still be folded, but they are not core constant expressions
239     /// and we cannot perform lvalue-to-rvalue conversions on them.
240     unsigned Invalid : 1;
241 
242     /// Is this a pointer one past the end of an object?
243     unsigned IsOnePastTheEnd : 1;
244 
245     /// Indicator of whether the first entry is an unsized array.
246     unsigned FirstEntryIsAnUnsizedArray : 1;
247 
248     /// Indicator of whether the most-derived object is an array element.
249     unsigned MostDerivedIsArrayElement : 1;
250 
251     /// The length of the path to the most-derived object of which this is a
252     /// subobject.
253     unsigned MostDerivedPathLength : 28;
254 
255     /// The size of the array of which the most-derived object is an element.
256     /// This will always be 0 if the most-derived object is not an array
257     /// element. 0 is not an indicator of whether or not the most-derived object
258     /// is an array, however, because 0-length arrays are allowed.
259     ///
260     /// If the current array is an unsized array, the value of this is
261     /// undefined.
262     uint64_t MostDerivedArraySize;
263 
264     /// The type of the most derived object referred to by this address.
265     QualType MostDerivedType;
266 
267     typedef APValue::LValuePathEntry PathEntry;
268 
269     /// The entries on the path from the glvalue to the designated subobject.
270     SmallVector<PathEntry, 8> Entries;
271 
272     SubobjectDesignator() : Invalid(true) {}
273 
274     explicit SubobjectDesignator(QualType T)
275         : Invalid(false), IsOnePastTheEnd(false),
276           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
277           MostDerivedPathLength(0), MostDerivedArraySize(0),
278           MostDerivedType(T) {}
279 
280     SubobjectDesignator(ASTContext &Ctx, const APValue &V)
281         : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
282           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
283           MostDerivedPathLength(0), MostDerivedArraySize(0) {
284       assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
285       if (!Invalid) {
286         IsOnePastTheEnd = V.isLValueOnePastTheEnd();
287         ArrayRef<PathEntry> VEntries = V.getLValuePath();
288         Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
289         if (V.getLValueBase()) {
290           bool IsArray = false;
291           bool FirstIsUnsizedArray = false;
292           MostDerivedPathLength = findMostDerivedSubobject(
293               Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
294               MostDerivedType, IsArray, FirstIsUnsizedArray);
295           MostDerivedIsArrayElement = IsArray;
296           FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
297         }
298       }
299     }
300 
301     void truncate(ASTContext &Ctx, APValue::LValueBase Base,
302                   unsigned NewLength) {
303       if (Invalid)
304         return;
305 
306       assert(Base && "cannot truncate path for null pointer");
307       assert(NewLength <= Entries.size() && "not a truncation");
308 
309       if (NewLength == Entries.size())
310         return;
311       Entries.resize(NewLength);
312 
313       bool IsArray = false;
314       bool FirstIsUnsizedArray = false;
315       MostDerivedPathLength = findMostDerivedSubobject(
316           Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
317           FirstIsUnsizedArray);
318       MostDerivedIsArrayElement = IsArray;
319       FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
320     }
321 
322     void setInvalid() {
323       Invalid = true;
324       Entries.clear();
325     }
326 
327     /// Determine whether the most derived subobject is an array without a
328     /// known bound.
329     bool isMostDerivedAnUnsizedArray() const {
330       assert(!Invalid && "Calling this makes no sense on invalid designators");
331       return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
332     }
333 
334     /// Determine what the most derived array's size is. Results in an assertion
335     /// failure if the most derived array lacks a size.
336     uint64_t getMostDerivedArraySize() const {
337       assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
338       return MostDerivedArraySize;
339     }
340 
341     /// Determine whether this is a one-past-the-end pointer.
342     bool isOnePastTheEnd() const {
343       assert(!Invalid);
344       if (IsOnePastTheEnd)
345         return true;
346       if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
347           Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
348               MostDerivedArraySize)
349         return true;
350       return false;
351     }
352 
353     /// Get the range of valid index adjustments in the form
354     ///   {maximum value that can be subtracted from this pointer,
355     ///    maximum value that can be added to this pointer}
356     std::pair<uint64_t, uint64_t> validIndexAdjustments() {
357       if (Invalid || isMostDerivedAnUnsizedArray())
358         return {0, 0};
359 
360       // [expr.add]p4: For the purposes of these operators, a pointer to a
361       // nonarray object behaves the same as a pointer to the first element of
362       // an array of length one with the type of the object as its element type.
363       bool IsArray = MostDerivedPathLength == Entries.size() &&
364                      MostDerivedIsArrayElement;
365       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
366                                     : (uint64_t)IsOnePastTheEnd;
367       uint64_t ArraySize =
368           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
369       return {ArrayIndex, ArraySize - ArrayIndex};
370     }
371 
372     /// Check that this refers to a valid subobject.
373     bool isValidSubobject() const {
374       if (Invalid)
375         return false;
376       return !isOnePastTheEnd();
377     }
378     /// Check that this refers to a valid subobject, and if not, produce a
379     /// relevant diagnostic and set the designator as invalid.
380     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
381 
382     /// Get the type of the designated object.
383     QualType getType(ASTContext &Ctx) const {
384       assert(!Invalid && "invalid designator has no subobject type");
385       return MostDerivedPathLength == Entries.size()
386                  ? MostDerivedType
387                  : Ctx.getRecordType(getAsBaseClass(Entries.back()));
388     }
389 
390     /// Update this designator to refer to the first element within this array.
391     void addArrayUnchecked(const ConstantArrayType *CAT) {
392       Entries.push_back(PathEntry::ArrayIndex(0));
393 
394       // This is a most-derived object.
395       MostDerivedType = CAT->getElementType();
396       MostDerivedIsArrayElement = true;
397       MostDerivedArraySize = CAT->getSize().getZExtValue();
398       MostDerivedPathLength = Entries.size();
399     }
400     /// Update this designator to refer to the first element within the array of
401     /// elements of type T. This is an array of unknown size.
402     void addUnsizedArrayUnchecked(QualType ElemTy) {
403       Entries.push_back(PathEntry::ArrayIndex(0));
404 
405       MostDerivedType = ElemTy;
406       MostDerivedIsArrayElement = true;
407       // The value in MostDerivedArraySize is undefined in this case. So, set it
408       // to an arbitrary value that's likely to loudly break things if it's
409       // used.
410       MostDerivedArraySize = AssumedSizeForUnsizedArray;
411       MostDerivedPathLength = Entries.size();
412     }
413     /// Update this designator to refer to the given base or member of this
414     /// object.
415     void addDeclUnchecked(const Decl *D, bool Virtual = false) {
416       Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
417 
418       // If this isn't a base class, it's a new most-derived object.
419       if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
420         MostDerivedType = FD->getType();
421         MostDerivedIsArrayElement = false;
422         MostDerivedArraySize = 0;
423         MostDerivedPathLength = Entries.size();
424       }
425     }
426     /// Update this designator to refer to the given complex component.
427     void addComplexUnchecked(QualType EltTy, bool Imag) {
428       Entries.push_back(PathEntry::ArrayIndex(Imag));
429 
430       // This is technically a most-derived object, though in practice this
431       // is unlikely to matter.
432       MostDerivedType = EltTy;
433       MostDerivedIsArrayElement = true;
434       MostDerivedArraySize = 2;
435       MostDerivedPathLength = Entries.size();
436     }
437     void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
438     void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
439                                    const APSInt &N);
440     /// Add N to the address of this subobject.
441     void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
442       if (Invalid || !N) return;
443       uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
444       if (isMostDerivedAnUnsizedArray()) {
445         diagnoseUnsizedArrayPointerArithmetic(Info, E);
446         // Can't verify -- trust that the user is doing the right thing (or if
447         // not, trust that the caller will catch the bad behavior).
448         // FIXME: Should we reject if this overflows, at least?
449         Entries.back() = PathEntry::ArrayIndex(
450             Entries.back().getAsArrayIndex() + TruncatedN);
451         return;
452       }
453 
454       // [expr.add]p4: For the purposes of these operators, a pointer to a
455       // nonarray object behaves the same as a pointer to the first element of
456       // an array of length one with the type of the object as its element type.
457       bool IsArray = MostDerivedPathLength == Entries.size() &&
458                      MostDerivedIsArrayElement;
459       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
460                                     : (uint64_t)IsOnePastTheEnd;
461       uint64_t ArraySize =
462           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
463 
464       if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
465         // Calculate the actual index in a wide enough type, so we can include
466         // it in the note.
467         N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
468         (llvm::APInt&)N += ArrayIndex;
469         assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
470         diagnosePointerArithmetic(Info, E, N);
471         setInvalid();
472         return;
473       }
474 
475       ArrayIndex += TruncatedN;
476       assert(ArrayIndex <= ArraySize &&
477              "bounds check succeeded for out-of-bounds index");
478 
479       if (IsArray)
480         Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
481       else
482         IsOnePastTheEnd = (ArrayIndex != 0);
483     }
484   };
485 
486   /// A scope at the end of which an object can need to be destroyed.
487   enum class ScopeKind {
488     Block,
489     FullExpression,
490     Call
491   };
492 
493   /// A reference to a particular call and its arguments.
494   struct CallRef {
495     CallRef() : OrigCallee(), CallIndex(0), Version() {}
496     CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
497         : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
498 
499     explicit operator bool() const { return OrigCallee; }
500 
501     /// Get the parameter that the caller initialized, corresponding to the
502     /// given parameter in the callee.
503     const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
504       return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
505                         : PVD;
506     }
507 
508     /// The callee at the point where the arguments were evaluated. This might
509     /// be different from the actual callee (a different redeclaration, or a
510     /// virtual override), but this function's parameters are the ones that
511     /// appear in the parameter map.
512     const FunctionDecl *OrigCallee;
513     /// The call index of the frame that holds the argument values.
514     unsigned CallIndex;
515     /// The version of the parameters corresponding to this call.
516     unsigned Version;
517   };
518 
519   /// A stack frame in the constexpr call stack.
520   class CallStackFrame : public interp::Frame {
521   public:
522     EvalInfo &Info;
523 
524     /// Parent - The caller of this stack frame.
525     CallStackFrame *Caller;
526 
527     /// Callee - The function which was called.
528     const FunctionDecl *Callee;
529 
530     /// This - The binding for the this pointer in this call, if any.
531     const LValue *This;
532 
533     /// Information on how to find the arguments to this call. Our arguments
534     /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
535     /// key and this value as the version.
536     CallRef Arguments;
537 
538     /// Source location information about the default argument or default
539     /// initializer expression we're evaluating, if any.
540     CurrentSourceLocExprScope CurSourceLocExprScope;
541 
542     // Note that we intentionally use std::map here so that references to
543     // values are stable.
544     typedef std::pair<const void *, unsigned> MapKeyTy;
545     typedef std::map<MapKeyTy, APValue> MapTy;
546     /// Temporaries - Temporary lvalues materialized within this stack frame.
547     MapTy Temporaries;
548 
549     /// CallLoc - The location of the call expression for this call.
550     SourceLocation CallLoc;
551 
552     /// Index - The call index of this call.
553     unsigned Index;
554 
555     /// The stack of integers for tracking version numbers for temporaries.
556     SmallVector<unsigned, 2> TempVersionStack = {1};
557     unsigned CurTempVersion = TempVersionStack.back();
558 
559     unsigned getTempVersion() const { return TempVersionStack.back(); }
560 
561     void pushTempVersion() {
562       TempVersionStack.push_back(++CurTempVersion);
563     }
564 
565     void popTempVersion() {
566       TempVersionStack.pop_back();
567     }
568 
569     CallRef createCall(const FunctionDecl *Callee) {
570       return {Callee, Index, ++CurTempVersion};
571     }
572 
573     // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
574     // on the overall stack usage of deeply-recursing constexpr evaluations.
575     // (We should cache this map rather than recomputing it repeatedly.)
576     // But let's try this and see how it goes; we can look into caching the map
577     // as a later change.
578 
579     /// LambdaCaptureFields - Mapping from captured variables/this to
580     /// corresponding data members in the closure class.
581     llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
582     FieldDecl *LambdaThisCaptureField;
583 
584     CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
585                    const FunctionDecl *Callee, const LValue *This,
586                    CallRef Arguments);
587     ~CallStackFrame();
588 
589     // Return the temporary for Key whose version number is Version.
590     APValue *getTemporary(const void *Key, unsigned Version) {
591       MapKeyTy KV(Key, Version);
592       auto LB = Temporaries.lower_bound(KV);
593       if (LB != Temporaries.end() && LB->first == KV)
594         return &LB->second;
595       // Pair (Key,Version) wasn't found in the map. Check that no elements
596       // in the map have 'Key' as their key.
597       assert((LB == Temporaries.end() || LB->first.first != Key) &&
598              (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
599              "Element with key 'Key' found in map");
600       return nullptr;
601     }
602 
603     // Return the current temporary for Key in the map.
604     APValue *getCurrentTemporary(const void *Key) {
605       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
606       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
607         return &std::prev(UB)->second;
608       return nullptr;
609     }
610 
611     // Return the version number of the current temporary for Key.
612     unsigned getCurrentTemporaryVersion(const void *Key) const {
613       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
614       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
615         return std::prev(UB)->first.second;
616       return 0;
617     }
618 
619     /// Allocate storage for an object of type T in this stack frame.
620     /// Populates LV with a handle to the created object. Key identifies
621     /// the temporary within the stack frame, and must not be reused without
622     /// bumping the temporary version number.
623     template<typename KeyT>
624     APValue &createTemporary(const KeyT *Key, QualType T,
625                              ScopeKind Scope, LValue &LV);
626 
627     /// Allocate storage for a parameter of a function call made in this frame.
628     APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
629 
630     void describe(llvm::raw_ostream &OS) override;
631 
632     Frame *getCaller() const override { return Caller; }
633     SourceLocation getCallLocation() const override { return CallLoc; }
634     const FunctionDecl *getCallee() const override { return Callee; }
635 
636     bool isStdFunction() const {
637       for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
638         if (DC->isStdNamespace())
639           return true;
640       return false;
641     }
642 
643   private:
644     APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
645                          ScopeKind Scope);
646   };
647 
648   /// Temporarily override 'this'.
649   class ThisOverrideRAII {
650   public:
651     ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
652         : Frame(Frame), OldThis(Frame.This) {
653       if (Enable)
654         Frame.This = NewThis;
655     }
656     ~ThisOverrideRAII() {
657       Frame.This = OldThis;
658     }
659   private:
660     CallStackFrame &Frame;
661     const LValue *OldThis;
662   };
663 }
664 
665 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
666                               const LValue &This, QualType ThisType);
667 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
668                               APValue::LValueBase LVBase, APValue &Value,
669                               QualType T);
670 
671 namespace {
672   /// A cleanup, and a flag indicating whether it is lifetime-extended.
673   class Cleanup {
674     llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
675     APValue::LValueBase Base;
676     QualType T;
677 
678   public:
679     Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
680             ScopeKind Scope)
681         : Value(Val, Scope), Base(Base), T(T) {}
682 
683     /// Determine whether this cleanup should be performed at the end of the
684     /// given kind of scope.
685     bool isDestroyedAtEndOf(ScopeKind K) const {
686       return (int)Value.getInt() >= (int)K;
687     }
688     bool endLifetime(EvalInfo &Info, bool RunDestructors) {
689       if (RunDestructors) {
690         SourceLocation Loc;
691         if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
692           Loc = VD->getLocation();
693         else if (const Expr *E = Base.dyn_cast<const Expr*>())
694           Loc = E->getExprLoc();
695         return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
696       }
697       *Value.getPointer() = APValue();
698       return true;
699     }
700 
701     bool hasSideEffect() {
702       return T.isDestructedType();
703     }
704   };
705 
706   /// A reference to an object whose construction we are currently evaluating.
707   struct ObjectUnderConstruction {
708     APValue::LValueBase Base;
709     ArrayRef<APValue::LValuePathEntry> Path;
710     friend bool operator==(const ObjectUnderConstruction &LHS,
711                            const ObjectUnderConstruction &RHS) {
712       return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
713     }
714     friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
715       return llvm::hash_combine(Obj.Base, Obj.Path);
716     }
717   };
718   enum class ConstructionPhase {
719     None,
720     Bases,
721     AfterBases,
722     AfterFields,
723     Destroying,
724     DestroyingBases
725   };
726 }
727 
728 namespace llvm {
729 template<> struct DenseMapInfo<ObjectUnderConstruction> {
730   using Base = DenseMapInfo<APValue::LValueBase>;
731   static ObjectUnderConstruction getEmptyKey() {
732     return {Base::getEmptyKey(), {}}; }
733   static ObjectUnderConstruction getTombstoneKey() {
734     return {Base::getTombstoneKey(), {}};
735   }
736   static unsigned getHashValue(const ObjectUnderConstruction &Object) {
737     return hash_value(Object);
738   }
739   static bool isEqual(const ObjectUnderConstruction &LHS,
740                       const ObjectUnderConstruction &RHS) {
741     return LHS == RHS;
742   }
743 };
744 }
745 
746 namespace {
747   /// A dynamically-allocated heap object.
748   struct DynAlloc {
749     /// The value of this heap-allocated object.
750     APValue Value;
751     /// The allocating expression; used for diagnostics. Either a CXXNewExpr
752     /// or a CallExpr (the latter is for direct calls to operator new inside
753     /// std::allocator<T>::allocate).
754     const Expr *AllocExpr = nullptr;
755 
756     enum Kind {
757       New,
758       ArrayNew,
759       StdAllocator
760     };
761 
762     /// Get the kind of the allocation. This must match between allocation
763     /// and deallocation.
764     Kind getKind() const {
765       if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
766         return NE->isArray() ? ArrayNew : New;
767       assert(isa<CallExpr>(AllocExpr));
768       return StdAllocator;
769     }
770   };
771 
772   struct DynAllocOrder {
773     bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
774       return L.getIndex() < R.getIndex();
775     }
776   };
777 
778   /// EvalInfo - This is a private struct used by the evaluator to capture
779   /// information about a subexpression as it is folded.  It retains information
780   /// about the AST context, but also maintains information about the folded
781   /// expression.
782   ///
783   /// If an expression could be evaluated, it is still possible it is not a C
784   /// "integer constant expression" or constant expression.  If not, this struct
785   /// captures information about how and why not.
786   ///
787   /// One bit of information passed *into* the request for constant folding
788   /// indicates whether the subexpression is "evaluated" or not according to C
789   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
790   /// evaluate the expression regardless of what the RHS is, but C only allows
791   /// certain things in certain situations.
792   class EvalInfo : public interp::State {
793   public:
794     ASTContext &Ctx;
795 
796     /// EvalStatus - Contains information about the evaluation.
797     Expr::EvalStatus &EvalStatus;
798 
799     /// CurrentCall - The top of the constexpr call stack.
800     CallStackFrame *CurrentCall;
801 
802     /// CallStackDepth - The number of calls in the call stack right now.
803     unsigned CallStackDepth;
804 
805     /// NextCallIndex - The next call index to assign.
806     unsigned NextCallIndex;
807 
808     /// StepsLeft - The remaining number of evaluation steps we're permitted
809     /// to perform. This is essentially a limit for the number of statements
810     /// we will evaluate.
811     unsigned StepsLeft;
812 
813     /// Enable the experimental new constant interpreter. If an expression is
814     /// not supported by the interpreter, an error is triggered.
815     bool EnableNewConstInterp;
816 
817     /// BottomFrame - The frame in which evaluation started. This must be
818     /// initialized after CurrentCall and CallStackDepth.
819     CallStackFrame BottomFrame;
820 
821     /// A stack of values whose lifetimes end at the end of some surrounding
822     /// evaluation frame.
823     llvm::SmallVector<Cleanup, 16> CleanupStack;
824 
825     /// EvaluatingDecl - This is the declaration whose initializer is being
826     /// evaluated, if any.
827     APValue::LValueBase EvaluatingDecl;
828 
829     enum class EvaluatingDeclKind {
830       None,
831       /// We're evaluating the construction of EvaluatingDecl.
832       Ctor,
833       /// We're evaluating the destruction of EvaluatingDecl.
834       Dtor,
835     };
836     EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
837 
838     /// EvaluatingDeclValue - This is the value being constructed for the
839     /// declaration whose initializer is being evaluated, if any.
840     APValue *EvaluatingDeclValue;
841 
842     /// Set of objects that are currently being constructed.
843     llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
844         ObjectsUnderConstruction;
845 
846     /// Current heap allocations, along with the location where each was
847     /// allocated. We use std::map here because we need stable addresses
848     /// for the stored APValues.
849     std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
850 
851     /// The number of heap allocations performed so far in this evaluation.
852     unsigned NumHeapAllocs = 0;
853 
854     struct EvaluatingConstructorRAII {
855       EvalInfo &EI;
856       ObjectUnderConstruction Object;
857       bool DidInsert;
858       EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
859                                 bool HasBases)
860           : EI(EI), Object(Object) {
861         DidInsert =
862             EI.ObjectsUnderConstruction
863                 .insert({Object, HasBases ? ConstructionPhase::Bases
864                                           : ConstructionPhase::AfterBases})
865                 .second;
866       }
867       void finishedConstructingBases() {
868         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
869       }
870       void finishedConstructingFields() {
871         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
872       }
873       ~EvaluatingConstructorRAII() {
874         if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
875       }
876     };
877 
878     struct EvaluatingDestructorRAII {
879       EvalInfo &EI;
880       ObjectUnderConstruction Object;
881       bool DidInsert;
882       EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
883           : EI(EI), Object(Object) {
884         DidInsert = EI.ObjectsUnderConstruction
885                         .insert({Object, ConstructionPhase::Destroying})
886                         .second;
887       }
888       void startedDestroyingBases() {
889         EI.ObjectsUnderConstruction[Object] =
890             ConstructionPhase::DestroyingBases;
891       }
892       ~EvaluatingDestructorRAII() {
893         if (DidInsert)
894           EI.ObjectsUnderConstruction.erase(Object);
895       }
896     };
897 
898     ConstructionPhase
899     isEvaluatingCtorDtor(APValue::LValueBase Base,
900                          ArrayRef<APValue::LValuePathEntry> Path) {
901       return ObjectsUnderConstruction.lookup({Base, Path});
902     }
903 
904     /// If we're currently speculatively evaluating, the outermost call stack
905     /// depth at which we can mutate state, otherwise 0.
906     unsigned SpeculativeEvaluationDepth = 0;
907 
908     /// The current array initialization index, if we're performing array
909     /// initialization.
910     uint64_t ArrayInitIndex = -1;
911 
912     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
913     /// notes attached to it will also be stored, otherwise they will not be.
914     bool HasActiveDiagnostic;
915 
916     /// Have we emitted a diagnostic explaining why we couldn't constant
917     /// fold (not just why it's not strictly a constant expression)?
918     bool HasFoldFailureDiagnostic;
919 
920     /// Whether or not we're in a context where the front end requires a
921     /// constant value.
922     bool InConstantContext;
923 
924     /// Whether we're checking that an expression is a potential constant
925     /// expression. If so, do not fail on constructs that could become constant
926     /// later on (such as a use of an undefined global).
927     bool CheckingPotentialConstantExpression = false;
928 
929     /// Whether we're checking for an expression that has undefined behavior.
930     /// If so, we will produce warnings if we encounter an operation that is
931     /// always undefined.
932     ///
933     /// Note that we still need to evaluate the expression normally when this
934     /// is set; this is used when evaluating ICEs in C.
935     bool CheckingForUndefinedBehavior = false;
936 
937     enum EvaluationMode {
938       /// Evaluate as a constant expression. Stop if we find that the expression
939       /// is not a constant expression.
940       EM_ConstantExpression,
941 
942       /// Evaluate as a constant expression. Stop if we find that the expression
943       /// is not a constant expression. Some expressions can be retried in the
944       /// optimizer if we don't constant fold them here, but in an unevaluated
945       /// context we try to fold them immediately since the optimizer never
946       /// gets a chance to look at it.
947       EM_ConstantExpressionUnevaluated,
948 
949       /// Fold the expression to a constant. Stop if we hit a side-effect that
950       /// we can't model.
951       EM_ConstantFold,
952 
953       /// Evaluate in any way we know how. Don't worry about side-effects that
954       /// can't be modeled.
955       EM_IgnoreSideEffects,
956     } EvalMode;
957 
958     /// Are we checking whether the expression is a potential constant
959     /// expression?
960     bool checkingPotentialConstantExpression() const override  {
961       return CheckingPotentialConstantExpression;
962     }
963 
964     /// Are we checking an expression for overflow?
965     // FIXME: We should check for any kind of undefined or suspicious behavior
966     // in such constructs, not just overflow.
967     bool checkingForUndefinedBehavior() const override {
968       return CheckingForUndefinedBehavior;
969     }
970 
971     EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
972         : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
973           CallStackDepth(0), NextCallIndex(1),
974           StepsLeft(C.getLangOpts().ConstexprStepLimit),
975           EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
976           BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()),
977           EvaluatingDecl((const ValueDecl *)nullptr),
978           EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
979           HasFoldFailureDiagnostic(false), InConstantContext(false),
980           EvalMode(Mode) {}
981 
982     ~EvalInfo() {
983       discardCleanups();
984     }
985 
986     ASTContext &getCtx() const override { return Ctx; }
987 
988     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
989                            EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
990       EvaluatingDecl = Base;
991       IsEvaluatingDecl = EDK;
992       EvaluatingDeclValue = &Value;
993     }
994 
995     bool CheckCallLimit(SourceLocation Loc) {
996       // Don't perform any constexpr calls (other than the call we're checking)
997       // when checking a potential constant expression.
998       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
999         return false;
1000       if (NextCallIndex == 0) {
1001         // NextCallIndex has wrapped around.
1002         FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
1003         return false;
1004       }
1005       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
1006         return true;
1007       FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
1008         << getLangOpts().ConstexprCallDepth;
1009       return false;
1010     }
1011 
1012     std::pair<CallStackFrame *, unsigned>
1013     getCallFrameAndDepth(unsigned CallIndex) {
1014       assert(CallIndex && "no call index in getCallFrameAndDepth");
1015       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1016       // be null in this loop.
1017       unsigned Depth = CallStackDepth;
1018       CallStackFrame *Frame = CurrentCall;
1019       while (Frame->Index > CallIndex) {
1020         Frame = Frame->Caller;
1021         --Depth;
1022       }
1023       if (Frame->Index == CallIndex)
1024         return {Frame, Depth};
1025       return {nullptr, 0};
1026     }
1027 
1028     bool nextStep(const Stmt *S) {
1029       if (!StepsLeft) {
1030         FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1031         return false;
1032       }
1033       --StepsLeft;
1034       return true;
1035     }
1036 
1037     APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1038 
1039     Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) {
1040       Optional<DynAlloc*> Result;
1041       auto It = HeapAllocs.find(DA);
1042       if (It != HeapAllocs.end())
1043         Result = &It->second;
1044       return Result;
1045     }
1046 
1047     /// Get the allocated storage for the given parameter of the given call.
1048     APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1049       CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1050       return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1051                    : nullptr;
1052     }
1053 
1054     /// Information about a stack frame for std::allocator<T>::[de]allocate.
1055     struct StdAllocatorCaller {
1056       unsigned FrameIndex;
1057       QualType ElemType;
1058       explicit operator bool() const { return FrameIndex != 0; };
1059     };
1060 
1061     StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1062       for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1063            Call = Call->Caller) {
1064         const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1065         if (!MD)
1066           continue;
1067         const IdentifierInfo *FnII = MD->getIdentifier();
1068         if (!FnII || !FnII->isStr(FnName))
1069           continue;
1070 
1071         const auto *CTSD =
1072             dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1073         if (!CTSD)
1074           continue;
1075 
1076         const IdentifierInfo *ClassII = CTSD->getIdentifier();
1077         const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1078         if (CTSD->isInStdNamespace() && ClassII &&
1079             ClassII->isStr("allocator") && TAL.size() >= 1 &&
1080             TAL[0].getKind() == TemplateArgument::Type)
1081           return {Call->Index, TAL[0].getAsType()};
1082       }
1083 
1084       return {};
1085     }
1086 
1087     void performLifetimeExtension() {
1088       // Disable the cleanups for lifetime-extended temporaries.
1089       llvm::erase_if(CleanupStack, [](Cleanup &C) {
1090         return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1091       });
1092     }
1093 
1094     /// Throw away any remaining cleanups at the end of evaluation. If any
1095     /// cleanups would have had a side-effect, note that as an unmodeled
1096     /// side-effect and return false. Otherwise, return true.
1097     bool discardCleanups() {
1098       for (Cleanup &C : CleanupStack) {
1099         if (C.hasSideEffect() && !noteSideEffect()) {
1100           CleanupStack.clear();
1101           return false;
1102         }
1103       }
1104       CleanupStack.clear();
1105       return true;
1106     }
1107 
1108   private:
1109     interp::Frame *getCurrentFrame() override { return CurrentCall; }
1110     const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1111 
1112     bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1113     void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1114 
1115     void setFoldFailureDiagnostic(bool Flag) override {
1116       HasFoldFailureDiagnostic = Flag;
1117     }
1118 
1119     Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1120 
1121     // If we have a prior diagnostic, it will be noting that the expression
1122     // isn't a constant expression. This diagnostic is more important,
1123     // unless we require this evaluation to produce a constant expression.
1124     //
1125     // FIXME: We might want to show both diagnostics to the user in
1126     // EM_ConstantFold mode.
1127     bool hasPriorDiagnostic() override {
1128       if (!EvalStatus.Diag->empty()) {
1129         switch (EvalMode) {
1130         case EM_ConstantFold:
1131         case EM_IgnoreSideEffects:
1132           if (!HasFoldFailureDiagnostic)
1133             break;
1134           // We've already failed to fold something. Keep that diagnostic.
1135           LLVM_FALLTHROUGH;
1136         case EM_ConstantExpression:
1137         case EM_ConstantExpressionUnevaluated:
1138           setActiveDiagnostic(false);
1139           return true;
1140         }
1141       }
1142       return false;
1143     }
1144 
1145     unsigned getCallStackDepth() override { return CallStackDepth; }
1146 
1147   public:
1148     /// Should we continue evaluation after encountering a side-effect that we
1149     /// couldn't model?
1150     bool keepEvaluatingAfterSideEffect() {
1151       switch (EvalMode) {
1152       case EM_IgnoreSideEffects:
1153         return true;
1154 
1155       case EM_ConstantExpression:
1156       case EM_ConstantExpressionUnevaluated:
1157       case EM_ConstantFold:
1158         // By default, assume any side effect might be valid in some other
1159         // evaluation of this expression from a different context.
1160         return checkingPotentialConstantExpression() ||
1161                checkingForUndefinedBehavior();
1162       }
1163       llvm_unreachable("Missed EvalMode case");
1164     }
1165 
1166     /// Note that we have had a side-effect, and determine whether we should
1167     /// keep evaluating.
1168     bool noteSideEffect() {
1169       EvalStatus.HasSideEffects = true;
1170       return keepEvaluatingAfterSideEffect();
1171     }
1172 
1173     /// Should we continue evaluation after encountering undefined behavior?
1174     bool keepEvaluatingAfterUndefinedBehavior() {
1175       switch (EvalMode) {
1176       case EM_IgnoreSideEffects:
1177       case EM_ConstantFold:
1178         return true;
1179 
1180       case EM_ConstantExpression:
1181       case EM_ConstantExpressionUnevaluated:
1182         return checkingForUndefinedBehavior();
1183       }
1184       llvm_unreachable("Missed EvalMode case");
1185     }
1186 
1187     /// Note that we hit something that was technically undefined behavior, but
1188     /// that we can evaluate past it (such as signed overflow or floating-point
1189     /// division by zero.)
1190     bool noteUndefinedBehavior() override {
1191       EvalStatus.HasUndefinedBehavior = true;
1192       return keepEvaluatingAfterUndefinedBehavior();
1193     }
1194 
1195     /// Should we continue evaluation as much as possible after encountering a
1196     /// construct which can't be reduced to a value?
1197     bool keepEvaluatingAfterFailure() const override {
1198       if (!StepsLeft)
1199         return false;
1200 
1201       switch (EvalMode) {
1202       case EM_ConstantExpression:
1203       case EM_ConstantExpressionUnevaluated:
1204       case EM_ConstantFold:
1205       case EM_IgnoreSideEffects:
1206         return checkingPotentialConstantExpression() ||
1207                checkingForUndefinedBehavior();
1208       }
1209       llvm_unreachable("Missed EvalMode case");
1210     }
1211 
1212     /// Notes that we failed to evaluate an expression that other expressions
1213     /// directly depend on, and determine if we should keep evaluating. This
1214     /// should only be called if we actually intend to keep evaluating.
1215     ///
1216     /// Call noteSideEffect() instead if we may be able to ignore the value that
1217     /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1218     ///
1219     /// (Foo(), 1)      // use noteSideEffect
1220     /// (Foo() || true) // use noteSideEffect
1221     /// Foo() + 1       // use noteFailure
1222     LLVM_NODISCARD bool noteFailure() {
1223       // Failure when evaluating some expression often means there is some
1224       // subexpression whose evaluation was skipped. Therefore, (because we
1225       // don't track whether we skipped an expression when unwinding after an
1226       // evaluation failure) every evaluation failure that bubbles up from a
1227       // subexpression implies that a side-effect has potentially happened. We
1228       // skip setting the HasSideEffects flag to true until we decide to
1229       // continue evaluating after that point, which happens here.
1230       bool KeepGoing = keepEvaluatingAfterFailure();
1231       EvalStatus.HasSideEffects |= KeepGoing;
1232       return KeepGoing;
1233     }
1234 
1235     class ArrayInitLoopIndex {
1236       EvalInfo &Info;
1237       uint64_t OuterIndex;
1238 
1239     public:
1240       ArrayInitLoopIndex(EvalInfo &Info)
1241           : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1242         Info.ArrayInitIndex = 0;
1243       }
1244       ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1245 
1246       operator uint64_t&() { return Info.ArrayInitIndex; }
1247     };
1248   };
1249 
1250   /// Object used to treat all foldable expressions as constant expressions.
1251   struct FoldConstant {
1252     EvalInfo &Info;
1253     bool Enabled;
1254     bool HadNoPriorDiags;
1255     EvalInfo::EvaluationMode OldMode;
1256 
1257     explicit FoldConstant(EvalInfo &Info, bool Enabled)
1258       : Info(Info),
1259         Enabled(Enabled),
1260         HadNoPriorDiags(Info.EvalStatus.Diag &&
1261                         Info.EvalStatus.Diag->empty() &&
1262                         !Info.EvalStatus.HasSideEffects),
1263         OldMode(Info.EvalMode) {
1264       if (Enabled)
1265         Info.EvalMode = EvalInfo::EM_ConstantFold;
1266     }
1267     void keepDiagnostics() { Enabled = false; }
1268     ~FoldConstant() {
1269       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1270           !Info.EvalStatus.HasSideEffects)
1271         Info.EvalStatus.Diag->clear();
1272       Info.EvalMode = OldMode;
1273     }
1274   };
1275 
1276   /// RAII object used to set the current evaluation mode to ignore
1277   /// side-effects.
1278   struct IgnoreSideEffectsRAII {
1279     EvalInfo &Info;
1280     EvalInfo::EvaluationMode OldMode;
1281     explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1282         : Info(Info), OldMode(Info.EvalMode) {
1283       Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1284     }
1285 
1286     ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1287   };
1288 
1289   /// RAII object used to optionally suppress diagnostics and side-effects from
1290   /// a speculative evaluation.
1291   class SpeculativeEvaluationRAII {
1292     EvalInfo *Info = nullptr;
1293     Expr::EvalStatus OldStatus;
1294     unsigned OldSpeculativeEvaluationDepth;
1295 
1296     void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1297       Info = Other.Info;
1298       OldStatus = Other.OldStatus;
1299       OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1300       Other.Info = nullptr;
1301     }
1302 
1303     void maybeRestoreState() {
1304       if (!Info)
1305         return;
1306 
1307       Info->EvalStatus = OldStatus;
1308       Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1309     }
1310 
1311   public:
1312     SpeculativeEvaluationRAII() = default;
1313 
1314     SpeculativeEvaluationRAII(
1315         EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1316         : Info(&Info), OldStatus(Info.EvalStatus),
1317           OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1318       Info.EvalStatus.Diag = NewDiag;
1319       Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1320     }
1321 
1322     SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1323     SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1324       moveFromAndCancel(std::move(Other));
1325     }
1326 
1327     SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1328       maybeRestoreState();
1329       moveFromAndCancel(std::move(Other));
1330       return *this;
1331     }
1332 
1333     ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1334   };
1335 
1336   /// RAII object wrapping a full-expression or block scope, and handling
1337   /// the ending of the lifetime of temporaries created within it.
1338   template<ScopeKind Kind>
1339   class ScopeRAII {
1340     EvalInfo &Info;
1341     unsigned OldStackSize;
1342   public:
1343     ScopeRAII(EvalInfo &Info)
1344         : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1345       // Push a new temporary version. This is needed to distinguish between
1346       // temporaries created in different iterations of a loop.
1347       Info.CurrentCall->pushTempVersion();
1348     }
1349     bool destroy(bool RunDestructors = true) {
1350       bool OK = cleanup(Info, RunDestructors, OldStackSize);
1351       OldStackSize = -1U;
1352       return OK;
1353     }
1354     ~ScopeRAII() {
1355       if (OldStackSize != -1U)
1356         destroy(false);
1357       // Body moved to a static method to encourage the compiler to inline away
1358       // instances of this class.
1359       Info.CurrentCall->popTempVersion();
1360     }
1361   private:
1362     static bool cleanup(EvalInfo &Info, bool RunDestructors,
1363                         unsigned OldStackSize) {
1364       assert(OldStackSize <= Info.CleanupStack.size() &&
1365              "running cleanups out of order?");
1366 
1367       // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1368       // for a full-expression scope.
1369       bool Success = true;
1370       for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1371         if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1372           if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1373             Success = false;
1374             break;
1375           }
1376         }
1377       }
1378 
1379       // Compact any retained cleanups.
1380       auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1381       if (Kind != ScopeKind::Block)
1382         NewEnd =
1383             std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1384               return C.isDestroyedAtEndOf(Kind);
1385             });
1386       Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1387       return Success;
1388     }
1389   };
1390   typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1391   typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1392   typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1393 }
1394 
1395 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1396                                          CheckSubobjectKind CSK) {
1397   if (Invalid)
1398     return false;
1399   if (isOnePastTheEnd()) {
1400     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1401       << CSK;
1402     setInvalid();
1403     return false;
1404   }
1405   // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1406   // must actually be at least one array element; even a VLA cannot have a
1407   // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1408   return true;
1409 }
1410 
1411 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1412                                                                 const Expr *E) {
1413   Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1414   // Do not set the designator as invalid: we can represent this situation,
1415   // and correct handling of __builtin_object_size requires us to do so.
1416 }
1417 
1418 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1419                                                     const Expr *E,
1420                                                     const APSInt &N) {
1421   // If we're complaining, we must be able to statically determine the size of
1422   // the most derived array.
1423   if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1424     Info.CCEDiag(E, diag::note_constexpr_array_index)
1425       << N << /*array*/ 0
1426       << static_cast<unsigned>(getMostDerivedArraySize());
1427   else
1428     Info.CCEDiag(E, diag::note_constexpr_array_index)
1429       << N << /*non-array*/ 1;
1430   setInvalid();
1431 }
1432 
1433 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1434                                const FunctionDecl *Callee, const LValue *This,
1435                                CallRef Call)
1436     : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1437       Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1438   Info.CurrentCall = this;
1439   ++Info.CallStackDepth;
1440 }
1441 
1442 CallStackFrame::~CallStackFrame() {
1443   assert(Info.CurrentCall == this && "calls retired out of order");
1444   --Info.CallStackDepth;
1445   Info.CurrentCall = Caller;
1446 }
1447 
1448 static bool isRead(AccessKinds AK) {
1449   return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1450 }
1451 
1452 static bool isModification(AccessKinds AK) {
1453   switch (AK) {
1454   case AK_Read:
1455   case AK_ReadObjectRepresentation:
1456   case AK_MemberCall:
1457   case AK_DynamicCast:
1458   case AK_TypeId:
1459     return false;
1460   case AK_Assign:
1461   case AK_Increment:
1462   case AK_Decrement:
1463   case AK_Construct:
1464   case AK_Destroy:
1465     return true;
1466   }
1467   llvm_unreachable("unknown access kind");
1468 }
1469 
1470 static bool isAnyAccess(AccessKinds AK) {
1471   return isRead(AK) || isModification(AK);
1472 }
1473 
1474 /// Is this an access per the C++ definition?
1475 static bool isFormalAccess(AccessKinds AK) {
1476   return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
1477 }
1478 
1479 /// Is this kind of axcess valid on an indeterminate object value?
1480 static bool isValidIndeterminateAccess(AccessKinds AK) {
1481   switch (AK) {
1482   case AK_Read:
1483   case AK_Increment:
1484   case AK_Decrement:
1485     // These need the object's value.
1486     return false;
1487 
1488   case AK_ReadObjectRepresentation:
1489   case AK_Assign:
1490   case AK_Construct:
1491   case AK_Destroy:
1492     // Construction and destruction don't need the value.
1493     return true;
1494 
1495   case AK_MemberCall:
1496   case AK_DynamicCast:
1497   case AK_TypeId:
1498     // These aren't really meaningful on scalars.
1499     return true;
1500   }
1501   llvm_unreachable("unknown access kind");
1502 }
1503 
1504 namespace {
1505   struct ComplexValue {
1506   private:
1507     bool IsInt;
1508 
1509   public:
1510     APSInt IntReal, IntImag;
1511     APFloat FloatReal, FloatImag;
1512 
1513     ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1514 
1515     void makeComplexFloat() { IsInt = false; }
1516     bool isComplexFloat() const { return !IsInt; }
1517     APFloat &getComplexFloatReal() { return FloatReal; }
1518     APFloat &getComplexFloatImag() { return FloatImag; }
1519 
1520     void makeComplexInt() { IsInt = true; }
1521     bool isComplexInt() const { return IsInt; }
1522     APSInt &getComplexIntReal() { return IntReal; }
1523     APSInt &getComplexIntImag() { return IntImag; }
1524 
1525     void moveInto(APValue &v) const {
1526       if (isComplexFloat())
1527         v = APValue(FloatReal, FloatImag);
1528       else
1529         v = APValue(IntReal, IntImag);
1530     }
1531     void setFrom(const APValue &v) {
1532       assert(v.isComplexFloat() || v.isComplexInt());
1533       if (v.isComplexFloat()) {
1534         makeComplexFloat();
1535         FloatReal = v.getComplexFloatReal();
1536         FloatImag = v.getComplexFloatImag();
1537       } else {
1538         makeComplexInt();
1539         IntReal = v.getComplexIntReal();
1540         IntImag = v.getComplexIntImag();
1541       }
1542     }
1543   };
1544 
1545   struct LValue {
1546     APValue::LValueBase Base;
1547     CharUnits Offset;
1548     SubobjectDesignator Designator;
1549     bool IsNullPtr : 1;
1550     bool InvalidBase : 1;
1551 
1552     const APValue::LValueBase getLValueBase() const { return Base; }
1553     CharUnits &getLValueOffset() { return Offset; }
1554     const CharUnits &getLValueOffset() const { return Offset; }
1555     SubobjectDesignator &getLValueDesignator() { return Designator; }
1556     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1557     bool isNullPointer() const { return IsNullPtr;}
1558 
1559     unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1560     unsigned getLValueVersion() const { return Base.getVersion(); }
1561 
1562     void moveInto(APValue &V) const {
1563       if (Designator.Invalid)
1564         V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1565       else {
1566         assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1567         V = APValue(Base, Offset, Designator.Entries,
1568                     Designator.IsOnePastTheEnd, IsNullPtr);
1569       }
1570     }
1571     void setFrom(ASTContext &Ctx, const APValue &V) {
1572       assert(V.isLValue() && "Setting LValue from a non-LValue?");
1573       Base = V.getLValueBase();
1574       Offset = V.getLValueOffset();
1575       InvalidBase = false;
1576       Designator = SubobjectDesignator(Ctx, V);
1577       IsNullPtr = V.isNullPointer();
1578     }
1579 
1580     void set(APValue::LValueBase B, bool BInvalid = false) {
1581 #ifndef NDEBUG
1582       // We only allow a few types of invalid bases. Enforce that here.
1583       if (BInvalid) {
1584         const auto *E = B.get<const Expr *>();
1585         assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1586                "Unexpected type of invalid base");
1587       }
1588 #endif
1589 
1590       Base = B;
1591       Offset = CharUnits::fromQuantity(0);
1592       InvalidBase = BInvalid;
1593       Designator = SubobjectDesignator(getType(B));
1594       IsNullPtr = false;
1595     }
1596 
1597     void setNull(ASTContext &Ctx, QualType PointerTy) {
1598       Base = (const ValueDecl *)nullptr;
1599       Offset =
1600           CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
1601       InvalidBase = false;
1602       Designator = SubobjectDesignator(PointerTy->getPointeeType());
1603       IsNullPtr = true;
1604     }
1605 
1606     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1607       set(B, true);
1608     }
1609 
1610     std::string toString(ASTContext &Ctx, QualType T) const {
1611       APValue Printable;
1612       moveInto(Printable);
1613       return Printable.getAsString(Ctx, T);
1614     }
1615 
1616   private:
1617     // Check that this LValue is not based on a null pointer. If it is, produce
1618     // a diagnostic and mark the designator as invalid.
1619     template <typename GenDiagType>
1620     bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1621       if (Designator.Invalid)
1622         return false;
1623       if (IsNullPtr) {
1624         GenDiag();
1625         Designator.setInvalid();
1626         return false;
1627       }
1628       return true;
1629     }
1630 
1631   public:
1632     bool checkNullPointer(EvalInfo &Info, const Expr *E,
1633                           CheckSubobjectKind CSK) {
1634       return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1635         Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1636       });
1637     }
1638 
1639     bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1640                                        AccessKinds AK) {
1641       return checkNullPointerDiagnosingWith([&Info, E, AK] {
1642         Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1643       });
1644     }
1645 
1646     // Check this LValue refers to an object. If not, set the designator to be
1647     // invalid and emit a diagnostic.
1648     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1649       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1650              Designator.checkSubobject(Info, E, CSK);
1651     }
1652 
1653     void addDecl(EvalInfo &Info, const Expr *E,
1654                  const Decl *D, bool Virtual = false) {
1655       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1656         Designator.addDeclUnchecked(D, Virtual);
1657     }
1658     void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1659       if (!Designator.Entries.empty()) {
1660         Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1661         Designator.setInvalid();
1662         return;
1663       }
1664       if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1665         assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1666         Designator.FirstEntryIsAnUnsizedArray = true;
1667         Designator.addUnsizedArrayUnchecked(ElemTy);
1668       }
1669     }
1670     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1671       if (checkSubobject(Info, E, CSK_ArrayToPointer))
1672         Designator.addArrayUnchecked(CAT);
1673     }
1674     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1675       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1676         Designator.addComplexUnchecked(EltTy, Imag);
1677     }
1678     void clearIsNullPointer() {
1679       IsNullPtr = false;
1680     }
1681     void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1682                               const APSInt &Index, CharUnits ElementSize) {
1683       // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1684       // but we're not required to diagnose it and it's valid in C++.)
1685       if (!Index)
1686         return;
1687 
1688       // Compute the new offset in the appropriate width, wrapping at 64 bits.
1689       // FIXME: When compiling for a 32-bit target, we should use 32-bit
1690       // offsets.
1691       uint64_t Offset64 = Offset.getQuantity();
1692       uint64_t ElemSize64 = ElementSize.getQuantity();
1693       uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1694       Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1695 
1696       if (checkNullPointer(Info, E, CSK_ArrayIndex))
1697         Designator.adjustIndex(Info, E, Index);
1698       clearIsNullPointer();
1699     }
1700     void adjustOffset(CharUnits N) {
1701       Offset += N;
1702       if (N.getQuantity())
1703         clearIsNullPointer();
1704     }
1705   };
1706 
1707   struct MemberPtr {
1708     MemberPtr() {}
1709     explicit MemberPtr(const ValueDecl *Decl)
1710         : DeclAndIsDerivedMember(Decl, false) {}
1711 
1712     /// The member or (direct or indirect) field referred to by this member
1713     /// pointer, or 0 if this is a null member pointer.
1714     const ValueDecl *getDecl() const {
1715       return DeclAndIsDerivedMember.getPointer();
1716     }
1717     /// Is this actually a member of some type derived from the relevant class?
1718     bool isDerivedMember() const {
1719       return DeclAndIsDerivedMember.getInt();
1720     }
1721     /// Get the class which the declaration actually lives in.
1722     const CXXRecordDecl *getContainingRecord() const {
1723       return cast<CXXRecordDecl>(
1724           DeclAndIsDerivedMember.getPointer()->getDeclContext());
1725     }
1726 
1727     void moveInto(APValue &V) const {
1728       V = APValue(getDecl(), isDerivedMember(), Path);
1729     }
1730     void setFrom(const APValue &V) {
1731       assert(V.isMemberPointer());
1732       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1733       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1734       Path.clear();
1735       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1736       Path.insert(Path.end(), P.begin(), P.end());
1737     }
1738 
1739     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1740     /// whether the member is a member of some class derived from the class type
1741     /// of the member pointer.
1742     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1743     /// Path - The path of base/derived classes from the member declaration's
1744     /// class (exclusive) to the class type of the member pointer (inclusive).
1745     SmallVector<const CXXRecordDecl*, 4> Path;
1746 
1747     /// Perform a cast towards the class of the Decl (either up or down the
1748     /// hierarchy).
1749     bool castBack(const CXXRecordDecl *Class) {
1750       assert(!Path.empty());
1751       const CXXRecordDecl *Expected;
1752       if (Path.size() >= 2)
1753         Expected = Path[Path.size() - 2];
1754       else
1755         Expected = getContainingRecord();
1756       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1757         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1758         // if B does not contain the original member and is not a base or
1759         // derived class of the class containing the original member, the result
1760         // of the cast is undefined.
1761         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1762         // (D::*). We consider that to be a language defect.
1763         return false;
1764       }
1765       Path.pop_back();
1766       return true;
1767     }
1768     /// Perform a base-to-derived member pointer cast.
1769     bool castToDerived(const CXXRecordDecl *Derived) {
1770       if (!getDecl())
1771         return true;
1772       if (!isDerivedMember()) {
1773         Path.push_back(Derived);
1774         return true;
1775       }
1776       if (!castBack(Derived))
1777         return false;
1778       if (Path.empty())
1779         DeclAndIsDerivedMember.setInt(false);
1780       return true;
1781     }
1782     /// Perform a derived-to-base member pointer cast.
1783     bool castToBase(const CXXRecordDecl *Base) {
1784       if (!getDecl())
1785         return true;
1786       if (Path.empty())
1787         DeclAndIsDerivedMember.setInt(true);
1788       if (isDerivedMember()) {
1789         Path.push_back(Base);
1790         return true;
1791       }
1792       return castBack(Base);
1793     }
1794   };
1795 
1796   /// Compare two member pointers, which are assumed to be of the same type.
1797   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1798     if (!LHS.getDecl() || !RHS.getDecl())
1799       return !LHS.getDecl() && !RHS.getDecl();
1800     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1801       return false;
1802     return LHS.Path == RHS.Path;
1803   }
1804 }
1805 
1806 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1807 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1808                             const LValue &This, const Expr *E,
1809                             bool AllowNonLiteralTypes = false);
1810 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1811                            bool InvalidBaseOK = false);
1812 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1813                             bool InvalidBaseOK = false);
1814 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1815                                   EvalInfo &Info);
1816 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1817 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1818 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1819                                     EvalInfo &Info);
1820 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1821 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1822 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1823                            EvalInfo &Info);
1824 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1825 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
1826                                   EvalInfo &Info);
1827 
1828 /// Evaluate an integer or fixed point expression into an APResult.
1829 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1830                                         EvalInfo &Info);
1831 
1832 /// Evaluate only a fixed point expression into an APResult.
1833 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1834                                EvalInfo &Info);
1835 
1836 //===----------------------------------------------------------------------===//
1837 // Misc utilities
1838 //===----------------------------------------------------------------------===//
1839 
1840 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1841 /// preserving its value (by extending by up to one bit as needed).
1842 static void negateAsSigned(APSInt &Int) {
1843   if (Int.isUnsigned() || Int.isMinSignedValue()) {
1844     Int = Int.extend(Int.getBitWidth() + 1);
1845     Int.setIsSigned(true);
1846   }
1847   Int = -Int;
1848 }
1849 
1850 template<typename KeyT>
1851 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1852                                          ScopeKind Scope, LValue &LV) {
1853   unsigned Version = getTempVersion();
1854   APValue::LValueBase Base(Key, Index, Version);
1855   LV.set(Base);
1856   return createLocal(Base, Key, T, Scope);
1857 }
1858 
1859 /// Allocate storage for a parameter of a function call made in this frame.
1860 APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1861                                      LValue &LV) {
1862   assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1863   APValue::LValueBase Base(PVD, Index, Args.Version);
1864   LV.set(Base);
1865   // We always destroy parameters at the end of the call, even if we'd allow
1866   // them to live to the end of the full-expression at runtime, in order to
1867   // give portable results and match other compilers.
1868   return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1869 }
1870 
1871 APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1872                                      QualType T, ScopeKind Scope) {
1873   assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1874   unsigned Version = Base.getVersion();
1875   APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1876   assert(Result.isAbsent() && "local created multiple times");
1877 
1878   // If we're creating a local immediately in the operand of a speculative
1879   // evaluation, don't register a cleanup to be run outside the speculative
1880   // evaluation context, since we won't actually be able to initialize this
1881   // object.
1882   if (Index <= Info.SpeculativeEvaluationDepth) {
1883     if (T.isDestructedType())
1884       Info.noteSideEffect();
1885   } else {
1886     Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1887   }
1888   return Result;
1889 }
1890 
1891 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1892   if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1893     FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1894     return nullptr;
1895   }
1896 
1897   DynamicAllocLValue DA(NumHeapAllocs++);
1898   LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1899   auto Result = HeapAllocs.emplace(std::piecewise_construct,
1900                                    std::forward_as_tuple(DA), std::tuple<>());
1901   assert(Result.second && "reused a heap alloc index?");
1902   Result.first->second.AllocExpr = E;
1903   return &Result.first->second.Value;
1904 }
1905 
1906 /// Produce a string describing the given constexpr call.
1907 void CallStackFrame::describe(raw_ostream &Out) {
1908   unsigned ArgIndex = 0;
1909   bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1910                       !isa<CXXConstructorDecl>(Callee) &&
1911                       cast<CXXMethodDecl>(Callee)->isInstance();
1912 
1913   if (!IsMemberCall)
1914     Out << *Callee << '(';
1915 
1916   if (This && IsMemberCall) {
1917     APValue Val;
1918     This->moveInto(Val);
1919     Val.printPretty(Out, Info.Ctx,
1920                     This->Designator.MostDerivedType);
1921     // FIXME: Add parens around Val if needed.
1922     Out << "->" << *Callee << '(';
1923     IsMemberCall = false;
1924   }
1925 
1926   for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1927        E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
1928     if (ArgIndex > (unsigned)IsMemberCall)
1929       Out << ", ";
1930 
1931     const ParmVarDecl *Param = *I;
1932     APValue *V = Info.getParamSlot(Arguments, Param);
1933     if (V)
1934       V->printPretty(Out, Info.Ctx, Param->getType());
1935     else
1936       Out << "<...>";
1937 
1938     if (ArgIndex == 0 && IsMemberCall)
1939       Out << "->" << *Callee << '(';
1940   }
1941 
1942   Out << ')';
1943 }
1944 
1945 /// Evaluate an expression to see if it had side-effects, and discard its
1946 /// result.
1947 /// \return \c true if the caller should keep evaluating.
1948 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1949   assert(!E->isValueDependent());
1950   APValue Scratch;
1951   if (!Evaluate(Scratch, Info, E))
1952     // We don't need the value, but we might have skipped a side effect here.
1953     return Info.noteSideEffect();
1954   return true;
1955 }
1956 
1957 /// Should this call expression be treated as a constant?
1958 static bool IsConstantCall(const CallExpr *E) {
1959   unsigned Builtin = E->getBuiltinCallee();
1960   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1961           Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
1962           Builtin == Builtin::BI__builtin_function_start);
1963 }
1964 
1965 static bool IsGlobalLValue(APValue::LValueBase B) {
1966   // C++11 [expr.const]p3 An address constant expression is a prvalue core
1967   // constant expression of pointer type that evaluates to...
1968 
1969   // ... a null pointer value, or a prvalue core constant expression of type
1970   // std::nullptr_t.
1971   if (!B) return true;
1972 
1973   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1974     // ... the address of an object with static storage duration,
1975     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1976       return VD->hasGlobalStorage();
1977     if (isa<TemplateParamObjectDecl>(D))
1978       return true;
1979     // ... the address of a function,
1980     // ... the address of a GUID [MS extension],
1981     // ... the address of an unnamed global constant
1982     return isa<FunctionDecl, MSGuidDecl, UnnamedGlobalConstantDecl>(D);
1983   }
1984 
1985   if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
1986     return true;
1987 
1988   const Expr *E = B.get<const Expr*>();
1989   switch (E->getStmtClass()) {
1990   default:
1991     return false;
1992   case Expr::CompoundLiteralExprClass: {
1993     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1994     return CLE->isFileScope() && CLE->isLValue();
1995   }
1996   case Expr::MaterializeTemporaryExprClass:
1997     // A materialized temporary might have been lifetime-extended to static
1998     // storage duration.
1999     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
2000   // A string literal has static storage duration.
2001   case Expr::StringLiteralClass:
2002   case Expr::PredefinedExprClass:
2003   case Expr::ObjCStringLiteralClass:
2004   case Expr::ObjCEncodeExprClass:
2005     return true;
2006   case Expr::ObjCBoxedExprClass:
2007     return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2008   case Expr::CallExprClass:
2009     return IsConstantCall(cast<CallExpr>(E));
2010   // For GCC compatibility, &&label has static storage duration.
2011   case Expr::AddrLabelExprClass:
2012     return true;
2013   // A Block literal expression may be used as the initialization value for
2014   // Block variables at global or local static scope.
2015   case Expr::BlockExprClass:
2016     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2017   // The APValue generated from a __builtin_source_location will be emitted as a
2018   // literal.
2019   case Expr::SourceLocExprClass:
2020     return true;
2021   case Expr::ImplicitValueInitExprClass:
2022     // FIXME:
2023     // We can never form an lvalue with an implicit value initialization as its
2024     // base through expression evaluation, so these only appear in one case: the
2025     // implicit variable declaration we invent when checking whether a constexpr
2026     // constructor can produce a constant expression. We must assume that such
2027     // an expression might be a global lvalue.
2028     return true;
2029   }
2030 }
2031 
2032 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2033   return LVal.Base.dyn_cast<const ValueDecl*>();
2034 }
2035 
2036 static bool IsLiteralLValue(const LValue &Value) {
2037   if (Value.getLValueCallIndex())
2038     return false;
2039   const Expr *E = Value.Base.dyn_cast<const Expr*>();
2040   return E && !isa<MaterializeTemporaryExpr>(E);
2041 }
2042 
2043 static bool IsWeakLValue(const LValue &Value) {
2044   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2045   return Decl && Decl->isWeak();
2046 }
2047 
2048 static bool isZeroSized(const LValue &Value) {
2049   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2050   if (Decl && isa<VarDecl>(Decl)) {
2051     QualType Ty = Decl->getType();
2052     if (Ty->isArrayType())
2053       return Ty->isIncompleteType() ||
2054              Decl->getASTContext().getTypeSize(Ty) == 0;
2055   }
2056   return false;
2057 }
2058 
2059 static bool HasSameBase(const LValue &A, const LValue &B) {
2060   if (!A.getLValueBase())
2061     return !B.getLValueBase();
2062   if (!B.getLValueBase())
2063     return false;
2064 
2065   if (A.getLValueBase().getOpaqueValue() !=
2066       B.getLValueBase().getOpaqueValue())
2067     return false;
2068 
2069   return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2070          A.getLValueVersion() == B.getLValueVersion();
2071 }
2072 
2073 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2074   assert(Base && "no location for a null lvalue");
2075   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2076 
2077   // For a parameter, find the corresponding call stack frame (if it still
2078   // exists), and point at the parameter of the function definition we actually
2079   // invoked.
2080   if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2081     unsigned Idx = PVD->getFunctionScopeIndex();
2082     for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2083       if (F->Arguments.CallIndex == Base.getCallIndex() &&
2084           F->Arguments.Version == Base.getVersion() && F->Callee &&
2085           Idx < F->Callee->getNumParams()) {
2086         VD = F->Callee->getParamDecl(Idx);
2087         break;
2088       }
2089     }
2090   }
2091 
2092   if (VD)
2093     Info.Note(VD->getLocation(), diag::note_declared_at);
2094   else if (const Expr *E = Base.dyn_cast<const Expr*>())
2095     Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2096   else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2097     // FIXME: Produce a note for dangling pointers too.
2098     if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA))
2099       Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2100                 diag::note_constexpr_dynamic_alloc_here);
2101   }
2102   // We have no information to show for a typeid(T) object.
2103 }
2104 
2105 enum class CheckEvaluationResultKind {
2106   ConstantExpression,
2107   FullyInitialized,
2108 };
2109 
2110 /// Materialized temporaries that we've already checked to determine if they're
2111 /// initializsed by a constant expression.
2112 using CheckedTemporaries =
2113     llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
2114 
2115 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2116                                   EvalInfo &Info, SourceLocation DiagLoc,
2117                                   QualType Type, const APValue &Value,
2118                                   ConstantExprKind Kind,
2119                                   SourceLocation SubobjectLoc,
2120                                   CheckedTemporaries &CheckedTemps);
2121 
2122 /// Check that this reference or pointer core constant expression is a valid
2123 /// value for an address or reference constant expression. Return true if we
2124 /// can fold this expression, whether or not it's a constant expression.
2125 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2126                                           QualType Type, const LValue &LVal,
2127                                           ConstantExprKind Kind,
2128                                           CheckedTemporaries &CheckedTemps) {
2129   bool IsReferenceType = Type->isReferenceType();
2130 
2131   APValue::LValueBase Base = LVal.getLValueBase();
2132   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2133 
2134   const Expr *BaseE = Base.dyn_cast<const Expr *>();
2135   const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2136 
2137   // Additional restrictions apply in a template argument. We only enforce the
2138   // C++20 restrictions here; additional syntactic and semantic restrictions
2139   // are applied elsewhere.
2140   if (isTemplateArgument(Kind)) {
2141     int InvalidBaseKind = -1;
2142     StringRef Ident;
2143     if (Base.is<TypeInfoLValue>())
2144       InvalidBaseKind = 0;
2145     else if (isa_and_nonnull<StringLiteral>(BaseE))
2146       InvalidBaseKind = 1;
2147     else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2148              isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2149       InvalidBaseKind = 2;
2150     else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2151       InvalidBaseKind = 3;
2152       Ident = PE->getIdentKindName();
2153     }
2154 
2155     if (InvalidBaseKind != -1) {
2156       Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2157           << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2158           << Ident;
2159       return false;
2160     }
2161   }
2162 
2163   if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD)) {
2164     if (FD->isConsteval()) {
2165       Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2166           << !Type->isAnyPointerType();
2167       Info.Note(FD->getLocation(), diag::note_declared_at);
2168       return false;
2169     }
2170   }
2171 
2172   // Check that the object is a global. Note that the fake 'this' object we
2173   // manufacture when checking potential constant expressions is conservatively
2174   // assumed to be global here.
2175   if (!IsGlobalLValue(Base)) {
2176     if (Info.getLangOpts().CPlusPlus11) {
2177       const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2178       Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2179         << IsReferenceType << !Designator.Entries.empty()
2180         << !!VD << VD;
2181 
2182       auto *VarD = dyn_cast_or_null<VarDecl>(VD);
2183       if (VarD && VarD->isConstexpr()) {
2184         // Non-static local constexpr variables have unintuitive semantics:
2185         //   constexpr int a = 1;
2186         //   constexpr const int *p = &a;
2187         // ... is invalid because the address of 'a' is not constant. Suggest
2188         // adding a 'static' in this case.
2189         Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2190             << VarD
2191             << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2192       } else {
2193         NoteLValueLocation(Info, Base);
2194       }
2195     } else {
2196       Info.FFDiag(Loc);
2197     }
2198     // Don't allow references to temporaries to escape.
2199     return false;
2200   }
2201   assert((Info.checkingPotentialConstantExpression() ||
2202           LVal.getLValueCallIndex() == 0) &&
2203          "have call index for global lvalue");
2204 
2205   if (Base.is<DynamicAllocLValue>()) {
2206     Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2207         << IsReferenceType << !Designator.Entries.empty();
2208     NoteLValueLocation(Info, Base);
2209     return false;
2210   }
2211 
2212   if (BaseVD) {
2213     if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2214       // Check if this is a thread-local variable.
2215       if (Var->getTLSKind())
2216         // FIXME: Diagnostic!
2217         return false;
2218 
2219       // A dllimport variable never acts like a constant, unless we're
2220       // evaluating a value for use only in name mangling.
2221       if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2222         // FIXME: Diagnostic!
2223         return false;
2224 
2225       // In CUDA/HIP device compilation, only device side variables have
2226       // constant addresses.
2227       if (Info.getCtx().getLangOpts().CUDA &&
2228           Info.getCtx().getLangOpts().CUDAIsDevice &&
2229           Info.getCtx().CUDAConstantEvalCtx.NoWrongSidedVars) {
2230         if ((!Var->hasAttr<CUDADeviceAttr>() &&
2231              !Var->hasAttr<CUDAConstantAttr>() &&
2232              !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2233              !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
2234             Var->hasAttr<HIPManagedAttr>())
2235           return false;
2236       }
2237     }
2238     if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2239       // __declspec(dllimport) must be handled very carefully:
2240       // We must never initialize an expression with the thunk in C++.
2241       // Doing otherwise would allow the same id-expression to yield
2242       // different addresses for the same function in different translation
2243       // units.  However, this means that we must dynamically initialize the
2244       // expression with the contents of the import address table at runtime.
2245       //
2246       // The C language has no notion of ODR; furthermore, it has no notion of
2247       // dynamic initialization.  This means that we are permitted to
2248       // perform initialization with the address of the thunk.
2249       if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2250           FD->hasAttr<DLLImportAttr>())
2251         // FIXME: Diagnostic!
2252         return false;
2253     }
2254   } else if (const auto *MTE =
2255                  dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2256     if (CheckedTemps.insert(MTE).second) {
2257       QualType TempType = getType(Base);
2258       if (TempType.isDestructedType()) {
2259         Info.FFDiag(MTE->getExprLoc(),
2260                     diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2261             << TempType;
2262         return false;
2263       }
2264 
2265       APValue *V = MTE->getOrCreateValue(false);
2266       assert(V && "evasluation result refers to uninitialised temporary");
2267       if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2268                                  Info, MTE->getExprLoc(), TempType, *V,
2269                                  Kind, SourceLocation(), CheckedTemps))
2270         return false;
2271     }
2272   }
2273 
2274   // Allow address constant expressions to be past-the-end pointers. This is
2275   // an extension: the standard requires them to point to an object.
2276   if (!IsReferenceType)
2277     return true;
2278 
2279   // A reference constant expression must refer to an object.
2280   if (!Base) {
2281     // FIXME: diagnostic
2282     Info.CCEDiag(Loc);
2283     return true;
2284   }
2285 
2286   // Does this refer one past the end of some object?
2287   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2288     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2289       << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2290     NoteLValueLocation(Info, Base);
2291   }
2292 
2293   return true;
2294 }
2295 
2296 /// Member pointers are constant expressions unless they point to a
2297 /// non-virtual dllimport member function.
2298 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2299                                                  SourceLocation Loc,
2300                                                  QualType Type,
2301                                                  const APValue &Value,
2302                                                  ConstantExprKind Kind) {
2303   const ValueDecl *Member = Value.getMemberPointerDecl();
2304   const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2305   if (!FD)
2306     return true;
2307   if (FD->isConsteval()) {
2308     Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2309     Info.Note(FD->getLocation(), diag::note_declared_at);
2310     return false;
2311   }
2312   return isForManglingOnly(Kind) || FD->isVirtual() ||
2313          !FD->hasAttr<DLLImportAttr>();
2314 }
2315 
2316 /// Check that this core constant expression is of literal type, and if not,
2317 /// produce an appropriate diagnostic.
2318 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2319                              const LValue *This = nullptr) {
2320   if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2321     return true;
2322 
2323   // C++1y: A constant initializer for an object o [...] may also invoke
2324   // constexpr constructors for o and its subobjects even if those objects
2325   // are of non-literal class types.
2326   //
2327   // C++11 missed this detail for aggregates, so classes like this:
2328   //   struct foo_t { union { int i; volatile int j; } u; };
2329   // are not (obviously) initializable like so:
2330   //   __attribute__((__require_constant_initialization__))
2331   //   static const foo_t x = {{0}};
2332   // because "i" is a subobject with non-literal initialization (due to the
2333   // volatile member of the union). See:
2334   //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2335   // Therefore, we use the C++1y behavior.
2336   if (This && Info.EvaluatingDecl == This->getLValueBase())
2337     return true;
2338 
2339   // Prvalue constant expressions must be of literal types.
2340   if (Info.getLangOpts().CPlusPlus11)
2341     Info.FFDiag(E, diag::note_constexpr_nonliteral)
2342       << E->getType();
2343   else
2344     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2345   return false;
2346 }
2347 
2348 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2349                                   EvalInfo &Info, SourceLocation DiagLoc,
2350                                   QualType Type, const APValue &Value,
2351                                   ConstantExprKind Kind,
2352                                   SourceLocation SubobjectLoc,
2353                                   CheckedTemporaries &CheckedTemps) {
2354   if (!Value.hasValue()) {
2355     Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2356       << true << Type;
2357     if (SubobjectLoc.isValid())
2358       Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2359     return false;
2360   }
2361 
2362   // We allow _Atomic(T) to be initialized from anything that T can be
2363   // initialized from.
2364   if (const AtomicType *AT = Type->getAs<AtomicType>())
2365     Type = AT->getValueType();
2366 
2367   // Core issue 1454: For a literal constant expression of array or class type,
2368   // each subobject of its value shall have been initialized by a constant
2369   // expression.
2370   if (Value.isArray()) {
2371     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2372     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2373       if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2374                                  Value.getArrayInitializedElt(I), Kind,
2375                                  SubobjectLoc, CheckedTemps))
2376         return false;
2377     }
2378     if (!Value.hasArrayFiller())
2379       return true;
2380     return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2381                                  Value.getArrayFiller(), Kind, SubobjectLoc,
2382                                  CheckedTemps);
2383   }
2384   if (Value.isUnion() && Value.getUnionField()) {
2385     return CheckEvaluationResult(
2386         CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2387         Value.getUnionValue(), Kind, Value.getUnionField()->getLocation(),
2388         CheckedTemps);
2389   }
2390   if (Value.isStruct()) {
2391     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2392     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2393       unsigned BaseIndex = 0;
2394       for (const CXXBaseSpecifier &BS : CD->bases()) {
2395         if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2396                                    Value.getStructBase(BaseIndex), Kind,
2397                                    BS.getBeginLoc(), CheckedTemps))
2398           return false;
2399         ++BaseIndex;
2400       }
2401     }
2402     for (const auto *I : RD->fields()) {
2403       if (I->isUnnamedBitfield())
2404         continue;
2405 
2406       if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2407                                  Value.getStructField(I->getFieldIndex()),
2408                                  Kind, I->getLocation(), CheckedTemps))
2409         return false;
2410     }
2411   }
2412 
2413   if (Value.isLValue() &&
2414       CERK == CheckEvaluationResultKind::ConstantExpression) {
2415     LValue LVal;
2416     LVal.setFrom(Info.Ctx, Value);
2417     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2418                                          CheckedTemps);
2419   }
2420 
2421   if (Value.isMemberPointer() &&
2422       CERK == CheckEvaluationResultKind::ConstantExpression)
2423     return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2424 
2425   // Everything else is fine.
2426   return true;
2427 }
2428 
2429 /// Check that this core constant expression value is a valid value for a
2430 /// constant expression. If not, report an appropriate diagnostic. Does not
2431 /// check that the expression is of literal type.
2432 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2433                                     QualType Type, const APValue &Value,
2434                                     ConstantExprKind Kind) {
2435   // Nothing to check for a constant expression of type 'cv void'.
2436   if (Type->isVoidType())
2437     return true;
2438 
2439   CheckedTemporaries CheckedTemps;
2440   return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2441                                Info, DiagLoc, Type, Value, Kind,
2442                                SourceLocation(), CheckedTemps);
2443 }
2444 
2445 /// Check that this evaluated value is fully-initialized and can be loaded by
2446 /// an lvalue-to-rvalue conversion.
2447 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2448                                   QualType Type, const APValue &Value) {
2449   CheckedTemporaries CheckedTemps;
2450   return CheckEvaluationResult(
2451       CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2452       ConstantExprKind::Normal, SourceLocation(), CheckedTemps);
2453 }
2454 
2455 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2456 /// "the allocated storage is deallocated within the evaluation".
2457 static bool CheckMemoryLeaks(EvalInfo &Info) {
2458   if (!Info.HeapAllocs.empty()) {
2459     // We can still fold to a constant despite a compile-time memory leak,
2460     // so long as the heap allocation isn't referenced in the result (we check
2461     // that in CheckConstantExpression).
2462     Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2463                  diag::note_constexpr_memory_leak)
2464         << unsigned(Info.HeapAllocs.size() - 1);
2465   }
2466   return true;
2467 }
2468 
2469 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2470   // A null base expression indicates a null pointer.  These are always
2471   // evaluatable, and they are false unless the offset is zero.
2472   if (!Value.getLValueBase()) {
2473     Result = !Value.getLValueOffset().isZero();
2474     return true;
2475   }
2476 
2477   // We have a non-null base.  These are generally known to be true, but if it's
2478   // a weak declaration it can be null at runtime.
2479   Result = true;
2480   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2481   return !Decl || !Decl->isWeak();
2482 }
2483 
2484 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2485   switch (Val.getKind()) {
2486   case APValue::None:
2487   case APValue::Indeterminate:
2488     return false;
2489   case APValue::Int:
2490     Result = Val.getInt().getBoolValue();
2491     return true;
2492   case APValue::FixedPoint:
2493     Result = Val.getFixedPoint().getBoolValue();
2494     return true;
2495   case APValue::Float:
2496     Result = !Val.getFloat().isZero();
2497     return true;
2498   case APValue::ComplexInt:
2499     Result = Val.getComplexIntReal().getBoolValue() ||
2500              Val.getComplexIntImag().getBoolValue();
2501     return true;
2502   case APValue::ComplexFloat:
2503     Result = !Val.getComplexFloatReal().isZero() ||
2504              !Val.getComplexFloatImag().isZero();
2505     return true;
2506   case APValue::LValue:
2507     return EvalPointerValueAsBool(Val, Result);
2508   case APValue::MemberPointer:
2509     Result = Val.getMemberPointerDecl();
2510     return true;
2511   case APValue::Vector:
2512   case APValue::Array:
2513   case APValue::Struct:
2514   case APValue::Union:
2515   case APValue::AddrLabelDiff:
2516     return false;
2517   }
2518 
2519   llvm_unreachable("unknown APValue kind");
2520 }
2521 
2522 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2523                                        EvalInfo &Info) {
2524   assert(!E->isValueDependent());
2525   assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2526   APValue Val;
2527   if (!Evaluate(Val, Info, E))
2528     return false;
2529   return HandleConversionToBool(Val, Result);
2530 }
2531 
2532 template<typename T>
2533 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2534                            const T &SrcValue, QualType DestType) {
2535   Info.CCEDiag(E, diag::note_constexpr_overflow)
2536     << SrcValue << DestType;
2537   return Info.noteUndefinedBehavior();
2538 }
2539 
2540 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2541                                  QualType SrcType, const APFloat &Value,
2542                                  QualType DestType, APSInt &Result) {
2543   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2544   // Determine whether we are converting to unsigned or signed.
2545   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2546 
2547   Result = APSInt(DestWidth, !DestSigned);
2548   bool ignored;
2549   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2550       & APFloat::opInvalidOp)
2551     return HandleOverflow(Info, E, Value, DestType);
2552   return true;
2553 }
2554 
2555 /// Get rounding mode used for evaluation of the specified expression.
2556 /// \param[out] DynamicRM Is set to true is the requested rounding mode is
2557 ///                       dynamic.
2558 /// If rounding mode is unknown at compile time, still try to evaluate the
2559 /// expression. If the result is exact, it does not depend on rounding mode.
2560 /// So return "tonearest" mode instead of "dynamic".
2561 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E,
2562                                                 bool &DynamicRM) {
2563   llvm::RoundingMode RM =
2564       E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2565   DynamicRM = (RM == llvm::RoundingMode::Dynamic);
2566   if (DynamicRM)
2567     RM = llvm::RoundingMode::NearestTiesToEven;
2568   return RM;
2569 }
2570 
2571 /// Check if the given evaluation result is allowed for constant evaluation.
2572 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2573                                      APFloat::opStatus St) {
2574   // In a constant context, assume that any dynamic rounding mode or FP
2575   // exception state matches the default floating-point environment.
2576   if (Info.InConstantContext)
2577     return true;
2578 
2579   FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2580   if ((St & APFloat::opInexact) &&
2581       FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2582     // Inexact result means that it depends on rounding mode. If the requested
2583     // mode is dynamic, the evaluation cannot be made in compile time.
2584     Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2585     return false;
2586   }
2587 
2588   if ((St != APFloat::opOK) &&
2589       (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2590        FPO.getFPExceptionMode() != LangOptions::FPE_Ignore ||
2591        FPO.getAllowFEnvAccess())) {
2592     Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2593     return false;
2594   }
2595 
2596   if ((St & APFloat::opStatus::opInvalidOp) &&
2597       FPO.getFPExceptionMode() != LangOptions::FPE_Ignore) {
2598     // There is no usefully definable result.
2599     Info.FFDiag(E);
2600     return false;
2601   }
2602 
2603   // FIXME: if:
2604   // - evaluation triggered other FP exception, and
2605   // - exception mode is not "ignore", and
2606   // - the expression being evaluated is not a part of global variable
2607   //   initializer,
2608   // the evaluation probably need to be rejected.
2609   return true;
2610 }
2611 
2612 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2613                                    QualType SrcType, QualType DestType,
2614                                    APFloat &Result) {
2615   assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E));
2616   bool DynamicRM;
2617   llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM);
2618   APFloat::opStatus St;
2619   APFloat Value = Result;
2620   bool ignored;
2621   St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2622   return checkFloatingPointResult(Info, E, St);
2623 }
2624 
2625 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2626                                  QualType DestType, QualType SrcType,
2627                                  const APSInt &Value) {
2628   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2629   // Figure out if this is a truncate, extend or noop cast.
2630   // If the input is signed, do a sign extend, noop, or truncate.
2631   APSInt Result = Value.extOrTrunc(DestWidth);
2632   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2633   if (DestType->isBooleanType())
2634     Result = Value.getBoolValue();
2635   return Result;
2636 }
2637 
2638 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2639                                  const FPOptions FPO,
2640                                  QualType SrcType, const APSInt &Value,
2641                                  QualType DestType, APFloat &Result) {
2642   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2643   APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(),
2644        APFloat::rmNearestTiesToEven);
2645   if (!Info.InConstantContext && St != llvm::APFloatBase::opOK &&
2646       FPO.isFPConstrained()) {
2647     Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2648     return false;
2649   }
2650   return true;
2651 }
2652 
2653 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2654                                   APValue &Value, const FieldDecl *FD) {
2655   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2656 
2657   if (!Value.isInt()) {
2658     // Trying to store a pointer-cast-to-integer into a bitfield.
2659     // FIXME: In this case, we should provide the diagnostic for casting
2660     // a pointer to an integer.
2661     assert(Value.isLValue() && "integral value neither int nor lvalue?");
2662     Info.FFDiag(E);
2663     return false;
2664   }
2665 
2666   APSInt &Int = Value.getInt();
2667   unsigned OldBitWidth = Int.getBitWidth();
2668   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2669   if (NewBitWidth < OldBitWidth)
2670     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2671   return true;
2672 }
2673 
2674 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2675                                   llvm::APInt &Res) {
2676   APValue SVal;
2677   if (!Evaluate(SVal, Info, E))
2678     return false;
2679   if (SVal.isInt()) {
2680     Res = SVal.getInt();
2681     return true;
2682   }
2683   if (SVal.isFloat()) {
2684     Res = SVal.getFloat().bitcastToAPInt();
2685     return true;
2686   }
2687   if (SVal.isVector()) {
2688     QualType VecTy = E->getType();
2689     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2690     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2691     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2692     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2693     Res = llvm::APInt::getZero(VecSize);
2694     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2695       APValue &Elt = SVal.getVectorElt(i);
2696       llvm::APInt EltAsInt;
2697       if (Elt.isInt()) {
2698         EltAsInt = Elt.getInt();
2699       } else if (Elt.isFloat()) {
2700         EltAsInt = Elt.getFloat().bitcastToAPInt();
2701       } else {
2702         // Don't try to handle vectors of anything other than int or float
2703         // (not sure if it's possible to hit this case).
2704         Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2705         return false;
2706       }
2707       unsigned BaseEltSize = EltAsInt.getBitWidth();
2708       if (BigEndian)
2709         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2710       else
2711         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2712     }
2713     return true;
2714   }
2715   // Give up if the input isn't an int, float, or vector.  For example, we
2716   // reject "(v4i16)(intptr_t)&a".
2717   Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2718   return false;
2719 }
2720 
2721 /// Perform the given integer operation, which is known to need at most BitWidth
2722 /// bits, and check for overflow in the original type (if that type was not an
2723 /// unsigned type).
2724 template<typename Operation>
2725 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2726                                  const APSInt &LHS, const APSInt &RHS,
2727                                  unsigned BitWidth, Operation Op,
2728                                  APSInt &Result) {
2729   if (LHS.isUnsigned()) {
2730     Result = Op(LHS, RHS);
2731     return true;
2732   }
2733 
2734   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2735   Result = Value.trunc(LHS.getBitWidth());
2736   if (Result.extend(BitWidth) != Value) {
2737     if (Info.checkingForUndefinedBehavior())
2738       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2739                                        diag::warn_integer_constant_overflow)
2740           << toString(Result, 10) << E->getType();
2741     return HandleOverflow(Info, E, Value, E->getType());
2742   }
2743   return true;
2744 }
2745 
2746 /// Perform the given binary integer operation.
2747 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2748                               BinaryOperatorKind Opcode, APSInt RHS,
2749                               APSInt &Result) {
2750   switch (Opcode) {
2751   default:
2752     Info.FFDiag(E);
2753     return false;
2754   case BO_Mul:
2755     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2756                                 std::multiplies<APSInt>(), Result);
2757   case BO_Add:
2758     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2759                                 std::plus<APSInt>(), Result);
2760   case BO_Sub:
2761     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2762                                 std::minus<APSInt>(), Result);
2763   case BO_And: Result = LHS & RHS; return true;
2764   case BO_Xor: Result = LHS ^ RHS; return true;
2765   case BO_Or:  Result = LHS | RHS; return true;
2766   case BO_Div:
2767   case BO_Rem:
2768     if (RHS == 0) {
2769       Info.FFDiag(E, diag::note_expr_divide_by_zero);
2770       return false;
2771     }
2772     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2773     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2774     // this operation and gives the two's complement result.
2775     if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2776         LHS.isMinSignedValue())
2777       return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2778                             E->getType());
2779     return true;
2780   case BO_Shl: {
2781     if (Info.getLangOpts().OpenCL)
2782       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2783       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2784                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2785                     RHS.isUnsigned());
2786     else if (RHS.isSigned() && RHS.isNegative()) {
2787       // During constant-folding, a negative shift is an opposite shift. Such
2788       // a shift is not a constant expression.
2789       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2790       RHS = -RHS;
2791       goto shift_right;
2792     }
2793   shift_left:
2794     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2795     // the shifted type.
2796     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2797     if (SA != RHS) {
2798       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2799         << RHS << E->getType() << LHS.getBitWidth();
2800     } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2801       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2802       // operand, and must not overflow the corresponding unsigned type.
2803       // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2804       // E1 x 2^E2 module 2^N.
2805       if (LHS.isNegative())
2806         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2807       else if (LHS.countLeadingZeros() < SA)
2808         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2809     }
2810     Result = LHS << SA;
2811     return true;
2812   }
2813   case BO_Shr: {
2814     if (Info.getLangOpts().OpenCL)
2815       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2816       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2817                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2818                     RHS.isUnsigned());
2819     else if (RHS.isSigned() && RHS.isNegative()) {
2820       // During constant-folding, a negative shift is an opposite shift. Such a
2821       // shift is not a constant expression.
2822       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2823       RHS = -RHS;
2824       goto shift_left;
2825     }
2826   shift_right:
2827     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2828     // shifted type.
2829     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2830     if (SA != RHS)
2831       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2832         << RHS << E->getType() << LHS.getBitWidth();
2833     Result = LHS >> SA;
2834     return true;
2835   }
2836 
2837   case BO_LT: Result = LHS < RHS; return true;
2838   case BO_GT: Result = LHS > RHS; return true;
2839   case BO_LE: Result = LHS <= RHS; return true;
2840   case BO_GE: Result = LHS >= RHS; return true;
2841   case BO_EQ: Result = LHS == RHS; return true;
2842   case BO_NE: Result = LHS != RHS; return true;
2843   case BO_Cmp:
2844     llvm_unreachable("BO_Cmp should be handled elsewhere");
2845   }
2846 }
2847 
2848 /// Perform the given binary floating-point operation, in-place, on LHS.
2849 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2850                                   APFloat &LHS, BinaryOperatorKind Opcode,
2851                                   const APFloat &RHS) {
2852   bool DynamicRM;
2853   llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM);
2854   APFloat::opStatus St;
2855   switch (Opcode) {
2856   default:
2857     Info.FFDiag(E);
2858     return false;
2859   case BO_Mul:
2860     St = LHS.multiply(RHS, RM);
2861     break;
2862   case BO_Add:
2863     St = LHS.add(RHS, RM);
2864     break;
2865   case BO_Sub:
2866     St = LHS.subtract(RHS, RM);
2867     break;
2868   case BO_Div:
2869     // [expr.mul]p4:
2870     //   If the second operand of / or % is zero the behavior is undefined.
2871     if (RHS.isZero())
2872       Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2873     St = LHS.divide(RHS, RM);
2874     break;
2875   }
2876 
2877   // [expr.pre]p4:
2878   //   If during the evaluation of an expression, the result is not
2879   //   mathematically defined [...], the behavior is undefined.
2880   // FIXME: C++ rules require us to not conform to IEEE 754 here.
2881   if (LHS.isNaN()) {
2882     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2883     return Info.noteUndefinedBehavior();
2884   }
2885 
2886   return checkFloatingPointResult(Info, E, St);
2887 }
2888 
2889 static bool handleLogicalOpForVector(const APInt &LHSValue,
2890                                      BinaryOperatorKind Opcode,
2891                                      const APInt &RHSValue, APInt &Result) {
2892   bool LHS = (LHSValue != 0);
2893   bool RHS = (RHSValue != 0);
2894 
2895   if (Opcode == BO_LAnd)
2896     Result = LHS && RHS;
2897   else
2898     Result = LHS || RHS;
2899   return true;
2900 }
2901 static bool handleLogicalOpForVector(const APFloat &LHSValue,
2902                                      BinaryOperatorKind Opcode,
2903                                      const APFloat &RHSValue, APInt &Result) {
2904   bool LHS = !LHSValue.isZero();
2905   bool RHS = !RHSValue.isZero();
2906 
2907   if (Opcode == BO_LAnd)
2908     Result = LHS && RHS;
2909   else
2910     Result = LHS || RHS;
2911   return true;
2912 }
2913 
2914 static bool handleLogicalOpForVector(const APValue &LHSValue,
2915                                      BinaryOperatorKind Opcode,
2916                                      const APValue &RHSValue, APInt &Result) {
2917   // The result is always an int type, however operands match the first.
2918   if (LHSValue.getKind() == APValue::Int)
2919     return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2920                                     RHSValue.getInt(), Result);
2921   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2922   return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2923                                   RHSValue.getFloat(), Result);
2924 }
2925 
2926 template <typename APTy>
2927 static bool
2928 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
2929                                const APTy &RHSValue, APInt &Result) {
2930   switch (Opcode) {
2931   default:
2932     llvm_unreachable("unsupported binary operator");
2933   case BO_EQ:
2934     Result = (LHSValue == RHSValue);
2935     break;
2936   case BO_NE:
2937     Result = (LHSValue != RHSValue);
2938     break;
2939   case BO_LT:
2940     Result = (LHSValue < RHSValue);
2941     break;
2942   case BO_GT:
2943     Result = (LHSValue > RHSValue);
2944     break;
2945   case BO_LE:
2946     Result = (LHSValue <= RHSValue);
2947     break;
2948   case BO_GE:
2949     Result = (LHSValue >= RHSValue);
2950     break;
2951   }
2952 
2953   // The boolean operations on these vector types use an instruction that
2954   // results in a mask of '-1' for the 'truth' value.  Ensure that we negate 1
2955   // to -1 to make sure that we produce the correct value.
2956   Result.negate();
2957 
2958   return true;
2959 }
2960 
2961 static bool handleCompareOpForVector(const APValue &LHSValue,
2962                                      BinaryOperatorKind Opcode,
2963                                      const APValue &RHSValue, APInt &Result) {
2964   // The result is always an int type, however operands match the first.
2965   if (LHSValue.getKind() == APValue::Int)
2966     return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
2967                                           RHSValue.getInt(), Result);
2968   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2969   return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
2970                                         RHSValue.getFloat(), Result);
2971 }
2972 
2973 // Perform binary operations for vector types, in place on the LHS.
2974 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
2975                                     BinaryOperatorKind Opcode,
2976                                     APValue &LHSValue,
2977                                     const APValue &RHSValue) {
2978   assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
2979          "Operation not supported on vector types");
2980 
2981   const auto *VT = E->getType()->castAs<VectorType>();
2982   unsigned NumElements = VT->getNumElements();
2983   QualType EltTy = VT->getElementType();
2984 
2985   // In the cases (typically C as I've observed) where we aren't evaluating
2986   // constexpr but are checking for cases where the LHS isn't yet evaluatable,
2987   // just give up.
2988   if (!LHSValue.isVector()) {
2989     assert(LHSValue.isLValue() &&
2990            "A vector result that isn't a vector OR uncalculated LValue");
2991     Info.FFDiag(E);
2992     return false;
2993   }
2994 
2995   assert(LHSValue.getVectorLength() == NumElements &&
2996          RHSValue.getVectorLength() == NumElements && "Different vector sizes");
2997 
2998   SmallVector<APValue, 4> ResultElements;
2999 
3000   for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
3001     APValue LHSElt = LHSValue.getVectorElt(EltNum);
3002     APValue RHSElt = RHSValue.getVectorElt(EltNum);
3003 
3004     if (EltTy->isIntegerType()) {
3005       APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3006                        EltTy->isUnsignedIntegerType()};
3007       bool Success = true;
3008 
3009       if (BinaryOperator::isLogicalOp(Opcode))
3010         Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3011       else if (BinaryOperator::isComparisonOp(Opcode))
3012         Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3013       else
3014         Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3015                                     RHSElt.getInt(), EltResult);
3016 
3017       if (!Success) {
3018         Info.FFDiag(E);
3019         return false;
3020       }
3021       ResultElements.emplace_back(EltResult);
3022 
3023     } else if (EltTy->isFloatingType()) {
3024       assert(LHSElt.getKind() == APValue::Float &&
3025              RHSElt.getKind() == APValue::Float &&
3026              "Mismatched LHS/RHS/Result Type");
3027       APFloat LHSFloat = LHSElt.getFloat();
3028 
3029       if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3030                                  RHSElt.getFloat())) {
3031         Info.FFDiag(E);
3032         return false;
3033       }
3034 
3035       ResultElements.emplace_back(LHSFloat);
3036     }
3037   }
3038 
3039   LHSValue = APValue(ResultElements.data(), ResultElements.size());
3040   return true;
3041 }
3042 
3043 /// Cast an lvalue referring to a base subobject to a derived class, by
3044 /// truncating the lvalue's path to the given length.
3045 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3046                                const RecordDecl *TruncatedType,
3047                                unsigned TruncatedElements) {
3048   SubobjectDesignator &D = Result.Designator;
3049 
3050   // Check we actually point to a derived class object.
3051   if (TruncatedElements == D.Entries.size())
3052     return true;
3053   assert(TruncatedElements >= D.MostDerivedPathLength &&
3054          "not casting to a derived class");
3055   if (!Result.checkSubobject(Info, E, CSK_Derived))
3056     return false;
3057 
3058   // Truncate the path to the subobject, and remove any derived-to-base offsets.
3059   const RecordDecl *RD = TruncatedType;
3060   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3061     if (RD->isInvalidDecl()) return false;
3062     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3063     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3064     if (isVirtualBaseClass(D.Entries[I]))
3065       Result.Offset -= Layout.getVBaseClassOffset(Base);
3066     else
3067       Result.Offset -= Layout.getBaseClassOffset(Base);
3068     RD = Base;
3069   }
3070   D.Entries.resize(TruncatedElements);
3071   return true;
3072 }
3073 
3074 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3075                                    const CXXRecordDecl *Derived,
3076                                    const CXXRecordDecl *Base,
3077                                    const ASTRecordLayout *RL = nullptr) {
3078   if (!RL) {
3079     if (Derived->isInvalidDecl()) return false;
3080     RL = &Info.Ctx.getASTRecordLayout(Derived);
3081   }
3082 
3083   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3084   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3085   return true;
3086 }
3087 
3088 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3089                              const CXXRecordDecl *DerivedDecl,
3090                              const CXXBaseSpecifier *Base) {
3091   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3092 
3093   if (!Base->isVirtual())
3094     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3095 
3096   SubobjectDesignator &D = Obj.Designator;
3097   if (D.Invalid)
3098     return false;
3099 
3100   // Extract most-derived object and corresponding type.
3101   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3102   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3103     return false;
3104 
3105   // Find the virtual base class.
3106   if (DerivedDecl->isInvalidDecl()) return false;
3107   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3108   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3109   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3110   return true;
3111 }
3112 
3113 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3114                                  QualType Type, LValue &Result) {
3115   for (CastExpr::path_const_iterator PathI = E->path_begin(),
3116                                      PathE = E->path_end();
3117        PathI != PathE; ++PathI) {
3118     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3119                           *PathI))
3120       return false;
3121     Type = (*PathI)->getType();
3122   }
3123   return true;
3124 }
3125 
3126 /// Cast an lvalue referring to a derived class to a known base subobject.
3127 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3128                             const CXXRecordDecl *DerivedRD,
3129                             const CXXRecordDecl *BaseRD) {
3130   CXXBasePaths Paths(/*FindAmbiguities=*/false,
3131                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
3132   if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3133     llvm_unreachable("Class must be derived from the passed in base class!");
3134 
3135   for (CXXBasePathElement &Elem : Paths.front())
3136     if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3137       return false;
3138   return true;
3139 }
3140 
3141 /// Update LVal to refer to the given field, which must be a member of the type
3142 /// currently described by LVal.
3143 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3144                                const FieldDecl *FD,
3145                                const ASTRecordLayout *RL = nullptr) {
3146   if (!RL) {
3147     if (FD->getParent()->isInvalidDecl()) return false;
3148     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3149   }
3150 
3151   unsigned I = FD->getFieldIndex();
3152   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3153   LVal.addDecl(Info, E, FD);
3154   return true;
3155 }
3156 
3157 /// Update LVal to refer to the given indirect field.
3158 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3159                                        LValue &LVal,
3160                                        const IndirectFieldDecl *IFD) {
3161   for (const auto *C : IFD->chain())
3162     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3163       return false;
3164   return true;
3165 }
3166 
3167 /// Get the size of the given type in char units.
3168 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
3169                          QualType Type, CharUnits &Size) {
3170   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3171   // extension.
3172   if (Type->isVoidType() || Type->isFunctionType()) {
3173     Size = CharUnits::One();
3174     return true;
3175   }
3176 
3177   if (Type->isDependentType()) {
3178     Info.FFDiag(Loc);
3179     return false;
3180   }
3181 
3182   if (!Type->isConstantSizeType()) {
3183     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3184     // FIXME: Better diagnostic.
3185     Info.FFDiag(Loc);
3186     return false;
3187   }
3188 
3189   Size = Info.Ctx.getTypeSizeInChars(Type);
3190   return true;
3191 }
3192 
3193 /// Update a pointer value to model pointer arithmetic.
3194 /// \param Info - Information about the ongoing evaluation.
3195 /// \param E - The expression being evaluated, for diagnostic purposes.
3196 /// \param LVal - The pointer value to be updated.
3197 /// \param EltTy - The pointee type represented by LVal.
3198 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3199 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3200                                         LValue &LVal, QualType EltTy,
3201                                         APSInt Adjustment) {
3202   CharUnits SizeOfPointee;
3203   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3204     return false;
3205 
3206   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3207   return true;
3208 }
3209 
3210 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3211                                         LValue &LVal, QualType EltTy,
3212                                         int64_t Adjustment) {
3213   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3214                                      APSInt::get(Adjustment));
3215 }
3216 
3217 /// Update an lvalue to refer to a component of a complex number.
3218 /// \param Info - Information about the ongoing evaluation.
3219 /// \param LVal - The lvalue to be updated.
3220 /// \param EltTy - The complex number's component type.
3221 /// \param Imag - False for the real component, true for the imaginary.
3222 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3223                                        LValue &LVal, QualType EltTy,
3224                                        bool Imag) {
3225   if (Imag) {
3226     CharUnits SizeOfComponent;
3227     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3228       return false;
3229     LVal.Offset += SizeOfComponent;
3230   }
3231   LVal.addComplex(Info, E, EltTy, Imag);
3232   return true;
3233 }
3234 
3235 /// Try to evaluate the initializer for a variable declaration.
3236 ///
3237 /// \param Info   Information about the ongoing evaluation.
3238 /// \param E      An expression to be used when printing diagnostics.
3239 /// \param VD     The variable whose initializer should be obtained.
3240 /// \param Version The version of the variable within the frame.
3241 /// \param Frame  The frame in which the variable was created. Must be null
3242 ///               if this variable is not local to the evaluation.
3243 /// \param Result Filled in with a pointer to the value of the variable.
3244 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3245                                 const VarDecl *VD, CallStackFrame *Frame,
3246                                 unsigned Version, APValue *&Result) {
3247   APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3248 
3249   // If this is a local variable, dig out its value.
3250   if (Frame) {
3251     Result = Frame->getTemporary(VD, Version);
3252     if (Result)
3253       return true;
3254 
3255     if (!isa<ParmVarDecl>(VD)) {
3256       // Assume variables referenced within a lambda's call operator that were
3257       // not declared within the call operator are captures and during checking
3258       // of a potential constant expression, assume they are unknown constant
3259       // expressions.
3260       assert(isLambdaCallOperator(Frame->Callee) &&
3261              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3262              "missing value for local variable");
3263       if (Info.checkingPotentialConstantExpression())
3264         return false;
3265       // FIXME: This diagnostic is bogus; we do support captures. Is this code
3266       // still reachable at all?
3267       Info.FFDiag(E->getBeginLoc(),
3268                   diag::note_unimplemented_constexpr_lambda_feature_ast)
3269           << "captures not currently allowed";
3270       return false;
3271     }
3272   }
3273 
3274   // If we're currently evaluating the initializer of this declaration, use that
3275   // in-flight value.
3276   if (Info.EvaluatingDecl == Base) {
3277     Result = Info.EvaluatingDeclValue;
3278     return true;
3279   }
3280 
3281   if (isa<ParmVarDecl>(VD)) {
3282     // Assume parameters of a potential constant expression are usable in
3283     // constant expressions.
3284     if (!Info.checkingPotentialConstantExpression() ||
3285         !Info.CurrentCall->Callee ||
3286         !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3287       if (Info.getLangOpts().CPlusPlus11) {
3288         Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3289             << VD;
3290         NoteLValueLocation(Info, Base);
3291       } else {
3292         Info.FFDiag(E);
3293       }
3294     }
3295     return false;
3296   }
3297 
3298   // Dig out the initializer, and use the declaration which it's attached to.
3299   // FIXME: We should eventually check whether the variable has a reachable
3300   // initializing declaration.
3301   const Expr *Init = VD->getAnyInitializer(VD);
3302   if (!Init) {
3303     // Don't diagnose during potential constant expression checking; an
3304     // initializer might be added later.
3305     if (!Info.checkingPotentialConstantExpression()) {
3306       Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3307         << VD;
3308       NoteLValueLocation(Info, Base);
3309     }
3310     return false;
3311   }
3312 
3313   if (Init->isValueDependent()) {
3314     // The DeclRefExpr is not value-dependent, but the variable it refers to
3315     // has a value-dependent initializer. This should only happen in
3316     // constant-folding cases, where the variable is not actually of a suitable
3317     // type for use in a constant expression (otherwise the DeclRefExpr would
3318     // have been value-dependent too), so diagnose that.
3319     assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3320     if (!Info.checkingPotentialConstantExpression()) {
3321       Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3322                          ? diag::note_constexpr_ltor_non_constexpr
3323                          : diag::note_constexpr_ltor_non_integral, 1)
3324           << VD << VD->getType();
3325       NoteLValueLocation(Info, Base);
3326     }
3327     return false;
3328   }
3329 
3330   // Check that we can fold the initializer. In C++, we will have already done
3331   // this in the cases where it matters for conformance.
3332   if (!VD->evaluateValue()) {
3333     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3334     NoteLValueLocation(Info, Base);
3335     return false;
3336   }
3337 
3338   // Check that the variable is actually usable in constant expressions. For a
3339   // const integral variable or a reference, we might have a non-constant
3340   // initializer that we can nonetheless evaluate the initializer for. Such
3341   // variables are not usable in constant expressions. In C++98, the
3342   // initializer also syntactically needs to be an ICE.
3343   //
3344   // FIXME: We don't diagnose cases that aren't potentially usable in constant
3345   // expressions here; doing so would regress diagnostics for things like
3346   // reading from a volatile constexpr variable.
3347   if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3348        VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||
3349       ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3350        !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3351     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3352     NoteLValueLocation(Info, Base);
3353   }
3354 
3355   // Never use the initializer of a weak variable, not even for constant
3356   // folding. We can't be sure that this is the definition that will be used.
3357   if (VD->isWeak()) {
3358     Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3359     NoteLValueLocation(Info, Base);
3360     return false;
3361   }
3362 
3363   Result = VD->getEvaluatedValue();
3364   return true;
3365 }
3366 
3367 /// Get the base index of the given base class within an APValue representing
3368 /// the given derived class.
3369 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3370                              const CXXRecordDecl *Base) {
3371   Base = Base->getCanonicalDecl();
3372   unsigned Index = 0;
3373   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3374          E = Derived->bases_end(); I != E; ++I, ++Index) {
3375     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3376       return Index;
3377   }
3378 
3379   llvm_unreachable("base class missing from derived class's bases list");
3380 }
3381 
3382 /// Extract the value of a character from a string literal.
3383 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3384                                             uint64_t Index) {
3385   assert(!isa<SourceLocExpr>(Lit) &&
3386          "SourceLocExpr should have already been converted to a StringLiteral");
3387 
3388   // FIXME: Support MakeStringConstant
3389   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3390     std::string Str;
3391     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3392     assert(Index <= Str.size() && "Index too large");
3393     return APSInt::getUnsigned(Str.c_str()[Index]);
3394   }
3395 
3396   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3397     Lit = PE->getFunctionName();
3398   const StringLiteral *S = cast<StringLiteral>(Lit);
3399   const ConstantArrayType *CAT =
3400       Info.Ctx.getAsConstantArrayType(S->getType());
3401   assert(CAT && "string literal isn't an array");
3402   QualType CharType = CAT->getElementType();
3403   assert(CharType->isIntegerType() && "unexpected character type");
3404 
3405   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3406                CharType->isUnsignedIntegerType());
3407   if (Index < S->getLength())
3408     Value = S->getCodeUnit(Index);
3409   return Value;
3410 }
3411 
3412 // Expand a string literal into an array of characters.
3413 //
3414 // FIXME: This is inefficient; we should probably introduce something similar
3415 // to the LLVM ConstantDataArray to make this cheaper.
3416 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3417                                 APValue &Result,
3418                                 QualType AllocType = QualType()) {
3419   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3420       AllocType.isNull() ? S->getType() : AllocType);
3421   assert(CAT && "string literal isn't an array");
3422   QualType CharType = CAT->getElementType();
3423   assert(CharType->isIntegerType() && "unexpected character type");
3424 
3425   unsigned Elts = CAT->getSize().getZExtValue();
3426   Result = APValue(APValue::UninitArray(),
3427                    std::min(S->getLength(), Elts), Elts);
3428   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3429                CharType->isUnsignedIntegerType());
3430   if (Result.hasArrayFiller())
3431     Result.getArrayFiller() = APValue(Value);
3432   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3433     Value = S->getCodeUnit(I);
3434     Result.getArrayInitializedElt(I) = APValue(Value);
3435   }
3436 }
3437 
3438 // Expand an array so that it has more than Index filled elements.
3439 static void expandArray(APValue &Array, unsigned Index) {
3440   unsigned Size = Array.getArraySize();
3441   assert(Index < Size);
3442 
3443   // Always at least double the number of elements for which we store a value.
3444   unsigned OldElts = Array.getArrayInitializedElts();
3445   unsigned NewElts = std::max(Index+1, OldElts * 2);
3446   NewElts = std::min(Size, std::max(NewElts, 8u));
3447 
3448   // Copy the data across.
3449   APValue NewValue(APValue::UninitArray(), NewElts, Size);
3450   for (unsigned I = 0; I != OldElts; ++I)
3451     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3452   for (unsigned I = OldElts; I != NewElts; ++I)
3453     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3454   if (NewValue.hasArrayFiller())
3455     NewValue.getArrayFiller() = Array.getArrayFiller();
3456   Array.swap(NewValue);
3457 }
3458 
3459 /// Determine whether a type would actually be read by an lvalue-to-rvalue
3460 /// conversion. If it's of class type, we may assume that the copy operation
3461 /// is trivial. Note that this is never true for a union type with fields
3462 /// (because the copy always "reads" the active member) and always true for
3463 /// a non-class type.
3464 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3465 static bool isReadByLvalueToRvalueConversion(QualType T) {
3466   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3467   return !RD || isReadByLvalueToRvalueConversion(RD);
3468 }
3469 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3470   // FIXME: A trivial copy of a union copies the object representation, even if
3471   // the union is empty.
3472   if (RD->isUnion())
3473     return !RD->field_empty();
3474   if (RD->isEmpty())
3475     return false;
3476 
3477   for (auto *Field : RD->fields())
3478     if (!Field->isUnnamedBitfield() &&
3479         isReadByLvalueToRvalueConversion(Field->getType()))
3480       return true;
3481 
3482   for (auto &BaseSpec : RD->bases())
3483     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3484       return true;
3485 
3486   return false;
3487 }
3488 
3489 /// Diagnose an attempt to read from any unreadable field within the specified
3490 /// type, which might be a class type.
3491 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3492                                   QualType T) {
3493   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3494   if (!RD)
3495     return false;
3496 
3497   if (!RD->hasMutableFields())
3498     return false;
3499 
3500   for (auto *Field : RD->fields()) {
3501     // If we're actually going to read this field in some way, then it can't
3502     // be mutable. If we're in a union, then assigning to a mutable field
3503     // (even an empty one) can change the active member, so that's not OK.
3504     // FIXME: Add core issue number for the union case.
3505     if (Field->isMutable() &&
3506         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3507       Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3508       Info.Note(Field->getLocation(), diag::note_declared_at);
3509       return true;
3510     }
3511 
3512     if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3513       return true;
3514   }
3515 
3516   for (auto &BaseSpec : RD->bases())
3517     if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3518       return true;
3519 
3520   // All mutable fields were empty, and thus not actually read.
3521   return false;
3522 }
3523 
3524 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3525                                         APValue::LValueBase Base,
3526                                         bool MutableSubobject = false) {
3527   // A temporary or transient heap allocation we created.
3528   if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3529     return true;
3530 
3531   switch (Info.IsEvaluatingDecl) {
3532   case EvalInfo::EvaluatingDeclKind::None:
3533     return false;
3534 
3535   case EvalInfo::EvaluatingDeclKind::Ctor:
3536     // The variable whose initializer we're evaluating.
3537     if (Info.EvaluatingDecl == Base)
3538       return true;
3539 
3540     // A temporary lifetime-extended by the variable whose initializer we're
3541     // evaluating.
3542     if (auto *BaseE = Base.dyn_cast<const Expr *>())
3543       if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3544         return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3545     return false;
3546 
3547   case EvalInfo::EvaluatingDeclKind::Dtor:
3548     // C++2a [expr.const]p6:
3549     //   [during constant destruction] the lifetime of a and its non-mutable
3550     //   subobjects (but not its mutable subobjects) [are] considered to start
3551     //   within e.
3552     if (MutableSubobject || Base != Info.EvaluatingDecl)
3553       return false;
3554     // FIXME: We can meaningfully extend this to cover non-const objects, but
3555     // we will need special handling: we should be able to access only
3556     // subobjects of such objects that are themselves declared const.
3557     QualType T = getType(Base);
3558     return T.isConstQualified() || T->isReferenceType();
3559   }
3560 
3561   llvm_unreachable("unknown evaluating decl kind");
3562 }
3563 
3564 namespace {
3565 /// A handle to a complete object (an object that is not a subobject of
3566 /// another object).
3567 struct CompleteObject {
3568   /// The identity of the object.
3569   APValue::LValueBase Base;
3570   /// The value of the complete object.
3571   APValue *Value;
3572   /// The type of the complete object.
3573   QualType Type;
3574 
3575   CompleteObject() : Value(nullptr) {}
3576   CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3577       : Base(Base), Value(Value), Type(Type) {}
3578 
3579   bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3580     // If this isn't a "real" access (eg, if it's just accessing the type
3581     // info), allow it. We assume the type doesn't change dynamically for
3582     // subobjects of constexpr objects (even though we'd hit UB here if it
3583     // did). FIXME: Is this right?
3584     if (!isAnyAccess(AK))
3585       return true;
3586 
3587     // In C++14 onwards, it is permitted to read a mutable member whose
3588     // lifetime began within the evaluation.
3589     // FIXME: Should we also allow this in C++11?
3590     if (!Info.getLangOpts().CPlusPlus14)
3591       return false;
3592     return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3593   }
3594 
3595   explicit operator bool() const { return !Type.isNull(); }
3596 };
3597 } // end anonymous namespace
3598 
3599 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3600                                  bool IsMutable = false) {
3601   // C++ [basic.type.qualifier]p1:
3602   // - A const object is an object of type const T or a non-mutable subobject
3603   //   of a const object.
3604   if (ObjType.isConstQualified() && !IsMutable)
3605     SubobjType.addConst();
3606   // - A volatile object is an object of type const T or a subobject of a
3607   //   volatile object.
3608   if (ObjType.isVolatileQualified())
3609     SubobjType.addVolatile();
3610   return SubobjType;
3611 }
3612 
3613 /// Find the designated sub-object of an rvalue.
3614 template<typename SubobjectHandler>
3615 typename SubobjectHandler::result_type
3616 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3617               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3618   if (Sub.Invalid)
3619     // A diagnostic will have already been produced.
3620     return handler.failed();
3621   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3622     if (Info.getLangOpts().CPlusPlus11)
3623       Info.FFDiag(E, Sub.isOnePastTheEnd()
3624                          ? diag::note_constexpr_access_past_end
3625                          : diag::note_constexpr_access_unsized_array)
3626           << handler.AccessKind;
3627     else
3628       Info.FFDiag(E);
3629     return handler.failed();
3630   }
3631 
3632   APValue *O = Obj.Value;
3633   QualType ObjType = Obj.Type;
3634   const FieldDecl *LastField = nullptr;
3635   const FieldDecl *VolatileField = nullptr;
3636 
3637   // Walk the designator's path to find the subobject.
3638   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3639     // Reading an indeterminate value is undefined, but assigning over one is OK.
3640     if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3641         (O->isIndeterminate() &&
3642          !isValidIndeterminateAccess(handler.AccessKind))) {
3643       if (!Info.checkingPotentialConstantExpression())
3644         Info.FFDiag(E, diag::note_constexpr_access_uninit)
3645             << handler.AccessKind << O->isIndeterminate();
3646       return handler.failed();
3647     }
3648 
3649     // C++ [class.ctor]p5, C++ [class.dtor]p5:
3650     //    const and volatile semantics are not applied on an object under
3651     //    {con,de}struction.
3652     if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3653         ObjType->isRecordType() &&
3654         Info.isEvaluatingCtorDtor(
3655             Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3656                                          Sub.Entries.begin() + I)) !=
3657                           ConstructionPhase::None) {
3658       ObjType = Info.Ctx.getCanonicalType(ObjType);
3659       ObjType.removeLocalConst();
3660       ObjType.removeLocalVolatile();
3661     }
3662 
3663     // If this is our last pass, check that the final object type is OK.
3664     if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3665       // Accesses to volatile objects are prohibited.
3666       if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3667         if (Info.getLangOpts().CPlusPlus) {
3668           int DiagKind;
3669           SourceLocation Loc;
3670           const NamedDecl *Decl = nullptr;
3671           if (VolatileField) {
3672             DiagKind = 2;
3673             Loc = VolatileField->getLocation();
3674             Decl = VolatileField;
3675           } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3676             DiagKind = 1;
3677             Loc = VD->getLocation();
3678             Decl = VD;
3679           } else {
3680             DiagKind = 0;
3681             if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3682               Loc = E->getExprLoc();
3683           }
3684           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3685               << handler.AccessKind << DiagKind << Decl;
3686           Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3687         } else {
3688           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3689         }
3690         return handler.failed();
3691       }
3692 
3693       // If we are reading an object of class type, there may still be more
3694       // things we need to check: if there are any mutable subobjects, we
3695       // cannot perform this read. (This only happens when performing a trivial
3696       // copy or assignment.)
3697       if (ObjType->isRecordType() &&
3698           !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3699           diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3700         return handler.failed();
3701     }
3702 
3703     if (I == N) {
3704       if (!handler.found(*O, ObjType))
3705         return false;
3706 
3707       // If we modified a bit-field, truncate it to the right width.
3708       if (isModification(handler.AccessKind) &&
3709           LastField && LastField->isBitField() &&
3710           !truncateBitfieldValue(Info, E, *O, LastField))
3711         return false;
3712 
3713       return true;
3714     }
3715 
3716     LastField = nullptr;
3717     if (ObjType->isArrayType()) {
3718       // Next subobject is an array element.
3719       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3720       assert(CAT && "vla in literal type?");
3721       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3722       if (CAT->getSize().ule(Index)) {
3723         // Note, it should not be possible to form a pointer with a valid
3724         // designator which points more than one past the end of the array.
3725         if (Info.getLangOpts().CPlusPlus11)
3726           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3727             << handler.AccessKind;
3728         else
3729           Info.FFDiag(E);
3730         return handler.failed();
3731       }
3732 
3733       ObjType = CAT->getElementType();
3734 
3735       if (O->getArrayInitializedElts() > Index)
3736         O = &O->getArrayInitializedElt(Index);
3737       else if (!isRead(handler.AccessKind)) {
3738         expandArray(*O, Index);
3739         O = &O->getArrayInitializedElt(Index);
3740       } else
3741         O = &O->getArrayFiller();
3742     } else if (ObjType->isAnyComplexType()) {
3743       // Next subobject is a complex number.
3744       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3745       if (Index > 1) {
3746         if (Info.getLangOpts().CPlusPlus11)
3747           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3748             << handler.AccessKind;
3749         else
3750           Info.FFDiag(E);
3751         return handler.failed();
3752       }
3753 
3754       ObjType = getSubobjectType(
3755           ObjType, ObjType->castAs<ComplexType>()->getElementType());
3756 
3757       assert(I == N - 1 && "extracting subobject of scalar?");
3758       if (O->isComplexInt()) {
3759         return handler.found(Index ? O->getComplexIntImag()
3760                                    : O->getComplexIntReal(), ObjType);
3761       } else {
3762         assert(O->isComplexFloat());
3763         return handler.found(Index ? O->getComplexFloatImag()
3764                                    : O->getComplexFloatReal(), ObjType);
3765       }
3766     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3767       if (Field->isMutable() &&
3768           !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3769         Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3770           << handler.AccessKind << Field;
3771         Info.Note(Field->getLocation(), diag::note_declared_at);
3772         return handler.failed();
3773       }
3774 
3775       // Next subobject is a class, struct or union field.
3776       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3777       if (RD->isUnion()) {
3778         const FieldDecl *UnionField = O->getUnionField();
3779         if (!UnionField ||
3780             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3781           if (I == N - 1 && handler.AccessKind == AK_Construct) {
3782             // Placement new onto an inactive union member makes it active.
3783             O->setUnion(Field, APValue());
3784           } else {
3785             // FIXME: If O->getUnionValue() is absent, report that there's no
3786             // active union member rather than reporting the prior active union
3787             // member. We'll need to fix nullptr_t to not use APValue() as its
3788             // representation first.
3789             Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3790                 << handler.AccessKind << Field << !UnionField << UnionField;
3791             return handler.failed();
3792           }
3793         }
3794         O = &O->getUnionValue();
3795       } else
3796         O = &O->getStructField(Field->getFieldIndex());
3797 
3798       ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3799       LastField = Field;
3800       if (Field->getType().isVolatileQualified())
3801         VolatileField = Field;
3802     } else {
3803       // Next subobject is a base class.
3804       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3805       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3806       O = &O->getStructBase(getBaseIndex(Derived, Base));
3807 
3808       ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3809     }
3810   }
3811 }
3812 
3813 namespace {
3814 struct ExtractSubobjectHandler {
3815   EvalInfo &Info;
3816   const Expr *E;
3817   APValue &Result;
3818   const AccessKinds AccessKind;
3819 
3820   typedef bool result_type;
3821   bool failed() { return false; }
3822   bool found(APValue &Subobj, QualType SubobjType) {
3823     Result = Subobj;
3824     if (AccessKind == AK_ReadObjectRepresentation)
3825       return true;
3826     return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3827   }
3828   bool found(APSInt &Value, QualType SubobjType) {
3829     Result = APValue(Value);
3830     return true;
3831   }
3832   bool found(APFloat &Value, QualType SubobjType) {
3833     Result = APValue(Value);
3834     return true;
3835   }
3836 };
3837 } // end anonymous namespace
3838 
3839 /// Extract the designated sub-object of an rvalue.
3840 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3841                              const CompleteObject &Obj,
3842                              const SubobjectDesignator &Sub, APValue &Result,
3843                              AccessKinds AK = AK_Read) {
3844   assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3845   ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3846   return findSubobject(Info, E, Obj, Sub, Handler);
3847 }
3848 
3849 namespace {
3850 struct ModifySubobjectHandler {
3851   EvalInfo &Info;
3852   APValue &NewVal;
3853   const Expr *E;
3854 
3855   typedef bool result_type;
3856   static const AccessKinds AccessKind = AK_Assign;
3857 
3858   bool checkConst(QualType QT) {
3859     // Assigning to a const object has undefined behavior.
3860     if (QT.isConstQualified()) {
3861       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3862       return false;
3863     }
3864     return true;
3865   }
3866 
3867   bool failed() { return false; }
3868   bool found(APValue &Subobj, QualType SubobjType) {
3869     if (!checkConst(SubobjType))
3870       return false;
3871     // We've been given ownership of NewVal, so just swap it in.
3872     Subobj.swap(NewVal);
3873     return true;
3874   }
3875   bool found(APSInt &Value, QualType SubobjType) {
3876     if (!checkConst(SubobjType))
3877       return false;
3878     if (!NewVal.isInt()) {
3879       // Maybe trying to write a cast pointer value into a complex?
3880       Info.FFDiag(E);
3881       return false;
3882     }
3883     Value = NewVal.getInt();
3884     return true;
3885   }
3886   bool found(APFloat &Value, QualType SubobjType) {
3887     if (!checkConst(SubobjType))
3888       return false;
3889     Value = NewVal.getFloat();
3890     return true;
3891   }
3892 };
3893 } // end anonymous namespace
3894 
3895 const AccessKinds ModifySubobjectHandler::AccessKind;
3896 
3897 /// Update the designated sub-object of an rvalue to the given value.
3898 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3899                             const CompleteObject &Obj,
3900                             const SubobjectDesignator &Sub,
3901                             APValue &NewVal) {
3902   ModifySubobjectHandler Handler = { Info, NewVal, E };
3903   return findSubobject(Info, E, Obj, Sub, Handler);
3904 }
3905 
3906 /// Find the position where two subobject designators diverge, or equivalently
3907 /// the length of the common initial subsequence.
3908 static unsigned FindDesignatorMismatch(QualType ObjType,
3909                                        const SubobjectDesignator &A,
3910                                        const SubobjectDesignator &B,
3911                                        bool &WasArrayIndex) {
3912   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3913   for (/**/; I != N; ++I) {
3914     if (!ObjType.isNull() &&
3915         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3916       // Next subobject is an array element.
3917       if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3918         WasArrayIndex = true;
3919         return I;
3920       }
3921       if (ObjType->isAnyComplexType())
3922         ObjType = ObjType->castAs<ComplexType>()->getElementType();
3923       else
3924         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3925     } else {
3926       if (A.Entries[I].getAsBaseOrMember() !=
3927           B.Entries[I].getAsBaseOrMember()) {
3928         WasArrayIndex = false;
3929         return I;
3930       }
3931       if (const FieldDecl *FD = getAsField(A.Entries[I]))
3932         // Next subobject is a field.
3933         ObjType = FD->getType();
3934       else
3935         // Next subobject is a base class.
3936         ObjType = QualType();
3937     }
3938   }
3939   WasArrayIndex = false;
3940   return I;
3941 }
3942 
3943 /// Determine whether the given subobject designators refer to elements of the
3944 /// same array object.
3945 static bool AreElementsOfSameArray(QualType ObjType,
3946                                    const SubobjectDesignator &A,
3947                                    const SubobjectDesignator &B) {
3948   if (A.Entries.size() != B.Entries.size())
3949     return false;
3950 
3951   bool IsArray = A.MostDerivedIsArrayElement;
3952   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3953     // A is a subobject of the array element.
3954     return false;
3955 
3956   // If A (and B) designates an array element, the last entry will be the array
3957   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3958   // of length 1' case, and the entire path must match.
3959   bool WasArrayIndex;
3960   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3961   return CommonLength >= A.Entries.size() - IsArray;
3962 }
3963 
3964 /// Find the complete object to which an LValue refers.
3965 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3966                                          AccessKinds AK, const LValue &LVal,
3967                                          QualType LValType) {
3968   if (LVal.InvalidBase) {
3969     Info.FFDiag(E);
3970     return CompleteObject();
3971   }
3972 
3973   if (!LVal.Base) {
3974     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3975     return CompleteObject();
3976   }
3977 
3978   CallStackFrame *Frame = nullptr;
3979   unsigned Depth = 0;
3980   if (LVal.getLValueCallIndex()) {
3981     std::tie(Frame, Depth) =
3982         Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3983     if (!Frame) {
3984       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3985         << AK << LVal.Base.is<const ValueDecl*>();
3986       NoteLValueLocation(Info, LVal.Base);
3987       return CompleteObject();
3988     }
3989   }
3990 
3991   bool IsAccess = isAnyAccess(AK);
3992 
3993   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3994   // is not a constant expression (even if the object is non-volatile). We also
3995   // apply this rule to C++98, in order to conform to the expected 'volatile'
3996   // semantics.
3997   if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
3998     if (Info.getLangOpts().CPlusPlus)
3999       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
4000         << AK << LValType;
4001     else
4002       Info.FFDiag(E);
4003     return CompleteObject();
4004   }
4005 
4006   // Compute value storage location and type of base object.
4007   APValue *BaseVal = nullptr;
4008   QualType BaseType = getType(LVal.Base);
4009 
4010   if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4011       lifetimeStartedInEvaluation(Info, LVal.Base)) {
4012     // This is the object whose initializer we're evaluating, so its lifetime
4013     // started in the current evaluation.
4014     BaseVal = Info.EvaluatingDeclValue;
4015   } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4016     // Allow reading from a GUID declaration.
4017     if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4018       if (isModification(AK)) {
4019         // All the remaining cases do not permit modification of the object.
4020         Info.FFDiag(E, diag::note_constexpr_modify_global);
4021         return CompleteObject();
4022       }
4023       APValue &V = GD->getAsAPValue();
4024       if (V.isAbsent()) {
4025         Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4026             << GD->getType();
4027         return CompleteObject();
4028       }
4029       return CompleteObject(LVal.Base, &V, GD->getType());
4030     }
4031 
4032     // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4033     if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4034       if (isModification(AK)) {
4035         Info.FFDiag(E, diag::note_constexpr_modify_global);
4036         return CompleteObject();
4037       }
4038       return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4039                             GCD->getType());
4040     }
4041 
4042     // Allow reading from template parameter objects.
4043     if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4044       if (isModification(AK)) {
4045         Info.FFDiag(E, diag::note_constexpr_modify_global);
4046         return CompleteObject();
4047       }
4048       return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4049                             TPO->getType());
4050     }
4051 
4052     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4053     // In C++11, constexpr, non-volatile variables initialized with constant
4054     // expressions are constant expressions too. Inside constexpr functions,
4055     // parameters are constant expressions even if they're non-const.
4056     // In C++1y, objects local to a constant expression (those with a Frame) are
4057     // both readable and writable inside constant expressions.
4058     // In C, such things can also be folded, although they are not ICEs.
4059     const VarDecl *VD = dyn_cast<VarDecl>(D);
4060     if (VD) {
4061       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4062         VD = VDef;
4063     }
4064     if (!VD || VD->isInvalidDecl()) {
4065       Info.FFDiag(E);
4066       return CompleteObject();
4067     }
4068 
4069     bool IsConstant = BaseType.isConstant(Info.Ctx);
4070 
4071     // Unless we're looking at a local variable or argument in a constexpr call,
4072     // the variable we're reading must be const.
4073     if (!Frame) {
4074       if (IsAccess && isa<ParmVarDecl>(VD)) {
4075         // Access of a parameter that's not associated with a frame isn't going
4076         // to work out, but we can leave it to evaluateVarDeclInit to provide a
4077         // suitable diagnostic.
4078       } else if (Info.getLangOpts().CPlusPlus14 &&
4079                  lifetimeStartedInEvaluation(Info, LVal.Base)) {
4080         // OK, we can read and modify an object if we're in the process of
4081         // evaluating its initializer, because its lifetime began in this
4082         // evaluation.
4083       } else if (isModification(AK)) {
4084         // All the remaining cases do not permit modification of the object.
4085         Info.FFDiag(E, diag::note_constexpr_modify_global);
4086         return CompleteObject();
4087       } else if (VD->isConstexpr()) {
4088         // OK, we can read this variable.
4089       } else if (BaseType->isIntegralOrEnumerationType()) {
4090         if (!IsConstant) {
4091           if (!IsAccess)
4092             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4093           if (Info.getLangOpts().CPlusPlus) {
4094             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4095             Info.Note(VD->getLocation(), diag::note_declared_at);
4096           } else {
4097             Info.FFDiag(E);
4098           }
4099           return CompleteObject();
4100         }
4101       } else if (!IsAccess) {
4102         return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4103       } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
4104                  BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4105         // This variable might end up being constexpr. Don't diagnose it yet.
4106       } else if (IsConstant) {
4107         // Keep evaluating to see what we can do. In particular, we support
4108         // folding of const floating-point types, in order to make static const
4109         // data members of such types (supported as an extension) more useful.
4110         if (Info.getLangOpts().CPlusPlus) {
4111           Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4112                               ? diag::note_constexpr_ltor_non_constexpr
4113                               : diag::note_constexpr_ltor_non_integral, 1)
4114               << VD << BaseType;
4115           Info.Note(VD->getLocation(), diag::note_declared_at);
4116         } else {
4117           Info.CCEDiag(E);
4118         }
4119       } else {
4120         // Never allow reading a non-const value.
4121         if (Info.getLangOpts().CPlusPlus) {
4122           Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4123                              ? diag::note_constexpr_ltor_non_constexpr
4124                              : diag::note_constexpr_ltor_non_integral, 1)
4125               << VD << BaseType;
4126           Info.Note(VD->getLocation(), diag::note_declared_at);
4127         } else {
4128           Info.FFDiag(E);
4129         }
4130         return CompleteObject();
4131       }
4132     }
4133 
4134     if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
4135       return CompleteObject();
4136   } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4137     Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
4138     if (!Alloc) {
4139       Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4140       return CompleteObject();
4141     }
4142     return CompleteObject(LVal.Base, &(*Alloc)->Value,
4143                           LVal.Base.getDynamicAllocType());
4144   } else {
4145     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4146 
4147     if (!Frame) {
4148       if (const MaterializeTemporaryExpr *MTE =
4149               dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4150         assert(MTE->getStorageDuration() == SD_Static &&
4151                "should have a frame for a non-global materialized temporary");
4152 
4153         // C++20 [expr.const]p4: [DR2126]
4154         //   An object or reference is usable in constant expressions if it is
4155         //   - a temporary object of non-volatile const-qualified literal type
4156         //     whose lifetime is extended to that of a variable that is usable
4157         //     in constant expressions
4158         //
4159         // C++20 [expr.const]p5:
4160         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4161         //   - a non-volatile glvalue that refers to an object that is usable
4162         //     in constant expressions, or
4163         //   - a non-volatile glvalue of literal type that refers to a
4164         //     non-volatile object whose lifetime began within the evaluation
4165         //     of E;
4166         //
4167         // C++11 misses the 'began within the evaluation of e' check and
4168         // instead allows all temporaries, including things like:
4169         //   int &&r = 1;
4170         //   int x = ++r;
4171         //   constexpr int k = r;
4172         // Therefore we use the C++14-onwards rules in C++11 too.
4173         //
4174         // Note that temporaries whose lifetimes began while evaluating a
4175         // variable's constructor are not usable while evaluating the
4176         // corresponding destructor, not even if they're of const-qualified
4177         // types.
4178         if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4179             !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4180           if (!IsAccess)
4181             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4182           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4183           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4184           return CompleteObject();
4185         }
4186 
4187         BaseVal = MTE->getOrCreateValue(false);
4188         assert(BaseVal && "got reference to unevaluated temporary");
4189       } else {
4190         if (!IsAccess)
4191           return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4192         APValue Val;
4193         LVal.moveInto(Val);
4194         Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4195             << AK
4196             << Val.getAsString(Info.Ctx,
4197                                Info.Ctx.getLValueReferenceType(LValType));
4198         NoteLValueLocation(Info, LVal.Base);
4199         return CompleteObject();
4200       }
4201     } else {
4202       BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4203       assert(BaseVal && "missing value for temporary");
4204     }
4205   }
4206 
4207   // In C++14, we can't safely access any mutable state when we might be
4208   // evaluating after an unmodeled side effect. Parameters are modeled as state
4209   // in the caller, but aren't visible once the call returns, so they can be
4210   // modified in a speculatively-evaluated call.
4211   //
4212   // FIXME: Not all local state is mutable. Allow local constant subobjects
4213   // to be read here (but take care with 'mutable' fields).
4214   unsigned VisibleDepth = Depth;
4215   if (llvm::isa_and_nonnull<ParmVarDecl>(
4216           LVal.Base.dyn_cast<const ValueDecl *>()))
4217     ++VisibleDepth;
4218   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4219        Info.EvalStatus.HasSideEffects) ||
4220       (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4221     return CompleteObject();
4222 
4223   return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4224 }
4225 
4226 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4227 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4228 /// glvalue referred to by an entity of reference type.
4229 ///
4230 /// \param Info - Information about the ongoing evaluation.
4231 /// \param Conv - The expression for which we are performing the conversion.
4232 ///               Used for diagnostics.
4233 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4234 ///               case of a non-class type).
4235 /// \param LVal - The glvalue on which we are attempting to perform this action.
4236 /// \param RVal - The produced value will be placed here.
4237 /// \param WantObjectRepresentation - If true, we're looking for the object
4238 ///               representation rather than the value, and in particular,
4239 ///               there is no requirement that the result be fully initialized.
4240 static bool
4241 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
4242                                const LValue &LVal, APValue &RVal,
4243                                bool WantObjectRepresentation = false) {
4244   if (LVal.Designator.Invalid)
4245     return false;
4246 
4247   // Check for special cases where there is no existing APValue to look at.
4248   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4249 
4250   AccessKinds AK =
4251       WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4252 
4253   if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4254     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4255       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4256       // initializer until now for such expressions. Such an expression can't be
4257       // an ICE in C, so this only matters for fold.
4258       if (Type.isVolatileQualified()) {
4259         Info.FFDiag(Conv);
4260         return false;
4261       }
4262       APValue Lit;
4263       if (!Evaluate(Lit, Info, CLE->getInitializer()))
4264         return false;
4265       CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4266       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4267     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4268       // Special-case character extraction so we don't have to construct an
4269       // APValue for the whole string.
4270       assert(LVal.Designator.Entries.size() <= 1 &&
4271              "Can only read characters from string literals");
4272       if (LVal.Designator.Entries.empty()) {
4273         // Fail for now for LValue to RValue conversion of an array.
4274         // (This shouldn't show up in C/C++, but it could be triggered by a
4275         // weird EvaluateAsRValue call from a tool.)
4276         Info.FFDiag(Conv);
4277         return false;
4278       }
4279       if (LVal.Designator.isOnePastTheEnd()) {
4280         if (Info.getLangOpts().CPlusPlus11)
4281           Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4282         else
4283           Info.FFDiag(Conv);
4284         return false;
4285       }
4286       uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4287       RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4288       return true;
4289     }
4290   }
4291 
4292   CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4293   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4294 }
4295 
4296 /// Perform an assignment of Val to LVal. Takes ownership of Val.
4297 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4298                              QualType LValType, APValue &Val) {
4299   if (LVal.Designator.Invalid)
4300     return false;
4301 
4302   if (!Info.getLangOpts().CPlusPlus14) {
4303     Info.FFDiag(E);
4304     return false;
4305   }
4306 
4307   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4308   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4309 }
4310 
4311 namespace {
4312 struct CompoundAssignSubobjectHandler {
4313   EvalInfo &Info;
4314   const CompoundAssignOperator *E;
4315   QualType PromotedLHSType;
4316   BinaryOperatorKind Opcode;
4317   const APValue &RHS;
4318 
4319   static const AccessKinds AccessKind = AK_Assign;
4320 
4321   typedef bool result_type;
4322 
4323   bool checkConst(QualType QT) {
4324     // Assigning to a const object has undefined behavior.
4325     if (QT.isConstQualified()) {
4326       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4327       return false;
4328     }
4329     return true;
4330   }
4331 
4332   bool failed() { return false; }
4333   bool found(APValue &Subobj, QualType SubobjType) {
4334     switch (Subobj.getKind()) {
4335     case APValue::Int:
4336       return found(Subobj.getInt(), SubobjType);
4337     case APValue::Float:
4338       return found(Subobj.getFloat(), SubobjType);
4339     case APValue::ComplexInt:
4340     case APValue::ComplexFloat:
4341       // FIXME: Implement complex compound assignment.
4342       Info.FFDiag(E);
4343       return false;
4344     case APValue::LValue:
4345       return foundPointer(Subobj, SubobjType);
4346     case APValue::Vector:
4347       return foundVector(Subobj, SubobjType);
4348     default:
4349       // FIXME: can this happen?
4350       Info.FFDiag(E);
4351       return false;
4352     }
4353   }
4354 
4355   bool foundVector(APValue &Value, QualType SubobjType) {
4356     if (!checkConst(SubobjType))
4357       return false;
4358 
4359     if (!SubobjType->isVectorType()) {
4360       Info.FFDiag(E);
4361       return false;
4362     }
4363     return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4364   }
4365 
4366   bool found(APSInt &Value, QualType SubobjType) {
4367     if (!checkConst(SubobjType))
4368       return false;
4369 
4370     if (!SubobjType->isIntegerType()) {
4371       // We don't support compound assignment on integer-cast-to-pointer
4372       // values.
4373       Info.FFDiag(E);
4374       return false;
4375     }
4376 
4377     if (RHS.isInt()) {
4378       APSInt LHS =
4379           HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4380       if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4381         return false;
4382       Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4383       return true;
4384     } else if (RHS.isFloat()) {
4385       const FPOptions FPO = E->getFPFeaturesInEffect(
4386                                     Info.Ctx.getLangOpts());
4387       APFloat FValue(0.0);
4388       return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4389                                   PromotedLHSType, FValue) &&
4390              handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4391              HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4392                                   Value);
4393     }
4394 
4395     Info.FFDiag(E);
4396     return false;
4397   }
4398   bool found(APFloat &Value, QualType SubobjType) {
4399     return checkConst(SubobjType) &&
4400            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4401                                   Value) &&
4402            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4403            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4404   }
4405   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4406     if (!checkConst(SubobjType))
4407       return false;
4408 
4409     QualType PointeeType;
4410     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4411       PointeeType = PT->getPointeeType();
4412 
4413     if (PointeeType.isNull() || !RHS.isInt() ||
4414         (Opcode != BO_Add && Opcode != BO_Sub)) {
4415       Info.FFDiag(E);
4416       return false;
4417     }
4418 
4419     APSInt Offset = RHS.getInt();
4420     if (Opcode == BO_Sub)
4421       negateAsSigned(Offset);
4422 
4423     LValue LVal;
4424     LVal.setFrom(Info.Ctx, Subobj);
4425     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4426       return false;
4427     LVal.moveInto(Subobj);
4428     return true;
4429   }
4430 };
4431 } // end anonymous namespace
4432 
4433 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4434 
4435 /// Perform a compound assignment of LVal <op>= RVal.
4436 static bool handleCompoundAssignment(EvalInfo &Info,
4437                                      const CompoundAssignOperator *E,
4438                                      const LValue &LVal, QualType LValType,
4439                                      QualType PromotedLValType,
4440                                      BinaryOperatorKind Opcode,
4441                                      const APValue &RVal) {
4442   if (LVal.Designator.Invalid)
4443     return false;
4444 
4445   if (!Info.getLangOpts().CPlusPlus14) {
4446     Info.FFDiag(E);
4447     return false;
4448   }
4449 
4450   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4451   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4452                                              RVal };
4453   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4454 }
4455 
4456 namespace {
4457 struct IncDecSubobjectHandler {
4458   EvalInfo &Info;
4459   const UnaryOperator *E;
4460   AccessKinds AccessKind;
4461   APValue *Old;
4462 
4463   typedef bool result_type;
4464 
4465   bool checkConst(QualType QT) {
4466     // Assigning to a const object has undefined behavior.
4467     if (QT.isConstQualified()) {
4468       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4469       return false;
4470     }
4471     return true;
4472   }
4473 
4474   bool failed() { return false; }
4475   bool found(APValue &Subobj, QualType SubobjType) {
4476     // Stash the old value. Also clear Old, so we don't clobber it later
4477     // if we're post-incrementing a complex.
4478     if (Old) {
4479       *Old = Subobj;
4480       Old = nullptr;
4481     }
4482 
4483     switch (Subobj.getKind()) {
4484     case APValue::Int:
4485       return found(Subobj.getInt(), SubobjType);
4486     case APValue::Float:
4487       return found(Subobj.getFloat(), SubobjType);
4488     case APValue::ComplexInt:
4489       return found(Subobj.getComplexIntReal(),
4490                    SubobjType->castAs<ComplexType>()->getElementType()
4491                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4492     case APValue::ComplexFloat:
4493       return found(Subobj.getComplexFloatReal(),
4494                    SubobjType->castAs<ComplexType>()->getElementType()
4495                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4496     case APValue::LValue:
4497       return foundPointer(Subobj, SubobjType);
4498     default:
4499       // FIXME: can this happen?
4500       Info.FFDiag(E);
4501       return false;
4502     }
4503   }
4504   bool found(APSInt &Value, QualType SubobjType) {
4505     if (!checkConst(SubobjType))
4506       return false;
4507 
4508     if (!SubobjType->isIntegerType()) {
4509       // We don't support increment / decrement on integer-cast-to-pointer
4510       // values.
4511       Info.FFDiag(E);
4512       return false;
4513     }
4514 
4515     if (Old) *Old = APValue(Value);
4516 
4517     // bool arithmetic promotes to int, and the conversion back to bool
4518     // doesn't reduce mod 2^n, so special-case it.
4519     if (SubobjType->isBooleanType()) {
4520       if (AccessKind == AK_Increment)
4521         Value = 1;
4522       else
4523         Value = !Value;
4524       return true;
4525     }
4526 
4527     bool WasNegative = Value.isNegative();
4528     if (AccessKind == AK_Increment) {
4529       ++Value;
4530 
4531       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4532         APSInt ActualValue(Value, /*IsUnsigned*/true);
4533         return HandleOverflow(Info, E, ActualValue, SubobjType);
4534       }
4535     } else {
4536       --Value;
4537 
4538       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4539         unsigned BitWidth = Value.getBitWidth();
4540         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4541         ActualValue.setBit(BitWidth);
4542         return HandleOverflow(Info, E, ActualValue, SubobjType);
4543       }
4544     }
4545     return true;
4546   }
4547   bool found(APFloat &Value, QualType SubobjType) {
4548     if (!checkConst(SubobjType))
4549       return false;
4550 
4551     if (Old) *Old = APValue(Value);
4552 
4553     APFloat One(Value.getSemantics(), 1);
4554     if (AccessKind == AK_Increment)
4555       Value.add(One, APFloat::rmNearestTiesToEven);
4556     else
4557       Value.subtract(One, APFloat::rmNearestTiesToEven);
4558     return true;
4559   }
4560   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4561     if (!checkConst(SubobjType))
4562       return false;
4563 
4564     QualType PointeeType;
4565     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4566       PointeeType = PT->getPointeeType();
4567     else {
4568       Info.FFDiag(E);
4569       return false;
4570     }
4571 
4572     LValue LVal;
4573     LVal.setFrom(Info.Ctx, Subobj);
4574     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4575                                      AccessKind == AK_Increment ? 1 : -1))
4576       return false;
4577     LVal.moveInto(Subobj);
4578     return true;
4579   }
4580 };
4581 } // end anonymous namespace
4582 
4583 /// Perform an increment or decrement on LVal.
4584 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4585                          QualType LValType, bool IsIncrement, APValue *Old) {
4586   if (LVal.Designator.Invalid)
4587     return false;
4588 
4589   if (!Info.getLangOpts().CPlusPlus14) {
4590     Info.FFDiag(E);
4591     return false;
4592   }
4593 
4594   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4595   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4596   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4597   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4598 }
4599 
4600 /// Build an lvalue for the object argument of a member function call.
4601 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4602                                    LValue &This) {
4603   if (Object->getType()->isPointerType() && Object->isPRValue())
4604     return EvaluatePointer(Object, This, Info);
4605 
4606   if (Object->isGLValue())
4607     return EvaluateLValue(Object, This, Info);
4608 
4609   if (Object->getType()->isLiteralType(Info.Ctx))
4610     return EvaluateTemporary(Object, This, Info);
4611 
4612   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4613   return false;
4614 }
4615 
4616 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
4617 /// lvalue referring to the result.
4618 ///
4619 /// \param Info - Information about the ongoing evaluation.
4620 /// \param LV - An lvalue referring to the base of the member pointer.
4621 /// \param RHS - The member pointer expression.
4622 /// \param IncludeMember - Specifies whether the member itself is included in
4623 ///        the resulting LValue subobject designator. This is not possible when
4624 ///        creating a bound member function.
4625 /// \return The field or method declaration to which the member pointer refers,
4626 ///         or 0 if evaluation fails.
4627 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4628                                                   QualType LVType,
4629                                                   LValue &LV,
4630                                                   const Expr *RHS,
4631                                                   bool IncludeMember = true) {
4632   MemberPtr MemPtr;
4633   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4634     return nullptr;
4635 
4636   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4637   // member value, the behavior is undefined.
4638   if (!MemPtr.getDecl()) {
4639     // FIXME: Specific diagnostic.
4640     Info.FFDiag(RHS);
4641     return nullptr;
4642   }
4643 
4644   if (MemPtr.isDerivedMember()) {
4645     // This is a member of some derived class. Truncate LV appropriately.
4646     // The end of the derived-to-base path for the base object must match the
4647     // derived-to-base path for the member pointer.
4648     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4649         LV.Designator.Entries.size()) {
4650       Info.FFDiag(RHS);
4651       return nullptr;
4652     }
4653     unsigned PathLengthToMember =
4654         LV.Designator.Entries.size() - MemPtr.Path.size();
4655     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4656       const CXXRecordDecl *LVDecl = getAsBaseClass(
4657           LV.Designator.Entries[PathLengthToMember + I]);
4658       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4659       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4660         Info.FFDiag(RHS);
4661         return nullptr;
4662       }
4663     }
4664 
4665     // Truncate the lvalue to the appropriate derived class.
4666     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4667                             PathLengthToMember))
4668       return nullptr;
4669   } else if (!MemPtr.Path.empty()) {
4670     // Extend the LValue path with the member pointer's path.
4671     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4672                                   MemPtr.Path.size() + IncludeMember);
4673 
4674     // Walk down to the appropriate base class.
4675     if (const PointerType *PT = LVType->getAs<PointerType>())
4676       LVType = PT->getPointeeType();
4677     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4678     assert(RD && "member pointer access on non-class-type expression");
4679     // The first class in the path is that of the lvalue.
4680     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4681       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4682       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4683         return nullptr;
4684       RD = Base;
4685     }
4686     // Finally cast to the class containing the member.
4687     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4688                                 MemPtr.getContainingRecord()))
4689       return nullptr;
4690   }
4691 
4692   // Add the member. Note that we cannot build bound member functions here.
4693   if (IncludeMember) {
4694     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4695       if (!HandleLValueMember(Info, RHS, LV, FD))
4696         return nullptr;
4697     } else if (const IndirectFieldDecl *IFD =
4698                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4699       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4700         return nullptr;
4701     } else {
4702       llvm_unreachable("can't construct reference to bound member function");
4703     }
4704   }
4705 
4706   return MemPtr.getDecl();
4707 }
4708 
4709 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4710                                                   const BinaryOperator *BO,
4711                                                   LValue &LV,
4712                                                   bool IncludeMember = true) {
4713   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4714 
4715   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4716     if (Info.noteFailure()) {
4717       MemberPtr MemPtr;
4718       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4719     }
4720     return nullptr;
4721   }
4722 
4723   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4724                                    BO->getRHS(), IncludeMember);
4725 }
4726 
4727 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4728 /// the provided lvalue, which currently refers to the base object.
4729 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4730                                     LValue &Result) {
4731   SubobjectDesignator &D = Result.Designator;
4732   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4733     return false;
4734 
4735   QualType TargetQT = E->getType();
4736   if (const PointerType *PT = TargetQT->getAs<PointerType>())
4737     TargetQT = PT->getPointeeType();
4738 
4739   // Check this cast lands within the final derived-to-base subobject path.
4740   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4741     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4742       << D.MostDerivedType << TargetQT;
4743     return false;
4744   }
4745 
4746   // Check the type of the final cast. We don't need to check the path,
4747   // since a cast can only be formed if the path is unique.
4748   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4749   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4750   const CXXRecordDecl *FinalType;
4751   if (NewEntriesSize == D.MostDerivedPathLength)
4752     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4753   else
4754     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4755   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4756     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4757       << D.MostDerivedType << TargetQT;
4758     return false;
4759   }
4760 
4761   // Truncate the lvalue to the appropriate derived class.
4762   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4763 }
4764 
4765 /// Get the value to use for a default-initialized object of type T.
4766 /// Return false if it encounters something invalid.
4767 static bool getDefaultInitValue(QualType T, APValue &Result) {
4768   bool Success = true;
4769   if (auto *RD = T->getAsCXXRecordDecl()) {
4770     if (RD->isInvalidDecl()) {
4771       Result = APValue();
4772       return false;
4773     }
4774     if (RD->isUnion()) {
4775       Result = APValue((const FieldDecl *)nullptr);
4776       return true;
4777     }
4778     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4779                      std::distance(RD->field_begin(), RD->field_end()));
4780 
4781     unsigned Index = 0;
4782     for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4783                                                   End = RD->bases_end();
4784          I != End; ++I, ++Index)
4785       Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index));
4786 
4787     for (const auto *I : RD->fields()) {
4788       if (I->isUnnamedBitfield())
4789         continue;
4790       Success &= getDefaultInitValue(I->getType(),
4791                                      Result.getStructField(I->getFieldIndex()));
4792     }
4793     return Success;
4794   }
4795 
4796   if (auto *AT =
4797           dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4798     Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4799     if (Result.hasArrayFiller())
4800       Success &=
4801           getDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
4802 
4803     return Success;
4804   }
4805 
4806   Result = APValue::IndeterminateValue();
4807   return true;
4808 }
4809 
4810 namespace {
4811 enum EvalStmtResult {
4812   /// Evaluation failed.
4813   ESR_Failed,
4814   /// Hit a 'return' statement.
4815   ESR_Returned,
4816   /// Evaluation succeeded.
4817   ESR_Succeeded,
4818   /// Hit a 'continue' statement.
4819   ESR_Continue,
4820   /// Hit a 'break' statement.
4821   ESR_Break,
4822   /// Still scanning for 'case' or 'default' statement.
4823   ESR_CaseNotFound
4824 };
4825 }
4826 
4827 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4828   // We don't need to evaluate the initializer for a static local.
4829   if (!VD->hasLocalStorage())
4830     return true;
4831 
4832   LValue Result;
4833   APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
4834                                                    ScopeKind::Block, Result);
4835 
4836   const Expr *InitE = VD->getInit();
4837   if (!InitE) {
4838     if (VD->getType()->isDependentType())
4839       return Info.noteSideEffect();
4840     return getDefaultInitValue(VD->getType(), Val);
4841   }
4842   if (InitE->isValueDependent())
4843     return false;
4844 
4845   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4846     // Wipe out any partially-computed value, to allow tracking that this
4847     // evaluation failed.
4848     Val = APValue();
4849     return false;
4850   }
4851 
4852   return true;
4853 }
4854 
4855 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4856   bool OK = true;
4857 
4858   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4859     OK &= EvaluateVarDecl(Info, VD);
4860 
4861   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4862     for (auto *BD : DD->bindings())
4863       if (auto *VD = BD->getHoldingVar())
4864         OK &= EvaluateDecl(Info, VD);
4865 
4866   return OK;
4867 }
4868 
4869 static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
4870   assert(E->isValueDependent());
4871   if (Info.noteSideEffect())
4872     return true;
4873   assert(E->containsErrors() && "valid value-dependent expression should never "
4874                                 "reach invalid code path.");
4875   return false;
4876 }
4877 
4878 /// Evaluate a condition (either a variable declaration or an expression).
4879 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4880                          const Expr *Cond, bool &Result) {
4881   if (Cond->isValueDependent())
4882     return false;
4883   FullExpressionRAII Scope(Info);
4884   if (CondDecl && !EvaluateDecl(Info, CondDecl))
4885     return false;
4886   if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4887     return false;
4888   return Scope.destroy();
4889 }
4890 
4891 namespace {
4892 /// A location where the result (returned value) of evaluating a
4893 /// statement should be stored.
4894 struct StmtResult {
4895   /// The APValue that should be filled in with the returned value.
4896   APValue &Value;
4897   /// The location containing the result, if any (used to support RVO).
4898   const LValue *Slot;
4899 };
4900 
4901 struct TempVersionRAII {
4902   CallStackFrame &Frame;
4903 
4904   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4905     Frame.pushTempVersion();
4906   }
4907 
4908   ~TempVersionRAII() {
4909     Frame.popTempVersion();
4910   }
4911 };
4912 
4913 }
4914 
4915 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4916                                    const Stmt *S,
4917                                    const SwitchCase *SC = nullptr);
4918 
4919 /// Evaluate the body of a loop, and translate the result as appropriate.
4920 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4921                                        const Stmt *Body,
4922                                        const SwitchCase *Case = nullptr) {
4923   BlockScopeRAII Scope(Info);
4924 
4925   EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4926   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4927     ESR = ESR_Failed;
4928 
4929   switch (ESR) {
4930   case ESR_Break:
4931     return ESR_Succeeded;
4932   case ESR_Succeeded:
4933   case ESR_Continue:
4934     return ESR_Continue;
4935   case ESR_Failed:
4936   case ESR_Returned:
4937   case ESR_CaseNotFound:
4938     return ESR;
4939   }
4940   llvm_unreachable("Invalid EvalStmtResult!");
4941 }
4942 
4943 /// Evaluate a switch statement.
4944 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4945                                      const SwitchStmt *SS) {
4946   BlockScopeRAII Scope(Info);
4947 
4948   // Evaluate the switch condition.
4949   APSInt Value;
4950   {
4951     if (const Stmt *Init = SS->getInit()) {
4952       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4953       if (ESR != ESR_Succeeded) {
4954         if (ESR != ESR_Failed && !Scope.destroy())
4955           ESR = ESR_Failed;
4956         return ESR;
4957       }
4958     }
4959 
4960     FullExpressionRAII CondScope(Info);
4961     if (SS->getConditionVariable() &&
4962         !EvaluateDecl(Info, SS->getConditionVariable()))
4963       return ESR_Failed;
4964     if (SS->getCond()->isValueDependent()) {
4965       if (!EvaluateDependentExpr(SS->getCond(), Info))
4966         return ESR_Failed;
4967     } else {
4968       if (!EvaluateInteger(SS->getCond(), Value, Info))
4969         return ESR_Failed;
4970     }
4971     if (!CondScope.destroy())
4972       return ESR_Failed;
4973   }
4974 
4975   // Find the switch case corresponding to the value of the condition.
4976   // FIXME: Cache this lookup.
4977   const SwitchCase *Found = nullptr;
4978   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4979        SC = SC->getNextSwitchCase()) {
4980     if (isa<DefaultStmt>(SC)) {
4981       Found = SC;
4982       continue;
4983     }
4984 
4985     const CaseStmt *CS = cast<CaseStmt>(SC);
4986     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4987     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4988                               : LHS;
4989     if (LHS <= Value && Value <= RHS) {
4990       Found = SC;
4991       break;
4992     }
4993   }
4994 
4995   if (!Found)
4996     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4997 
4998   // Search the switch body for the switch case and evaluate it from there.
4999   EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5000   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5001     return ESR_Failed;
5002 
5003   switch (ESR) {
5004   case ESR_Break:
5005     return ESR_Succeeded;
5006   case ESR_Succeeded:
5007   case ESR_Continue:
5008   case ESR_Failed:
5009   case ESR_Returned:
5010     return ESR;
5011   case ESR_CaseNotFound:
5012     // This can only happen if the switch case is nested within a statement
5013     // expression. We have no intention of supporting that.
5014     Info.FFDiag(Found->getBeginLoc(),
5015                 diag::note_constexpr_stmt_expr_unsupported);
5016     return ESR_Failed;
5017   }
5018   llvm_unreachable("Invalid EvalStmtResult!");
5019 }
5020 
5021 static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5022   // An expression E is a core constant expression unless the evaluation of E
5023   // would evaluate one of the following: [C++2b] - a control flow that passes
5024   // through a declaration of a variable with static or thread storage duration.
5025   if (VD->isLocalVarDecl() && VD->isStaticLocal()) {
5026     Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5027         << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5028     return false;
5029   }
5030   return true;
5031 }
5032 
5033 // Evaluate a statement.
5034 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5035                                    const Stmt *S, const SwitchCase *Case) {
5036   if (!Info.nextStep(S))
5037     return ESR_Failed;
5038 
5039   // If we're hunting down a 'case' or 'default' label, recurse through
5040   // substatements until we hit the label.
5041   if (Case) {
5042     switch (S->getStmtClass()) {
5043     case Stmt::CompoundStmtClass:
5044       // FIXME: Precompute which substatement of a compound statement we
5045       // would jump to, and go straight there rather than performing a
5046       // linear scan each time.
5047     case Stmt::LabelStmtClass:
5048     case Stmt::AttributedStmtClass:
5049     case Stmt::DoStmtClass:
5050       break;
5051 
5052     case Stmt::CaseStmtClass:
5053     case Stmt::DefaultStmtClass:
5054       if (Case == S)
5055         Case = nullptr;
5056       break;
5057 
5058     case Stmt::IfStmtClass: {
5059       // FIXME: Precompute which side of an 'if' we would jump to, and go
5060       // straight there rather than scanning both sides.
5061       const IfStmt *IS = cast<IfStmt>(S);
5062 
5063       // Wrap the evaluation in a block scope, in case it's a DeclStmt
5064       // preceded by our switch label.
5065       BlockScopeRAII Scope(Info);
5066 
5067       // Step into the init statement in case it brings an (uninitialized)
5068       // variable into scope.
5069       if (const Stmt *Init = IS->getInit()) {
5070         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5071         if (ESR != ESR_CaseNotFound) {
5072           assert(ESR != ESR_Succeeded);
5073           return ESR;
5074         }
5075       }
5076 
5077       // Condition variable must be initialized if it exists.
5078       // FIXME: We can skip evaluating the body if there's a condition
5079       // variable, as there can't be any case labels within it.
5080       // (The same is true for 'for' statements.)
5081 
5082       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5083       if (ESR == ESR_Failed)
5084         return ESR;
5085       if (ESR != ESR_CaseNotFound)
5086         return Scope.destroy() ? ESR : ESR_Failed;
5087       if (!IS->getElse())
5088         return ESR_CaseNotFound;
5089 
5090       ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5091       if (ESR == ESR_Failed)
5092         return ESR;
5093       if (ESR != ESR_CaseNotFound)
5094         return Scope.destroy() ? ESR : ESR_Failed;
5095       return ESR_CaseNotFound;
5096     }
5097 
5098     case Stmt::WhileStmtClass: {
5099       EvalStmtResult ESR =
5100           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5101       if (ESR != ESR_Continue)
5102         return ESR;
5103       break;
5104     }
5105 
5106     case Stmt::ForStmtClass: {
5107       const ForStmt *FS = cast<ForStmt>(S);
5108       BlockScopeRAII Scope(Info);
5109 
5110       // Step into the init statement in case it brings an (uninitialized)
5111       // variable into scope.
5112       if (const Stmt *Init = FS->getInit()) {
5113         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5114         if (ESR != ESR_CaseNotFound) {
5115           assert(ESR != ESR_Succeeded);
5116           return ESR;
5117         }
5118       }
5119 
5120       EvalStmtResult ESR =
5121           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5122       if (ESR != ESR_Continue)
5123         return ESR;
5124       if (const auto *Inc = FS->getInc()) {
5125         if (Inc->isValueDependent()) {
5126           if (!EvaluateDependentExpr(Inc, Info))
5127             return ESR_Failed;
5128         } else {
5129           FullExpressionRAII IncScope(Info);
5130           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5131             return ESR_Failed;
5132         }
5133       }
5134       break;
5135     }
5136 
5137     case Stmt::DeclStmtClass: {
5138       // Start the lifetime of any uninitialized variables we encounter. They
5139       // might be used by the selected branch of the switch.
5140       const DeclStmt *DS = cast<DeclStmt>(S);
5141       for (const auto *D : DS->decls()) {
5142         if (const auto *VD = dyn_cast<VarDecl>(D)) {
5143           if (!CheckLocalVariableDeclaration(Info, VD))
5144             return ESR_Failed;
5145           if (VD->hasLocalStorage() && !VD->getInit())
5146             if (!EvaluateVarDecl(Info, VD))
5147               return ESR_Failed;
5148           // FIXME: If the variable has initialization that can't be jumped
5149           // over, bail out of any immediately-surrounding compound-statement
5150           // too. There can't be any case labels here.
5151         }
5152       }
5153       return ESR_CaseNotFound;
5154     }
5155 
5156     default:
5157       return ESR_CaseNotFound;
5158     }
5159   }
5160 
5161   switch (S->getStmtClass()) {
5162   default:
5163     if (const Expr *E = dyn_cast<Expr>(S)) {
5164       if (E->isValueDependent()) {
5165         if (!EvaluateDependentExpr(E, Info))
5166           return ESR_Failed;
5167       } else {
5168         // Don't bother evaluating beyond an expression-statement which couldn't
5169         // be evaluated.
5170         // FIXME: Do we need the FullExpressionRAII object here?
5171         // VisitExprWithCleanups should create one when necessary.
5172         FullExpressionRAII Scope(Info);
5173         if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5174           return ESR_Failed;
5175       }
5176       return ESR_Succeeded;
5177     }
5178 
5179     Info.FFDiag(S->getBeginLoc());
5180     return ESR_Failed;
5181 
5182   case Stmt::NullStmtClass:
5183     return ESR_Succeeded;
5184 
5185   case Stmt::DeclStmtClass: {
5186     const DeclStmt *DS = cast<DeclStmt>(S);
5187     for (const auto *D : DS->decls()) {
5188       const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
5189       if (VD && !CheckLocalVariableDeclaration(Info, VD))
5190         return ESR_Failed;
5191       // Each declaration initialization is its own full-expression.
5192       FullExpressionRAII Scope(Info);
5193       if (!EvaluateDecl(Info, D) && !Info.noteFailure())
5194         return ESR_Failed;
5195       if (!Scope.destroy())
5196         return ESR_Failed;
5197     }
5198     return ESR_Succeeded;
5199   }
5200 
5201   case Stmt::ReturnStmtClass: {
5202     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5203     FullExpressionRAII Scope(Info);
5204     if (RetExpr && RetExpr->isValueDependent()) {
5205       EvaluateDependentExpr(RetExpr, Info);
5206       // We know we returned, but we don't know what the value is.
5207       return ESR_Failed;
5208     }
5209     if (RetExpr &&
5210         !(Result.Slot
5211               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5212               : Evaluate(Result.Value, Info, RetExpr)))
5213       return ESR_Failed;
5214     return Scope.destroy() ? ESR_Returned : ESR_Failed;
5215   }
5216 
5217   case Stmt::CompoundStmtClass: {
5218     BlockScopeRAII Scope(Info);
5219 
5220     const CompoundStmt *CS = cast<CompoundStmt>(S);
5221     for (const auto *BI : CS->body()) {
5222       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5223       if (ESR == ESR_Succeeded)
5224         Case = nullptr;
5225       else if (ESR != ESR_CaseNotFound) {
5226         if (ESR != ESR_Failed && !Scope.destroy())
5227           return ESR_Failed;
5228         return ESR;
5229       }
5230     }
5231     if (Case)
5232       return ESR_CaseNotFound;
5233     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5234   }
5235 
5236   case Stmt::IfStmtClass: {
5237     const IfStmt *IS = cast<IfStmt>(S);
5238 
5239     // Evaluate the condition, as either a var decl or as an expression.
5240     BlockScopeRAII Scope(Info);
5241     if (const Stmt *Init = IS->getInit()) {
5242       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5243       if (ESR != ESR_Succeeded) {
5244         if (ESR != ESR_Failed && !Scope.destroy())
5245           return ESR_Failed;
5246         return ESR;
5247       }
5248     }
5249     bool Cond;
5250     if (IS->isConsteval())
5251       Cond = IS->isNonNegatedConsteval();
5252     else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
5253                            Cond))
5254       return ESR_Failed;
5255 
5256     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5257       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5258       if (ESR != ESR_Succeeded) {
5259         if (ESR != ESR_Failed && !Scope.destroy())
5260           return ESR_Failed;
5261         return ESR;
5262       }
5263     }
5264     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5265   }
5266 
5267   case Stmt::WhileStmtClass: {
5268     const WhileStmt *WS = cast<WhileStmt>(S);
5269     while (true) {
5270       BlockScopeRAII Scope(Info);
5271       bool Continue;
5272       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5273                         Continue))
5274         return ESR_Failed;
5275       if (!Continue)
5276         break;
5277 
5278       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5279       if (ESR != ESR_Continue) {
5280         if (ESR != ESR_Failed && !Scope.destroy())
5281           return ESR_Failed;
5282         return ESR;
5283       }
5284       if (!Scope.destroy())
5285         return ESR_Failed;
5286     }
5287     return ESR_Succeeded;
5288   }
5289 
5290   case Stmt::DoStmtClass: {
5291     const DoStmt *DS = cast<DoStmt>(S);
5292     bool Continue;
5293     do {
5294       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5295       if (ESR != ESR_Continue)
5296         return ESR;
5297       Case = nullptr;
5298 
5299       if (DS->getCond()->isValueDependent()) {
5300         EvaluateDependentExpr(DS->getCond(), Info);
5301         // Bailout as we don't know whether to keep going or terminate the loop.
5302         return ESR_Failed;
5303       }
5304       FullExpressionRAII CondScope(Info);
5305       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5306           !CondScope.destroy())
5307         return ESR_Failed;
5308     } while (Continue);
5309     return ESR_Succeeded;
5310   }
5311 
5312   case Stmt::ForStmtClass: {
5313     const ForStmt *FS = cast<ForStmt>(S);
5314     BlockScopeRAII ForScope(Info);
5315     if (FS->getInit()) {
5316       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5317       if (ESR != ESR_Succeeded) {
5318         if (ESR != ESR_Failed && !ForScope.destroy())
5319           return ESR_Failed;
5320         return ESR;
5321       }
5322     }
5323     while (true) {
5324       BlockScopeRAII IterScope(Info);
5325       bool Continue = true;
5326       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5327                                          FS->getCond(), Continue))
5328         return ESR_Failed;
5329       if (!Continue)
5330         break;
5331 
5332       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5333       if (ESR != ESR_Continue) {
5334         if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5335           return ESR_Failed;
5336         return ESR;
5337       }
5338 
5339       if (const auto *Inc = FS->getInc()) {
5340         if (Inc->isValueDependent()) {
5341           if (!EvaluateDependentExpr(Inc, Info))
5342             return ESR_Failed;
5343         } else {
5344           FullExpressionRAII IncScope(Info);
5345           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5346             return ESR_Failed;
5347         }
5348       }
5349 
5350       if (!IterScope.destroy())
5351         return ESR_Failed;
5352     }
5353     return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5354   }
5355 
5356   case Stmt::CXXForRangeStmtClass: {
5357     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5358     BlockScopeRAII Scope(Info);
5359 
5360     // Evaluate the init-statement if present.
5361     if (FS->getInit()) {
5362       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5363       if (ESR != ESR_Succeeded) {
5364         if (ESR != ESR_Failed && !Scope.destroy())
5365           return ESR_Failed;
5366         return ESR;
5367       }
5368     }
5369 
5370     // Initialize the __range variable.
5371     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5372     if (ESR != ESR_Succeeded) {
5373       if (ESR != ESR_Failed && !Scope.destroy())
5374         return ESR_Failed;
5375       return ESR;
5376     }
5377 
5378     // In error-recovery cases it's possible to get here even if we failed to
5379     // synthesize the __begin and __end variables.
5380     if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
5381       return ESR_Failed;
5382 
5383     // Create the __begin and __end iterators.
5384     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5385     if (ESR != ESR_Succeeded) {
5386       if (ESR != ESR_Failed && !Scope.destroy())
5387         return ESR_Failed;
5388       return ESR;
5389     }
5390     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5391     if (ESR != ESR_Succeeded) {
5392       if (ESR != ESR_Failed && !Scope.destroy())
5393         return ESR_Failed;
5394       return ESR;
5395     }
5396 
5397     while (true) {
5398       // Condition: __begin != __end.
5399       {
5400         if (FS->getCond()->isValueDependent()) {
5401           EvaluateDependentExpr(FS->getCond(), Info);
5402           // We don't know whether to keep going or terminate the loop.
5403           return ESR_Failed;
5404         }
5405         bool Continue = true;
5406         FullExpressionRAII CondExpr(Info);
5407         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5408           return ESR_Failed;
5409         if (!Continue)
5410           break;
5411       }
5412 
5413       // User's variable declaration, initialized by *__begin.
5414       BlockScopeRAII InnerScope(Info);
5415       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5416       if (ESR != ESR_Succeeded) {
5417         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5418           return ESR_Failed;
5419         return ESR;
5420       }
5421 
5422       // Loop body.
5423       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5424       if (ESR != ESR_Continue) {
5425         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5426           return ESR_Failed;
5427         return ESR;
5428       }
5429       if (FS->getInc()->isValueDependent()) {
5430         if (!EvaluateDependentExpr(FS->getInc(), Info))
5431           return ESR_Failed;
5432       } else {
5433         // Increment: ++__begin
5434         if (!EvaluateIgnoredValue(Info, FS->getInc()))
5435           return ESR_Failed;
5436       }
5437 
5438       if (!InnerScope.destroy())
5439         return ESR_Failed;
5440     }
5441 
5442     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5443   }
5444 
5445   case Stmt::SwitchStmtClass:
5446     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5447 
5448   case Stmt::ContinueStmtClass:
5449     return ESR_Continue;
5450 
5451   case Stmt::BreakStmtClass:
5452     return ESR_Break;
5453 
5454   case Stmt::LabelStmtClass:
5455     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5456 
5457   case Stmt::AttributedStmtClass:
5458     // As a general principle, C++11 attributes can be ignored without
5459     // any semantic impact.
5460     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
5461                         Case);
5462 
5463   case Stmt::CaseStmtClass:
5464   case Stmt::DefaultStmtClass:
5465     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5466   case Stmt::CXXTryStmtClass:
5467     // Evaluate try blocks by evaluating all sub statements.
5468     return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5469   }
5470 }
5471 
5472 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5473 /// default constructor. If so, we'll fold it whether or not it's marked as
5474 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
5475 /// so we need special handling.
5476 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5477                                            const CXXConstructorDecl *CD,
5478                                            bool IsValueInitialization) {
5479   if (!CD->isTrivial() || !CD->isDefaultConstructor())
5480     return false;
5481 
5482   // Value-initialization does not call a trivial default constructor, so such a
5483   // call is a core constant expression whether or not the constructor is
5484   // constexpr.
5485   if (!CD->isConstexpr() && !IsValueInitialization) {
5486     if (Info.getLangOpts().CPlusPlus11) {
5487       // FIXME: If DiagDecl is an implicitly-declared special member function,
5488       // we should be much more explicit about why it's not constexpr.
5489       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5490         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5491       Info.Note(CD->getLocation(), diag::note_declared_at);
5492     } else {
5493       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5494     }
5495   }
5496   return true;
5497 }
5498 
5499 /// CheckConstexprFunction - Check that a function can be called in a constant
5500 /// expression.
5501 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5502                                    const FunctionDecl *Declaration,
5503                                    const FunctionDecl *Definition,
5504                                    const Stmt *Body) {
5505   // Potential constant expressions can contain calls to declared, but not yet
5506   // defined, constexpr functions.
5507   if (Info.checkingPotentialConstantExpression() && !Definition &&
5508       Declaration->isConstexpr())
5509     return false;
5510 
5511   // Bail out if the function declaration itself is invalid.  We will
5512   // have produced a relevant diagnostic while parsing it, so just
5513   // note the problematic sub-expression.
5514   if (Declaration->isInvalidDecl()) {
5515     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5516     return false;
5517   }
5518 
5519   // DR1872: An instantiated virtual constexpr function can't be called in a
5520   // constant expression (prior to C++20). We can still constant-fold such a
5521   // call.
5522   if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5523       cast<CXXMethodDecl>(Declaration)->isVirtual())
5524     Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5525 
5526   if (Definition && Definition->isInvalidDecl()) {
5527     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5528     return false;
5529   }
5530 
5531   // Can we evaluate this function call?
5532   if (Definition && Definition->isConstexpr() && Body)
5533     return true;
5534 
5535   if (Info.getLangOpts().CPlusPlus11) {
5536     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5537 
5538     // If this function is not constexpr because it is an inherited
5539     // non-constexpr constructor, diagnose that directly.
5540     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5541     if (CD && CD->isInheritingConstructor()) {
5542       auto *Inherited = CD->getInheritedConstructor().getConstructor();
5543       if (!Inherited->isConstexpr())
5544         DiagDecl = CD = Inherited;
5545     }
5546 
5547     // FIXME: If DiagDecl is an implicitly-declared special member function
5548     // or an inheriting constructor, we should be much more explicit about why
5549     // it's not constexpr.
5550     if (CD && CD->isInheritingConstructor())
5551       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5552         << CD->getInheritedConstructor().getConstructor()->getParent();
5553     else
5554       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5555         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5556     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5557   } else {
5558     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5559   }
5560   return false;
5561 }
5562 
5563 namespace {
5564 struct CheckDynamicTypeHandler {
5565   AccessKinds AccessKind;
5566   typedef bool result_type;
5567   bool failed() { return false; }
5568   bool found(APValue &Subobj, QualType SubobjType) { return true; }
5569   bool found(APSInt &Value, QualType SubobjType) { return true; }
5570   bool found(APFloat &Value, QualType SubobjType) { return true; }
5571 };
5572 } // end anonymous namespace
5573 
5574 /// Check that we can access the notional vptr of an object / determine its
5575 /// dynamic type.
5576 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5577                              AccessKinds AK, bool Polymorphic) {
5578   if (This.Designator.Invalid)
5579     return false;
5580 
5581   CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5582 
5583   if (!Obj)
5584     return false;
5585 
5586   if (!Obj.Value) {
5587     // The object is not usable in constant expressions, so we can't inspect
5588     // its value to see if it's in-lifetime or what the active union members
5589     // are. We can still check for a one-past-the-end lvalue.
5590     if (This.Designator.isOnePastTheEnd() ||
5591         This.Designator.isMostDerivedAnUnsizedArray()) {
5592       Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5593                          ? diag::note_constexpr_access_past_end
5594                          : diag::note_constexpr_access_unsized_array)
5595           << AK;
5596       return false;
5597     } else if (Polymorphic) {
5598       // Conservatively refuse to perform a polymorphic operation if we would
5599       // not be able to read a notional 'vptr' value.
5600       APValue Val;
5601       This.moveInto(Val);
5602       QualType StarThisType =
5603           Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5604       Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5605           << AK << Val.getAsString(Info.Ctx, StarThisType);
5606       return false;
5607     }
5608     return true;
5609   }
5610 
5611   CheckDynamicTypeHandler Handler{AK};
5612   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5613 }
5614 
5615 /// Check that the pointee of the 'this' pointer in a member function call is
5616 /// either within its lifetime or in its period of construction or destruction.
5617 static bool
5618 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5619                                      const LValue &This,
5620                                      const CXXMethodDecl *NamedMember) {
5621   return checkDynamicType(
5622       Info, E, This,
5623       isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5624 }
5625 
5626 struct DynamicType {
5627   /// The dynamic class type of the object.
5628   const CXXRecordDecl *Type;
5629   /// The corresponding path length in the lvalue.
5630   unsigned PathLength;
5631 };
5632 
5633 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5634                                              unsigned PathLength) {
5635   assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5636       Designator.Entries.size() && "invalid path length");
5637   return (PathLength == Designator.MostDerivedPathLength)
5638              ? Designator.MostDerivedType->getAsCXXRecordDecl()
5639              : getAsBaseClass(Designator.Entries[PathLength - 1]);
5640 }
5641 
5642 /// Determine the dynamic type of an object.
5643 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
5644                                                 LValue &This, AccessKinds AK) {
5645   // If we don't have an lvalue denoting an object of class type, there is no
5646   // meaningful dynamic type. (We consider objects of non-class type to have no
5647   // dynamic type.)
5648   if (!checkDynamicType(Info, E, This, AK, true))
5649     return None;
5650 
5651   // Refuse to compute a dynamic type in the presence of virtual bases. This
5652   // shouldn't happen other than in constant-folding situations, since literal
5653   // types can't have virtual bases.
5654   //
5655   // Note that consumers of DynamicType assume that the type has no virtual
5656   // bases, and will need modifications if this restriction is relaxed.
5657   const CXXRecordDecl *Class =
5658       This.Designator.MostDerivedType->getAsCXXRecordDecl();
5659   if (!Class || Class->getNumVBases()) {
5660     Info.FFDiag(E);
5661     return None;
5662   }
5663 
5664   // FIXME: For very deep class hierarchies, it might be beneficial to use a
5665   // binary search here instead. But the overwhelmingly common case is that
5666   // we're not in the middle of a constructor, so it probably doesn't matter
5667   // in practice.
5668   ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5669   for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5670        PathLength <= Path.size(); ++PathLength) {
5671     switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5672                                       Path.slice(0, PathLength))) {
5673     case ConstructionPhase::Bases:
5674     case ConstructionPhase::DestroyingBases:
5675       // We're constructing or destroying a base class. This is not the dynamic
5676       // type.
5677       break;
5678 
5679     case ConstructionPhase::None:
5680     case ConstructionPhase::AfterBases:
5681     case ConstructionPhase::AfterFields:
5682     case ConstructionPhase::Destroying:
5683       // We've finished constructing the base classes and not yet started
5684       // destroying them again, so this is the dynamic type.
5685       return DynamicType{getBaseClassType(This.Designator, PathLength),
5686                          PathLength};
5687     }
5688   }
5689 
5690   // CWG issue 1517: we're constructing a base class of the object described by
5691   // 'This', so that object has not yet begun its period of construction and
5692   // any polymorphic operation on it results in undefined behavior.
5693   Info.FFDiag(E);
5694   return None;
5695 }
5696 
5697 /// Perform virtual dispatch.
5698 static const CXXMethodDecl *HandleVirtualDispatch(
5699     EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5700     llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5701   Optional<DynamicType> DynType = ComputeDynamicType(
5702       Info, E, This,
5703       isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5704   if (!DynType)
5705     return nullptr;
5706 
5707   // Find the final overrider. It must be declared in one of the classes on the
5708   // path from the dynamic type to the static type.
5709   // FIXME: If we ever allow literal types to have virtual base classes, that
5710   // won't be true.
5711   const CXXMethodDecl *Callee = Found;
5712   unsigned PathLength = DynType->PathLength;
5713   for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5714     const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5715     const CXXMethodDecl *Overrider =
5716         Found->getCorrespondingMethodDeclaredInClass(Class, false);
5717     if (Overrider) {
5718       Callee = Overrider;
5719       break;
5720     }
5721   }
5722 
5723   // C++2a [class.abstract]p6:
5724   //   the effect of making a virtual call to a pure virtual function [...] is
5725   //   undefined
5726   if (Callee->isPure()) {
5727     Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5728     Info.Note(Callee->getLocation(), diag::note_declared_at);
5729     return nullptr;
5730   }
5731 
5732   // If necessary, walk the rest of the path to determine the sequence of
5733   // covariant adjustment steps to apply.
5734   if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5735                                        Found->getReturnType())) {
5736     CovariantAdjustmentPath.push_back(Callee->getReturnType());
5737     for (unsigned CovariantPathLength = PathLength + 1;
5738          CovariantPathLength != This.Designator.Entries.size();
5739          ++CovariantPathLength) {
5740       const CXXRecordDecl *NextClass =
5741           getBaseClassType(This.Designator, CovariantPathLength);
5742       const CXXMethodDecl *Next =
5743           Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5744       if (Next && !Info.Ctx.hasSameUnqualifiedType(
5745                       Next->getReturnType(), CovariantAdjustmentPath.back()))
5746         CovariantAdjustmentPath.push_back(Next->getReturnType());
5747     }
5748     if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5749                                          CovariantAdjustmentPath.back()))
5750       CovariantAdjustmentPath.push_back(Found->getReturnType());
5751   }
5752 
5753   // Perform 'this' adjustment.
5754   if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5755     return nullptr;
5756 
5757   return Callee;
5758 }
5759 
5760 /// Perform the adjustment from a value returned by a virtual function to
5761 /// a value of the statically expected type, which may be a pointer or
5762 /// reference to a base class of the returned type.
5763 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5764                                             APValue &Result,
5765                                             ArrayRef<QualType> Path) {
5766   assert(Result.isLValue() &&
5767          "unexpected kind of APValue for covariant return");
5768   if (Result.isNullPointer())
5769     return true;
5770 
5771   LValue LVal;
5772   LVal.setFrom(Info.Ctx, Result);
5773 
5774   const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5775   for (unsigned I = 1; I != Path.size(); ++I) {
5776     const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5777     assert(OldClass && NewClass && "unexpected kind of covariant return");
5778     if (OldClass != NewClass &&
5779         !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5780       return false;
5781     OldClass = NewClass;
5782   }
5783 
5784   LVal.moveInto(Result);
5785   return true;
5786 }
5787 
5788 /// Determine whether \p Base, which is known to be a direct base class of
5789 /// \p Derived, is a public base class.
5790 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5791                               const CXXRecordDecl *Base) {
5792   for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5793     auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5794     if (BaseClass && declaresSameEntity(BaseClass, Base))
5795       return BaseSpec.getAccessSpecifier() == AS_public;
5796   }
5797   llvm_unreachable("Base is not a direct base of Derived");
5798 }
5799 
5800 /// Apply the given dynamic cast operation on the provided lvalue.
5801 ///
5802 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
5803 /// to find a suitable target subobject.
5804 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5805                               LValue &Ptr) {
5806   // We can't do anything with a non-symbolic pointer value.
5807   SubobjectDesignator &D = Ptr.Designator;
5808   if (D.Invalid)
5809     return false;
5810 
5811   // C++ [expr.dynamic.cast]p6:
5812   //   If v is a null pointer value, the result is a null pointer value.
5813   if (Ptr.isNullPointer() && !E->isGLValue())
5814     return true;
5815 
5816   // For all the other cases, we need the pointer to point to an object within
5817   // its lifetime / period of construction / destruction, and we need to know
5818   // its dynamic type.
5819   Optional<DynamicType> DynType =
5820       ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5821   if (!DynType)
5822     return false;
5823 
5824   // C++ [expr.dynamic.cast]p7:
5825   //   If T is "pointer to cv void", then the result is a pointer to the most
5826   //   derived object
5827   if (E->getType()->isVoidPointerType())
5828     return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5829 
5830   const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5831   assert(C && "dynamic_cast target is not void pointer nor class");
5832   CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5833 
5834   auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5835     // C++ [expr.dynamic.cast]p9:
5836     if (!E->isGLValue()) {
5837       //   The value of a failed cast to pointer type is the null pointer value
5838       //   of the required result type.
5839       Ptr.setNull(Info.Ctx, E->getType());
5840       return true;
5841     }
5842 
5843     //   A failed cast to reference type throws [...] std::bad_cast.
5844     unsigned DiagKind;
5845     if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5846                    DynType->Type->isDerivedFrom(C)))
5847       DiagKind = 0;
5848     else if (!Paths || Paths->begin() == Paths->end())
5849       DiagKind = 1;
5850     else if (Paths->isAmbiguous(CQT))
5851       DiagKind = 2;
5852     else {
5853       assert(Paths->front().Access != AS_public && "why did the cast fail?");
5854       DiagKind = 3;
5855     }
5856     Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5857         << DiagKind << Ptr.Designator.getType(Info.Ctx)
5858         << Info.Ctx.getRecordType(DynType->Type)
5859         << E->getType().getUnqualifiedType();
5860     return false;
5861   };
5862 
5863   // Runtime check, phase 1:
5864   //   Walk from the base subobject towards the derived object looking for the
5865   //   target type.
5866   for (int PathLength = Ptr.Designator.Entries.size();
5867        PathLength >= (int)DynType->PathLength; --PathLength) {
5868     const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5869     if (declaresSameEntity(Class, C))
5870       return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5871     // We can only walk across public inheritance edges.
5872     if (PathLength > (int)DynType->PathLength &&
5873         !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5874                            Class))
5875       return RuntimeCheckFailed(nullptr);
5876   }
5877 
5878   // Runtime check, phase 2:
5879   //   Search the dynamic type for an unambiguous public base of type C.
5880   CXXBasePaths Paths(/*FindAmbiguities=*/true,
5881                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
5882   if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5883       Paths.front().Access == AS_public) {
5884     // Downcast to the dynamic type...
5885     if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5886       return false;
5887     // ... then upcast to the chosen base class subobject.
5888     for (CXXBasePathElement &Elem : Paths.front())
5889       if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5890         return false;
5891     return true;
5892   }
5893 
5894   // Otherwise, the runtime check fails.
5895   return RuntimeCheckFailed(&Paths);
5896 }
5897 
5898 namespace {
5899 struct StartLifetimeOfUnionMemberHandler {
5900   EvalInfo &Info;
5901   const Expr *LHSExpr;
5902   const FieldDecl *Field;
5903   bool DuringInit;
5904   bool Failed = false;
5905   static const AccessKinds AccessKind = AK_Assign;
5906 
5907   typedef bool result_type;
5908   bool failed() { return Failed; }
5909   bool found(APValue &Subobj, QualType SubobjType) {
5910     // We are supposed to perform no initialization but begin the lifetime of
5911     // the object. We interpret that as meaning to do what default
5912     // initialization of the object would do if all constructors involved were
5913     // trivial:
5914     //  * All base, non-variant member, and array element subobjects' lifetimes
5915     //    begin
5916     //  * No variant members' lifetimes begin
5917     //  * All scalar subobjects whose lifetimes begin have indeterminate values
5918     assert(SubobjType->isUnionType());
5919     if (declaresSameEntity(Subobj.getUnionField(), Field)) {
5920       // This union member is already active. If it's also in-lifetime, there's
5921       // nothing to do.
5922       if (Subobj.getUnionValue().hasValue())
5923         return true;
5924     } else if (DuringInit) {
5925       // We're currently in the process of initializing a different union
5926       // member.  If we carried on, that initialization would attempt to
5927       // store to an inactive union member, resulting in undefined behavior.
5928       Info.FFDiag(LHSExpr,
5929                   diag::note_constexpr_union_member_change_during_init);
5930       return false;
5931     }
5932     APValue Result;
5933     Failed = !getDefaultInitValue(Field->getType(), Result);
5934     Subobj.setUnion(Field, Result);
5935     return true;
5936   }
5937   bool found(APSInt &Value, QualType SubobjType) {
5938     llvm_unreachable("wrong value kind for union object");
5939   }
5940   bool found(APFloat &Value, QualType SubobjType) {
5941     llvm_unreachable("wrong value kind for union object");
5942   }
5943 };
5944 } // end anonymous namespace
5945 
5946 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5947 
5948 /// Handle a builtin simple-assignment or a call to a trivial assignment
5949 /// operator whose left-hand side might involve a union member access. If it
5950 /// does, implicitly start the lifetime of any accessed union elements per
5951 /// C++20 [class.union]5.
5952 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5953                                           const LValue &LHS) {
5954   if (LHS.InvalidBase || LHS.Designator.Invalid)
5955     return false;
5956 
5957   llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5958   // C++ [class.union]p5:
5959   //   define the set S(E) of subexpressions of E as follows:
5960   unsigned PathLength = LHS.Designator.Entries.size();
5961   for (const Expr *E = LHSExpr; E != nullptr;) {
5962     //   -- If E is of the form A.B, S(E) contains the elements of S(A)...
5963     if (auto *ME = dyn_cast<MemberExpr>(E)) {
5964       auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5965       // Note that we can't implicitly start the lifetime of a reference,
5966       // so we don't need to proceed any further if we reach one.
5967       if (!FD || FD->getType()->isReferenceType())
5968         break;
5969 
5970       //    ... and also contains A.B if B names a union member ...
5971       if (FD->getParent()->isUnion()) {
5972         //    ... of a non-class, non-array type, or of a class type with a
5973         //    trivial default constructor that is not deleted, or an array of
5974         //    such types.
5975         auto *RD =
5976             FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5977         if (!RD || RD->hasTrivialDefaultConstructor())
5978           UnionPathLengths.push_back({PathLength - 1, FD});
5979       }
5980 
5981       E = ME->getBase();
5982       --PathLength;
5983       assert(declaresSameEntity(FD,
5984                                 LHS.Designator.Entries[PathLength]
5985                                     .getAsBaseOrMember().getPointer()));
5986 
5987       //   -- If E is of the form A[B] and is interpreted as a built-in array
5988       //      subscripting operator, S(E) is [S(the array operand, if any)].
5989     } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5990       // Step over an ArrayToPointerDecay implicit cast.
5991       auto *Base = ASE->getBase()->IgnoreImplicit();
5992       if (!Base->getType()->isArrayType())
5993         break;
5994 
5995       E = Base;
5996       --PathLength;
5997 
5998     } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5999       // Step over a derived-to-base conversion.
6000       E = ICE->getSubExpr();
6001       if (ICE->getCastKind() == CK_NoOp)
6002         continue;
6003       if (ICE->getCastKind() != CK_DerivedToBase &&
6004           ICE->getCastKind() != CK_UncheckedDerivedToBase)
6005         break;
6006       // Walk path backwards as we walk up from the base to the derived class.
6007       for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
6008         --PathLength;
6009         (void)Elt;
6010         assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
6011                                   LHS.Designator.Entries[PathLength]
6012                                       .getAsBaseOrMember().getPointer()));
6013       }
6014 
6015     //   -- Otherwise, S(E) is empty.
6016     } else {
6017       break;
6018     }
6019   }
6020 
6021   // Common case: no unions' lifetimes are started.
6022   if (UnionPathLengths.empty())
6023     return true;
6024 
6025   //   if modification of X [would access an inactive union member], an object
6026   //   of the type of X is implicitly created
6027   CompleteObject Obj =
6028       findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
6029   if (!Obj)
6030     return false;
6031   for (std::pair<unsigned, const FieldDecl *> LengthAndField :
6032            llvm::reverse(UnionPathLengths)) {
6033     // Form a designator for the union object.
6034     SubobjectDesignator D = LHS.Designator;
6035     D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
6036 
6037     bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
6038                       ConstructionPhase::AfterBases;
6039     StartLifetimeOfUnionMemberHandler StartLifetime{
6040         Info, LHSExpr, LengthAndField.second, DuringInit};
6041     if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
6042       return false;
6043   }
6044 
6045   return true;
6046 }
6047 
6048 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
6049                             CallRef Call, EvalInfo &Info,
6050                             bool NonNull = false) {
6051   LValue LV;
6052   // Create the parameter slot and register its destruction. For a vararg
6053   // argument, create a temporary.
6054   // FIXME: For calling conventions that destroy parameters in the callee,
6055   // should we consider performing destruction when the function returns
6056   // instead?
6057   APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6058                    : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6059                                                        ScopeKind::Call, LV);
6060   if (!EvaluateInPlace(V, Info, LV, Arg))
6061     return false;
6062 
6063   // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6064   // undefined behavior, so is non-constant.
6065   if (NonNull && V.isLValue() && V.isNullPointer()) {
6066     Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6067     return false;
6068   }
6069 
6070   return true;
6071 }
6072 
6073 /// Evaluate the arguments to a function call.
6074 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6075                          EvalInfo &Info, const FunctionDecl *Callee,
6076                          bool RightToLeft = false) {
6077   bool Success = true;
6078   llvm::SmallBitVector ForbiddenNullArgs;
6079   if (Callee->hasAttr<NonNullAttr>()) {
6080     ForbiddenNullArgs.resize(Args.size());
6081     for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6082       if (!Attr->args_size()) {
6083         ForbiddenNullArgs.set();
6084         break;
6085       } else
6086         for (auto Idx : Attr->args()) {
6087           unsigned ASTIdx = Idx.getASTIndex();
6088           if (ASTIdx >= Args.size())
6089             continue;
6090           ForbiddenNullArgs[ASTIdx] = true;
6091         }
6092     }
6093   }
6094   for (unsigned I = 0; I < Args.size(); I++) {
6095     unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6096     const ParmVarDecl *PVD =
6097         Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6098     bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6099     if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) {
6100       // If we're checking for a potential constant expression, evaluate all
6101       // initializers even if some of them fail.
6102       if (!Info.noteFailure())
6103         return false;
6104       Success = false;
6105     }
6106   }
6107   return Success;
6108 }
6109 
6110 /// Perform a trivial copy from Param, which is the parameter of a copy or move
6111 /// constructor or assignment operator.
6112 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6113                               const Expr *E, APValue &Result,
6114                               bool CopyObjectRepresentation) {
6115   // Find the reference argument.
6116   CallStackFrame *Frame = Info.CurrentCall;
6117   APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6118   if (!RefValue) {
6119     Info.FFDiag(E);
6120     return false;
6121   }
6122 
6123   // Copy out the contents of the RHS object.
6124   LValue RefLValue;
6125   RefLValue.setFrom(Info.Ctx, *RefValue);
6126   return handleLValueToRValueConversion(
6127       Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6128       CopyObjectRepresentation);
6129 }
6130 
6131 /// Evaluate a function call.
6132 static bool HandleFunctionCall(SourceLocation CallLoc,
6133                                const FunctionDecl *Callee, const LValue *This,
6134                                ArrayRef<const Expr *> Args, CallRef Call,
6135                                const Stmt *Body, EvalInfo &Info,
6136                                APValue &Result, const LValue *ResultSlot) {
6137   if (!Info.CheckCallLimit(CallLoc))
6138     return false;
6139 
6140   CallStackFrame Frame(Info, CallLoc, Callee, This, Call);
6141 
6142   // For a trivial copy or move assignment, perform an APValue copy. This is
6143   // essential for unions, where the operations performed by the assignment
6144   // operator cannot be represented as statements.
6145   //
6146   // Skip this for non-union classes with no fields; in that case, the defaulted
6147   // copy/move does not actually read the object.
6148   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6149   if (MD && MD->isDefaulted() &&
6150       (MD->getParent()->isUnion() ||
6151        (MD->isTrivial() &&
6152         isReadByLvalueToRvalueConversion(MD->getParent())))) {
6153     assert(This &&
6154            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
6155     APValue RHSValue;
6156     if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6157                            MD->getParent()->isUnion()))
6158       return false;
6159     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
6160                           RHSValue))
6161       return false;
6162     This->moveInto(Result);
6163     return true;
6164   } else if (MD && isLambdaCallOperator(MD)) {
6165     // We're in a lambda; determine the lambda capture field maps unless we're
6166     // just constexpr checking a lambda's call operator. constexpr checking is
6167     // done before the captures have been added to the closure object (unless
6168     // we're inferring constexpr-ness), so we don't have access to them in this
6169     // case. But since we don't need the captures to constexpr check, we can
6170     // just ignore them.
6171     if (!Info.checkingPotentialConstantExpression())
6172       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6173                                         Frame.LambdaThisCaptureField);
6174   }
6175 
6176   StmtResult Ret = {Result, ResultSlot};
6177   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6178   if (ESR == ESR_Succeeded) {
6179     if (Callee->getReturnType()->isVoidType())
6180       return true;
6181     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6182   }
6183   return ESR == ESR_Returned;
6184 }
6185 
6186 /// Evaluate a constructor call.
6187 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6188                                   CallRef Call,
6189                                   const CXXConstructorDecl *Definition,
6190                                   EvalInfo &Info, APValue &Result) {
6191   SourceLocation CallLoc = E->getExprLoc();
6192   if (!Info.CheckCallLimit(CallLoc))
6193     return false;
6194 
6195   const CXXRecordDecl *RD = Definition->getParent();
6196   if (RD->getNumVBases()) {
6197     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6198     return false;
6199   }
6200 
6201   EvalInfo::EvaluatingConstructorRAII EvalObj(
6202       Info,
6203       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6204       RD->getNumBases());
6205   CallStackFrame Frame(Info, CallLoc, Definition, &This, Call);
6206 
6207   // FIXME: Creating an APValue just to hold a nonexistent return value is
6208   // wasteful.
6209   APValue RetVal;
6210   StmtResult Ret = {RetVal, nullptr};
6211 
6212   // If it's a delegating constructor, delegate.
6213   if (Definition->isDelegatingConstructor()) {
6214     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
6215     if ((*I)->getInit()->isValueDependent()) {
6216       if (!EvaluateDependentExpr((*I)->getInit(), Info))
6217         return false;
6218     } else {
6219       FullExpressionRAII InitScope(Info);
6220       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6221           !InitScope.destroy())
6222         return false;
6223     }
6224     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6225   }
6226 
6227   // For a trivial copy or move constructor, perform an APValue copy. This is
6228   // essential for unions (or classes with anonymous union members), where the
6229   // operations performed by the constructor cannot be represented by
6230   // ctor-initializers.
6231   //
6232   // Skip this for empty non-union classes; we should not perform an
6233   // lvalue-to-rvalue conversion on them because their copy constructor does not
6234   // actually read them.
6235   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6236       (Definition->getParent()->isUnion() ||
6237        (Definition->isTrivial() &&
6238         isReadByLvalueToRvalueConversion(Definition->getParent())))) {
6239     return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6240                              Definition->getParent()->isUnion());
6241   }
6242 
6243   // Reserve space for the struct members.
6244   if (!Result.hasValue()) {
6245     if (!RD->isUnion())
6246       Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6247                        std::distance(RD->field_begin(), RD->field_end()));
6248     else
6249       // A union starts with no active member.
6250       Result = APValue((const FieldDecl*)nullptr);
6251   }
6252 
6253   if (RD->isInvalidDecl()) return false;
6254   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6255 
6256   // A scope for temporaries lifetime-extended by reference members.
6257   BlockScopeRAII LifetimeExtendedScope(Info);
6258 
6259   bool Success = true;
6260   unsigned BasesSeen = 0;
6261 #ifndef NDEBUG
6262   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
6263 #endif
6264   CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
6265   auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6266     // We might be initializing the same field again if this is an indirect
6267     // field initialization.
6268     if (FieldIt == RD->field_end() ||
6269         FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6270       assert(Indirect && "fields out of order?");
6271       return;
6272     }
6273 
6274     // Default-initialize any fields with no explicit initializer.
6275     for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6276       assert(FieldIt != RD->field_end() && "missing field?");
6277       if (!FieldIt->isUnnamedBitfield())
6278         Success &= getDefaultInitValue(
6279             FieldIt->getType(),
6280             Result.getStructField(FieldIt->getFieldIndex()));
6281     }
6282     ++FieldIt;
6283   };
6284   for (const auto *I : Definition->inits()) {
6285     LValue Subobject = This;
6286     LValue SubobjectParent = This;
6287     APValue *Value = &Result;
6288 
6289     // Determine the subobject to initialize.
6290     FieldDecl *FD = nullptr;
6291     if (I->isBaseInitializer()) {
6292       QualType BaseType(I->getBaseClass(), 0);
6293 #ifndef NDEBUG
6294       // Non-virtual base classes are initialized in the order in the class
6295       // definition. We have already checked for virtual base classes.
6296       assert(!BaseIt->isVirtual() && "virtual base for literal type");
6297       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
6298              "base class initializers not in expected order");
6299       ++BaseIt;
6300 #endif
6301       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6302                                   BaseType->getAsCXXRecordDecl(), &Layout))
6303         return false;
6304       Value = &Result.getStructBase(BasesSeen++);
6305     } else if ((FD = I->getMember())) {
6306       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6307         return false;
6308       if (RD->isUnion()) {
6309         Result = APValue(FD);
6310         Value = &Result.getUnionValue();
6311       } else {
6312         SkipToField(FD, false);
6313         Value = &Result.getStructField(FD->getFieldIndex());
6314       }
6315     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6316       // Walk the indirect field decl's chain to find the object to initialize,
6317       // and make sure we've initialized every step along it.
6318       auto IndirectFieldChain = IFD->chain();
6319       for (auto *C : IndirectFieldChain) {
6320         FD = cast<FieldDecl>(C);
6321         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6322         // Switch the union field if it differs. This happens if we had
6323         // preceding zero-initialization, and we're now initializing a union
6324         // subobject other than the first.
6325         // FIXME: In this case, the values of the other subobjects are
6326         // specified, since zero-initialization sets all padding bits to zero.
6327         if (!Value->hasValue() ||
6328             (Value->isUnion() && Value->getUnionField() != FD)) {
6329           if (CD->isUnion())
6330             *Value = APValue(FD);
6331           else
6332             // FIXME: This immediately starts the lifetime of all members of
6333             // an anonymous struct. It would be preferable to strictly start
6334             // member lifetime in initialization order.
6335             Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
6336         }
6337         // Store Subobject as its parent before updating it for the last element
6338         // in the chain.
6339         if (C == IndirectFieldChain.back())
6340           SubobjectParent = Subobject;
6341         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6342           return false;
6343         if (CD->isUnion())
6344           Value = &Value->getUnionValue();
6345         else {
6346           if (C == IndirectFieldChain.front() && !RD->isUnion())
6347             SkipToField(FD, true);
6348           Value = &Value->getStructField(FD->getFieldIndex());
6349         }
6350       }
6351     } else {
6352       llvm_unreachable("unknown base initializer kind");
6353     }
6354 
6355     // Need to override This for implicit field initializers as in this case
6356     // This refers to innermost anonymous struct/union containing initializer,
6357     // not to currently constructed class.
6358     const Expr *Init = I->getInit();
6359     if (Init->isValueDependent()) {
6360       if (!EvaluateDependentExpr(Init, Info))
6361         return false;
6362     } else {
6363       ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6364                                     isa<CXXDefaultInitExpr>(Init));
6365       FullExpressionRAII InitScope(Info);
6366       if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6367           (FD && FD->isBitField() &&
6368            !truncateBitfieldValue(Info, Init, *Value, FD))) {
6369         // If we're checking for a potential constant expression, evaluate all
6370         // initializers even if some of them fail.
6371         if (!Info.noteFailure())
6372           return false;
6373         Success = false;
6374       }
6375     }
6376 
6377     // This is the point at which the dynamic type of the object becomes this
6378     // class type.
6379     if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6380       EvalObj.finishedConstructingBases();
6381   }
6382 
6383   // Default-initialize any remaining fields.
6384   if (!RD->isUnion()) {
6385     for (; FieldIt != RD->field_end(); ++FieldIt) {
6386       if (!FieldIt->isUnnamedBitfield())
6387         Success &= getDefaultInitValue(
6388             FieldIt->getType(),
6389             Result.getStructField(FieldIt->getFieldIndex()));
6390     }
6391   }
6392 
6393   EvalObj.finishedConstructingFields();
6394 
6395   return Success &&
6396          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6397          LifetimeExtendedScope.destroy();
6398 }
6399 
6400 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6401                                   ArrayRef<const Expr*> Args,
6402                                   const CXXConstructorDecl *Definition,
6403                                   EvalInfo &Info, APValue &Result) {
6404   CallScopeRAII CallScope(Info);
6405   CallRef Call = Info.CurrentCall->createCall(Definition);
6406   if (!EvaluateArgs(Args, Call, Info, Definition))
6407     return false;
6408 
6409   return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6410          CallScope.destroy();
6411 }
6412 
6413 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
6414                                   const LValue &This, APValue &Value,
6415                                   QualType T) {
6416   // Objects can only be destroyed while they're within their lifetimes.
6417   // FIXME: We have no representation for whether an object of type nullptr_t
6418   // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6419   // as indeterminate instead?
6420   if (Value.isAbsent() && !T->isNullPtrType()) {
6421     APValue Printable;
6422     This.moveInto(Printable);
6423     Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
6424       << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6425     return false;
6426   }
6427 
6428   // Invent an expression for location purposes.
6429   // FIXME: We shouldn't need to do this.
6430   OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_PRValue);
6431 
6432   // For arrays, destroy elements right-to-left.
6433   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6434     uint64_t Size = CAT->getSize().getZExtValue();
6435     QualType ElemT = CAT->getElementType();
6436 
6437     LValue ElemLV = This;
6438     ElemLV.addArray(Info, &LocE, CAT);
6439     if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6440       return false;
6441 
6442     // Ensure that we have actual array elements available to destroy; the
6443     // destructors might mutate the value, so we can't run them on the array
6444     // filler.
6445     if (Size && Size > Value.getArrayInitializedElts())
6446       expandArray(Value, Value.getArraySize() - 1);
6447 
6448     for (; Size != 0; --Size) {
6449       APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6450       if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6451           !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
6452         return false;
6453     }
6454 
6455     // End the lifetime of this array now.
6456     Value = APValue();
6457     return true;
6458   }
6459 
6460   const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6461   if (!RD) {
6462     if (T.isDestructedType()) {
6463       Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
6464       return false;
6465     }
6466 
6467     Value = APValue();
6468     return true;
6469   }
6470 
6471   if (RD->getNumVBases()) {
6472     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6473     return false;
6474   }
6475 
6476   const CXXDestructorDecl *DD = RD->getDestructor();
6477   if (!DD && !RD->hasTrivialDestructor()) {
6478     Info.FFDiag(CallLoc);
6479     return false;
6480   }
6481 
6482   if (!DD || DD->isTrivial() ||
6483       (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6484     // A trivial destructor just ends the lifetime of the object. Check for
6485     // this case before checking for a body, because we might not bother
6486     // building a body for a trivial destructor. Note that it doesn't matter
6487     // whether the destructor is constexpr in this case; all trivial
6488     // destructors are constexpr.
6489     //
6490     // If an anonymous union would be destroyed, some enclosing destructor must
6491     // have been explicitly defined, and the anonymous union destruction should
6492     // have no effect.
6493     Value = APValue();
6494     return true;
6495   }
6496 
6497   if (!Info.CheckCallLimit(CallLoc))
6498     return false;
6499 
6500   const FunctionDecl *Definition = nullptr;
6501   const Stmt *Body = DD->getBody(Definition);
6502 
6503   if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
6504     return false;
6505 
6506   CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef());
6507 
6508   // We're now in the period of destruction of this object.
6509   unsigned BasesLeft = RD->getNumBases();
6510   EvalInfo::EvaluatingDestructorRAII EvalObj(
6511       Info,
6512       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6513   if (!EvalObj.DidInsert) {
6514     // C++2a [class.dtor]p19:
6515     //   the behavior is undefined if the destructor is invoked for an object
6516     //   whose lifetime has ended
6517     // (Note that formally the lifetime ends when the period of destruction
6518     // begins, even though certain uses of the object remain valid until the
6519     // period of destruction ends.)
6520     Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
6521     return false;
6522   }
6523 
6524   // FIXME: Creating an APValue just to hold a nonexistent return value is
6525   // wasteful.
6526   APValue RetVal;
6527   StmtResult Ret = {RetVal, nullptr};
6528   if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6529     return false;
6530 
6531   // A union destructor does not implicitly destroy its members.
6532   if (RD->isUnion())
6533     return true;
6534 
6535   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6536 
6537   // We don't have a good way to iterate fields in reverse, so collect all the
6538   // fields first and then walk them backwards.
6539   SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
6540   for (const FieldDecl *FD : llvm::reverse(Fields)) {
6541     if (FD->isUnnamedBitfield())
6542       continue;
6543 
6544     LValue Subobject = This;
6545     if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6546       return false;
6547 
6548     APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6549     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6550                                FD->getType()))
6551       return false;
6552   }
6553 
6554   if (BasesLeft != 0)
6555     EvalObj.startedDestroyingBases();
6556 
6557   // Destroy base classes in reverse order.
6558   for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6559     --BasesLeft;
6560 
6561     QualType BaseType = Base.getType();
6562     LValue Subobject = This;
6563     if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
6564                                 BaseType->getAsCXXRecordDecl(), &Layout))
6565       return false;
6566 
6567     APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
6568     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6569                                BaseType))
6570       return false;
6571   }
6572   assert(BasesLeft == 0 && "NumBases was wrong?");
6573 
6574   // The period of destruction ends now. The object is gone.
6575   Value = APValue();
6576   return true;
6577 }
6578 
6579 namespace {
6580 struct DestroyObjectHandler {
6581   EvalInfo &Info;
6582   const Expr *E;
6583   const LValue &This;
6584   const AccessKinds AccessKind;
6585 
6586   typedef bool result_type;
6587   bool failed() { return false; }
6588   bool found(APValue &Subobj, QualType SubobjType) {
6589     return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
6590                                  SubobjType);
6591   }
6592   bool found(APSInt &Value, QualType SubobjType) {
6593     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6594     return false;
6595   }
6596   bool found(APFloat &Value, QualType SubobjType) {
6597     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6598     return false;
6599   }
6600 };
6601 }
6602 
6603 /// Perform a destructor or pseudo-destructor call on the given object, which
6604 /// might in general not be a complete object.
6605 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6606                               const LValue &This, QualType ThisType) {
6607   CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6608   DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6609   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6610 }
6611 
6612 /// Destroy and end the lifetime of the given complete object.
6613 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6614                               APValue::LValueBase LVBase, APValue &Value,
6615                               QualType T) {
6616   // If we've had an unmodeled side-effect, we can't rely on mutable state
6617   // (such as the object we're about to destroy) being correct.
6618   if (Info.EvalStatus.HasSideEffects)
6619     return false;
6620 
6621   LValue LV;
6622   LV.set({LVBase});
6623   return HandleDestructionImpl(Info, Loc, LV, Value, T);
6624 }
6625 
6626 /// Perform a call to 'perator new' or to `__builtin_operator_new'.
6627 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6628                                   LValue &Result) {
6629   if (Info.checkingPotentialConstantExpression() ||
6630       Info.SpeculativeEvaluationDepth)
6631     return false;
6632 
6633   // This is permitted only within a call to std::allocator<T>::allocate.
6634   auto Caller = Info.getStdAllocatorCaller("allocate");
6635   if (!Caller) {
6636     Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
6637                                      ? diag::note_constexpr_new_untyped
6638                                      : diag::note_constexpr_new);
6639     return false;
6640   }
6641 
6642   QualType ElemType = Caller.ElemType;
6643   if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6644     Info.FFDiag(E->getExprLoc(),
6645                 diag::note_constexpr_new_not_complete_object_type)
6646         << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6647     return false;
6648   }
6649 
6650   APSInt ByteSize;
6651   if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6652     return false;
6653   bool IsNothrow = false;
6654   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6655     EvaluateIgnoredValue(Info, E->getArg(I));
6656     IsNothrow |= E->getType()->isNothrowT();
6657   }
6658 
6659   CharUnits ElemSize;
6660   if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6661     return false;
6662   APInt Size, Remainder;
6663   APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6664   APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6665   if (Remainder != 0) {
6666     // This likely indicates a bug in the implementation of 'std::allocator'.
6667     Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6668         << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6669     return false;
6670   }
6671 
6672   if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
6673     if (IsNothrow) {
6674       Result.setNull(Info.Ctx, E->getType());
6675       return true;
6676     }
6677 
6678     Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
6679     return false;
6680   }
6681 
6682   QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
6683                                                      ArrayType::Normal, 0);
6684   APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6685   *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6686   Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6687   return true;
6688 }
6689 
6690 static bool hasVirtualDestructor(QualType T) {
6691   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6692     if (CXXDestructorDecl *DD = RD->getDestructor())
6693       return DD->isVirtual();
6694   return false;
6695 }
6696 
6697 static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6698   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6699     if (CXXDestructorDecl *DD = RD->getDestructor())
6700       return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6701   return nullptr;
6702 }
6703 
6704 /// Check that the given object is a suitable pointer to a heap allocation that
6705 /// still exists and is of the right kind for the purpose of a deletion.
6706 ///
6707 /// On success, returns the heap allocation to deallocate. On failure, produces
6708 /// a diagnostic and returns None.
6709 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6710                                             const LValue &Pointer,
6711                                             DynAlloc::Kind DeallocKind) {
6712   auto PointerAsString = [&] {
6713     return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6714   };
6715 
6716   DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6717   if (!DA) {
6718     Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6719         << PointerAsString();
6720     if (Pointer.Base)
6721       NoteLValueLocation(Info, Pointer.Base);
6722     return None;
6723   }
6724 
6725   Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6726   if (!Alloc) {
6727     Info.FFDiag(E, diag::note_constexpr_double_delete);
6728     return None;
6729   }
6730 
6731   QualType AllocType = Pointer.Base.getDynamicAllocType();
6732   if (DeallocKind != (*Alloc)->getKind()) {
6733     Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6734         << DeallocKind << (*Alloc)->getKind() << AllocType;
6735     NoteLValueLocation(Info, Pointer.Base);
6736     return None;
6737   }
6738 
6739   bool Subobject = false;
6740   if (DeallocKind == DynAlloc::New) {
6741     Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6742                 Pointer.Designator.isOnePastTheEnd();
6743   } else {
6744     Subobject = Pointer.Designator.Entries.size() != 1 ||
6745                 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6746   }
6747   if (Subobject) {
6748     Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6749         << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6750     return None;
6751   }
6752 
6753   return Alloc;
6754 }
6755 
6756 // Perform a call to 'operator delete' or '__builtin_operator_delete'.
6757 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6758   if (Info.checkingPotentialConstantExpression() ||
6759       Info.SpeculativeEvaluationDepth)
6760     return false;
6761 
6762   // This is permitted only within a call to std::allocator<T>::deallocate.
6763   if (!Info.getStdAllocatorCaller("deallocate")) {
6764     Info.FFDiag(E->getExprLoc());
6765     return true;
6766   }
6767 
6768   LValue Pointer;
6769   if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6770     return false;
6771   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6772     EvaluateIgnoredValue(Info, E->getArg(I));
6773 
6774   if (Pointer.Designator.Invalid)
6775     return false;
6776 
6777   // Deleting a null pointer would have no effect, but it's not permitted by
6778   // std::allocator<T>::deallocate's contract.
6779   if (Pointer.isNullPointer()) {
6780     Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
6781     return true;
6782   }
6783 
6784   if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6785     return false;
6786 
6787   Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6788   return true;
6789 }
6790 
6791 //===----------------------------------------------------------------------===//
6792 // Generic Evaluation
6793 //===----------------------------------------------------------------------===//
6794 namespace {
6795 
6796 class BitCastBuffer {
6797   // FIXME: We're going to need bit-level granularity when we support
6798   // bit-fields.
6799   // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6800   // we don't support a host or target where that is the case. Still, we should
6801   // use a more generic type in case we ever do.
6802   SmallVector<Optional<unsigned char>, 32> Bytes;
6803 
6804   static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6805                 "Need at least 8 bit unsigned char");
6806 
6807   bool TargetIsLittleEndian;
6808 
6809 public:
6810   BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6811       : Bytes(Width.getQuantity()),
6812         TargetIsLittleEndian(TargetIsLittleEndian) {}
6813 
6814   LLVM_NODISCARD
6815   bool readObject(CharUnits Offset, CharUnits Width,
6816                   SmallVectorImpl<unsigned char> &Output) const {
6817     for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6818       // If a byte of an integer is uninitialized, then the whole integer is
6819       // uninitialized.
6820       if (!Bytes[I.getQuantity()])
6821         return false;
6822       Output.push_back(*Bytes[I.getQuantity()]);
6823     }
6824     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6825       std::reverse(Output.begin(), Output.end());
6826     return true;
6827   }
6828 
6829   void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6830     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6831       std::reverse(Input.begin(), Input.end());
6832 
6833     size_t Index = 0;
6834     for (unsigned char Byte : Input) {
6835       assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
6836       Bytes[Offset.getQuantity() + Index] = Byte;
6837       ++Index;
6838     }
6839   }
6840 
6841   size_t size() { return Bytes.size(); }
6842 };
6843 
6844 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6845 /// target would represent the value at runtime.
6846 class APValueToBufferConverter {
6847   EvalInfo &Info;
6848   BitCastBuffer Buffer;
6849   const CastExpr *BCE;
6850 
6851   APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6852                            const CastExpr *BCE)
6853       : Info(Info),
6854         Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6855         BCE(BCE) {}
6856 
6857   bool visit(const APValue &Val, QualType Ty) {
6858     return visit(Val, Ty, CharUnits::fromQuantity(0));
6859   }
6860 
6861   // Write out Val with type Ty into Buffer starting at Offset.
6862   bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6863     assert((size_t)Offset.getQuantity() <= Buffer.size());
6864 
6865     // As a special case, nullptr_t has an indeterminate value.
6866     if (Ty->isNullPtrType())
6867       return true;
6868 
6869     // Dig through Src to find the byte at SrcOffset.
6870     switch (Val.getKind()) {
6871     case APValue::Indeterminate:
6872     case APValue::None:
6873       return true;
6874 
6875     case APValue::Int:
6876       return visitInt(Val.getInt(), Ty, Offset);
6877     case APValue::Float:
6878       return visitFloat(Val.getFloat(), Ty, Offset);
6879     case APValue::Array:
6880       return visitArray(Val, Ty, Offset);
6881     case APValue::Struct:
6882       return visitRecord(Val, Ty, Offset);
6883 
6884     case APValue::ComplexInt:
6885     case APValue::ComplexFloat:
6886     case APValue::Vector:
6887     case APValue::FixedPoint:
6888       // FIXME: We should support these.
6889 
6890     case APValue::Union:
6891     case APValue::MemberPointer:
6892     case APValue::AddrLabelDiff: {
6893       Info.FFDiag(BCE->getBeginLoc(),
6894                   diag::note_constexpr_bit_cast_unsupported_type)
6895           << Ty;
6896       return false;
6897     }
6898 
6899     case APValue::LValue:
6900       llvm_unreachable("LValue subobject in bit_cast?");
6901     }
6902     llvm_unreachable("Unhandled APValue::ValueKind");
6903   }
6904 
6905   bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
6906     const RecordDecl *RD = Ty->getAsRecordDecl();
6907     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6908 
6909     // Visit the base classes.
6910     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6911       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6912         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6913         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6914 
6915         if (!visitRecord(Val.getStructBase(I), BS.getType(),
6916                          Layout.getBaseClassOffset(BaseDecl) + Offset))
6917           return false;
6918       }
6919     }
6920 
6921     // Visit the fields.
6922     unsigned FieldIdx = 0;
6923     for (FieldDecl *FD : RD->fields()) {
6924       if (FD->isBitField()) {
6925         Info.FFDiag(BCE->getBeginLoc(),
6926                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6927         return false;
6928       }
6929 
6930       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6931 
6932       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
6933              "only bit-fields can have sub-char alignment");
6934       CharUnits FieldOffset =
6935           Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
6936       QualType FieldTy = FD->getType();
6937       if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
6938         return false;
6939       ++FieldIdx;
6940     }
6941 
6942     return true;
6943   }
6944 
6945   bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
6946     const auto *CAT =
6947         dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
6948     if (!CAT)
6949       return false;
6950 
6951     CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
6952     unsigned NumInitializedElts = Val.getArrayInitializedElts();
6953     unsigned ArraySize = Val.getArraySize();
6954     // First, initialize the initialized elements.
6955     for (unsigned I = 0; I != NumInitializedElts; ++I) {
6956       const APValue &SubObj = Val.getArrayInitializedElt(I);
6957       if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
6958         return false;
6959     }
6960 
6961     // Next, initialize the rest of the array using the filler.
6962     if (Val.hasArrayFiller()) {
6963       const APValue &Filler = Val.getArrayFiller();
6964       for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
6965         if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
6966           return false;
6967       }
6968     }
6969 
6970     return true;
6971   }
6972 
6973   bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
6974     APSInt AdjustedVal = Val;
6975     unsigned Width = AdjustedVal.getBitWidth();
6976     if (Ty->isBooleanType()) {
6977       Width = Info.Ctx.getTypeSize(Ty);
6978       AdjustedVal = AdjustedVal.extend(Width);
6979     }
6980 
6981     SmallVector<unsigned char, 8> Bytes(Width / 8);
6982     llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
6983     Buffer.writeObject(Offset, Bytes);
6984     return true;
6985   }
6986 
6987   bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
6988     APSInt AsInt(Val.bitcastToAPInt());
6989     return visitInt(AsInt, Ty, Offset);
6990   }
6991 
6992 public:
6993   static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
6994                                          const CastExpr *BCE) {
6995     CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
6996     APValueToBufferConverter Converter(Info, DstSize, BCE);
6997     if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
6998       return None;
6999     return Converter.Buffer;
7000   }
7001 };
7002 
7003 /// Write an BitCastBuffer into an APValue.
7004 class BufferToAPValueConverter {
7005   EvalInfo &Info;
7006   const BitCastBuffer &Buffer;
7007   const CastExpr *BCE;
7008 
7009   BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
7010                            const CastExpr *BCE)
7011       : Info(Info), Buffer(Buffer), BCE(BCE) {}
7012 
7013   // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
7014   // with an invalid type, so anything left is a deficiency on our part (FIXME).
7015   // Ideally this will be unreachable.
7016   llvm::NoneType unsupportedType(QualType Ty) {
7017     Info.FFDiag(BCE->getBeginLoc(),
7018                 diag::note_constexpr_bit_cast_unsupported_type)
7019         << Ty;
7020     return None;
7021   }
7022 
7023   llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) {
7024     Info.FFDiag(BCE->getBeginLoc(),
7025                 diag::note_constexpr_bit_cast_unrepresentable_value)
7026         << Ty << toString(Val, /*Radix=*/10);
7027     return None;
7028   }
7029 
7030   Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
7031                           const EnumType *EnumSugar = nullptr) {
7032     if (T->isNullPtrType()) {
7033       uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
7034       return APValue((Expr *)nullptr,
7035                      /*Offset=*/CharUnits::fromQuantity(NullValue),
7036                      APValue::NoLValuePath{}, /*IsNullPtr=*/true);
7037     }
7038 
7039     CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
7040 
7041     // Work around floating point types that contain unused padding bytes. This
7042     // is really just `long double` on x86, which is the only fundamental type
7043     // with padding bytes.
7044     if (T->isRealFloatingType()) {
7045       const llvm::fltSemantics &Semantics =
7046           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7047       unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
7048       assert(NumBits % 8 == 0);
7049       CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
7050       if (NumBytes != SizeOf)
7051         SizeOf = NumBytes;
7052     }
7053 
7054     SmallVector<uint8_t, 8> Bytes;
7055     if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
7056       // If this is std::byte or unsigned char, then its okay to store an
7057       // indeterminate value.
7058       bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
7059       bool IsUChar =
7060           !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
7061                          T->isSpecificBuiltinType(BuiltinType::Char_U));
7062       if (!IsStdByte && !IsUChar) {
7063         QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
7064         Info.FFDiag(BCE->getExprLoc(),
7065                     diag::note_constexpr_bit_cast_indet_dest)
7066             << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
7067         return None;
7068       }
7069 
7070       return APValue::IndeterminateValue();
7071     }
7072 
7073     APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
7074     llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
7075 
7076     if (T->isIntegralOrEnumerationType()) {
7077       Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7078 
7079       unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
7080       if (IntWidth != Val.getBitWidth()) {
7081         APSInt Truncated = Val.trunc(IntWidth);
7082         if (Truncated.extend(Val.getBitWidth()) != Val)
7083           return unrepresentableValue(QualType(T, 0), Val);
7084         Val = Truncated;
7085       }
7086 
7087       return APValue(Val);
7088     }
7089 
7090     if (T->isRealFloatingType()) {
7091       const llvm::fltSemantics &Semantics =
7092           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7093       return APValue(APFloat(Semantics, Val));
7094     }
7095 
7096     return unsupportedType(QualType(T, 0));
7097   }
7098 
7099   Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7100     const RecordDecl *RD = RTy->getAsRecordDecl();
7101     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7102 
7103     unsigned NumBases = 0;
7104     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7105       NumBases = CXXRD->getNumBases();
7106 
7107     APValue ResultVal(APValue::UninitStruct(), NumBases,
7108                       std::distance(RD->field_begin(), RD->field_end()));
7109 
7110     // Visit the base classes.
7111     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7112       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7113         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7114         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7115         if (BaseDecl->isEmpty() ||
7116             Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
7117           continue;
7118 
7119         Optional<APValue> SubObj = visitType(
7120             BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7121         if (!SubObj)
7122           return None;
7123         ResultVal.getStructBase(I) = *SubObj;
7124       }
7125     }
7126 
7127     // Visit the fields.
7128     unsigned FieldIdx = 0;
7129     for (FieldDecl *FD : RD->fields()) {
7130       // FIXME: We don't currently support bit-fields. A lot of the logic for
7131       // this is in CodeGen, so we need to factor it around.
7132       if (FD->isBitField()) {
7133         Info.FFDiag(BCE->getBeginLoc(),
7134                     diag::note_constexpr_bit_cast_unsupported_bitfield);
7135         return None;
7136       }
7137 
7138       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7139       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
7140 
7141       CharUnits FieldOffset =
7142           CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7143           Offset;
7144       QualType FieldTy = FD->getType();
7145       Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7146       if (!SubObj)
7147         return None;
7148       ResultVal.getStructField(FieldIdx) = *SubObj;
7149       ++FieldIdx;
7150     }
7151 
7152     return ResultVal;
7153   }
7154 
7155   Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7156     QualType RepresentationType = Ty->getDecl()->getIntegerType();
7157     assert(!RepresentationType.isNull() &&
7158            "enum forward decl should be caught by Sema");
7159     const auto *AsBuiltin =
7160         RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7161     // Recurse into the underlying type. Treat std::byte transparently as
7162     // unsigned char.
7163     return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7164   }
7165 
7166   Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7167     size_t Size = Ty->getSize().getLimitedValue();
7168     CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7169 
7170     APValue ArrayValue(APValue::UninitArray(), Size, Size);
7171     for (size_t I = 0; I != Size; ++I) {
7172       Optional<APValue> ElementValue =
7173           visitType(Ty->getElementType(), Offset + I * ElementWidth);
7174       if (!ElementValue)
7175         return None;
7176       ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7177     }
7178 
7179     return ArrayValue;
7180   }
7181 
7182   Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7183     return unsupportedType(QualType(Ty, 0));
7184   }
7185 
7186   Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7187     QualType Can = Ty.getCanonicalType();
7188 
7189     switch (Can->getTypeClass()) {
7190 #define TYPE(Class, Base)                                                      \
7191   case Type::Class:                                                            \
7192     return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7193 #define ABSTRACT_TYPE(Class, Base)
7194 #define NON_CANONICAL_TYPE(Class, Base)                                        \
7195   case Type::Class:                                                            \
7196     llvm_unreachable("non-canonical type should be impossible!");
7197 #define DEPENDENT_TYPE(Class, Base)                                            \
7198   case Type::Class:                                                            \
7199     llvm_unreachable(                                                          \
7200         "dependent types aren't supported in the constant evaluator!");
7201 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)                            \
7202   case Type::Class:                                                            \
7203     llvm_unreachable("either dependent or not canonical!");
7204 #include "clang/AST/TypeNodes.inc"
7205     }
7206     llvm_unreachable("Unhandled Type::TypeClass");
7207   }
7208 
7209 public:
7210   // Pull out a full value of type DstType.
7211   static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7212                                    const CastExpr *BCE) {
7213     BufferToAPValueConverter Converter(Info, Buffer, BCE);
7214     return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7215   }
7216 };
7217 
7218 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7219                                                  QualType Ty, EvalInfo *Info,
7220                                                  const ASTContext &Ctx,
7221                                                  bool CheckingDest) {
7222   Ty = Ty.getCanonicalType();
7223 
7224   auto diag = [&](int Reason) {
7225     if (Info)
7226       Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7227           << CheckingDest << (Reason == 4) << Reason;
7228     return false;
7229   };
7230   auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7231     if (Info)
7232       Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7233           << NoteTy << Construct << Ty;
7234     return false;
7235   };
7236 
7237   if (Ty->isUnionType())
7238     return diag(0);
7239   if (Ty->isPointerType())
7240     return diag(1);
7241   if (Ty->isMemberPointerType())
7242     return diag(2);
7243   if (Ty.isVolatileQualified())
7244     return diag(3);
7245 
7246   if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7247     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7248       for (CXXBaseSpecifier &BS : CXXRD->bases())
7249         if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7250                                                   CheckingDest))
7251           return note(1, BS.getType(), BS.getBeginLoc());
7252     }
7253     for (FieldDecl *FD : Record->fields()) {
7254       if (FD->getType()->isReferenceType())
7255         return diag(4);
7256       if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7257                                                 CheckingDest))
7258         return note(0, FD->getType(), FD->getBeginLoc());
7259     }
7260   }
7261 
7262   if (Ty->isArrayType() &&
7263       !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7264                                             Info, Ctx, CheckingDest))
7265     return false;
7266 
7267   return true;
7268 }
7269 
7270 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
7271                                              const ASTContext &Ctx,
7272                                              const CastExpr *BCE) {
7273   bool DestOK = checkBitCastConstexprEligibilityType(
7274       BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
7275   bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
7276                                 BCE->getBeginLoc(),
7277                                 BCE->getSubExpr()->getType(), Info, Ctx, false);
7278   return SourceOK;
7279 }
7280 
7281 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7282                                         APValue &SourceValue,
7283                                         const CastExpr *BCE) {
7284   assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7285          "no host or target supports non 8-bit chars");
7286   assert(SourceValue.isLValue() &&
7287          "LValueToRValueBitcast requires an lvalue operand!");
7288 
7289   if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
7290     return false;
7291 
7292   LValue SourceLValue;
7293   APValue SourceRValue;
7294   SourceLValue.setFrom(Info.Ctx, SourceValue);
7295   if (!handleLValueToRValueConversion(
7296           Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
7297           SourceRValue, /*WantObjectRepresentation=*/true))
7298     return false;
7299 
7300   // Read out SourceValue into a char buffer.
7301   Optional<BitCastBuffer> Buffer =
7302       APValueToBufferConverter::convert(Info, SourceRValue, BCE);
7303   if (!Buffer)
7304     return false;
7305 
7306   // Write out the buffer into a new APValue.
7307   Optional<APValue> MaybeDestValue =
7308       BufferToAPValueConverter::convert(Info, *Buffer, BCE);
7309   if (!MaybeDestValue)
7310     return false;
7311 
7312   DestValue = std::move(*MaybeDestValue);
7313   return true;
7314 }
7315 
7316 template <class Derived>
7317 class ExprEvaluatorBase
7318   : public ConstStmtVisitor<Derived, bool> {
7319 private:
7320   Derived &getDerived() { return static_cast<Derived&>(*this); }
7321   bool DerivedSuccess(const APValue &V, const Expr *E) {
7322     return getDerived().Success(V, E);
7323   }
7324   bool DerivedZeroInitialization(const Expr *E) {
7325     return getDerived().ZeroInitialization(E);
7326   }
7327 
7328   // Check whether a conditional operator with a non-constant condition is a
7329   // potential constant expression. If neither arm is a potential constant
7330   // expression, then the conditional operator is not either.
7331   template<typename ConditionalOperator>
7332   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7333     assert(Info.checkingPotentialConstantExpression());
7334 
7335     // Speculatively evaluate both arms.
7336     SmallVector<PartialDiagnosticAt, 8> Diag;
7337     {
7338       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7339       StmtVisitorTy::Visit(E->getFalseExpr());
7340       if (Diag.empty())
7341         return;
7342     }
7343 
7344     {
7345       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7346       Diag.clear();
7347       StmtVisitorTy::Visit(E->getTrueExpr());
7348       if (Diag.empty())
7349         return;
7350     }
7351 
7352     Error(E, diag::note_constexpr_conditional_never_const);
7353   }
7354 
7355 
7356   template<typename ConditionalOperator>
7357   bool HandleConditionalOperator(const ConditionalOperator *E) {
7358     bool BoolResult;
7359     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7360       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7361         CheckPotentialConstantConditional(E);
7362         return false;
7363       }
7364       if (Info.noteFailure()) {
7365         StmtVisitorTy::Visit(E->getTrueExpr());
7366         StmtVisitorTy::Visit(E->getFalseExpr());
7367       }
7368       return false;
7369     }
7370 
7371     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
7372     return StmtVisitorTy::Visit(EvalExpr);
7373   }
7374 
7375 protected:
7376   EvalInfo &Info;
7377   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
7378   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
7379 
7380   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7381     return Info.CCEDiag(E, D);
7382   }
7383 
7384   bool ZeroInitialization(const Expr *E) { return Error(E); }
7385 
7386 public:
7387   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
7388 
7389   EvalInfo &getEvalInfo() { return Info; }
7390 
7391   /// Report an evaluation error. This should only be called when an error is
7392   /// first discovered. When propagating an error, just return false.
7393   bool Error(const Expr *E, diag::kind D) {
7394     Info.FFDiag(E, D);
7395     return false;
7396   }
7397   bool Error(const Expr *E) {
7398     return Error(E, diag::note_invalid_subexpr_in_const_expr);
7399   }
7400 
7401   bool VisitStmt(const Stmt *) {
7402     llvm_unreachable("Expression evaluator should not be called on stmts");
7403   }
7404   bool VisitExpr(const Expr *E) {
7405     return Error(E);
7406   }
7407 
7408   bool VisitConstantExpr(const ConstantExpr *E) {
7409     if (E->hasAPValueResult())
7410       return DerivedSuccess(E->getAPValueResult(), E);
7411 
7412     return StmtVisitorTy::Visit(E->getSubExpr());
7413   }
7414 
7415   bool VisitParenExpr(const ParenExpr *E)
7416     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7417   bool VisitUnaryExtension(const UnaryOperator *E)
7418     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7419   bool VisitUnaryPlus(const UnaryOperator *E)
7420     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7421   bool VisitChooseExpr(const ChooseExpr *E)
7422     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
7423   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
7424     { return StmtVisitorTy::Visit(E->getResultExpr()); }
7425   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
7426     { return StmtVisitorTy::Visit(E->getReplacement()); }
7427   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7428     TempVersionRAII RAII(*Info.CurrentCall);
7429     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7430     return StmtVisitorTy::Visit(E->getExpr());
7431   }
7432   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7433     TempVersionRAII RAII(*Info.CurrentCall);
7434     // The initializer may not have been parsed yet, or might be erroneous.
7435     if (!E->getExpr())
7436       return Error(E);
7437     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7438     return StmtVisitorTy::Visit(E->getExpr());
7439   }
7440 
7441   bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7442     FullExpressionRAII Scope(Info);
7443     return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
7444   }
7445 
7446   // Temporaries are registered when created, so we don't care about
7447   // CXXBindTemporaryExpr.
7448   bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7449     return StmtVisitorTy::Visit(E->getSubExpr());
7450   }
7451 
7452   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7453     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7454     return static_cast<Derived*>(this)->VisitCastExpr(E);
7455   }
7456   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7457     if (!Info.Ctx.getLangOpts().CPlusPlus20)
7458       CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
7459     return static_cast<Derived*>(this)->VisitCastExpr(E);
7460   }
7461   bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7462     return static_cast<Derived*>(this)->VisitCastExpr(E);
7463   }
7464 
7465   bool VisitBinaryOperator(const BinaryOperator *E) {
7466     switch (E->getOpcode()) {
7467     default:
7468       return Error(E);
7469 
7470     case BO_Comma:
7471       VisitIgnoredValue(E->getLHS());
7472       return StmtVisitorTy::Visit(E->getRHS());
7473 
7474     case BO_PtrMemD:
7475     case BO_PtrMemI: {
7476       LValue Obj;
7477       if (!HandleMemberPointerAccess(Info, E, Obj))
7478         return false;
7479       APValue Result;
7480       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7481         return false;
7482       return DerivedSuccess(Result, E);
7483     }
7484     }
7485   }
7486 
7487   bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
7488     return StmtVisitorTy::Visit(E->getSemanticForm());
7489   }
7490 
7491   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7492     // Evaluate and cache the common expression. We treat it as a temporary,
7493     // even though it's not quite the same thing.
7494     LValue CommonLV;
7495     if (!Evaluate(Info.CurrentCall->createTemporary(
7496                       E->getOpaqueValue(),
7497                       getStorageType(Info.Ctx, E->getOpaqueValue()),
7498                       ScopeKind::FullExpression, CommonLV),
7499                   Info, E->getCommon()))
7500       return false;
7501 
7502     return HandleConditionalOperator(E);
7503   }
7504 
7505   bool VisitConditionalOperator(const ConditionalOperator *E) {
7506     bool IsBcpCall = false;
7507     // If the condition (ignoring parens) is a __builtin_constant_p call,
7508     // the result is a constant expression if it can be folded without
7509     // side-effects. This is an important GNU extension. See GCC PR38377
7510     // for discussion.
7511     if (const CallExpr *CallCE =
7512           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7513       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7514         IsBcpCall = true;
7515 
7516     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7517     // constant expression; we can't check whether it's potentially foldable.
7518     // FIXME: We should instead treat __builtin_constant_p as non-constant if
7519     // it would return 'false' in this mode.
7520     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
7521       return false;
7522 
7523     FoldConstant Fold(Info, IsBcpCall);
7524     if (!HandleConditionalOperator(E)) {
7525       Fold.keepDiagnostics();
7526       return false;
7527     }
7528 
7529     return true;
7530   }
7531 
7532   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7533     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
7534       return DerivedSuccess(*Value, E);
7535 
7536     const Expr *Source = E->getSourceExpr();
7537     if (!Source)
7538       return Error(E);
7539     if (Source == E) {
7540       assert(0 && "OpaqueValueExpr recursively refers to itself");
7541       return Error(E);
7542     }
7543     return StmtVisitorTy::Visit(Source);
7544   }
7545 
7546   bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7547     for (const Expr *SemE : E->semantics()) {
7548       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7549         // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7550         // result expression: there could be two different LValues that would
7551         // refer to the same object in that case, and we can't model that.
7552         if (SemE == E->getResultExpr())
7553           return Error(E);
7554 
7555         // Unique OVEs get evaluated if and when we encounter them when
7556         // emitting the rest of the semantic form, rather than eagerly.
7557         if (OVE->isUnique())
7558           continue;
7559 
7560         LValue LV;
7561         if (!Evaluate(Info.CurrentCall->createTemporary(
7562                           OVE, getStorageType(Info.Ctx, OVE),
7563                           ScopeKind::FullExpression, LV),
7564                       Info, OVE->getSourceExpr()))
7565           return false;
7566       } else if (SemE == E->getResultExpr()) {
7567         if (!StmtVisitorTy::Visit(SemE))
7568           return false;
7569       } else {
7570         if (!EvaluateIgnoredValue(Info, SemE))
7571           return false;
7572       }
7573     }
7574     return true;
7575   }
7576 
7577   bool VisitCallExpr(const CallExpr *E) {
7578     APValue Result;
7579     if (!handleCallExpr(E, Result, nullptr))
7580       return false;
7581     return DerivedSuccess(Result, E);
7582   }
7583 
7584   bool handleCallExpr(const CallExpr *E, APValue &Result,
7585                      const LValue *ResultSlot) {
7586     CallScopeRAII CallScope(Info);
7587 
7588     const Expr *Callee = E->getCallee()->IgnoreParens();
7589     QualType CalleeType = Callee->getType();
7590 
7591     const FunctionDecl *FD = nullptr;
7592     LValue *This = nullptr, ThisVal;
7593     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
7594     bool HasQualifier = false;
7595 
7596     CallRef Call;
7597 
7598     // Extract function decl and 'this' pointer from the callee.
7599     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7600       const CXXMethodDecl *Member = nullptr;
7601       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7602         // Explicit bound member calls, such as x.f() or p->g();
7603         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7604           return false;
7605         Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7606         if (!Member)
7607           return Error(Callee);
7608         This = &ThisVal;
7609         HasQualifier = ME->hasQualifier();
7610       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
7611         // Indirect bound member calls ('.*' or '->*').
7612         const ValueDecl *D =
7613             HandleMemberPointerAccess(Info, BE, ThisVal, false);
7614         if (!D)
7615           return false;
7616         Member = dyn_cast<CXXMethodDecl>(D);
7617         if (!Member)
7618           return Error(Callee);
7619         This = &ThisVal;
7620       } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7621         if (!Info.getLangOpts().CPlusPlus20)
7622           Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7623         return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7624                HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7625       } else
7626         return Error(Callee);
7627       FD = Member;
7628     } else if (CalleeType->isFunctionPointerType()) {
7629       LValue CalleeLV;
7630       if (!EvaluatePointer(Callee, CalleeLV, Info))
7631         return false;
7632 
7633       if (!CalleeLV.getLValueOffset().isZero())
7634         return Error(Callee);
7635       FD = dyn_cast_or_null<FunctionDecl>(
7636           CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
7637       if (!FD)
7638         return Error(Callee);
7639       // Don't call function pointers which have been cast to some other type.
7640       // Per DR (no number yet), the caller and callee can differ in noexcept.
7641       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7642         CalleeType->getPointeeType(), FD->getType())) {
7643         return Error(E);
7644       }
7645 
7646       // For an (overloaded) assignment expression, evaluate the RHS before the
7647       // LHS.
7648       auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
7649       if (OCE && OCE->isAssignmentOp()) {
7650         assert(Args.size() == 2 && "wrong number of arguments in assignment");
7651         Call = Info.CurrentCall->createCall(FD);
7652         if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call,
7653                           Info, FD, /*RightToLeft=*/true))
7654           return false;
7655       }
7656 
7657       // Overloaded operator calls to member functions are represented as normal
7658       // calls with '*this' as the first argument.
7659       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7660       if (MD && !MD->isStatic()) {
7661         // FIXME: When selecting an implicit conversion for an overloaded
7662         // operator delete, we sometimes try to evaluate calls to conversion
7663         // operators without a 'this' parameter!
7664         if (Args.empty())
7665           return Error(E);
7666 
7667         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7668           return false;
7669         This = &ThisVal;
7670 
7671         // If this is syntactically a simple assignment using a trivial
7672         // assignment operator, start the lifetimes of union members as needed,
7673         // per C++20 [class.union]5.
7674         if (Info.getLangOpts().CPlusPlus20 && OCE &&
7675             OCE->getOperator() == OO_Equal && MD->isTrivial() &&
7676             !HandleUnionActiveMemberChange(Info, Args[0], ThisVal))
7677           return false;
7678 
7679         Args = Args.slice(1);
7680       } else if (MD && MD->isLambdaStaticInvoker()) {
7681         // Map the static invoker for the lambda back to the call operator.
7682         // Conveniently, we don't have to slice out the 'this' argument (as is
7683         // being done for the non-static case), since a static member function
7684         // doesn't have an implicit argument passed in.
7685         const CXXRecordDecl *ClosureClass = MD->getParent();
7686         assert(
7687             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7688             "Number of captures must be zero for conversion to function-ptr");
7689 
7690         const CXXMethodDecl *LambdaCallOp =
7691             ClosureClass->getLambdaCallOperator();
7692 
7693         // Set 'FD', the function that will be called below, to the call
7694         // operator.  If the closure object represents a generic lambda, find
7695         // the corresponding specialization of the call operator.
7696 
7697         if (ClosureClass->isGenericLambda()) {
7698           assert(MD->isFunctionTemplateSpecialization() &&
7699                  "A generic lambda's static-invoker function must be a "
7700                  "template specialization");
7701           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7702           FunctionTemplateDecl *CallOpTemplate =
7703               LambdaCallOp->getDescribedFunctionTemplate();
7704           void *InsertPos = nullptr;
7705           FunctionDecl *CorrespondingCallOpSpecialization =
7706               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7707           assert(CorrespondingCallOpSpecialization &&
7708                  "We must always have a function call operator specialization "
7709                  "that corresponds to our static invoker specialization");
7710           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7711         } else
7712           FD = LambdaCallOp;
7713       } else if (FD->isReplaceableGlobalAllocationFunction()) {
7714         if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7715             FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7716           LValue Ptr;
7717           if (!HandleOperatorNewCall(Info, E, Ptr))
7718             return false;
7719           Ptr.moveInto(Result);
7720           return CallScope.destroy();
7721         } else {
7722           return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
7723         }
7724       }
7725     } else
7726       return Error(E);
7727 
7728     // Evaluate the arguments now if we've not already done so.
7729     if (!Call) {
7730       Call = Info.CurrentCall->createCall(FD);
7731       if (!EvaluateArgs(Args, Call, Info, FD))
7732         return false;
7733     }
7734 
7735     SmallVector<QualType, 4> CovariantAdjustmentPath;
7736     if (This) {
7737       auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7738       if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
7739         // Perform virtual dispatch, if necessary.
7740         FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
7741                                    CovariantAdjustmentPath);
7742         if (!FD)
7743           return false;
7744       } else {
7745         // Check that the 'this' pointer points to an object of the right type.
7746         // FIXME: If this is an assignment operator call, we may need to change
7747         // the active union member before we check this.
7748         if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
7749           return false;
7750       }
7751     }
7752 
7753     // Destructor calls are different enough that they have their own codepath.
7754     if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
7755       assert(This && "no 'this' pointer for destructor call");
7756       return HandleDestruction(Info, E, *This,
7757                                Info.Ctx.getRecordType(DD->getParent())) &&
7758              CallScope.destroy();
7759     }
7760 
7761     const FunctionDecl *Definition = nullptr;
7762     Stmt *Body = FD->getBody(Definition);
7763 
7764     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
7765         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call,
7766                             Body, Info, Result, ResultSlot))
7767       return false;
7768 
7769     if (!CovariantAdjustmentPath.empty() &&
7770         !HandleCovariantReturnAdjustment(Info, E, Result,
7771                                          CovariantAdjustmentPath))
7772       return false;
7773 
7774     return CallScope.destroy();
7775   }
7776 
7777   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7778     return StmtVisitorTy::Visit(E->getInitializer());
7779   }
7780   bool VisitInitListExpr(const InitListExpr *E) {
7781     if (E->getNumInits() == 0)
7782       return DerivedZeroInitialization(E);
7783     if (E->getNumInits() == 1)
7784       return StmtVisitorTy::Visit(E->getInit(0));
7785     return Error(E);
7786   }
7787   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
7788     return DerivedZeroInitialization(E);
7789   }
7790   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
7791     return DerivedZeroInitialization(E);
7792   }
7793   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
7794     return DerivedZeroInitialization(E);
7795   }
7796 
7797   /// A member expression where the object is a prvalue is itself a prvalue.
7798   bool VisitMemberExpr(const MemberExpr *E) {
7799     assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
7800            "missing temporary materialization conversion");
7801     assert(!E->isArrow() && "missing call to bound member function?");
7802 
7803     APValue Val;
7804     if (!Evaluate(Val, Info, E->getBase()))
7805       return false;
7806 
7807     QualType BaseTy = E->getBase()->getType();
7808 
7809     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
7810     if (!FD) return Error(E);
7811     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
7812     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7813            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7814 
7815     // Note: there is no lvalue base here. But this case should only ever
7816     // happen in C or in C++98, where we cannot be evaluating a constexpr
7817     // constructor, which is the only case the base matters.
7818     CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
7819     SubobjectDesignator Designator(BaseTy);
7820     Designator.addDeclUnchecked(FD);
7821 
7822     APValue Result;
7823     return extractSubobject(Info, E, Obj, Designator, Result) &&
7824            DerivedSuccess(Result, E);
7825   }
7826 
7827   bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
7828     APValue Val;
7829     if (!Evaluate(Val, Info, E->getBase()))
7830       return false;
7831 
7832     if (Val.isVector()) {
7833       SmallVector<uint32_t, 4> Indices;
7834       E->getEncodedElementAccess(Indices);
7835       if (Indices.size() == 1) {
7836         // Return scalar.
7837         return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
7838       } else {
7839         // Construct new APValue vector.
7840         SmallVector<APValue, 4> Elts;
7841         for (unsigned I = 0; I < Indices.size(); ++I) {
7842           Elts.push_back(Val.getVectorElt(Indices[I]));
7843         }
7844         APValue VecResult(Elts.data(), Indices.size());
7845         return DerivedSuccess(VecResult, E);
7846       }
7847     }
7848 
7849     return false;
7850   }
7851 
7852   bool VisitCastExpr(const CastExpr *E) {
7853     switch (E->getCastKind()) {
7854     default:
7855       break;
7856 
7857     case CK_AtomicToNonAtomic: {
7858       APValue AtomicVal;
7859       // This does not need to be done in place even for class/array types:
7860       // atomic-to-non-atomic conversion implies copying the object
7861       // representation.
7862       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
7863         return false;
7864       return DerivedSuccess(AtomicVal, E);
7865     }
7866 
7867     case CK_NoOp:
7868     case CK_UserDefinedConversion:
7869       return StmtVisitorTy::Visit(E->getSubExpr());
7870 
7871     case CK_LValueToRValue: {
7872       LValue LVal;
7873       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
7874         return false;
7875       APValue RVal;
7876       // Note, we use the subexpression's type in order to retain cv-qualifiers.
7877       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7878                                           LVal, RVal))
7879         return false;
7880       return DerivedSuccess(RVal, E);
7881     }
7882     case CK_LValueToRValueBitCast: {
7883       APValue DestValue, SourceValue;
7884       if (!Evaluate(SourceValue, Info, E->getSubExpr()))
7885         return false;
7886       if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
7887         return false;
7888       return DerivedSuccess(DestValue, E);
7889     }
7890 
7891     case CK_AddressSpaceConversion: {
7892       APValue Value;
7893       if (!Evaluate(Value, Info, E->getSubExpr()))
7894         return false;
7895       return DerivedSuccess(Value, E);
7896     }
7897     }
7898 
7899     return Error(E);
7900   }
7901 
7902   bool VisitUnaryPostInc(const UnaryOperator *UO) {
7903     return VisitUnaryPostIncDec(UO);
7904   }
7905   bool VisitUnaryPostDec(const UnaryOperator *UO) {
7906     return VisitUnaryPostIncDec(UO);
7907   }
7908   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
7909     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7910       return Error(UO);
7911 
7912     LValue LVal;
7913     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
7914       return false;
7915     APValue RVal;
7916     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
7917                       UO->isIncrementOp(), &RVal))
7918       return false;
7919     return DerivedSuccess(RVal, UO);
7920   }
7921 
7922   bool VisitStmtExpr(const StmtExpr *E) {
7923     // We will have checked the full-expressions inside the statement expression
7924     // when they were completed, and don't need to check them again now.
7925     llvm::SaveAndRestore<bool> NotCheckingForUB(
7926         Info.CheckingForUndefinedBehavior, false);
7927 
7928     const CompoundStmt *CS = E->getSubStmt();
7929     if (CS->body_empty())
7930       return true;
7931 
7932     BlockScopeRAII Scope(Info);
7933     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
7934                                            BE = CS->body_end();
7935          /**/; ++BI) {
7936       if (BI + 1 == BE) {
7937         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
7938         if (!FinalExpr) {
7939           Info.FFDiag((*BI)->getBeginLoc(),
7940                       diag::note_constexpr_stmt_expr_unsupported);
7941           return false;
7942         }
7943         return this->Visit(FinalExpr) && Scope.destroy();
7944       }
7945 
7946       APValue ReturnValue;
7947       StmtResult Result = { ReturnValue, nullptr };
7948       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
7949       if (ESR != ESR_Succeeded) {
7950         // FIXME: If the statement-expression terminated due to 'return',
7951         // 'break', or 'continue', it would be nice to propagate that to
7952         // the outer statement evaluation rather than bailing out.
7953         if (ESR != ESR_Failed)
7954           Info.FFDiag((*BI)->getBeginLoc(),
7955                       diag::note_constexpr_stmt_expr_unsupported);
7956         return false;
7957       }
7958     }
7959 
7960     llvm_unreachable("Return from function from the loop above.");
7961   }
7962 
7963   /// Visit a value which is evaluated, but whose value is ignored.
7964   void VisitIgnoredValue(const Expr *E) {
7965     EvaluateIgnoredValue(Info, E);
7966   }
7967 
7968   /// Potentially visit a MemberExpr's base expression.
7969   void VisitIgnoredBaseExpression(const Expr *E) {
7970     // While MSVC doesn't evaluate the base expression, it does diagnose the
7971     // presence of side-effecting behavior.
7972     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
7973       return;
7974     VisitIgnoredValue(E);
7975   }
7976 };
7977 
7978 } // namespace
7979 
7980 //===----------------------------------------------------------------------===//
7981 // Common base class for lvalue and temporary evaluation.
7982 //===----------------------------------------------------------------------===//
7983 namespace {
7984 template<class Derived>
7985 class LValueExprEvaluatorBase
7986   : public ExprEvaluatorBase<Derived> {
7987 protected:
7988   LValue &Result;
7989   bool InvalidBaseOK;
7990   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
7991   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
7992 
7993   bool Success(APValue::LValueBase B) {
7994     Result.set(B);
7995     return true;
7996   }
7997 
7998   bool evaluatePointer(const Expr *E, LValue &Result) {
7999     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
8000   }
8001 
8002 public:
8003   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
8004       : ExprEvaluatorBaseTy(Info), Result(Result),
8005         InvalidBaseOK(InvalidBaseOK) {}
8006 
8007   bool Success(const APValue &V, const Expr *E) {
8008     Result.setFrom(this->Info.Ctx, V);
8009     return true;
8010   }
8011 
8012   bool VisitMemberExpr(const MemberExpr *E) {
8013     // Handle non-static data members.
8014     QualType BaseTy;
8015     bool EvalOK;
8016     if (E->isArrow()) {
8017       EvalOK = evaluatePointer(E->getBase(), Result);
8018       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
8019     } else if (E->getBase()->isPRValue()) {
8020       assert(E->getBase()->getType()->isRecordType());
8021       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
8022       BaseTy = E->getBase()->getType();
8023     } else {
8024       EvalOK = this->Visit(E->getBase());
8025       BaseTy = E->getBase()->getType();
8026     }
8027     if (!EvalOK) {
8028       if (!InvalidBaseOK)
8029         return false;
8030       Result.setInvalid(E);
8031       return true;
8032     }
8033 
8034     const ValueDecl *MD = E->getMemberDecl();
8035     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
8036       assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8037              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8038       (void)BaseTy;
8039       if (!HandleLValueMember(this->Info, E, Result, FD))
8040         return false;
8041     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
8042       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
8043         return false;
8044     } else
8045       return this->Error(E);
8046 
8047     if (MD->getType()->isReferenceType()) {
8048       APValue RefValue;
8049       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
8050                                           RefValue))
8051         return false;
8052       return Success(RefValue, E);
8053     }
8054     return true;
8055   }
8056 
8057   bool VisitBinaryOperator(const BinaryOperator *E) {
8058     switch (E->getOpcode()) {
8059     default:
8060       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8061 
8062     case BO_PtrMemD:
8063     case BO_PtrMemI:
8064       return HandleMemberPointerAccess(this->Info, E, Result);
8065     }
8066   }
8067 
8068   bool VisitCastExpr(const CastExpr *E) {
8069     switch (E->getCastKind()) {
8070     default:
8071       return ExprEvaluatorBaseTy::VisitCastExpr(E);
8072 
8073     case CK_DerivedToBase:
8074     case CK_UncheckedDerivedToBase:
8075       if (!this->Visit(E->getSubExpr()))
8076         return false;
8077 
8078       // Now figure out the necessary offset to add to the base LV to get from
8079       // the derived class to the base class.
8080       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8081                                   Result);
8082     }
8083   }
8084 };
8085 }
8086 
8087 //===----------------------------------------------------------------------===//
8088 // LValue Evaluation
8089 //
8090 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8091 // function designators (in C), decl references to void objects (in C), and
8092 // temporaries (if building with -Wno-address-of-temporary).
8093 //
8094 // LValue evaluation produces values comprising a base expression of one of the
8095 // following types:
8096 // - Declarations
8097 //  * VarDecl
8098 //  * FunctionDecl
8099 // - Literals
8100 //  * CompoundLiteralExpr in C (and in global scope in C++)
8101 //  * StringLiteral
8102 //  * PredefinedExpr
8103 //  * ObjCStringLiteralExpr
8104 //  * ObjCEncodeExpr
8105 //  * AddrLabelExpr
8106 //  * BlockExpr
8107 //  * CallExpr for a MakeStringConstant builtin
8108 // - typeid(T) expressions, as TypeInfoLValues
8109 // - Locals and temporaries
8110 //  * MaterializeTemporaryExpr
8111 //  * Any Expr, with a CallIndex indicating the function in which the temporary
8112 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
8113 //    from the AST (FIXME).
8114 //  * A MaterializeTemporaryExpr that has static storage duration, with no
8115 //    CallIndex, for a lifetime-extended temporary.
8116 //  * The ConstantExpr that is currently being evaluated during evaluation of an
8117 //    immediate invocation.
8118 // plus an offset in bytes.
8119 //===----------------------------------------------------------------------===//
8120 namespace {
8121 class LValueExprEvaluator
8122   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8123 public:
8124   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8125     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8126 
8127   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8128   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8129 
8130   bool VisitDeclRefExpr(const DeclRefExpr *E);
8131   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8132   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8133   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8134   bool VisitMemberExpr(const MemberExpr *E);
8135   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
8136   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8137   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8138   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8139   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8140   bool VisitUnaryDeref(const UnaryOperator *E);
8141   bool VisitUnaryReal(const UnaryOperator *E);
8142   bool VisitUnaryImag(const UnaryOperator *E);
8143   bool VisitUnaryPreInc(const UnaryOperator *UO) {
8144     return VisitUnaryPreIncDec(UO);
8145   }
8146   bool VisitUnaryPreDec(const UnaryOperator *UO) {
8147     return VisitUnaryPreIncDec(UO);
8148   }
8149   bool VisitBinAssign(const BinaryOperator *BO);
8150   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8151 
8152   bool VisitCastExpr(const CastExpr *E) {
8153     switch (E->getCastKind()) {
8154     default:
8155       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8156 
8157     case CK_LValueBitCast:
8158       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8159       if (!Visit(E->getSubExpr()))
8160         return false;
8161       Result.Designator.setInvalid();
8162       return true;
8163 
8164     case CK_BaseToDerived:
8165       if (!Visit(E->getSubExpr()))
8166         return false;
8167       return HandleBaseToDerivedCast(Info, E, Result);
8168 
8169     case CK_Dynamic:
8170       if (!Visit(E->getSubExpr()))
8171         return false;
8172       return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8173     }
8174   }
8175 };
8176 } // end anonymous namespace
8177 
8178 /// Evaluate an expression as an lvalue. This can be legitimately called on
8179 /// expressions which are not glvalues, in three cases:
8180 ///  * function designators in C, and
8181 ///  * "extern void" objects
8182 ///  * @selector() expressions in Objective-C
8183 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
8184                            bool InvalidBaseOK) {
8185   assert(!E->isValueDependent());
8186   assert(E->isGLValue() || E->getType()->isFunctionType() ||
8187          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
8188   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8189 }
8190 
8191 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
8192   const NamedDecl *D = E->getDecl();
8193   if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl,
8194           UnnamedGlobalConstantDecl>(D))
8195     return Success(cast<ValueDecl>(D));
8196   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
8197     return VisitVarDecl(E, VD);
8198   if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
8199     return Visit(BD->getBinding());
8200   return Error(E);
8201 }
8202 
8203 
8204 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
8205 
8206   // If we are within a lambda's call operator, check whether the 'VD' referred
8207   // to within 'E' actually represents a lambda-capture that maps to a
8208   // data-member/field within the closure object, and if so, evaluate to the
8209   // field or what the field refers to.
8210   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
8211       isa<DeclRefExpr>(E) &&
8212       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
8213     // We don't always have a complete capture-map when checking or inferring if
8214     // the function call operator meets the requirements of a constexpr function
8215     // - but we don't need to evaluate the captures to determine constexprness
8216     // (dcl.constexpr C++17).
8217     if (Info.checkingPotentialConstantExpression())
8218       return false;
8219 
8220     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
8221       // Start with 'Result' referring to the complete closure object...
8222       Result = *Info.CurrentCall->This;
8223       // ... then update it to refer to the field of the closure object
8224       // that represents the capture.
8225       if (!HandleLValueMember(Info, E, Result, FD))
8226         return false;
8227       // And if the field is of reference type, update 'Result' to refer to what
8228       // the field refers to.
8229       if (FD->getType()->isReferenceType()) {
8230         APValue RVal;
8231         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
8232                                             RVal))
8233           return false;
8234         Result.setFrom(Info.Ctx, RVal);
8235       }
8236       return true;
8237     }
8238   }
8239 
8240   CallStackFrame *Frame = nullptr;
8241   unsigned Version = 0;
8242   if (VD->hasLocalStorage()) {
8243     // Only if a local variable was declared in the function currently being
8244     // evaluated, do we expect to be able to find its value in the current
8245     // frame. (Otherwise it was likely declared in an enclosing context and
8246     // could either have a valid evaluatable value (for e.g. a constexpr
8247     // variable) or be ill-formed (and trigger an appropriate evaluation
8248     // diagnostic)).
8249     CallStackFrame *CurrFrame = Info.CurrentCall;
8250     if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
8251       // Function parameters are stored in some caller's frame. (Usually the
8252       // immediate caller, but for an inherited constructor they may be more
8253       // distant.)
8254       if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
8255         if (CurrFrame->Arguments) {
8256           VD = CurrFrame->Arguments.getOrigParam(PVD);
8257           Frame =
8258               Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
8259           Version = CurrFrame->Arguments.Version;
8260         }
8261       } else {
8262         Frame = CurrFrame;
8263         Version = CurrFrame->getCurrentTemporaryVersion(VD);
8264       }
8265     }
8266   }
8267 
8268   if (!VD->getType()->isReferenceType()) {
8269     if (Frame) {
8270       Result.set({VD, Frame->Index, Version});
8271       return true;
8272     }
8273     return Success(VD);
8274   }
8275 
8276   if (!Info.getLangOpts().CPlusPlus11) {
8277     Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
8278         << VD << VD->getType();
8279     Info.Note(VD->getLocation(), diag::note_declared_at);
8280   }
8281 
8282   APValue *V;
8283   if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
8284     return false;
8285   if (!V->hasValue()) {
8286     // FIXME: Is it possible for V to be indeterminate here? If so, we should
8287     // adjust the diagnostic to say that.
8288     if (!Info.checkingPotentialConstantExpression())
8289       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
8290     return false;
8291   }
8292   return Success(*V, E);
8293 }
8294 
8295 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
8296     const MaterializeTemporaryExpr *E) {
8297   // Walk through the expression to find the materialized temporary itself.
8298   SmallVector<const Expr *, 2> CommaLHSs;
8299   SmallVector<SubobjectAdjustment, 2> Adjustments;
8300   const Expr *Inner =
8301       E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
8302 
8303   // If we passed any comma operators, evaluate their LHSs.
8304   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
8305     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
8306       return false;
8307 
8308   // A materialized temporary with static storage duration can appear within the
8309   // result of a constant expression evaluation, so we need to preserve its
8310   // value for use outside this evaluation.
8311   APValue *Value;
8312   if (E->getStorageDuration() == SD_Static) {
8313     // FIXME: What about SD_Thread?
8314     Value = E->getOrCreateValue(true);
8315     *Value = APValue();
8316     Result.set(E);
8317   } else {
8318     Value = &Info.CurrentCall->createTemporary(
8319         E, E->getType(),
8320         E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
8321                                                      : ScopeKind::Block,
8322         Result);
8323   }
8324 
8325   QualType Type = Inner->getType();
8326 
8327   // Materialize the temporary itself.
8328   if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
8329     *Value = APValue();
8330     return false;
8331   }
8332 
8333   // Adjust our lvalue to refer to the desired subobject.
8334   for (unsigned I = Adjustments.size(); I != 0; /**/) {
8335     --I;
8336     switch (Adjustments[I].Kind) {
8337     case SubobjectAdjustment::DerivedToBaseAdjustment:
8338       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
8339                                 Type, Result))
8340         return false;
8341       Type = Adjustments[I].DerivedToBase.BasePath->getType();
8342       break;
8343 
8344     case SubobjectAdjustment::FieldAdjustment:
8345       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
8346         return false;
8347       Type = Adjustments[I].Field->getType();
8348       break;
8349 
8350     case SubobjectAdjustment::MemberPointerAdjustment:
8351       if (!HandleMemberPointerAccess(this->Info, Type, Result,
8352                                      Adjustments[I].Ptr.RHS))
8353         return false;
8354       Type = Adjustments[I].Ptr.MPT->getPointeeType();
8355       break;
8356     }
8357   }
8358 
8359   return true;
8360 }
8361 
8362 bool
8363 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8364   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
8365          "lvalue compound literal in c++?");
8366   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
8367   // only see this when folding in C, so there's no standard to follow here.
8368   return Success(E);
8369 }
8370 
8371 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
8372   TypeInfoLValue TypeInfo;
8373 
8374   if (!E->isPotentiallyEvaluated()) {
8375     if (E->isTypeOperand())
8376       TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
8377     else
8378       TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
8379   } else {
8380     if (!Info.Ctx.getLangOpts().CPlusPlus20) {
8381       Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
8382         << E->getExprOperand()->getType()
8383         << E->getExprOperand()->getSourceRange();
8384     }
8385 
8386     if (!Visit(E->getExprOperand()))
8387       return false;
8388 
8389     Optional<DynamicType> DynType =
8390         ComputeDynamicType(Info, E, Result, AK_TypeId);
8391     if (!DynType)
8392       return false;
8393 
8394     TypeInfo =
8395         TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
8396   }
8397 
8398   return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
8399 }
8400 
8401 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
8402   return Success(E->getGuidDecl());
8403 }
8404 
8405 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
8406   // Handle static data members.
8407   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
8408     VisitIgnoredBaseExpression(E->getBase());
8409     return VisitVarDecl(E, VD);
8410   }
8411 
8412   // Handle static member functions.
8413   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
8414     if (MD->isStatic()) {
8415       VisitIgnoredBaseExpression(E->getBase());
8416       return Success(MD);
8417     }
8418   }
8419 
8420   // Handle non-static data members.
8421   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
8422 }
8423 
8424 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
8425   // FIXME: Deal with vectors as array subscript bases.
8426   if (E->getBase()->getType()->isVectorType())
8427     return Error(E);
8428 
8429   APSInt Index;
8430   bool Success = true;
8431 
8432   // C++17's rules require us to evaluate the LHS first, regardless of which
8433   // side is the base.
8434   for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
8435     if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
8436                                 : !EvaluateInteger(SubExpr, Index, Info)) {
8437       if (!Info.noteFailure())
8438         return false;
8439       Success = false;
8440     }
8441   }
8442 
8443   return Success &&
8444          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
8445 }
8446 
8447 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
8448   return evaluatePointer(E->getSubExpr(), Result);
8449 }
8450 
8451 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8452   if (!Visit(E->getSubExpr()))
8453     return false;
8454   // __real is a no-op on scalar lvalues.
8455   if (E->getSubExpr()->getType()->isAnyComplexType())
8456     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
8457   return true;
8458 }
8459 
8460 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8461   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
8462          "lvalue __imag__ on scalar?");
8463   if (!Visit(E->getSubExpr()))
8464     return false;
8465   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
8466   return true;
8467 }
8468 
8469 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
8470   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8471     return Error(UO);
8472 
8473   if (!this->Visit(UO->getSubExpr()))
8474     return false;
8475 
8476   return handleIncDec(
8477       this->Info, UO, Result, UO->getSubExpr()->getType(),
8478       UO->isIncrementOp(), nullptr);
8479 }
8480 
8481 bool LValueExprEvaluator::VisitCompoundAssignOperator(
8482     const CompoundAssignOperator *CAO) {
8483   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8484     return Error(CAO);
8485 
8486   bool Success = true;
8487 
8488   // C++17 onwards require that we evaluate the RHS first.
8489   APValue RHS;
8490   if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
8491     if (!Info.noteFailure())
8492       return false;
8493     Success = false;
8494   }
8495 
8496   // The overall lvalue result is the result of evaluating the LHS.
8497   if (!this->Visit(CAO->getLHS()) || !Success)
8498     return false;
8499 
8500   return handleCompoundAssignment(
8501       this->Info, CAO,
8502       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
8503       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
8504 }
8505 
8506 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
8507   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8508     return Error(E);
8509 
8510   bool Success = true;
8511 
8512   // C++17 onwards require that we evaluate the RHS first.
8513   APValue NewVal;
8514   if (!Evaluate(NewVal, this->Info, E->getRHS())) {
8515     if (!Info.noteFailure())
8516       return false;
8517     Success = false;
8518   }
8519 
8520   if (!this->Visit(E->getLHS()) || !Success)
8521     return false;
8522 
8523   if (Info.getLangOpts().CPlusPlus20 &&
8524       !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
8525     return false;
8526 
8527   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
8528                           NewVal);
8529 }
8530 
8531 //===----------------------------------------------------------------------===//
8532 // Pointer Evaluation
8533 //===----------------------------------------------------------------------===//
8534 
8535 /// Attempts to compute the number of bytes available at the pointer
8536 /// returned by a function with the alloc_size attribute. Returns true if we
8537 /// were successful. Places an unsigned number into `Result`.
8538 ///
8539 /// This expects the given CallExpr to be a call to a function with an
8540 /// alloc_size attribute.
8541 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8542                                             const CallExpr *Call,
8543                                             llvm::APInt &Result) {
8544   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
8545 
8546   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
8547   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
8548   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
8549   if (Call->getNumArgs() <= SizeArgNo)
8550     return false;
8551 
8552   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
8553     Expr::EvalResult ExprResult;
8554     if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
8555       return false;
8556     Into = ExprResult.Val.getInt();
8557     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
8558       return false;
8559     Into = Into.zextOrSelf(BitsInSizeT);
8560     return true;
8561   };
8562 
8563   APSInt SizeOfElem;
8564   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
8565     return false;
8566 
8567   if (!AllocSize->getNumElemsParam().isValid()) {
8568     Result = std::move(SizeOfElem);
8569     return true;
8570   }
8571 
8572   APSInt NumberOfElems;
8573   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
8574   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
8575     return false;
8576 
8577   bool Overflow;
8578   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
8579   if (Overflow)
8580     return false;
8581 
8582   Result = std::move(BytesAvailable);
8583   return true;
8584 }
8585 
8586 /// Convenience function. LVal's base must be a call to an alloc_size
8587 /// function.
8588 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8589                                             const LValue &LVal,
8590                                             llvm::APInt &Result) {
8591   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8592          "Can't get the size of a non alloc_size function");
8593   const auto *Base = LVal.getLValueBase().get<const Expr *>();
8594   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
8595   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
8596 }
8597 
8598 /// Attempts to evaluate the given LValueBase as the result of a call to
8599 /// a function with the alloc_size attribute. If it was possible to do so, this
8600 /// function will return true, make Result's Base point to said function call,
8601 /// and mark Result's Base as invalid.
8602 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
8603                                       LValue &Result) {
8604   if (Base.isNull())
8605     return false;
8606 
8607   // Because we do no form of static analysis, we only support const variables.
8608   //
8609   // Additionally, we can't support parameters, nor can we support static
8610   // variables (in the latter case, use-before-assign isn't UB; in the former,
8611   // we have no clue what they'll be assigned to).
8612   const auto *VD =
8613       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
8614   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
8615     return false;
8616 
8617   const Expr *Init = VD->getAnyInitializer();
8618   if (!Init)
8619     return false;
8620 
8621   const Expr *E = Init->IgnoreParens();
8622   if (!tryUnwrapAllocSizeCall(E))
8623     return false;
8624 
8625   // Store E instead of E unwrapped so that the type of the LValue's base is
8626   // what the user wanted.
8627   Result.setInvalid(E);
8628 
8629   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
8630   Result.addUnsizedArray(Info, E, Pointee);
8631   return true;
8632 }
8633 
8634 namespace {
8635 class PointerExprEvaluator
8636   : public ExprEvaluatorBase<PointerExprEvaluator> {
8637   LValue &Result;
8638   bool InvalidBaseOK;
8639 
8640   bool Success(const Expr *E) {
8641     Result.set(E);
8642     return true;
8643   }
8644 
8645   bool evaluateLValue(const Expr *E, LValue &Result) {
8646     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
8647   }
8648 
8649   bool evaluatePointer(const Expr *E, LValue &Result) {
8650     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
8651   }
8652 
8653   bool visitNonBuiltinCallExpr(const CallExpr *E);
8654 public:
8655 
8656   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
8657       : ExprEvaluatorBaseTy(info), Result(Result),
8658         InvalidBaseOK(InvalidBaseOK) {}
8659 
8660   bool Success(const APValue &V, const Expr *E) {
8661     Result.setFrom(Info.Ctx, V);
8662     return true;
8663   }
8664   bool ZeroInitialization(const Expr *E) {
8665     Result.setNull(Info.Ctx, E->getType());
8666     return true;
8667   }
8668 
8669   bool VisitBinaryOperator(const BinaryOperator *E);
8670   bool VisitCastExpr(const CastExpr* E);
8671   bool VisitUnaryAddrOf(const UnaryOperator *E);
8672   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
8673       { return Success(E); }
8674   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
8675     if (E->isExpressibleAsConstantInitializer())
8676       return Success(E);
8677     if (Info.noteFailure())
8678       EvaluateIgnoredValue(Info, E->getSubExpr());
8679     return Error(E);
8680   }
8681   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
8682       { return Success(E); }
8683   bool VisitCallExpr(const CallExpr *E);
8684   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
8685   bool VisitBlockExpr(const BlockExpr *E) {
8686     if (!E->getBlockDecl()->hasCaptures())
8687       return Success(E);
8688     return Error(E);
8689   }
8690   bool VisitCXXThisExpr(const CXXThisExpr *E) {
8691     // Can't look at 'this' when checking a potential constant expression.
8692     if (Info.checkingPotentialConstantExpression())
8693       return false;
8694     if (!Info.CurrentCall->This) {
8695       if (Info.getLangOpts().CPlusPlus11)
8696         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
8697       else
8698         Info.FFDiag(E);
8699       return false;
8700     }
8701     Result = *Info.CurrentCall->This;
8702     // If we are inside a lambda's call operator, the 'this' expression refers
8703     // to the enclosing '*this' object (either by value or reference) which is
8704     // either copied into the closure object's field that represents the '*this'
8705     // or refers to '*this'.
8706     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
8707       // Ensure we actually have captured 'this'. (an error will have
8708       // been previously reported if not).
8709       if (!Info.CurrentCall->LambdaThisCaptureField)
8710         return false;
8711 
8712       // Update 'Result' to refer to the data member/field of the closure object
8713       // that represents the '*this' capture.
8714       if (!HandleLValueMember(Info, E, Result,
8715                              Info.CurrentCall->LambdaThisCaptureField))
8716         return false;
8717       // If we captured '*this' by reference, replace the field with its referent.
8718       if (Info.CurrentCall->LambdaThisCaptureField->getType()
8719               ->isPointerType()) {
8720         APValue RVal;
8721         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
8722                                             RVal))
8723           return false;
8724 
8725         Result.setFrom(Info.Ctx, RVal);
8726       }
8727     }
8728     return true;
8729   }
8730 
8731   bool VisitCXXNewExpr(const CXXNewExpr *E);
8732 
8733   bool VisitSourceLocExpr(const SourceLocExpr *E) {
8734     assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
8735     APValue LValResult = E->EvaluateInContext(
8736         Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8737     Result.setFrom(Info.Ctx, LValResult);
8738     return true;
8739   }
8740 
8741   bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
8742     std::string ResultStr = E->ComputeName(Info.Ctx);
8743 
8744     QualType CharTy = Info.Ctx.CharTy.withConst();
8745     APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
8746                ResultStr.size() + 1);
8747     QualType ArrayTy = Info.Ctx.getConstantArrayType(CharTy, Size, nullptr,
8748                                                      ArrayType::Normal, 0);
8749 
8750     StringLiteral *SL =
8751         StringLiteral::Create(Info.Ctx, ResultStr, StringLiteral::Ascii,
8752                               /*Pascal*/ false, ArrayTy, E->getLocation());
8753 
8754     evaluateLValue(SL, Result);
8755     Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
8756     return true;
8757   }
8758 
8759   // FIXME: Missing: @protocol, @selector
8760 };
8761 } // end anonymous namespace
8762 
8763 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
8764                             bool InvalidBaseOK) {
8765   assert(!E->isValueDependent());
8766   assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
8767   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8768 }
8769 
8770 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8771   if (E->getOpcode() != BO_Add &&
8772       E->getOpcode() != BO_Sub)
8773     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8774 
8775   const Expr *PExp = E->getLHS();
8776   const Expr *IExp = E->getRHS();
8777   if (IExp->getType()->isPointerType())
8778     std::swap(PExp, IExp);
8779 
8780   bool EvalPtrOK = evaluatePointer(PExp, Result);
8781   if (!EvalPtrOK && !Info.noteFailure())
8782     return false;
8783 
8784   llvm::APSInt Offset;
8785   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
8786     return false;
8787 
8788   if (E->getOpcode() == BO_Sub)
8789     negateAsSigned(Offset);
8790 
8791   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
8792   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
8793 }
8794 
8795 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8796   return evaluateLValue(E->getSubExpr(), Result);
8797 }
8798 
8799 // Is the provided decl 'std::source_location::current'?
8800 static bool IsDeclSourceLocationCurrent(const FunctionDecl *FD) {
8801   if (!FD)
8802     return false;
8803   const IdentifierInfo *FnII = FD->getIdentifier();
8804   if (!FnII || !FnII->isStr("current"))
8805     return false;
8806 
8807   const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
8808   if (!RD)
8809     return false;
8810 
8811   const IdentifierInfo *ClassII = RD->getIdentifier();
8812   return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
8813 }
8814 
8815 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8816   const Expr *SubExpr = E->getSubExpr();
8817 
8818   switch (E->getCastKind()) {
8819   default:
8820     break;
8821   case CK_BitCast:
8822   case CK_CPointerToObjCPointerCast:
8823   case CK_BlockPointerToObjCPointerCast:
8824   case CK_AnyPointerToBlockPointerCast:
8825   case CK_AddressSpaceConversion:
8826     if (!Visit(SubExpr))
8827       return false;
8828     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
8829     // permitted in constant expressions in C++11. Bitcasts from cv void* are
8830     // also static_casts, but we disallow them as a resolution to DR1312.
8831     if (!E->getType()->isVoidPointerType()) {
8832       // In some circumstances, we permit casting from void* to cv1 T*, when the
8833       // actual pointee object is actually a cv2 T.
8834       bool VoidPtrCastMaybeOK =
8835           !Result.InvalidBase && !Result.Designator.Invalid &&
8836           !Result.IsNullPtr &&
8837           Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
8838                                           E->getType()->getPointeeType());
8839       // 1. We'll allow it in std::allocator::allocate, and anything which that
8840       //    calls.
8841       // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
8842       //    <source_location> header. Fixed in GCC 12 and later (2022-04-??).
8843       //    We'll allow it in the body of std::source_location::current.  GCC's
8844       //    implementation had a parameter of type `void*`, and casts from
8845       //    that back to `const __impl*` in its body.
8846       if (VoidPtrCastMaybeOK &&
8847           (Info.getStdAllocatorCaller("allocate") ||
8848            IsDeclSourceLocationCurrent(Info.CurrentCall->Callee))) {
8849         // Permitted.
8850       } else {
8851         Result.Designator.setInvalid();
8852         if (SubExpr->getType()->isVoidPointerType())
8853           CCEDiag(E, diag::note_constexpr_invalid_cast)
8854             << 3 << SubExpr->getType();
8855         else
8856           CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8857       }
8858     }
8859     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
8860       ZeroInitialization(E);
8861     return true;
8862 
8863   case CK_DerivedToBase:
8864   case CK_UncheckedDerivedToBase:
8865     if (!evaluatePointer(E->getSubExpr(), Result))
8866       return false;
8867     if (!Result.Base && Result.Offset.isZero())
8868       return true;
8869 
8870     // Now figure out the necessary offset to add to the base LV to get from
8871     // the derived class to the base class.
8872     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
8873                                   castAs<PointerType>()->getPointeeType(),
8874                                 Result);
8875 
8876   case CK_BaseToDerived:
8877     if (!Visit(E->getSubExpr()))
8878       return false;
8879     if (!Result.Base && Result.Offset.isZero())
8880       return true;
8881     return HandleBaseToDerivedCast(Info, E, Result);
8882 
8883   case CK_Dynamic:
8884     if (!Visit(E->getSubExpr()))
8885       return false;
8886     return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8887 
8888   case CK_NullToPointer:
8889     VisitIgnoredValue(E->getSubExpr());
8890     return ZeroInitialization(E);
8891 
8892   case CK_IntegralToPointer: {
8893     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8894 
8895     APValue Value;
8896     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
8897       break;
8898 
8899     if (Value.isInt()) {
8900       unsigned Size = Info.Ctx.getTypeSize(E->getType());
8901       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
8902       Result.Base = (Expr*)nullptr;
8903       Result.InvalidBase = false;
8904       Result.Offset = CharUnits::fromQuantity(N);
8905       Result.Designator.setInvalid();
8906       Result.IsNullPtr = false;
8907       return true;
8908     } else {
8909       // Cast is of an lvalue, no need to change value.
8910       Result.setFrom(Info.Ctx, Value);
8911       return true;
8912     }
8913   }
8914 
8915   case CK_ArrayToPointerDecay: {
8916     if (SubExpr->isGLValue()) {
8917       if (!evaluateLValue(SubExpr, Result))
8918         return false;
8919     } else {
8920       APValue &Value = Info.CurrentCall->createTemporary(
8921           SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
8922       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
8923         return false;
8924     }
8925     // The result is a pointer to the first element of the array.
8926     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
8927     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
8928       Result.addArray(Info, E, CAT);
8929     else
8930       Result.addUnsizedArray(Info, E, AT->getElementType());
8931     return true;
8932   }
8933 
8934   case CK_FunctionToPointerDecay:
8935     return evaluateLValue(SubExpr, Result);
8936 
8937   case CK_LValueToRValue: {
8938     LValue LVal;
8939     if (!evaluateLValue(E->getSubExpr(), LVal))
8940       return false;
8941 
8942     APValue RVal;
8943     // Note, we use the subexpression's type in order to retain cv-qualifiers.
8944     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8945                                         LVal, RVal))
8946       return InvalidBaseOK &&
8947              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
8948     return Success(RVal, E);
8949   }
8950   }
8951 
8952   return ExprEvaluatorBaseTy::VisitCastExpr(E);
8953 }
8954 
8955 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
8956                                 UnaryExprOrTypeTrait ExprKind) {
8957   // C++ [expr.alignof]p3:
8958   //     When alignof is applied to a reference type, the result is the
8959   //     alignment of the referenced type.
8960   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
8961     T = Ref->getPointeeType();
8962 
8963   if (T.getQualifiers().hasUnaligned())
8964     return CharUnits::One();
8965 
8966   const bool AlignOfReturnsPreferred =
8967       Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
8968 
8969   // __alignof is defined to return the preferred alignment.
8970   // Before 8, clang returned the preferred alignment for alignof and _Alignof
8971   // as well.
8972   if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
8973     return Info.Ctx.toCharUnitsFromBits(
8974       Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
8975   // alignof and _Alignof are defined to return the ABI alignment.
8976   else if (ExprKind == UETT_AlignOf)
8977     return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
8978   else
8979     llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
8980 }
8981 
8982 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
8983                                 UnaryExprOrTypeTrait ExprKind) {
8984   E = E->IgnoreParens();
8985 
8986   // The kinds of expressions that we have special-case logic here for
8987   // should be kept up to date with the special checks for those
8988   // expressions in Sema.
8989 
8990   // alignof decl is always accepted, even if it doesn't make sense: we default
8991   // to 1 in those cases.
8992   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8993     return Info.Ctx.getDeclAlign(DRE->getDecl(),
8994                                  /*RefAsPointee*/true);
8995 
8996   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
8997     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
8998                                  /*RefAsPointee*/true);
8999 
9000   return GetAlignOfType(Info, E->getType(), ExprKind);
9001 }
9002 
9003 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
9004   if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
9005     return Info.Ctx.getDeclAlign(VD);
9006   if (const auto *E = Value.Base.dyn_cast<const Expr *>())
9007     return GetAlignOfExpr(Info, E, UETT_AlignOf);
9008   return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
9009 }
9010 
9011 /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
9012 /// __builtin_is_aligned and __builtin_assume_aligned.
9013 static bool getAlignmentArgument(const Expr *E, QualType ForType,
9014                                  EvalInfo &Info, APSInt &Alignment) {
9015   if (!EvaluateInteger(E, Alignment, Info))
9016     return false;
9017   if (Alignment < 0 || !Alignment.isPowerOf2()) {
9018     Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
9019     return false;
9020   }
9021   unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
9022   APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
9023   if (APSInt::compareValues(Alignment, MaxValue) > 0) {
9024     Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
9025         << MaxValue << ForType << Alignment;
9026     return false;
9027   }
9028   // Ensure both alignment and source value have the same bit width so that we
9029   // don't assert when computing the resulting value.
9030   APSInt ExtAlignment =
9031       APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
9032   assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
9033          "Alignment should not be changed by ext/trunc");
9034   Alignment = ExtAlignment;
9035   assert(Alignment.getBitWidth() == SrcWidth);
9036   return true;
9037 }
9038 
9039 // To be clear: this happily visits unsupported builtins. Better name welcomed.
9040 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
9041   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
9042     return true;
9043 
9044   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
9045     return false;
9046 
9047   Result.setInvalid(E);
9048   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
9049   Result.addUnsizedArray(Info, E, PointeeTy);
9050   return true;
9051 }
9052 
9053 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
9054   if (IsConstantCall(E))
9055     return Success(E);
9056 
9057   if (unsigned BuiltinOp = E->getBuiltinCallee())
9058     return VisitBuiltinCallExpr(E, BuiltinOp);
9059 
9060   return visitNonBuiltinCallExpr(E);
9061 }
9062 
9063 // Determine if T is a character type for which we guarantee that
9064 // sizeof(T) == 1.
9065 static bool isOneByteCharacterType(QualType T) {
9066   return T->isCharType() || T->isChar8Type();
9067 }
9068 
9069 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
9070                                                 unsigned BuiltinOp) {
9071   switch (BuiltinOp) {
9072   case Builtin::BI__builtin_addressof:
9073     return evaluateLValue(E->getArg(0), Result);
9074   case Builtin::BI__builtin_assume_aligned: {
9075     // We need to be very careful here because: if the pointer does not have the
9076     // asserted alignment, then the behavior is undefined, and undefined
9077     // behavior is non-constant.
9078     if (!evaluatePointer(E->getArg(0), Result))
9079       return false;
9080 
9081     LValue OffsetResult(Result);
9082     APSInt Alignment;
9083     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9084                               Alignment))
9085       return false;
9086     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
9087 
9088     if (E->getNumArgs() > 2) {
9089       APSInt Offset;
9090       if (!EvaluateInteger(E->getArg(2), Offset, Info))
9091         return false;
9092 
9093       int64_t AdditionalOffset = -Offset.getZExtValue();
9094       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
9095     }
9096 
9097     // If there is a base object, then it must have the correct alignment.
9098     if (OffsetResult.Base) {
9099       CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
9100 
9101       if (BaseAlignment < Align) {
9102         Result.Designator.setInvalid();
9103         // FIXME: Add support to Diagnostic for long / long long.
9104         CCEDiag(E->getArg(0),
9105                 diag::note_constexpr_baa_insufficient_alignment) << 0
9106           << (unsigned)BaseAlignment.getQuantity()
9107           << (unsigned)Align.getQuantity();
9108         return false;
9109       }
9110     }
9111 
9112     // The offset must also have the correct alignment.
9113     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
9114       Result.Designator.setInvalid();
9115 
9116       (OffsetResult.Base
9117            ? CCEDiag(E->getArg(0),
9118                      diag::note_constexpr_baa_insufficient_alignment) << 1
9119            : CCEDiag(E->getArg(0),
9120                      diag::note_constexpr_baa_value_insufficient_alignment))
9121         << (int)OffsetResult.Offset.getQuantity()
9122         << (unsigned)Align.getQuantity();
9123       return false;
9124     }
9125 
9126     return true;
9127   }
9128   case Builtin::BI__builtin_align_up:
9129   case Builtin::BI__builtin_align_down: {
9130     if (!evaluatePointer(E->getArg(0), Result))
9131       return false;
9132     APSInt Alignment;
9133     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9134                               Alignment))
9135       return false;
9136     CharUnits BaseAlignment = getBaseAlignment(Info, Result);
9137     CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
9138     // For align_up/align_down, we can return the same value if the alignment
9139     // is known to be greater or equal to the requested value.
9140     if (PtrAlign.getQuantity() >= Alignment)
9141       return true;
9142 
9143     // The alignment could be greater than the minimum at run-time, so we cannot
9144     // infer much about the resulting pointer value. One case is possible:
9145     // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
9146     // can infer the correct index if the requested alignment is smaller than
9147     // the base alignment so we can perform the computation on the offset.
9148     if (BaseAlignment.getQuantity() >= Alignment) {
9149       assert(Alignment.getBitWidth() <= 64 &&
9150              "Cannot handle > 64-bit address-space");
9151       uint64_t Alignment64 = Alignment.getZExtValue();
9152       CharUnits NewOffset = CharUnits::fromQuantity(
9153           BuiltinOp == Builtin::BI__builtin_align_down
9154               ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
9155               : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
9156       Result.adjustOffset(NewOffset - Result.Offset);
9157       // TODO: diagnose out-of-bounds values/only allow for arrays?
9158       return true;
9159     }
9160     // Otherwise, we cannot constant-evaluate the result.
9161     Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
9162         << Alignment;
9163     return false;
9164   }
9165   case Builtin::BI__builtin_operator_new:
9166     return HandleOperatorNewCall(Info, E, Result);
9167   case Builtin::BI__builtin_launder:
9168     return evaluatePointer(E->getArg(0), Result);
9169   case Builtin::BIstrchr:
9170   case Builtin::BIwcschr:
9171   case Builtin::BImemchr:
9172   case Builtin::BIwmemchr:
9173     if (Info.getLangOpts().CPlusPlus11)
9174       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9175         << /*isConstexpr*/0 << /*isConstructor*/0
9176         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9177     else
9178       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9179     LLVM_FALLTHROUGH;
9180   case Builtin::BI__builtin_strchr:
9181   case Builtin::BI__builtin_wcschr:
9182   case Builtin::BI__builtin_memchr:
9183   case Builtin::BI__builtin_char_memchr:
9184   case Builtin::BI__builtin_wmemchr: {
9185     if (!Visit(E->getArg(0)))
9186       return false;
9187     APSInt Desired;
9188     if (!EvaluateInteger(E->getArg(1), Desired, Info))
9189       return false;
9190     uint64_t MaxLength = uint64_t(-1);
9191     if (BuiltinOp != Builtin::BIstrchr &&
9192         BuiltinOp != Builtin::BIwcschr &&
9193         BuiltinOp != Builtin::BI__builtin_strchr &&
9194         BuiltinOp != Builtin::BI__builtin_wcschr) {
9195       APSInt N;
9196       if (!EvaluateInteger(E->getArg(2), N, Info))
9197         return false;
9198       MaxLength = N.getExtValue();
9199     }
9200     // We cannot find the value if there are no candidates to match against.
9201     if (MaxLength == 0u)
9202       return ZeroInitialization(E);
9203     if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9204         Result.Designator.Invalid)
9205       return false;
9206     QualType CharTy = Result.Designator.getType(Info.Ctx);
9207     bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
9208                      BuiltinOp == Builtin::BI__builtin_memchr;
9209     assert(IsRawByte ||
9210            Info.Ctx.hasSameUnqualifiedType(
9211                CharTy, E->getArg(0)->getType()->getPointeeType()));
9212     // Pointers to const void may point to objects of incomplete type.
9213     if (IsRawByte && CharTy->isIncompleteType()) {
9214       Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
9215       return false;
9216     }
9217     // Give up on byte-oriented matching against multibyte elements.
9218     // FIXME: We can compare the bytes in the correct order.
9219     if (IsRawByte && !isOneByteCharacterType(CharTy)) {
9220       Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
9221           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
9222           << CharTy;
9223       return false;
9224     }
9225     // Figure out what value we're actually looking for (after converting to
9226     // the corresponding unsigned type if necessary).
9227     uint64_t DesiredVal;
9228     bool StopAtNull = false;
9229     switch (BuiltinOp) {
9230     case Builtin::BIstrchr:
9231     case Builtin::BI__builtin_strchr:
9232       // strchr compares directly to the passed integer, and therefore
9233       // always fails if given an int that is not a char.
9234       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
9235                                                   E->getArg(1)->getType(),
9236                                                   Desired),
9237                                Desired))
9238         return ZeroInitialization(E);
9239       StopAtNull = true;
9240       LLVM_FALLTHROUGH;
9241     case Builtin::BImemchr:
9242     case Builtin::BI__builtin_memchr:
9243     case Builtin::BI__builtin_char_memchr:
9244       // memchr compares by converting both sides to unsigned char. That's also
9245       // correct for strchr if we get this far (to cope with plain char being
9246       // unsigned in the strchr case).
9247       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
9248       break;
9249 
9250     case Builtin::BIwcschr:
9251     case Builtin::BI__builtin_wcschr:
9252       StopAtNull = true;
9253       LLVM_FALLTHROUGH;
9254     case Builtin::BIwmemchr:
9255     case Builtin::BI__builtin_wmemchr:
9256       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
9257       DesiredVal = Desired.getZExtValue();
9258       break;
9259     }
9260 
9261     for (; MaxLength; --MaxLength) {
9262       APValue Char;
9263       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
9264           !Char.isInt())
9265         return false;
9266       if (Char.getInt().getZExtValue() == DesiredVal)
9267         return true;
9268       if (StopAtNull && !Char.getInt())
9269         break;
9270       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
9271         return false;
9272     }
9273     // Not found: return nullptr.
9274     return ZeroInitialization(E);
9275   }
9276 
9277   case Builtin::BImemcpy:
9278   case Builtin::BImemmove:
9279   case Builtin::BIwmemcpy:
9280   case Builtin::BIwmemmove:
9281     if (Info.getLangOpts().CPlusPlus11)
9282       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9283         << /*isConstexpr*/0 << /*isConstructor*/0
9284         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9285     else
9286       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9287     LLVM_FALLTHROUGH;
9288   case Builtin::BI__builtin_memcpy:
9289   case Builtin::BI__builtin_memmove:
9290   case Builtin::BI__builtin_wmemcpy:
9291   case Builtin::BI__builtin_wmemmove: {
9292     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
9293                  BuiltinOp == Builtin::BIwmemmove ||
9294                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
9295                  BuiltinOp == Builtin::BI__builtin_wmemmove;
9296     bool Move = BuiltinOp == Builtin::BImemmove ||
9297                 BuiltinOp == Builtin::BIwmemmove ||
9298                 BuiltinOp == Builtin::BI__builtin_memmove ||
9299                 BuiltinOp == Builtin::BI__builtin_wmemmove;
9300 
9301     // The result of mem* is the first argument.
9302     if (!Visit(E->getArg(0)))
9303       return false;
9304     LValue Dest = Result;
9305 
9306     LValue Src;
9307     if (!EvaluatePointer(E->getArg(1), Src, Info))
9308       return false;
9309 
9310     APSInt N;
9311     if (!EvaluateInteger(E->getArg(2), N, Info))
9312       return false;
9313     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
9314 
9315     // If the size is zero, we treat this as always being a valid no-op.
9316     // (Even if one of the src and dest pointers is null.)
9317     if (!N)
9318       return true;
9319 
9320     // Otherwise, if either of the operands is null, we can't proceed. Don't
9321     // try to determine the type of the copied objects, because there aren't
9322     // any.
9323     if (!Src.Base || !Dest.Base) {
9324       APValue Val;
9325       (!Src.Base ? Src : Dest).moveInto(Val);
9326       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
9327           << Move << WChar << !!Src.Base
9328           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
9329       return false;
9330     }
9331     if (Src.Designator.Invalid || Dest.Designator.Invalid)
9332       return false;
9333 
9334     // We require that Src and Dest are both pointers to arrays of
9335     // trivially-copyable type. (For the wide version, the designator will be
9336     // invalid if the designated object is not a wchar_t.)
9337     QualType T = Dest.Designator.getType(Info.Ctx);
9338     QualType SrcT = Src.Designator.getType(Info.Ctx);
9339     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
9340       // FIXME: Consider using our bit_cast implementation to support this.
9341       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
9342       return false;
9343     }
9344     if (T->isIncompleteType()) {
9345       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
9346       return false;
9347     }
9348     if (!T.isTriviallyCopyableType(Info.Ctx)) {
9349       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
9350       return false;
9351     }
9352 
9353     // Figure out how many T's we're copying.
9354     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
9355     if (!WChar) {
9356       uint64_t Remainder;
9357       llvm::APInt OrigN = N;
9358       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
9359       if (Remainder) {
9360         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9361             << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
9362             << (unsigned)TSize;
9363         return false;
9364       }
9365     }
9366 
9367     // Check that the copying will remain within the arrays, just so that we
9368     // can give a more meaningful diagnostic. This implicitly also checks that
9369     // N fits into 64 bits.
9370     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
9371     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
9372     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
9373       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9374           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
9375           << toString(N, 10, /*Signed*/false);
9376       return false;
9377     }
9378     uint64_t NElems = N.getZExtValue();
9379     uint64_t NBytes = NElems * TSize;
9380 
9381     // Check for overlap.
9382     int Direction = 1;
9383     if (HasSameBase(Src, Dest)) {
9384       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
9385       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
9386       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
9387         // Dest is inside the source region.
9388         if (!Move) {
9389           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9390           return false;
9391         }
9392         // For memmove and friends, copy backwards.
9393         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
9394             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
9395           return false;
9396         Direction = -1;
9397       } else if (!Move && SrcOffset >= DestOffset &&
9398                  SrcOffset - DestOffset < NBytes) {
9399         // Src is inside the destination region for memcpy: invalid.
9400         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9401         return false;
9402       }
9403     }
9404 
9405     while (true) {
9406       APValue Val;
9407       // FIXME: Set WantObjectRepresentation to true if we're copying a
9408       // char-like type?
9409       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
9410           !handleAssignment(Info, E, Dest, T, Val))
9411         return false;
9412       // Do not iterate past the last element; if we're copying backwards, that
9413       // might take us off the start of the array.
9414       if (--NElems == 0)
9415         return true;
9416       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
9417           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
9418         return false;
9419     }
9420   }
9421 
9422   default:
9423     break;
9424   }
9425 
9426   return visitNonBuiltinCallExpr(E);
9427 }
9428 
9429 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9430                                      APValue &Result, const InitListExpr *ILE,
9431                                      QualType AllocType);
9432 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
9433                                           APValue &Result,
9434                                           const CXXConstructExpr *CCE,
9435                                           QualType AllocType);
9436 
9437 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
9438   if (!Info.getLangOpts().CPlusPlus20)
9439     Info.CCEDiag(E, diag::note_constexpr_new);
9440 
9441   // We cannot speculatively evaluate a delete expression.
9442   if (Info.SpeculativeEvaluationDepth)
9443     return false;
9444 
9445   FunctionDecl *OperatorNew = E->getOperatorNew();
9446 
9447   bool IsNothrow = false;
9448   bool IsPlacement = false;
9449   if (OperatorNew->isReservedGlobalPlacementOperator() &&
9450       Info.CurrentCall->isStdFunction() && !E->isArray()) {
9451     // FIXME Support array placement new.
9452     assert(E->getNumPlacementArgs() == 1);
9453     if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
9454       return false;
9455     if (Result.Designator.Invalid)
9456       return false;
9457     IsPlacement = true;
9458   } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
9459     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
9460         << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
9461     return false;
9462   } else if (E->getNumPlacementArgs()) {
9463     // The only new-placement list we support is of the form (std::nothrow).
9464     //
9465     // FIXME: There is no restriction on this, but it's not clear that any
9466     // other form makes any sense. We get here for cases such as:
9467     //
9468     //   new (std::align_val_t{N}) X(int)
9469     //
9470     // (which should presumably be valid only if N is a multiple of
9471     // alignof(int), and in any case can't be deallocated unless N is
9472     // alignof(X) and X has new-extended alignment).
9473     if (E->getNumPlacementArgs() != 1 ||
9474         !E->getPlacementArg(0)->getType()->isNothrowT())
9475       return Error(E, diag::note_constexpr_new_placement);
9476 
9477     LValue Nothrow;
9478     if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
9479       return false;
9480     IsNothrow = true;
9481   }
9482 
9483   const Expr *Init = E->getInitializer();
9484   const InitListExpr *ResizedArrayILE = nullptr;
9485   const CXXConstructExpr *ResizedArrayCCE = nullptr;
9486   bool ValueInit = false;
9487 
9488   QualType AllocType = E->getAllocatedType();
9489   if (Optional<const Expr *> ArraySize = E->getArraySize()) {
9490     const Expr *Stripped = *ArraySize;
9491     for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
9492          Stripped = ICE->getSubExpr())
9493       if (ICE->getCastKind() != CK_NoOp &&
9494           ICE->getCastKind() != CK_IntegralCast)
9495         break;
9496 
9497     llvm::APSInt ArrayBound;
9498     if (!EvaluateInteger(Stripped, ArrayBound, Info))
9499       return false;
9500 
9501     // C++ [expr.new]p9:
9502     //   The expression is erroneous if:
9503     //   -- [...] its value before converting to size_t [or] applying the
9504     //      second standard conversion sequence is less than zero
9505     if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
9506       if (IsNothrow)
9507         return ZeroInitialization(E);
9508 
9509       Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
9510           << ArrayBound << (*ArraySize)->getSourceRange();
9511       return false;
9512     }
9513 
9514     //   -- its value is such that the size of the allocated object would
9515     //      exceed the implementation-defined limit
9516     if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
9517                                                 ArrayBound) >
9518         ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
9519       if (IsNothrow)
9520         return ZeroInitialization(E);
9521 
9522       Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
9523         << ArrayBound << (*ArraySize)->getSourceRange();
9524       return false;
9525     }
9526 
9527     //   -- the new-initializer is a braced-init-list and the number of
9528     //      array elements for which initializers are provided [...]
9529     //      exceeds the number of elements to initialize
9530     if (!Init) {
9531       // No initialization is performed.
9532     } else if (isa<CXXScalarValueInitExpr>(Init) ||
9533                isa<ImplicitValueInitExpr>(Init)) {
9534       ValueInit = true;
9535     } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
9536       ResizedArrayCCE = CCE;
9537     } else {
9538       auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
9539       assert(CAT && "unexpected type for array initializer");
9540 
9541       unsigned Bits =
9542           std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
9543       llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits);
9544       llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits);
9545       if (InitBound.ugt(AllocBound)) {
9546         if (IsNothrow)
9547           return ZeroInitialization(E);
9548 
9549         Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
9550             << toString(AllocBound, 10, /*Signed=*/false)
9551             << toString(InitBound, 10, /*Signed=*/false)
9552             << (*ArraySize)->getSourceRange();
9553         return false;
9554       }
9555 
9556       // If the sizes differ, we must have an initializer list, and we need
9557       // special handling for this case when we initialize.
9558       if (InitBound != AllocBound)
9559         ResizedArrayILE = cast<InitListExpr>(Init);
9560     }
9561 
9562     AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
9563                                               ArrayType::Normal, 0);
9564   } else {
9565     assert(!AllocType->isArrayType() &&
9566            "array allocation with non-array new");
9567   }
9568 
9569   APValue *Val;
9570   if (IsPlacement) {
9571     AccessKinds AK = AK_Construct;
9572     struct FindObjectHandler {
9573       EvalInfo &Info;
9574       const Expr *E;
9575       QualType AllocType;
9576       const AccessKinds AccessKind;
9577       APValue *Value;
9578 
9579       typedef bool result_type;
9580       bool failed() { return false; }
9581       bool found(APValue &Subobj, QualType SubobjType) {
9582         // FIXME: Reject the cases where [basic.life]p8 would not permit the
9583         // old name of the object to be used to name the new object.
9584         if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
9585           Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
9586             SubobjType << AllocType;
9587           return false;
9588         }
9589         Value = &Subobj;
9590         return true;
9591       }
9592       bool found(APSInt &Value, QualType SubobjType) {
9593         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9594         return false;
9595       }
9596       bool found(APFloat &Value, QualType SubobjType) {
9597         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9598         return false;
9599       }
9600     } Handler = {Info, E, AllocType, AK, nullptr};
9601 
9602     CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
9603     if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
9604       return false;
9605 
9606     Val = Handler.Value;
9607 
9608     // [basic.life]p1:
9609     //   The lifetime of an object o of type T ends when [...] the storage
9610     //   which the object occupies is [...] reused by an object that is not
9611     //   nested within o (6.6.2).
9612     *Val = APValue();
9613   } else {
9614     // Perform the allocation and obtain a pointer to the resulting object.
9615     Val = Info.createHeapAlloc(E, AllocType, Result);
9616     if (!Val)
9617       return false;
9618   }
9619 
9620   if (ValueInit) {
9621     ImplicitValueInitExpr VIE(AllocType);
9622     if (!EvaluateInPlace(*Val, Info, Result, &VIE))
9623       return false;
9624   } else if (ResizedArrayILE) {
9625     if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
9626                                   AllocType))
9627       return false;
9628   } else if (ResizedArrayCCE) {
9629     if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
9630                                        AllocType))
9631       return false;
9632   } else if (Init) {
9633     if (!EvaluateInPlace(*Val, Info, Result, Init))
9634       return false;
9635   } else if (!getDefaultInitValue(AllocType, *Val)) {
9636     return false;
9637   }
9638 
9639   // Array new returns a pointer to the first element, not a pointer to the
9640   // array.
9641   if (auto *AT = AllocType->getAsArrayTypeUnsafe())
9642     Result.addArray(Info, E, cast<ConstantArrayType>(AT));
9643 
9644   return true;
9645 }
9646 //===----------------------------------------------------------------------===//
9647 // Member Pointer Evaluation
9648 //===----------------------------------------------------------------------===//
9649 
9650 namespace {
9651 class MemberPointerExprEvaluator
9652   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
9653   MemberPtr &Result;
9654 
9655   bool Success(const ValueDecl *D) {
9656     Result = MemberPtr(D);
9657     return true;
9658   }
9659 public:
9660 
9661   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
9662     : ExprEvaluatorBaseTy(Info), Result(Result) {}
9663 
9664   bool Success(const APValue &V, const Expr *E) {
9665     Result.setFrom(V);
9666     return true;
9667   }
9668   bool ZeroInitialization(const Expr *E) {
9669     return Success((const ValueDecl*)nullptr);
9670   }
9671 
9672   bool VisitCastExpr(const CastExpr *E);
9673   bool VisitUnaryAddrOf(const UnaryOperator *E);
9674 };
9675 } // end anonymous namespace
9676 
9677 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
9678                                   EvalInfo &Info) {
9679   assert(!E->isValueDependent());
9680   assert(E->isPRValue() && E->getType()->isMemberPointerType());
9681   return MemberPointerExprEvaluator(Info, Result).Visit(E);
9682 }
9683 
9684 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9685   switch (E->getCastKind()) {
9686   default:
9687     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9688 
9689   case CK_NullToMemberPointer:
9690     VisitIgnoredValue(E->getSubExpr());
9691     return ZeroInitialization(E);
9692 
9693   case CK_BaseToDerivedMemberPointer: {
9694     if (!Visit(E->getSubExpr()))
9695       return false;
9696     if (E->path_empty())
9697       return true;
9698     // Base-to-derived member pointer casts store the path in derived-to-base
9699     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
9700     // the wrong end of the derived->base arc, so stagger the path by one class.
9701     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
9702     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
9703          PathI != PathE; ++PathI) {
9704       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9705       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
9706       if (!Result.castToDerived(Derived))
9707         return Error(E);
9708     }
9709     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
9710     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
9711       return Error(E);
9712     return true;
9713   }
9714 
9715   case CK_DerivedToBaseMemberPointer:
9716     if (!Visit(E->getSubExpr()))
9717       return false;
9718     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9719          PathE = E->path_end(); PathI != PathE; ++PathI) {
9720       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9721       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9722       if (!Result.castToBase(Base))
9723         return Error(E);
9724     }
9725     return true;
9726   }
9727 }
9728 
9729 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9730   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
9731   // member can be formed.
9732   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
9733 }
9734 
9735 //===----------------------------------------------------------------------===//
9736 // Record Evaluation
9737 //===----------------------------------------------------------------------===//
9738 
9739 namespace {
9740   class RecordExprEvaluator
9741   : public ExprEvaluatorBase<RecordExprEvaluator> {
9742     const LValue &This;
9743     APValue &Result;
9744   public:
9745 
9746     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
9747       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
9748 
9749     bool Success(const APValue &V, const Expr *E) {
9750       Result = V;
9751       return true;
9752     }
9753     bool ZeroInitialization(const Expr *E) {
9754       return ZeroInitialization(E, E->getType());
9755     }
9756     bool ZeroInitialization(const Expr *E, QualType T);
9757 
9758     bool VisitCallExpr(const CallExpr *E) {
9759       return handleCallExpr(E, Result, &This);
9760     }
9761     bool VisitCastExpr(const CastExpr *E);
9762     bool VisitInitListExpr(const InitListExpr *E);
9763     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9764       return VisitCXXConstructExpr(E, E->getType());
9765     }
9766     bool VisitLambdaExpr(const LambdaExpr *E);
9767     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
9768     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
9769     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
9770     bool VisitBinCmp(const BinaryOperator *E);
9771   };
9772 }
9773 
9774 /// Perform zero-initialization on an object of non-union class type.
9775 /// C++11 [dcl.init]p5:
9776 ///  To zero-initialize an object or reference of type T means:
9777 ///    [...]
9778 ///    -- if T is a (possibly cv-qualified) non-union class type,
9779 ///       each non-static data member and each base-class subobject is
9780 ///       zero-initialized
9781 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
9782                                           const RecordDecl *RD,
9783                                           const LValue &This, APValue &Result) {
9784   assert(!RD->isUnion() && "Expected non-union class type");
9785   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
9786   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
9787                    std::distance(RD->field_begin(), RD->field_end()));
9788 
9789   if (RD->isInvalidDecl()) return false;
9790   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9791 
9792   if (CD) {
9793     unsigned Index = 0;
9794     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
9795            End = CD->bases_end(); I != End; ++I, ++Index) {
9796       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
9797       LValue Subobject = This;
9798       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
9799         return false;
9800       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
9801                                          Result.getStructBase(Index)))
9802         return false;
9803     }
9804   }
9805 
9806   for (const auto *I : RD->fields()) {
9807     // -- if T is a reference type, no initialization is performed.
9808     if (I->isUnnamedBitfield() || I->getType()->isReferenceType())
9809       continue;
9810 
9811     LValue Subobject = This;
9812     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
9813       return false;
9814 
9815     ImplicitValueInitExpr VIE(I->getType());
9816     if (!EvaluateInPlace(
9817           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
9818       return false;
9819   }
9820 
9821   return true;
9822 }
9823 
9824 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
9825   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
9826   if (RD->isInvalidDecl()) return false;
9827   if (RD->isUnion()) {
9828     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
9829     // object's first non-static named data member is zero-initialized
9830     RecordDecl::field_iterator I = RD->field_begin();
9831     while (I != RD->field_end() && (*I)->isUnnamedBitfield())
9832       ++I;
9833     if (I == RD->field_end()) {
9834       Result = APValue((const FieldDecl*)nullptr);
9835       return true;
9836     }
9837 
9838     LValue Subobject = This;
9839     if (!HandleLValueMember(Info, E, Subobject, *I))
9840       return false;
9841     Result = APValue(*I);
9842     ImplicitValueInitExpr VIE(I->getType());
9843     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
9844   }
9845 
9846   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
9847     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
9848     return false;
9849   }
9850 
9851   return HandleClassZeroInitialization(Info, E, RD, This, Result);
9852 }
9853 
9854 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
9855   switch (E->getCastKind()) {
9856   default:
9857     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9858 
9859   case CK_ConstructorConversion:
9860     return Visit(E->getSubExpr());
9861 
9862   case CK_DerivedToBase:
9863   case CK_UncheckedDerivedToBase: {
9864     APValue DerivedObject;
9865     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
9866       return false;
9867     if (!DerivedObject.isStruct())
9868       return Error(E->getSubExpr());
9869 
9870     // Derived-to-base rvalue conversion: just slice off the derived part.
9871     APValue *Value = &DerivedObject;
9872     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
9873     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9874          PathE = E->path_end(); PathI != PathE; ++PathI) {
9875       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
9876       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9877       Value = &Value->getStructBase(getBaseIndex(RD, Base));
9878       RD = Base;
9879     }
9880     Result = *Value;
9881     return true;
9882   }
9883   }
9884 }
9885 
9886 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9887   if (E->isTransparent())
9888     return Visit(E->getInit(0));
9889 
9890   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
9891   if (RD->isInvalidDecl()) return false;
9892   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9893   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
9894 
9895   EvalInfo::EvaluatingConstructorRAII EvalObj(
9896       Info,
9897       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
9898       CXXRD && CXXRD->getNumBases());
9899 
9900   if (RD->isUnion()) {
9901     const FieldDecl *Field = E->getInitializedFieldInUnion();
9902     Result = APValue(Field);
9903     if (!Field)
9904       return true;
9905 
9906     // If the initializer list for a union does not contain any elements, the
9907     // first element of the union is value-initialized.
9908     // FIXME: The element should be initialized from an initializer list.
9909     //        Is this difference ever observable for initializer lists which
9910     //        we don't build?
9911     ImplicitValueInitExpr VIE(Field->getType());
9912     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
9913 
9914     LValue Subobject = This;
9915     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
9916       return false;
9917 
9918     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9919     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9920                                   isa<CXXDefaultInitExpr>(InitExpr));
9921 
9922     if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
9923       if (Field->isBitField())
9924         return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
9925                                      Field);
9926       return true;
9927     }
9928 
9929     return false;
9930   }
9931 
9932   if (!Result.hasValue())
9933     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
9934                      std::distance(RD->field_begin(), RD->field_end()));
9935   unsigned ElementNo = 0;
9936   bool Success = true;
9937 
9938   // Initialize base classes.
9939   if (CXXRD && CXXRD->getNumBases()) {
9940     for (const auto &Base : CXXRD->bases()) {
9941       assert(ElementNo < E->getNumInits() && "missing init for base class");
9942       const Expr *Init = E->getInit(ElementNo);
9943 
9944       LValue Subobject = This;
9945       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
9946         return false;
9947 
9948       APValue &FieldVal = Result.getStructBase(ElementNo);
9949       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
9950         if (!Info.noteFailure())
9951           return false;
9952         Success = false;
9953       }
9954       ++ElementNo;
9955     }
9956 
9957     EvalObj.finishedConstructingBases();
9958   }
9959 
9960   // Initialize members.
9961   for (const auto *Field : RD->fields()) {
9962     // Anonymous bit-fields are not considered members of the class for
9963     // purposes of aggregate initialization.
9964     if (Field->isUnnamedBitfield())
9965       continue;
9966 
9967     LValue Subobject = This;
9968 
9969     bool HaveInit = ElementNo < E->getNumInits();
9970 
9971     // FIXME: Diagnostics here should point to the end of the initializer
9972     // list, not the start.
9973     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
9974                             Subobject, Field, &Layout))
9975       return false;
9976 
9977     // Perform an implicit value-initialization for members beyond the end of
9978     // the initializer list.
9979     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
9980     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
9981 
9982     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9983     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9984                                   isa<CXXDefaultInitExpr>(Init));
9985 
9986     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9987     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
9988         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
9989                                                        FieldVal, Field))) {
9990       if (!Info.noteFailure())
9991         return false;
9992       Success = false;
9993     }
9994   }
9995 
9996   EvalObj.finishedConstructingFields();
9997 
9998   return Success;
9999 }
10000 
10001 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10002                                                 QualType T) {
10003   // Note that E's type is not necessarily the type of our class here; we might
10004   // be initializing an array element instead.
10005   const CXXConstructorDecl *FD = E->getConstructor();
10006   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
10007 
10008   bool ZeroInit = E->requiresZeroInitialization();
10009   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
10010     // If we've already performed zero-initialization, we're already done.
10011     if (Result.hasValue())
10012       return true;
10013 
10014     if (ZeroInit)
10015       return ZeroInitialization(E, T);
10016 
10017     return getDefaultInitValue(T, Result);
10018   }
10019 
10020   const FunctionDecl *Definition = nullptr;
10021   auto Body = FD->getBody(Definition);
10022 
10023   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10024     return false;
10025 
10026   // Avoid materializing a temporary for an elidable copy/move constructor.
10027   if (E->isElidable() && !ZeroInit) {
10028     // FIXME: This only handles the simplest case, where the source object
10029     //        is passed directly as the first argument to the constructor.
10030     //        This should also handle stepping though implicit casts and
10031     //        and conversion sequences which involve two steps, with a
10032     //        conversion operator followed by a converting constructor.
10033     const Expr *SrcObj = E->getArg(0);
10034     assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
10035     assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
10036     if (const MaterializeTemporaryExpr *ME =
10037             dyn_cast<MaterializeTemporaryExpr>(SrcObj))
10038       return Visit(ME->getSubExpr());
10039   }
10040 
10041   if (ZeroInit && !ZeroInitialization(E, T))
10042     return false;
10043 
10044   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
10045   return HandleConstructorCall(E, This, Args,
10046                                cast<CXXConstructorDecl>(Definition), Info,
10047                                Result);
10048 }
10049 
10050 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
10051     const CXXInheritedCtorInitExpr *E) {
10052   if (!Info.CurrentCall) {
10053     assert(Info.checkingPotentialConstantExpression());
10054     return false;
10055   }
10056 
10057   const CXXConstructorDecl *FD = E->getConstructor();
10058   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
10059     return false;
10060 
10061   const FunctionDecl *Definition = nullptr;
10062   auto Body = FD->getBody(Definition);
10063 
10064   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10065     return false;
10066 
10067   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
10068                                cast<CXXConstructorDecl>(Definition), Info,
10069                                Result);
10070 }
10071 
10072 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
10073     const CXXStdInitializerListExpr *E) {
10074   const ConstantArrayType *ArrayType =
10075       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
10076 
10077   LValue Array;
10078   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
10079     return false;
10080 
10081   // Get a pointer to the first element of the array.
10082   Array.addArray(Info, E, ArrayType);
10083 
10084   auto InvalidType = [&] {
10085     Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
10086       << E->getType();
10087     return false;
10088   };
10089 
10090   // FIXME: Perform the checks on the field types in SemaInit.
10091   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
10092   RecordDecl::field_iterator Field = Record->field_begin();
10093   if (Field == Record->field_end())
10094     return InvalidType();
10095 
10096   // Start pointer.
10097   if (!Field->getType()->isPointerType() ||
10098       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10099                             ArrayType->getElementType()))
10100     return InvalidType();
10101 
10102   // FIXME: What if the initializer_list type has base classes, etc?
10103   Result = APValue(APValue::UninitStruct(), 0, 2);
10104   Array.moveInto(Result.getStructField(0));
10105 
10106   if (++Field == Record->field_end())
10107     return InvalidType();
10108 
10109   if (Field->getType()->isPointerType() &&
10110       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10111                            ArrayType->getElementType())) {
10112     // End pointer.
10113     if (!HandleLValueArrayAdjustment(Info, E, Array,
10114                                      ArrayType->getElementType(),
10115                                      ArrayType->getSize().getZExtValue()))
10116       return false;
10117     Array.moveInto(Result.getStructField(1));
10118   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
10119     // Length.
10120     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
10121   else
10122     return InvalidType();
10123 
10124   if (++Field != Record->field_end())
10125     return InvalidType();
10126 
10127   return true;
10128 }
10129 
10130 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
10131   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
10132   if (ClosureClass->isInvalidDecl())
10133     return false;
10134 
10135   const size_t NumFields =
10136       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
10137 
10138   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
10139                                             E->capture_init_end()) &&
10140          "The number of lambda capture initializers should equal the number of "
10141          "fields within the closure type");
10142 
10143   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
10144   // Iterate through all the lambda's closure object's fields and initialize
10145   // them.
10146   auto *CaptureInitIt = E->capture_init_begin();
10147   bool Success = true;
10148   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
10149   for (const auto *Field : ClosureClass->fields()) {
10150     assert(CaptureInitIt != E->capture_init_end());
10151     // Get the initializer for this field
10152     Expr *const CurFieldInit = *CaptureInitIt++;
10153 
10154     // If there is no initializer, either this is a VLA or an error has
10155     // occurred.
10156     if (!CurFieldInit)
10157       return Error(E);
10158 
10159     LValue Subobject = This;
10160 
10161     if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
10162       return false;
10163 
10164     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10165     if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
10166       if (!Info.keepEvaluatingAfterFailure())
10167         return false;
10168       Success = false;
10169     }
10170   }
10171   return Success;
10172 }
10173 
10174 static bool EvaluateRecord(const Expr *E, const LValue &This,
10175                            APValue &Result, EvalInfo &Info) {
10176   assert(!E->isValueDependent());
10177   assert(E->isPRValue() && E->getType()->isRecordType() &&
10178          "can't evaluate expression as a record rvalue");
10179   return RecordExprEvaluator(Info, This, Result).Visit(E);
10180 }
10181 
10182 //===----------------------------------------------------------------------===//
10183 // Temporary Evaluation
10184 //
10185 // Temporaries are represented in the AST as rvalues, but generally behave like
10186 // lvalues. The full-object of which the temporary is a subobject is implicitly
10187 // materialized so that a reference can bind to it.
10188 //===----------------------------------------------------------------------===//
10189 namespace {
10190 class TemporaryExprEvaluator
10191   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
10192 public:
10193   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
10194     LValueExprEvaluatorBaseTy(Info, Result, false) {}
10195 
10196   /// Visit an expression which constructs the value of this temporary.
10197   bool VisitConstructExpr(const Expr *E) {
10198     APValue &Value = Info.CurrentCall->createTemporary(
10199         E, E->getType(), ScopeKind::FullExpression, Result);
10200     return EvaluateInPlace(Value, Info, Result, E);
10201   }
10202 
10203   bool VisitCastExpr(const CastExpr *E) {
10204     switch (E->getCastKind()) {
10205     default:
10206       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
10207 
10208     case CK_ConstructorConversion:
10209       return VisitConstructExpr(E->getSubExpr());
10210     }
10211   }
10212   bool VisitInitListExpr(const InitListExpr *E) {
10213     return VisitConstructExpr(E);
10214   }
10215   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10216     return VisitConstructExpr(E);
10217   }
10218   bool VisitCallExpr(const CallExpr *E) {
10219     return VisitConstructExpr(E);
10220   }
10221   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
10222     return VisitConstructExpr(E);
10223   }
10224   bool VisitLambdaExpr(const LambdaExpr *E) {
10225     return VisitConstructExpr(E);
10226   }
10227 };
10228 } // end anonymous namespace
10229 
10230 /// Evaluate an expression of record type as a temporary.
10231 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
10232   assert(!E->isValueDependent());
10233   assert(E->isPRValue() && E->getType()->isRecordType());
10234   return TemporaryExprEvaluator(Info, Result).Visit(E);
10235 }
10236 
10237 //===----------------------------------------------------------------------===//
10238 // Vector Evaluation
10239 //===----------------------------------------------------------------------===//
10240 
10241 namespace {
10242   class VectorExprEvaluator
10243   : public ExprEvaluatorBase<VectorExprEvaluator> {
10244     APValue &Result;
10245   public:
10246 
10247     VectorExprEvaluator(EvalInfo &info, APValue &Result)
10248       : ExprEvaluatorBaseTy(info), Result(Result) {}
10249 
10250     bool Success(ArrayRef<APValue> V, const Expr *E) {
10251       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
10252       // FIXME: remove this APValue copy.
10253       Result = APValue(V.data(), V.size());
10254       return true;
10255     }
10256     bool Success(const APValue &V, const Expr *E) {
10257       assert(V.isVector());
10258       Result = V;
10259       return true;
10260     }
10261     bool ZeroInitialization(const Expr *E);
10262 
10263     bool VisitUnaryReal(const UnaryOperator *E)
10264       { return Visit(E->getSubExpr()); }
10265     bool VisitCastExpr(const CastExpr* E);
10266     bool VisitInitListExpr(const InitListExpr *E);
10267     bool VisitUnaryImag(const UnaryOperator *E);
10268     bool VisitBinaryOperator(const BinaryOperator *E);
10269     bool VisitUnaryOperator(const UnaryOperator *E);
10270     // FIXME: Missing: conditional operator (for GNU
10271     //                 conditional select), shufflevector, ExtVectorElementExpr
10272   };
10273 } // end anonymous namespace
10274 
10275 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
10276   assert(E->isPRValue() && E->getType()->isVectorType() &&
10277          "not a vector prvalue");
10278   return VectorExprEvaluator(Info, Result).Visit(E);
10279 }
10280 
10281 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
10282   const VectorType *VTy = E->getType()->castAs<VectorType>();
10283   unsigned NElts = VTy->getNumElements();
10284 
10285   const Expr *SE = E->getSubExpr();
10286   QualType SETy = SE->getType();
10287 
10288   switch (E->getCastKind()) {
10289   case CK_VectorSplat: {
10290     APValue Val = APValue();
10291     if (SETy->isIntegerType()) {
10292       APSInt IntResult;
10293       if (!EvaluateInteger(SE, IntResult, Info))
10294         return false;
10295       Val = APValue(std::move(IntResult));
10296     } else if (SETy->isRealFloatingType()) {
10297       APFloat FloatResult(0.0);
10298       if (!EvaluateFloat(SE, FloatResult, Info))
10299         return false;
10300       Val = APValue(std::move(FloatResult));
10301     } else {
10302       return Error(E);
10303     }
10304 
10305     // Splat and create vector APValue.
10306     SmallVector<APValue, 4> Elts(NElts, Val);
10307     return Success(Elts, E);
10308   }
10309   case CK_BitCast: {
10310     // Evaluate the operand into an APInt we can extract from.
10311     llvm::APInt SValInt;
10312     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
10313       return false;
10314     // Extract the elements
10315     QualType EltTy = VTy->getElementType();
10316     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
10317     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
10318     SmallVector<APValue, 4> Elts;
10319     if (EltTy->isRealFloatingType()) {
10320       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
10321       unsigned FloatEltSize = EltSize;
10322       if (&Sem == &APFloat::x87DoubleExtended())
10323         FloatEltSize = 80;
10324       for (unsigned i = 0; i < NElts; i++) {
10325         llvm::APInt Elt;
10326         if (BigEndian)
10327           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
10328         else
10329           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
10330         Elts.push_back(APValue(APFloat(Sem, Elt)));
10331       }
10332     } else if (EltTy->isIntegerType()) {
10333       for (unsigned i = 0; i < NElts; i++) {
10334         llvm::APInt Elt;
10335         if (BigEndian)
10336           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
10337         else
10338           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
10339         Elts.push_back(APValue(APSInt(Elt, !EltTy->isSignedIntegerType())));
10340       }
10341     } else {
10342       return Error(E);
10343     }
10344     return Success(Elts, E);
10345   }
10346   default:
10347     return ExprEvaluatorBaseTy::VisitCastExpr(E);
10348   }
10349 }
10350 
10351 bool
10352 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10353   const VectorType *VT = E->getType()->castAs<VectorType>();
10354   unsigned NumInits = E->getNumInits();
10355   unsigned NumElements = VT->getNumElements();
10356 
10357   QualType EltTy = VT->getElementType();
10358   SmallVector<APValue, 4> Elements;
10359 
10360   // The number of initializers can be less than the number of
10361   // vector elements. For OpenCL, this can be due to nested vector
10362   // initialization. For GCC compatibility, missing trailing elements
10363   // should be initialized with zeroes.
10364   unsigned CountInits = 0, CountElts = 0;
10365   while (CountElts < NumElements) {
10366     // Handle nested vector initialization.
10367     if (CountInits < NumInits
10368         && E->getInit(CountInits)->getType()->isVectorType()) {
10369       APValue v;
10370       if (!EvaluateVector(E->getInit(CountInits), v, Info))
10371         return Error(E);
10372       unsigned vlen = v.getVectorLength();
10373       for (unsigned j = 0; j < vlen; j++)
10374         Elements.push_back(v.getVectorElt(j));
10375       CountElts += vlen;
10376     } else if (EltTy->isIntegerType()) {
10377       llvm::APSInt sInt(32);
10378       if (CountInits < NumInits) {
10379         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
10380           return false;
10381       } else // trailing integer zero.
10382         sInt = Info.Ctx.MakeIntValue(0, EltTy);
10383       Elements.push_back(APValue(sInt));
10384       CountElts++;
10385     } else {
10386       llvm::APFloat f(0.0);
10387       if (CountInits < NumInits) {
10388         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
10389           return false;
10390       } else // trailing float zero.
10391         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
10392       Elements.push_back(APValue(f));
10393       CountElts++;
10394     }
10395     CountInits++;
10396   }
10397   return Success(Elements, E);
10398 }
10399 
10400 bool
10401 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
10402   const auto *VT = E->getType()->castAs<VectorType>();
10403   QualType EltTy = VT->getElementType();
10404   APValue ZeroElement;
10405   if (EltTy->isIntegerType())
10406     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
10407   else
10408     ZeroElement =
10409         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
10410 
10411   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
10412   return Success(Elements, E);
10413 }
10414 
10415 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
10416   VisitIgnoredValue(E->getSubExpr());
10417   return ZeroInitialization(E);
10418 }
10419 
10420 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10421   BinaryOperatorKind Op = E->getOpcode();
10422   assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
10423          "Operation not supported on vector types");
10424 
10425   if (Op == BO_Comma)
10426     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10427 
10428   Expr *LHS = E->getLHS();
10429   Expr *RHS = E->getRHS();
10430 
10431   assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
10432          "Must both be vector types");
10433   // Checking JUST the types are the same would be fine, except shifts don't
10434   // need to have their types be the same (since you always shift by an int).
10435   assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
10436              E->getType()->castAs<VectorType>()->getNumElements() &&
10437          RHS->getType()->castAs<VectorType>()->getNumElements() ==
10438              E->getType()->castAs<VectorType>()->getNumElements() &&
10439          "All operands must be the same size.");
10440 
10441   APValue LHSValue;
10442   APValue RHSValue;
10443   bool LHSOK = Evaluate(LHSValue, Info, LHS);
10444   if (!LHSOK && !Info.noteFailure())
10445     return false;
10446   if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
10447     return false;
10448 
10449   if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
10450     return false;
10451 
10452   return Success(LHSValue, E);
10453 }
10454 
10455 static llvm::Optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
10456                                                          QualType ResultTy,
10457                                                          UnaryOperatorKind Op,
10458                                                          APValue Elt) {
10459   switch (Op) {
10460   case UO_Plus:
10461     // Nothing to do here.
10462     return Elt;
10463   case UO_Minus:
10464     if (Elt.getKind() == APValue::Int) {
10465       Elt.getInt().negate();
10466     } else {
10467       assert(Elt.getKind() == APValue::Float &&
10468              "Vector can only be int or float type");
10469       Elt.getFloat().changeSign();
10470     }
10471     return Elt;
10472   case UO_Not:
10473     // This is only valid for integral types anyway, so we don't have to handle
10474     // float here.
10475     assert(Elt.getKind() == APValue::Int &&
10476            "Vector operator ~ can only be int");
10477     Elt.getInt().flipAllBits();
10478     return Elt;
10479   case UO_LNot: {
10480     if (Elt.getKind() == APValue::Int) {
10481       Elt.getInt() = !Elt.getInt();
10482       // operator ! on vectors returns -1 for 'truth', so negate it.
10483       Elt.getInt().negate();
10484       return Elt;
10485     }
10486     assert(Elt.getKind() == APValue::Float &&
10487            "Vector can only be int or float type");
10488     // Float types result in an int of the same size, but -1 for true, or 0 for
10489     // false.
10490     APSInt EltResult{Ctx.getIntWidth(ResultTy),
10491                      ResultTy->isUnsignedIntegerType()};
10492     if (Elt.getFloat().isZero())
10493       EltResult.setAllBits();
10494     else
10495       EltResult.clearAllBits();
10496 
10497     return APValue{EltResult};
10498   }
10499   default:
10500     // FIXME: Implement the rest of the unary operators.
10501     return llvm::None;
10502   }
10503 }
10504 
10505 bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10506   Expr *SubExpr = E->getSubExpr();
10507   const auto *VD = SubExpr->getType()->castAs<VectorType>();
10508   // This result element type differs in the case of negating a floating point
10509   // vector, since the result type is the a vector of the equivilant sized
10510   // integer.
10511   const QualType ResultEltTy = VD->getElementType();
10512   UnaryOperatorKind Op = E->getOpcode();
10513 
10514   APValue SubExprValue;
10515   if (!Evaluate(SubExprValue, Info, SubExpr))
10516     return false;
10517 
10518   // FIXME: This vector evaluator someday needs to be changed to be LValue
10519   // aware/keep LValue information around, rather than dealing with just vector
10520   // types directly. Until then, we cannot handle cases where the operand to
10521   // these unary operators is an LValue. The only case I've been able to see
10522   // cause this is operator++ assigning to a member expression (only valid in
10523   // altivec compilations) in C mode, so this shouldn't limit us too much.
10524   if (SubExprValue.isLValue())
10525     return false;
10526 
10527   assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
10528          "Vector length doesn't match type?");
10529 
10530   SmallVector<APValue, 4> ResultElements;
10531   for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
10532     llvm::Optional<APValue> Elt = handleVectorUnaryOperator(
10533         Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
10534     if (!Elt)
10535       return false;
10536     ResultElements.push_back(*Elt);
10537   }
10538   return Success(APValue(ResultElements.data(), ResultElements.size()), E);
10539 }
10540 
10541 //===----------------------------------------------------------------------===//
10542 // Array Evaluation
10543 //===----------------------------------------------------------------------===//
10544 
10545 namespace {
10546   class ArrayExprEvaluator
10547   : public ExprEvaluatorBase<ArrayExprEvaluator> {
10548     const LValue &This;
10549     APValue &Result;
10550   public:
10551 
10552     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
10553       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
10554 
10555     bool Success(const APValue &V, const Expr *E) {
10556       assert(V.isArray() && "expected array");
10557       Result = V;
10558       return true;
10559     }
10560 
10561     bool ZeroInitialization(const Expr *E) {
10562       const ConstantArrayType *CAT =
10563           Info.Ctx.getAsConstantArrayType(E->getType());
10564       if (!CAT) {
10565         if (E->getType()->isIncompleteArrayType()) {
10566           // We can be asked to zero-initialize a flexible array member; this
10567           // is represented as an ImplicitValueInitExpr of incomplete array
10568           // type. In this case, the array has zero elements.
10569           Result = APValue(APValue::UninitArray(), 0, 0);
10570           return true;
10571         }
10572         // FIXME: We could handle VLAs here.
10573         return Error(E);
10574       }
10575 
10576       Result = APValue(APValue::UninitArray(), 0,
10577                        CAT->getSize().getZExtValue());
10578       if (!Result.hasArrayFiller())
10579         return true;
10580 
10581       // Zero-initialize all elements.
10582       LValue Subobject = This;
10583       Subobject.addArray(Info, E, CAT);
10584       ImplicitValueInitExpr VIE(CAT->getElementType());
10585       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
10586     }
10587 
10588     bool VisitCallExpr(const CallExpr *E) {
10589       return handleCallExpr(E, Result, &This);
10590     }
10591     bool VisitInitListExpr(const InitListExpr *E,
10592                            QualType AllocType = QualType());
10593     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
10594     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
10595     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
10596                                const LValue &Subobject,
10597                                APValue *Value, QualType Type);
10598     bool VisitStringLiteral(const StringLiteral *E,
10599                             QualType AllocType = QualType()) {
10600       expandStringLiteral(Info, E, Result, AllocType);
10601       return true;
10602     }
10603   };
10604 } // end anonymous namespace
10605 
10606 static bool EvaluateArray(const Expr *E, const LValue &This,
10607                           APValue &Result, EvalInfo &Info) {
10608   assert(!E->isValueDependent());
10609   assert(E->isPRValue() && E->getType()->isArrayType() &&
10610          "not an array prvalue");
10611   return ArrayExprEvaluator(Info, This, Result).Visit(E);
10612 }
10613 
10614 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10615                                      APValue &Result, const InitListExpr *ILE,
10616                                      QualType AllocType) {
10617   assert(!ILE->isValueDependent());
10618   assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
10619          "not an array prvalue");
10620   return ArrayExprEvaluator(Info, This, Result)
10621       .VisitInitListExpr(ILE, AllocType);
10622 }
10623 
10624 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10625                                           APValue &Result,
10626                                           const CXXConstructExpr *CCE,
10627                                           QualType AllocType) {
10628   assert(!CCE->isValueDependent());
10629   assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
10630          "not an array prvalue");
10631   return ArrayExprEvaluator(Info, This, Result)
10632       .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
10633 }
10634 
10635 // Return true iff the given array filler may depend on the element index.
10636 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
10637   // For now, just allow non-class value-initialization and initialization
10638   // lists comprised of them.
10639   if (isa<ImplicitValueInitExpr>(FillerExpr))
10640     return false;
10641   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
10642     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
10643       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
10644         return true;
10645     }
10646     return false;
10647   }
10648   return true;
10649 }
10650 
10651 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
10652                                            QualType AllocType) {
10653   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
10654       AllocType.isNull() ? E->getType() : AllocType);
10655   if (!CAT)
10656     return Error(E);
10657 
10658   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
10659   // an appropriately-typed string literal enclosed in braces.
10660   if (E->isStringLiteralInit()) {
10661     auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
10662     // FIXME: Support ObjCEncodeExpr here once we support it in
10663     // ArrayExprEvaluator generally.
10664     if (!SL)
10665       return Error(E);
10666     return VisitStringLiteral(SL, AllocType);
10667   }
10668   // Any other transparent list init will need proper handling of the
10669   // AllocType; we can't just recurse to the inner initializer.
10670   assert(!E->isTransparent() &&
10671          "transparent array list initialization is not string literal init?");
10672 
10673   bool Success = true;
10674 
10675   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
10676          "zero-initialized array shouldn't have any initialized elts");
10677   APValue Filler;
10678   if (Result.isArray() && Result.hasArrayFiller())
10679     Filler = Result.getArrayFiller();
10680 
10681   unsigned NumEltsToInit = E->getNumInits();
10682   unsigned NumElts = CAT->getSize().getZExtValue();
10683   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
10684 
10685   // If the initializer might depend on the array index, run it for each
10686   // array element.
10687   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
10688     NumEltsToInit = NumElts;
10689 
10690   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
10691                           << NumEltsToInit << ".\n");
10692 
10693   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
10694 
10695   // If the array was previously zero-initialized, preserve the
10696   // zero-initialized values.
10697   if (Filler.hasValue()) {
10698     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
10699       Result.getArrayInitializedElt(I) = Filler;
10700     if (Result.hasArrayFiller())
10701       Result.getArrayFiller() = Filler;
10702   }
10703 
10704   LValue Subobject = This;
10705   Subobject.addArray(Info, E, CAT);
10706   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
10707     const Expr *Init =
10708         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
10709     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10710                          Info, Subobject, Init) ||
10711         !HandleLValueArrayAdjustment(Info, Init, Subobject,
10712                                      CAT->getElementType(), 1)) {
10713       if (!Info.noteFailure())
10714         return false;
10715       Success = false;
10716     }
10717   }
10718 
10719   if (!Result.hasArrayFiller())
10720     return Success;
10721 
10722   // If we get here, we have a trivial filler, which we can just evaluate
10723   // once and splat over the rest of the array elements.
10724   assert(FillerExpr && "no array filler for incomplete init list");
10725   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
10726                          FillerExpr) && Success;
10727 }
10728 
10729 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
10730   LValue CommonLV;
10731   if (E->getCommonExpr() &&
10732       !Evaluate(Info.CurrentCall->createTemporary(
10733                     E->getCommonExpr(),
10734                     getStorageType(Info.Ctx, E->getCommonExpr()),
10735                     ScopeKind::FullExpression, CommonLV),
10736                 Info, E->getCommonExpr()->getSourceExpr()))
10737     return false;
10738 
10739   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
10740 
10741   uint64_t Elements = CAT->getSize().getZExtValue();
10742   Result = APValue(APValue::UninitArray(), Elements, Elements);
10743 
10744   LValue Subobject = This;
10745   Subobject.addArray(Info, E, CAT);
10746 
10747   bool Success = true;
10748   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
10749     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10750                          Info, Subobject, E->getSubExpr()) ||
10751         !HandleLValueArrayAdjustment(Info, E, Subobject,
10752                                      CAT->getElementType(), 1)) {
10753       if (!Info.noteFailure())
10754         return false;
10755       Success = false;
10756     }
10757   }
10758 
10759   return Success;
10760 }
10761 
10762 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
10763   return VisitCXXConstructExpr(E, This, &Result, E->getType());
10764 }
10765 
10766 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10767                                                const LValue &Subobject,
10768                                                APValue *Value,
10769                                                QualType Type) {
10770   bool HadZeroInit = Value->hasValue();
10771 
10772   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
10773     unsigned FinalSize = CAT->getSize().getZExtValue();
10774 
10775     // Preserve the array filler if we had prior zero-initialization.
10776     APValue Filler =
10777       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
10778                                              : APValue();
10779 
10780     *Value = APValue(APValue::UninitArray(), 0, FinalSize);
10781     if (FinalSize == 0)
10782       return true;
10783 
10784     LValue ArrayElt = Subobject;
10785     ArrayElt.addArray(Info, E, CAT);
10786     // We do the whole initialization in two passes, first for just one element,
10787     // then for the whole array. It's possible we may find out we can't do const
10788     // init in the first pass, in which case we avoid allocating a potentially
10789     // large array. We don't do more passes because expanding array requires
10790     // copying the data, which is wasteful.
10791     for (const unsigned N : {1u, FinalSize}) {
10792       unsigned OldElts = Value->getArrayInitializedElts();
10793       if (OldElts == N)
10794         break;
10795 
10796       // Expand the array to appropriate size.
10797       APValue NewValue(APValue::UninitArray(), N, FinalSize);
10798       for (unsigned I = 0; I < OldElts; ++I)
10799         NewValue.getArrayInitializedElt(I).swap(
10800             Value->getArrayInitializedElt(I));
10801       Value->swap(NewValue);
10802 
10803       if (HadZeroInit)
10804         for (unsigned I = OldElts; I < N; ++I)
10805           Value->getArrayInitializedElt(I) = Filler;
10806 
10807       // Initialize the elements.
10808       for (unsigned I = OldElts; I < N; ++I) {
10809         if (!VisitCXXConstructExpr(E, ArrayElt,
10810                                    &Value->getArrayInitializedElt(I),
10811                                    CAT->getElementType()) ||
10812             !HandleLValueArrayAdjustment(Info, E, ArrayElt,
10813                                          CAT->getElementType(), 1))
10814           return false;
10815         // When checking for const initilization any diagnostic is considered
10816         // an error.
10817         if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
10818             !Info.keepEvaluatingAfterFailure())
10819           return false;
10820       }
10821     }
10822 
10823     return true;
10824   }
10825 
10826   if (!Type->isRecordType())
10827     return Error(E);
10828 
10829   return RecordExprEvaluator(Info, Subobject, *Value)
10830              .VisitCXXConstructExpr(E, Type);
10831 }
10832 
10833 //===----------------------------------------------------------------------===//
10834 // Integer Evaluation
10835 //
10836 // As a GNU extension, we support casting pointers to sufficiently-wide integer
10837 // types and back in constant folding. Integer values are thus represented
10838 // either as an integer-valued APValue, or as an lvalue-valued APValue.
10839 //===----------------------------------------------------------------------===//
10840 
10841 namespace {
10842 class IntExprEvaluator
10843         : public ExprEvaluatorBase<IntExprEvaluator> {
10844   APValue &Result;
10845 public:
10846   IntExprEvaluator(EvalInfo &info, APValue &result)
10847       : ExprEvaluatorBaseTy(info), Result(result) {}
10848 
10849   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
10850     assert(E->getType()->isIntegralOrEnumerationType() &&
10851            "Invalid evaluation result.");
10852     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
10853            "Invalid evaluation result.");
10854     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10855            "Invalid evaluation result.");
10856     Result = APValue(SI);
10857     return true;
10858   }
10859   bool Success(const llvm::APSInt &SI, const Expr *E) {
10860     return Success(SI, E, Result);
10861   }
10862 
10863   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
10864     assert(E->getType()->isIntegralOrEnumerationType() &&
10865            "Invalid evaluation result.");
10866     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10867            "Invalid evaluation result.");
10868     Result = APValue(APSInt(I));
10869     Result.getInt().setIsUnsigned(
10870                             E->getType()->isUnsignedIntegerOrEnumerationType());
10871     return true;
10872   }
10873   bool Success(const llvm::APInt &I, const Expr *E) {
10874     return Success(I, E, Result);
10875   }
10876 
10877   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
10878     assert(E->getType()->isIntegralOrEnumerationType() &&
10879            "Invalid evaluation result.");
10880     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
10881     return true;
10882   }
10883   bool Success(uint64_t Value, const Expr *E) {
10884     return Success(Value, E, Result);
10885   }
10886 
10887   bool Success(CharUnits Size, const Expr *E) {
10888     return Success(Size.getQuantity(), E);
10889   }
10890 
10891   bool Success(const APValue &V, const Expr *E) {
10892     if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
10893       Result = V;
10894       return true;
10895     }
10896     return Success(V.getInt(), E);
10897   }
10898 
10899   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
10900 
10901   //===--------------------------------------------------------------------===//
10902   //                            Visitor Methods
10903   //===--------------------------------------------------------------------===//
10904 
10905   bool VisitIntegerLiteral(const IntegerLiteral *E) {
10906     return Success(E->getValue(), E);
10907   }
10908   bool VisitCharacterLiteral(const CharacterLiteral *E) {
10909     return Success(E->getValue(), E);
10910   }
10911 
10912   bool CheckReferencedDecl(const Expr *E, const Decl *D);
10913   bool VisitDeclRefExpr(const DeclRefExpr *E) {
10914     if (CheckReferencedDecl(E, E->getDecl()))
10915       return true;
10916 
10917     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
10918   }
10919   bool VisitMemberExpr(const MemberExpr *E) {
10920     if (CheckReferencedDecl(E, E->getMemberDecl())) {
10921       VisitIgnoredBaseExpression(E->getBase());
10922       return true;
10923     }
10924 
10925     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
10926   }
10927 
10928   bool VisitCallExpr(const CallExpr *E);
10929   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
10930   bool VisitBinaryOperator(const BinaryOperator *E);
10931   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
10932   bool VisitUnaryOperator(const UnaryOperator *E);
10933 
10934   bool VisitCastExpr(const CastExpr* E);
10935   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
10936 
10937   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
10938     return Success(E->getValue(), E);
10939   }
10940 
10941   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
10942     return Success(E->getValue(), E);
10943   }
10944 
10945   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
10946     if (Info.ArrayInitIndex == uint64_t(-1)) {
10947       // We were asked to evaluate this subexpression independent of the
10948       // enclosing ArrayInitLoopExpr. We can't do that.
10949       Info.FFDiag(E);
10950       return false;
10951     }
10952     return Success(Info.ArrayInitIndex, E);
10953   }
10954 
10955   // Note, GNU defines __null as an integer, not a pointer.
10956   bool VisitGNUNullExpr(const GNUNullExpr *E) {
10957     return ZeroInitialization(E);
10958   }
10959 
10960   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
10961     return Success(E->getValue(), E);
10962   }
10963 
10964   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
10965     return Success(E->getValue(), E);
10966   }
10967 
10968   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
10969     return Success(E->getValue(), E);
10970   }
10971 
10972   bool VisitUnaryReal(const UnaryOperator *E);
10973   bool VisitUnaryImag(const UnaryOperator *E);
10974 
10975   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
10976   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
10977   bool VisitSourceLocExpr(const SourceLocExpr *E);
10978   bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
10979   bool VisitRequiresExpr(const RequiresExpr *E);
10980   // FIXME: Missing: array subscript of vector, member of vector
10981 };
10982 
10983 class FixedPointExprEvaluator
10984     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
10985   APValue &Result;
10986 
10987  public:
10988   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
10989       : ExprEvaluatorBaseTy(info), Result(result) {}
10990 
10991   bool Success(const llvm::APInt &I, const Expr *E) {
10992     return Success(
10993         APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10994   }
10995 
10996   bool Success(uint64_t Value, const Expr *E) {
10997     return Success(
10998         APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10999   }
11000 
11001   bool Success(const APValue &V, const Expr *E) {
11002     return Success(V.getFixedPoint(), E);
11003   }
11004 
11005   bool Success(const APFixedPoint &V, const Expr *E) {
11006     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
11007     assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11008            "Invalid evaluation result.");
11009     Result = APValue(V);
11010     return true;
11011   }
11012 
11013   //===--------------------------------------------------------------------===//
11014   //                            Visitor Methods
11015   //===--------------------------------------------------------------------===//
11016 
11017   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
11018     return Success(E->getValue(), E);
11019   }
11020 
11021   bool VisitCastExpr(const CastExpr *E);
11022   bool VisitUnaryOperator(const UnaryOperator *E);
11023   bool VisitBinaryOperator(const BinaryOperator *E);
11024 };
11025 } // end anonymous namespace
11026 
11027 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
11028 /// produce either the integer value or a pointer.
11029 ///
11030 /// GCC has a heinous extension which folds casts between pointer types and
11031 /// pointer-sized integral types. We support this by allowing the evaluation of
11032 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
11033 /// Some simple arithmetic on such values is supported (they are treated much
11034 /// like char*).
11035 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
11036                                     EvalInfo &Info) {
11037   assert(!E->isValueDependent());
11038   assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
11039   return IntExprEvaluator(Info, Result).Visit(E);
11040 }
11041 
11042 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
11043   assert(!E->isValueDependent());
11044   APValue Val;
11045   if (!EvaluateIntegerOrLValue(E, Val, Info))
11046     return false;
11047   if (!Val.isInt()) {
11048     // FIXME: It would be better to produce the diagnostic for casting
11049     //        a pointer to an integer.
11050     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11051     return false;
11052   }
11053   Result = Val.getInt();
11054   return true;
11055 }
11056 
11057 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
11058   APValue Evaluated = E->EvaluateInContext(
11059       Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
11060   return Success(Evaluated, E);
11061 }
11062 
11063 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
11064                                EvalInfo &Info) {
11065   assert(!E->isValueDependent());
11066   if (E->getType()->isFixedPointType()) {
11067     APValue Val;
11068     if (!FixedPointExprEvaluator(Info, Val).Visit(E))
11069       return false;
11070     if (!Val.isFixedPoint())
11071       return false;
11072 
11073     Result = Val.getFixedPoint();
11074     return true;
11075   }
11076   return false;
11077 }
11078 
11079 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
11080                                         EvalInfo &Info) {
11081   assert(!E->isValueDependent());
11082   if (E->getType()->isIntegerType()) {
11083     auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
11084     APSInt Val;
11085     if (!EvaluateInteger(E, Val, Info))
11086       return false;
11087     Result = APFixedPoint(Val, FXSema);
11088     return true;
11089   } else if (E->getType()->isFixedPointType()) {
11090     return EvaluateFixedPoint(E, Result, Info);
11091   }
11092   return false;
11093 }
11094 
11095 /// Check whether the given declaration can be directly converted to an integral
11096 /// rvalue. If not, no diagnostic is produced; there are other things we can
11097 /// try.
11098 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
11099   // Enums are integer constant exprs.
11100   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
11101     // Check for signedness/width mismatches between E type and ECD value.
11102     bool SameSign = (ECD->getInitVal().isSigned()
11103                      == E->getType()->isSignedIntegerOrEnumerationType());
11104     bool SameWidth = (ECD->getInitVal().getBitWidth()
11105                       == Info.Ctx.getIntWidth(E->getType()));
11106     if (SameSign && SameWidth)
11107       return Success(ECD->getInitVal(), E);
11108     else {
11109       // Get rid of mismatch (otherwise Success assertions will fail)
11110       // by computing a new value matching the type of E.
11111       llvm::APSInt Val = ECD->getInitVal();
11112       if (!SameSign)
11113         Val.setIsSigned(!ECD->getInitVal().isSigned());
11114       if (!SameWidth)
11115         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
11116       return Success(Val, E);
11117     }
11118   }
11119   return false;
11120 }
11121 
11122 /// Values returned by __builtin_classify_type, chosen to match the values
11123 /// produced by GCC's builtin.
11124 enum class GCCTypeClass {
11125   None = -1,
11126   Void = 0,
11127   Integer = 1,
11128   // GCC reserves 2 for character types, but instead classifies them as
11129   // integers.
11130   Enum = 3,
11131   Bool = 4,
11132   Pointer = 5,
11133   // GCC reserves 6 for references, but appears to never use it (because
11134   // expressions never have reference type, presumably).
11135   PointerToDataMember = 7,
11136   RealFloat = 8,
11137   Complex = 9,
11138   // GCC reserves 10 for functions, but does not use it since GCC version 6 due
11139   // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
11140   // GCC claims to reserve 11 for pointers to member functions, but *actually*
11141   // uses 12 for that purpose, same as for a class or struct. Maybe it
11142   // internally implements a pointer to member as a struct?  Who knows.
11143   PointerToMemberFunction = 12, // Not a bug, see above.
11144   ClassOrStruct = 12,
11145   Union = 13,
11146   // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
11147   // decay to pointer. (Prior to version 6 it was only used in C++ mode).
11148   // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
11149   // literals.
11150 };
11151 
11152 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11153 /// as GCC.
11154 static GCCTypeClass
11155 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
11156   assert(!T->isDependentType() && "unexpected dependent type");
11157 
11158   QualType CanTy = T.getCanonicalType();
11159   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
11160 
11161   switch (CanTy->getTypeClass()) {
11162 #define TYPE(ID, BASE)
11163 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
11164 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
11165 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
11166 #include "clang/AST/TypeNodes.inc"
11167   case Type::Auto:
11168   case Type::DeducedTemplateSpecialization:
11169       llvm_unreachable("unexpected non-canonical or dependent type");
11170 
11171   case Type::Builtin:
11172     switch (BT->getKind()) {
11173 #define BUILTIN_TYPE(ID, SINGLETON_ID)
11174 #define SIGNED_TYPE(ID, SINGLETON_ID) \
11175     case BuiltinType::ID: return GCCTypeClass::Integer;
11176 #define FLOATING_TYPE(ID, SINGLETON_ID) \
11177     case BuiltinType::ID: return GCCTypeClass::RealFloat;
11178 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
11179     case BuiltinType::ID: break;
11180 #include "clang/AST/BuiltinTypes.def"
11181     case BuiltinType::Void:
11182       return GCCTypeClass::Void;
11183 
11184     case BuiltinType::Bool:
11185       return GCCTypeClass::Bool;
11186 
11187     case BuiltinType::Char_U:
11188     case BuiltinType::UChar:
11189     case BuiltinType::WChar_U:
11190     case BuiltinType::Char8:
11191     case BuiltinType::Char16:
11192     case BuiltinType::Char32:
11193     case BuiltinType::UShort:
11194     case BuiltinType::UInt:
11195     case BuiltinType::ULong:
11196     case BuiltinType::ULongLong:
11197     case BuiltinType::UInt128:
11198       return GCCTypeClass::Integer;
11199 
11200     case BuiltinType::UShortAccum:
11201     case BuiltinType::UAccum:
11202     case BuiltinType::ULongAccum:
11203     case BuiltinType::UShortFract:
11204     case BuiltinType::UFract:
11205     case BuiltinType::ULongFract:
11206     case BuiltinType::SatUShortAccum:
11207     case BuiltinType::SatUAccum:
11208     case BuiltinType::SatULongAccum:
11209     case BuiltinType::SatUShortFract:
11210     case BuiltinType::SatUFract:
11211     case BuiltinType::SatULongFract:
11212       return GCCTypeClass::None;
11213 
11214     case BuiltinType::NullPtr:
11215 
11216     case BuiltinType::ObjCId:
11217     case BuiltinType::ObjCClass:
11218     case BuiltinType::ObjCSel:
11219 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
11220     case BuiltinType::Id:
11221 #include "clang/Basic/OpenCLImageTypes.def"
11222 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
11223     case BuiltinType::Id:
11224 #include "clang/Basic/OpenCLExtensionTypes.def"
11225     case BuiltinType::OCLSampler:
11226     case BuiltinType::OCLEvent:
11227     case BuiltinType::OCLClkEvent:
11228     case BuiltinType::OCLQueue:
11229     case BuiltinType::OCLReserveID:
11230 #define SVE_TYPE(Name, Id, SingletonId) \
11231     case BuiltinType::Id:
11232 #include "clang/Basic/AArch64SVEACLETypes.def"
11233 #define PPC_VECTOR_TYPE(Name, Id, Size) \
11234     case BuiltinType::Id:
11235 #include "clang/Basic/PPCTypes.def"
11236 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
11237 #include "clang/Basic/RISCVVTypes.def"
11238       return GCCTypeClass::None;
11239 
11240     case BuiltinType::Dependent:
11241       llvm_unreachable("unexpected dependent type");
11242     };
11243     llvm_unreachable("unexpected placeholder type");
11244 
11245   case Type::Enum:
11246     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
11247 
11248   case Type::Pointer:
11249   case Type::ConstantArray:
11250   case Type::VariableArray:
11251   case Type::IncompleteArray:
11252   case Type::FunctionNoProto:
11253   case Type::FunctionProto:
11254     return GCCTypeClass::Pointer;
11255 
11256   case Type::MemberPointer:
11257     return CanTy->isMemberDataPointerType()
11258                ? GCCTypeClass::PointerToDataMember
11259                : GCCTypeClass::PointerToMemberFunction;
11260 
11261   case Type::Complex:
11262     return GCCTypeClass::Complex;
11263 
11264   case Type::Record:
11265     return CanTy->isUnionType() ? GCCTypeClass::Union
11266                                 : GCCTypeClass::ClassOrStruct;
11267 
11268   case Type::Atomic:
11269     // GCC classifies _Atomic T the same as T.
11270     return EvaluateBuiltinClassifyType(
11271         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
11272 
11273   case Type::BlockPointer:
11274   case Type::Vector:
11275   case Type::ExtVector:
11276   case Type::ConstantMatrix:
11277   case Type::ObjCObject:
11278   case Type::ObjCInterface:
11279   case Type::ObjCObjectPointer:
11280   case Type::Pipe:
11281   case Type::BitInt:
11282     // GCC classifies vectors as None. We follow its lead and classify all
11283     // other types that don't fit into the regular classification the same way.
11284     return GCCTypeClass::None;
11285 
11286   case Type::LValueReference:
11287   case Type::RValueReference:
11288     llvm_unreachable("invalid type for expression");
11289   }
11290 
11291   llvm_unreachable("unexpected type class");
11292 }
11293 
11294 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11295 /// as GCC.
11296 static GCCTypeClass
11297 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
11298   // If no argument was supplied, default to None. This isn't
11299   // ideal, however it is what gcc does.
11300   if (E->getNumArgs() == 0)
11301     return GCCTypeClass::None;
11302 
11303   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
11304   // being an ICE, but still folds it to a constant using the type of the first
11305   // argument.
11306   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
11307 }
11308 
11309 /// EvaluateBuiltinConstantPForLValue - Determine the result of
11310 /// __builtin_constant_p when applied to the given pointer.
11311 ///
11312 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
11313 /// or it points to the first character of a string literal.
11314 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
11315   APValue::LValueBase Base = LV.getLValueBase();
11316   if (Base.isNull()) {
11317     // A null base is acceptable.
11318     return true;
11319   } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
11320     if (!isa<StringLiteral>(E))
11321       return false;
11322     return LV.getLValueOffset().isZero();
11323   } else if (Base.is<TypeInfoLValue>()) {
11324     // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
11325     // evaluate to true.
11326     return true;
11327   } else {
11328     // Any other base is not constant enough for GCC.
11329     return false;
11330   }
11331 }
11332 
11333 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
11334 /// GCC as we can manage.
11335 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
11336   // This evaluation is not permitted to have side-effects, so evaluate it in
11337   // a speculative evaluation context.
11338   SpeculativeEvaluationRAII SpeculativeEval(Info);
11339 
11340   // Constant-folding is always enabled for the operand of __builtin_constant_p
11341   // (even when the enclosing evaluation context otherwise requires a strict
11342   // language-specific constant expression).
11343   FoldConstant Fold(Info, true);
11344 
11345   QualType ArgType = Arg->getType();
11346 
11347   // __builtin_constant_p always has one operand. The rules which gcc follows
11348   // are not precisely documented, but are as follows:
11349   //
11350   //  - If the operand is of integral, floating, complex or enumeration type,
11351   //    and can be folded to a known value of that type, it returns 1.
11352   //  - If the operand can be folded to a pointer to the first character
11353   //    of a string literal (or such a pointer cast to an integral type)
11354   //    or to a null pointer or an integer cast to a pointer, it returns 1.
11355   //
11356   // Otherwise, it returns 0.
11357   //
11358   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
11359   // its support for this did not work prior to GCC 9 and is not yet well
11360   // understood.
11361   if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
11362       ArgType->isAnyComplexType() || ArgType->isPointerType() ||
11363       ArgType->isNullPtrType()) {
11364     APValue V;
11365     if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
11366       Fold.keepDiagnostics();
11367       return false;
11368     }
11369 
11370     // For a pointer (possibly cast to integer), there are special rules.
11371     if (V.getKind() == APValue::LValue)
11372       return EvaluateBuiltinConstantPForLValue(V);
11373 
11374     // Otherwise, any constant value is good enough.
11375     return V.hasValue();
11376   }
11377 
11378   // Anything else isn't considered to be sufficiently constant.
11379   return false;
11380 }
11381 
11382 /// Retrieves the "underlying object type" of the given expression,
11383 /// as used by __builtin_object_size.
11384 static QualType getObjectType(APValue::LValueBase B) {
11385   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
11386     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
11387       return VD->getType();
11388   } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
11389     if (isa<CompoundLiteralExpr>(E))
11390       return E->getType();
11391   } else if (B.is<TypeInfoLValue>()) {
11392     return B.getTypeInfoType();
11393   } else if (B.is<DynamicAllocLValue>()) {
11394     return B.getDynamicAllocType();
11395   }
11396 
11397   return QualType();
11398 }
11399 
11400 /// A more selective version of E->IgnoreParenCasts for
11401 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
11402 /// to change the type of E.
11403 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
11404 ///
11405 /// Always returns an RValue with a pointer representation.
11406 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
11407   assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
11408 
11409   auto *NoParens = E->IgnoreParens();
11410   auto *Cast = dyn_cast<CastExpr>(NoParens);
11411   if (Cast == nullptr)
11412     return NoParens;
11413 
11414   // We only conservatively allow a few kinds of casts, because this code is
11415   // inherently a simple solution that seeks to support the common case.
11416   auto CastKind = Cast->getCastKind();
11417   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
11418       CastKind != CK_AddressSpaceConversion)
11419     return NoParens;
11420 
11421   auto *SubExpr = Cast->getSubExpr();
11422   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
11423     return NoParens;
11424   return ignorePointerCastsAndParens(SubExpr);
11425 }
11426 
11427 /// Checks to see if the given LValue's Designator is at the end of the LValue's
11428 /// record layout. e.g.
11429 ///   struct { struct { int a, b; } fst, snd; } obj;
11430 ///   obj.fst   // no
11431 ///   obj.snd   // yes
11432 ///   obj.fst.a // no
11433 ///   obj.fst.b // no
11434 ///   obj.snd.a // no
11435 ///   obj.snd.b // yes
11436 ///
11437 /// Please note: this function is specialized for how __builtin_object_size
11438 /// views "objects".
11439 ///
11440 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
11441 /// correct result, it will always return true.
11442 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
11443   assert(!LVal.Designator.Invalid);
11444 
11445   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
11446     const RecordDecl *Parent = FD->getParent();
11447     Invalid = Parent->isInvalidDecl();
11448     if (Invalid || Parent->isUnion())
11449       return true;
11450     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
11451     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
11452   };
11453 
11454   auto &Base = LVal.getLValueBase();
11455   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
11456     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
11457       bool Invalid;
11458       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11459         return Invalid;
11460     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
11461       for (auto *FD : IFD->chain()) {
11462         bool Invalid;
11463         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
11464           return Invalid;
11465       }
11466     }
11467   }
11468 
11469   unsigned I = 0;
11470   QualType BaseType = getType(Base);
11471   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
11472     // If we don't know the array bound, conservatively assume we're looking at
11473     // the final array element.
11474     ++I;
11475     if (BaseType->isIncompleteArrayType())
11476       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
11477     else
11478       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
11479   }
11480 
11481   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
11482     const auto &Entry = LVal.Designator.Entries[I];
11483     if (BaseType->isArrayType()) {
11484       // Because __builtin_object_size treats arrays as objects, we can ignore
11485       // the index iff this is the last array in the Designator.
11486       if (I + 1 == E)
11487         return true;
11488       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
11489       uint64_t Index = Entry.getAsArrayIndex();
11490       if (Index + 1 != CAT->getSize())
11491         return false;
11492       BaseType = CAT->getElementType();
11493     } else if (BaseType->isAnyComplexType()) {
11494       const auto *CT = BaseType->castAs<ComplexType>();
11495       uint64_t Index = Entry.getAsArrayIndex();
11496       if (Index != 1)
11497         return false;
11498       BaseType = CT->getElementType();
11499     } else if (auto *FD = getAsField(Entry)) {
11500       bool Invalid;
11501       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11502         return Invalid;
11503       BaseType = FD->getType();
11504     } else {
11505       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
11506       return false;
11507     }
11508   }
11509   return true;
11510 }
11511 
11512 /// Tests to see if the LValue has a user-specified designator (that isn't
11513 /// necessarily valid). Note that this always returns 'true' if the LValue has
11514 /// an unsized array as its first designator entry, because there's currently no
11515 /// way to tell if the user typed *foo or foo[0].
11516 static bool refersToCompleteObject(const LValue &LVal) {
11517   if (LVal.Designator.Invalid)
11518     return false;
11519 
11520   if (!LVal.Designator.Entries.empty())
11521     return LVal.Designator.isMostDerivedAnUnsizedArray();
11522 
11523   if (!LVal.InvalidBase)
11524     return true;
11525 
11526   // If `E` is a MemberExpr, then the first part of the designator is hiding in
11527   // the LValueBase.
11528   const auto *E = LVal.Base.dyn_cast<const Expr *>();
11529   return !E || !isa<MemberExpr>(E);
11530 }
11531 
11532 /// Attempts to detect a user writing into a piece of memory that's impossible
11533 /// to figure out the size of by just using types.
11534 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
11535   const SubobjectDesignator &Designator = LVal.Designator;
11536   // Notes:
11537   // - Users can only write off of the end when we have an invalid base. Invalid
11538   //   bases imply we don't know where the memory came from.
11539   // - We used to be a bit more aggressive here; we'd only be conservative if
11540   //   the array at the end was flexible, or if it had 0 or 1 elements. This
11541   //   broke some common standard library extensions (PR30346), but was
11542   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
11543   //   with some sort of list. OTOH, it seems that GCC is always
11544   //   conservative with the last element in structs (if it's an array), so our
11545   //   current behavior is more compatible than an explicit list approach would
11546   //   be.
11547   return LVal.InvalidBase &&
11548          Designator.Entries.size() == Designator.MostDerivedPathLength &&
11549          Designator.MostDerivedIsArrayElement &&
11550          isDesignatorAtObjectEnd(Ctx, LVal);
11551 }
11552 
11553 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
11554 /// Fails if the conversion would cause loss of precision.
11555 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
11556                                             CharUnits &Result) {
11557   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
11558   if (Int.ugt(CharUnitsMax))
11559     return false;
11560   Result = CharUnits::fromQuantity(Int.getZExtValue());
11561   return true;
11562 }
11563 
11564 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
11565 /// determine how many bytes exist from the beginning of the object to either
11566 /// the end of the current subobject, or the end of the object itself, depending
11567 /// on what the LValue looks like + the value of Type.
11568 ///
11569 /// If this returns false, the value of Result is undefined.
11570 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
11571                                unsigned Type, const LValue &LVal,
11572                                CharUnits &EndOffset) {
11573   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
11574 
11575   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
11576     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
11577       return false;
11578     return HandleSizeof(Info, ExprLoc, Ty, Result);
11579   };
11580 
11581   // We want to evaluate the size of the entire object. This is a valid fallback
11582   // for when Type=1 and the designator is invalid, because we're asked for an
11583   // upper-bound.
11584   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
11585     // Type=3 wants a lower bound, so we can't fall back to this.
11586     if (Type == 3 && !DetermineForCompleteObject)
11587       return false;
11588 
11589     llvm::APInt APEndOffset;
11590     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11591         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11592       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11593 
11594     if (LVal.InvalidBase)
11595       return false;
11596 
11597     QualType BaseTy = getObjectType(LVal.getLValueBase());
11598     return CheckedHandleSizeof(BaseTy, EndOffset);
11599   }
11600 
11601   // We want to evaluate the size of a subobject.
11602   const SubobjectDesignator &Designator = LVal.Designator;
11603 
11604   // The following is a moderately common idiom in C:
11605   //
11606   // struct Foo { int a; char c[1]; };
11607   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
11608   // strcpy(&F->c[0], Bar);
11609   //
11610   // In order to not break too much legacy code, we need to support it.
11611   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
11612     // If we can resolve this to an alloc_size call, we can hand that back,
11613     // because we know for certain how many bytes there are to write to.
11614     llvm::APInt APEndOffset;
11615     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11616         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11617       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11618 
11619     // If we cannot determine the size of the initial allocation, then we can't
11620     // given an accurate upper-bound. However, we are still able to give
11621     // conservative lower-bounds for Type=3.
11622     if (Type == 1)
11623       return false;
11624   }
11625 
11626   CharUnits BytesPerElem;
11627   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
11628     return false;
11629 
11630   // According to the GCC documentation, we want the size of the subobject
11631   // denoted by the pointer. But that's not quite right -- what we actually
11632   // want is the size of the immediately-enclosing array, if there is one.
11633   int64_t ElemsRemaining;
11634   if (Designator.MostDerivedIsArrayElement &&
11635       Designator.Entries.size() == Designator.MostDerivedPathLength) {
11636     uint64_t ArraySize = Designator.getMostDerivedArraySize();
11637     uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
11638     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
11639   } else {
11640     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
11641   }
11642 
11643   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
11644   return true;
11645 }
11646 
11647 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
11648 /// returns true and stores the result in @p Size.
11649 ///
11650 /// If @p WasError is non-null, this will report whether the failure to evaluate
11651 /// is to be treated as an Error in IntExprEvaluator.
11652 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
11653                                          EvalInfo &Info, uint64_t &Size) {
11654   // Determine the denoted object.
11655   LValue LVal;
11656   {
11657     // The operand of __builtin_object_size is never evaluated for side-effects.
11658     // If there are any, but we can determine the pointed-to object anyway, then
11659     // ignore the side-effects.
11660     SpeculativeEvaluationRAII SpeculativeEval(Info);
11661     IgnoreSideEffectsRAII Fold(Info);
11662 
11663     if (E->isGLValue()) {
11664       // It's possible for us to be given GLValues if we're called via
11665       // Expr::tryEvaluateObjectSize.
11666       APValue RVal;
11667       if (!EvaluateAsRValue(Info, E, RVal))
11668         return false;
11669       LVal.setFrom(Info.Ctx, RVal);
11670     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
11671                                 /*InvalidBaseOK=*/true))
11672       return false;
11673   }
11674 
11675   // If we point to before the start of the object, there are no accessible
11676   // bytes.
11677   if (LVal.getLValueOffset().isNegative()) {
11678     Size = 0;
11679     return true;
11680   }
11681 
11682   CharUnits EndOffset;
11683   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
11684     return false;
11685 
11686   // If we've fallen outside of the end offset, just pretend there's nothing to
11687   // write to/read from.
11688   if (EndOffset <= LVal.getLValueOffset())
11689     Size = 0;
11690   else
11691     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
11692   return true;
11693 }
11694 
11695 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
11696   if (unsigned BuiltinOp = E->getBuiltinCallee())
11697     return VisitBuiltinCallExpr(E, BuiltinOp);
11698 
11699   return ExprEvaluatorBaseTy::VisitCallExpr(E);
11700 }
11701 
11702 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
11703                                      APValue &Val, APSInt &Alignment) {
11704   QualType SrcTy = E->getArg(0)->getType();
11705   if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
11706     return false;
11707   // Even though we are evaluating integer expressions we could get a pointer
11708   // argument for the __builtin_is_aligned() case.
11709   if (SrcTy->isPointerType()) {
11710     LValue Ptr;
11711     if (!EvaluatePointer(E->getArg(0), Ptr, Info))
11712       return false;
11713     Ptr.moveInto(Val);
11714   } else if (!SrcTy->isIntegralOrEnumerationType()) {
11715     Info.FFDiag(E->getArg(0));
11716     return false;
11717   } else {
11718     APSInt SrcInt;
11719     if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
11720       return false;
11721     assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
11722            "Bit widths must be the same");
11723     Val = APValue(SrcInt);
11724   }
11725   assert(Val.hasValue());
11726   return true;
11727 }
11728 
11729 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
11730                                             unsigned BuiltinOp) {
11731   switch (BuiltinOp) {
11732   default:
11733     return ExprEvaluatorBaseTy::VisitCallExpr(E);
11734 
11735   case Builtin::BI__builtin_dynamic_object_size:
11736   case Builtin::BI__builtin_object_size: {
11737     // The type was checked when we built the expression.
11738     unsigned Type =
11739         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11740     assert(Type <= 3 && "unexpected type");
11741 
11742     uint64_t Size;
11743     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
11744       return Success(Size, E);
11745 
11746     if (E->getArg(0)->HasSideEffects(Info.Ctx))
11747       return Success((Type & 2) ? 0 : -1, E);
11748 
11749     // Expression had no side effects, but we couldn't statically determine the
11750     // size of the referenced object.
11751     switch (Info.EvalMode) {
11752     case EvalInfo::EM_ConstantExpression:
11753     case EvalInfo::EM_ConstantFold:
11754     case EvalInfo::EM_IgnoreSideEffects:
11755       // Leave it to IR generation.
11756       return Error(E);
11757     case EvalInfo::EM_ConstantExpressionUnevaluated:
11758       // Reduce it to a constant now.
11759       return Success((Type & 2) ? 0 : -1, E);
11760     }
11761 
11762     llvm_unreachable("unexpected EvalMode");
11763   }
11764 
11765   case Builtin::BI__builtin_os_log_format_buffer_size: {
11766     analyze_os_log::OSLogBufferLayout Layout;
11767     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
11768     return Success(Layout.size().getQuantity(), E);
11769   }
11770 
11771   case Builtin::BI__builtin_is_aligned: {
11772     APValue Src;
11773     APSInt Alignment;
11774     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11775       return false;
11776     if (Src.isLValue()) {
11777       // If we evaluated a pointer, check the minimum known alignment.
11778       LValue Ptr;
11779       Ptr.setFrom(Info.Ctx, Src);
11780       CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
11781       CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
11782       // We can return true if the known alignment at the computed offset is
11783       // greater than the requested alignment.
11784       assert(PtrAlign.isPowerOfTwo());
11785       assert(Alignment.isPowerOf2());
11786       if (PtrAlign.getQuantity() >= Alignment)
11787         return Success(1, E);
11788       // If the alignment is not known to be sufficient, some cases could still
11789       // be aligned at run time. However, if the requested alignment is less or
11790       // equal to the base alignment and the offset is not aligned, we know that
11791       // the run-time value can never be aligned.
11792       if (BaseAlignment.getQuantity() >= Alignment &&
11793           PtrAlign.getQuantity() < Alignment)
11794         return Success(0, E);
11795       // Otherwise we can't infer whether the value is sufficiently aligned.
11796       // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
11797       //  in cases where we can't fully evaluate the pointer.
11798       Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
11799           << Alignment;
11800       return false;
11801     }
11802     assert(Src.isInt());
11803     return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
11804   }
11805   case Builtin::BI__builtin_align_up: {
11806     APValue Src;
11807     APSInt Alignment;
11808     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11809       return false;
11810     if (!Src.isInt())
11811       return Error(E);
11812     APSInt AlignedVal =
11813         APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
11814                Src.getInt().isUnsigned());
11815     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11816     return Success(AlignedVal, E);
11817   }
11818   case Builtin::BI__builtin_align_down: {
11819     APValue Src;
11820     APSInt Alignment;
11821     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11822       return false;
11823     if (!Src.isInt())
11824       return Error(E);
11825     APSInt AlignedVal =
11826         APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
11827     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11828     return Success(AlignedVal, E);
11829   }
11830 
11831   case Builtin::BI__builtin_bitreverse8:
11832   case Builtin::BI__builtin_bitreverse16:
11833   case Builtin::BI__builtin_bitreverse32:
11834   case Builtin::BI__builtin_bitreverse64: {
11835     APSInt Val;
11836     if (!EvaluateInteger(E->getArg(0), Val, Info))
11837       return false;
11838 
11839     return Success(Val.reverseBits(), E);
11840   }
11841 
11842   case Builtin::BI__builtin_bswap16:
11843   case Builtin::BI__builtin_bswap32:
11844   case Builtin::BI__builtin_bswap64: {
11845     APSInt Val;
11846     if (!EvaluateInteger(E->getArg(0), Val, Info))
11847       return false;
11848 
11849     return Success(Val.byteSwap(), E);
11850   }
11851 
11852   case Builtin::BI__builtin_classify_type:
11853     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
11854 
11855   case Builtin::BI__builtin_clrsb:
11856   case Builtin::BI__builtin_clrsbl:
11857   case Builtin::BI__builtin_clrsbll: {
11858     APSInt Val;
11859     if (!EvaluateInteger(E->getArg(0), Val, Info))
11860       return false;
11861 
11862     return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
11863   }
11864 
11865   case Builtin::BI__builtin_clz:
11866   case Builtin::BI__builtin_clzl:
11867   case Builtin::BI__builtin_clzll:
11868   case Builtin::BI__builtin_clzs: {
11869     APSInt Val;
11870     if (!EvaluateInteger(E->getArg(0), Val, Info))
11871       return false;
11872     if (!Val)
11873       return Error(E);
11874 
11875     return Success(Val.countLeadingZeros(), E);
11876   }
11877 
11878   case Builtin::BI__builtin_constant_p: {
11879     const Expr *Arg = E->getArg(0);
11880     if (EvaluateBuiltinConstantP(Info, Arg))
11881       return Success(true, E);
11882     if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
11883       // Outside a constant context, eagerly evaluate to false in the presence
11884       // of side-effects in order to avoid -Wunsequenced false-positives in
11885       // a branch on __builtin_constant_p(expr).
11886       return Success(false, E);
11887     }
11888     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11889     return false;
11890   }
11891 
11892   case Builtin::BI__builtin_is_constant_evaluated: {
11893     const auto *Callee = Info.CurrentCall->getCallee();
11894     if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
11895         (Info.CallStackDepth == 1 ||
11896          (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
11897           Callee->getIdentifier() &&
11898           Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
11899       // FIXME: Find a better way to avoid duplicated diagnostics.
11900       if (Info.EvalStatus.Diag)
11901         Info.report((Info.CallStackDepth == 1) ? E->getExprLoc()
11902                                                : Info.CurrentCall->CallLoc,
11903                     diag::warn_is_constant_evaluated_always_true_constexpr)
11904             << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
11905                                          : "std::is_constant_evaluated");
11906     }
11907 
11908     return Success(Info.InConstantContext, E);
11909   }
11910 
11911   case Builtin::BI__builtin_ctz:
11912   case Builtin::BI__builtin_ctzl:
11913   case Builtin::BI__builtin_ctzll:
11914   case Builtin::BI__builtin_ctzs: {
11915     APSInt Val;
11916     if (!EvaluateInteger(E->getArg(0), Val, Info))
11917       return false;
11918     if (!Val)
11919       return Error(E);
11920 
11921     return Success(Val.countTrailingZeros(), E);
11922   }
11923 
11924   case Builtin::BI__builtin_eh_return_data_regno: {
11925     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11926     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
11927     return Success(Operand, E);
11928   }
11929 
11930   case Builtin::BI__builtin_expect:
11931   case Builtin::BI__builtin_expect_with_probability:
11932     return Visit(E->getArg(0));
11933 
11934   case Builtin::BI__builtin_ffs:
11935   case Builtin::BI__builtin_ffsl:
11936   case Builtin::BI__builtin_ffsll: {
11937     APSInt Val;
11938     if (!EvaluateInteger(E->getArg(0), Val, Info))
11939       return false;
11940 
11941     unsigned N = Val.countTrailingZeros();
11942     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
11943   }
11944 
11945   case Builtin::BI__builtin_fpclassify: {
11946     APFloat Val(0.0);
11947     if (!EvaluateFloat(E->getArg(5), Val, Info))
11948       return false;
11949     unsigned Arg;
11950     switch (Val.getCategory()) {
11951     case APFloat::fcNaN: Arg = 0; break;
11952     case APFloat::fcInfinity: Arg = 1; break;
11953     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
11954     case APFloat::fcZero: Arg = 4; break;
11955     }
11956     return Visit(E->getArg(Arg));
11957   }
11958 
11959   case Builtin::BI__builtin_isinf_sign: {
11960     APFloat Val(0.0);
11961     return EvaluateFloat(E->getArg(0), Val, Info) &&
11962            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
11963   }
11964 
11965   case Builtin::BI__builtin_isinf: {
11966     APFloat Val(0.0);
11967     return EvaluateFloat(E->getArg(0), Val, Info) &&
11968            Success(Val.isInfinity() ? 1 : 0, E);
11969   }
11970 
11971   case Builtin::BI__builtin_isfinite: {
11972     APFloat Val(0.0);
11973     return EvaluateFloat(E->getArg(0), Val, Info) &&
11974            Success(Val.isFinite() ? 1 : 0, E);
11975   }
11976 
11977   case Builtin::BI__builtin_isnan: {
11978     APFloat Val(0.0);
11979     return EvaluateFloat(E->getArg(0), Val, Info) &&
11980            Success(Val.isNaN() ? 1 : 0, E);
11981   }
11982 
11983   case Builtin::BI__builtin_isnormal: {
11984     APFloat Val(0.0);
11985     return EvaluateFloat(E->getArg(0), Val, Info) &&
11986            Success(Val.isNormal() ? 1 : 0, E);
11987   }
11988 
11989   case Builtin::BI__builtin_parity:
11990   case Builtin::BI__builtin_parityl:
11991   case Builtin::BI__builtin_parityll: {
11992     APSInt Val;
11993     if (!EvaluateInteger(E->getArg(0), Val, Info))
11994       return false;
11995 
11996     return Success(Val.countPopulation() % 2, E);
11997   }
11998 
11999   case Builtin::BI__builtin_popcount:
12000   case Builtin::BI__builtin_popcountl:
12001   case Builtin::BI__builtin_popcountll: {
12002     APSInt Val;
12003     if (!EvaluateInteger(E->getArg(0), Val, Info))
12004       return false;
12005 
12006     return Success(Val.countPopulation(), E);
12007   }
12008 
12009   case Builtin::BI__builtin_rotateleft8:
12010   case Builtin::BI__builtin_rotateleft16:
12011   case Builtin::BI__builtin_rotateleft32:
12012   case Builtin::BI__builtin_rotateleft64:
12013   case Builtin::BI_rotl8: // Microsoft variants of rotate right
12014   case Builtin::BI_rotl16:
12015   case Builtin::BI_rotl:
12016   case Builtin::BI_lrotl:
12017   case Builtin::BI_rotl64: {
12018     APSInt Val, Amt;
12019     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
12020         !EvaluateInteger(E->getArg(1), Amt, Info))
12021       return false;
12022 
12023     return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
12024   }
12025 
12026   case Builtin::BI__builtin_rotateright8:
12027   case Builtin::BI__builtin_rotateright16:
12028   case Builtin::BI__builtin_rotateright32:
12029   case Builtin::BI__builtin_rotateright64:
12030   case Builtin::BI_rotr8: // Microsoft variants of rotate right
12031   case Builtin::BI_rotr16:
12032   case Builtin::BI_rotr:
12033   case Builtin::BI_lrotr:
12034   case Builtin::BI_rotr64: {
12035     APSInt Val, Amt;
12036     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
12037         !EvaluateInteger(E->getArg(1), Amt, Info))
12038       return false;
12039 
12040     return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
12041   }
12042 
12043   case Builtin::BIstrlen:
12044   case Builtin::BIwcslen:
12045     // A call to strlen is not a constant expression.
12046     if (Info.getLangOpts().CPlusPlus11)
12047       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
12048         << /*isConstexpr*/0 << /*isConstructor*/0
12049         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
12050     else
12051       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12052     LLVM_FALLTHROUGH;
12053   case Builtin::BI__builtin_strlen:
12054   case Builtin::BI__builtin_wcslen: {
12055     // As an extension, we support __builtin_strlen() as a constant expression,
12056     // and support folding strlen() to a constant.
12057     uint64_t StrLen;
12058     if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
12059       return Success(StrLen, E);
12060     return false;
12061   }
12062 
12063   case Builtin::BIstrcmp:
12064   case Builtin::BIwcscmp:
12065   case Builtin::BIstrncmp:
12066   case Builtin::BIwcsncmp:
12067   case Builtin::BImemcmp:
12068   case Builtin::BIbcmp:
12069   case Builtin::BIwmemcmp:
12070     // A call to strlen is not a constant expression.
12071     if (Info.getLangOpts().CPlusPlus11)
12072       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
12073         << /*isConstexpr*/0 << /*isConstructor*/0
12074         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
12075     else
12076       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12077     LLVM_FALLTHROUGH;
12078   case Builtin::BI__builtin_strcmp:
12079   case Builtin::BI__builtin_wcscmp:
12080   case Builtin::BI__builtin_strncmp:
12081   case Builtin::BI__builtin_wcsncmp:
12082   case Builtin::BI__builtin_memcmp:
12083   case Builtin::BI__builtin_bcmp:
12084   case Builtin::BI__builtin_wmemcmp: {
12085     LValue String1, String2;
12086     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
12087         !EvaluatePointer(E->getArg(1), String2, Info))
12088       return false;
12089 
12090     uint64_t MaxLength = uint64_t(-1);
12091     if (BuiltinOp != Builtin::BIstrcmp &&
12092         BuiltinOp != Builtin::BIwcscmp &&
12093         BuiltinOp != Builtin::BI__builtin_strcmp &&
12094         BuiltinOp != Builtin::BI__builtin_wcscmp) {
12095       APSInt N;
12096       if (!EvaluateInteger(E->getArg(2), N, Info))
12097         return false;
12098       MaxLength = N.getExtValue();
12099     }
12100 
12101     // Empty substrings compare equal by definition.
12102     if (MaxLength == 0u)
12103       return Success(0, E);
12104 
12105     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
12106         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
12107         String1.Designator.Invalid || String2.Designator.Invalid)
12108       return false;
12109 
12110     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
12111     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
12112 
12113     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
12114                      BuiltinOp == Builtin::BIbcmp ||
12115                      BuiltinOp == Builtin::BI__builtin_memcmp ||
12116                      BuiltinOp == Builtin::BI__builtin_bcmp;
12117 
12118     assert(IsRawByte ||
12119            (Info.Ctx.hasSameUnqualifiedType(
12120                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
12121             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
12122 
12123     // For memcmp, allow comparing any arrays of '[[un]signed] char' or
12124     // 'char8_t', but no other types.
12125     if (IsRawByte &&
12126         !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
12127       // FIXME: Consider using our bit_cast implementation to support this.
12128       Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
12129           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
12130           << CharTy1 << CharTy2;
12131       return false;
12132     }
12133 
12134     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
12135       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
12136              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
12137              Char1.isInt() && Char2.isInt();
12138     };
12139     const auto &AdvanceElems = [&] {
12140       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
12141              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
12142     };
12143 
12144     bool StopAtNull =
12145         (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
12146          BuiltinOp != Builtin::BIwmemcmp &&
12147          BuiltinOp != Builtin::BI__builtin_memcmp &&
12148          BuiltinOp != Builtin::BI__builtin_bcmp &&
12149          BuiltinOp != Builtin::BI__builtin_wmemcmp);
12150     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
12151                   BuiltinOp == Builtin::BIwcsncmp ||
12152                   BuiltinOp == Builtin::BIwmemcmp ||
12153                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
12154                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
12155                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
12156 
12157     for (; MaxLength; --MaxLength) {
12158       APValue Char1, Char2;
12159       if (!ReadCurElems(Char1, Char2))
12160         return false;
12161       if (Char1.getInt().ne(Char2.getInt())) {
12162         if (IsWide) // wmemcmp compares with wchar_t signedness.
12163           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
12164         // memcmp always compares unsigned chars.
12165         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
12166       }
12167       if (StopAtNull && !Char1.getInt())
12168         return Success(0, E);
12169       assert(!(StopAtNull && !Char2.getInt()));
12170       if (!AdvanceElems())
12171         return false;
12172     }
12173     // We hit the strncmp / memcmp limit.
12174     return Success(0, E);
12175   }
12176 
12177   case Builtin::BI__atomic_always_lock_free:
12178   case Builtin::BI__atomic_is_lock_free:
12179   case Builtin::BI__c11_atomic_is_lock_free: {
12180     APSInt SizeVal;
12181     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
12182       return false;
12183 
12184     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
12185     // of two less than or equal to the maximum inline atomic width, we know it
12186     // is lock-free.  If the size isn't a power of two, or greater than the
12187     // maximum alignment where we promote atomics, we know it is not lock-free
12188     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
12189     // the answer can only be determined at runtime; for example, 16-byte
12190     // atomics have lock-free implementations on some, but not all,
12191     // x86-64 processors.
12192 
12193     // Check power-of-two.
12194     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
12195     if (Size.isPowerOfTwo()) {
12196       // Check against inlining width.
12197       unsigned InlineWidthBits =
12198           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
12199       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
12200         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
12201             Size == CharUnits::One() ||
12202             E->getArg(1)->isNullPointerConstant(Info.Ctx,
12203                                                 Expr::NPC_NeverValueDependent))
12204           // OK, we will inline appropriately-aligned operations of this size,
12205           // and _Atomic(T) is appropriately-aligned.
12206           return Success(1, E);
12207 
12208         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
12209           castAs<PointerType>()->getPointeeType();
12210         if (!PointeeType->isIncompleteType() &&
12211             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
12212           // OK, we will inline operations on this object.
12213           return Success(1, E);
12214         }
12215       }
12216     }
12217 
12218     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
12219         Success(0, E) : Error(E);
12220   }
12221   case Builtin::BI__builtin_add_overflow:
12222   case Builtin::BI__builtin_sub_overflow:
12223   case Builtin::BI__builtin_mul_overflow:
12224   case Builtin::BI__builtin_sadd_overflow:
12225   case Builtin::BI__builtin_uadd_overflow:
12226   case Builtin::BI__builtin_uaddl_overflow:
12227   case Builtin::BI__builtin_uaddll_overflow:
12228   case Builtin::BI__builtin_usub_overflow:
12229   case Builtin::BI__builtin_usubl_overflow:
12230   case Builtin::BI__builtin_usubll_overflow:
12231   case Builtin::BI__builtin_umul_overflow:
12232   case Builtin::BI__builtin_umull_overflow:
12233   case Builtin::BI__builtin_umulll_overflow:
12234   case Builtin::BI__builtin_saddl_overflow:
12235   case Builtin::BI__builtin_saddll_overflow:
12236   case Builtin::BI__builtin_ssub_overflow:
12237   case Builtin::BI__builtin_ssubl_overflow:
12238   case Builtin::BI__builtin_ssubll_overflow:
12239   case Builtin::BI__builtin_smul_overflow:
12240   case Builtin::BI__builtin_smull_overflow:
12241   case Builtin::BI__builtin_smulll_overflow: {
12242     LValue ResultLValue;
12243     APSInt LHS, RHS;
12244 
12245     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
12246     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
12247         !EvaluateInteger(E->getArg(1), RHS, Info) ||
12248         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
12249       return false;
12250 
12251     APSInt Result;
12252     bool DidOverflow = false;
12253 
12254     // If the types don't have to match, enlarge all 3 to the largest of them.
12255     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12256         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12257         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12258       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
12259                       ResultType->isSignedIntegerOrEnumerationType();
12260       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
12261                       ResultType->isSignedIntegerOrEnumerationType();
12262       uint64_t LHSSize = LHS.getBitWidth();
12263       uint64_t RHSSize = RHS.getBitWidth();
12264       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
12265       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
12266 
12267       // Add an additional bit if the signedness isn't uniformly agreed to. We
12268       // could do this ONLY if there is a signed and an unsigned that both have
12269       // MaxBits, but the code to check that is pretty nasty.  The issue will be
12270       // caught in the shrink-to-result later anyway.
12271       if (IsSigned && !AllSigned)
12272         ++MaxBits;
12273 
12274       LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
12275       RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
12276       Result = APSInt(MaxBits, !IsSigned);
12277     }
12278 
12279     // Find largest int.
12280     switch (BuiltinOp) {
12281     default:
12282       llvm_unreachable("Invalid value for BuiltinOp");
12283     case Builtin::BI__builtin_add_overflow:
12284     case Builtin::BI__builtin_sadd_overflow:
12285     case Builtin::BI__builtin_saddl_overflow:
12286     case Builtin::BI__builtin_saddll_overflow:
12287     case Builtin::BI__builtin_uadd_overflow:
12288     case Builtin::BI__builtin_uaddl_overflow:
12289     case Builtin::BI__builtin_uaddll_overflow:
12290       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
12291                               : LHS.uadd_ov(RHS, DidOverflow);
12292       break;
12293     case Builtin::BI__builtin_sub_overflow:
12294     case Builtin::BI__builtin_ssub_overflow:
12295     case Builtin::BI__builtin_ssubl_overflow:
12296     case Builtin::BI__builtin_ssubll_overflow:
12297     case Builtin::BI__builtin_usub_overflow:
12298     case Builtin::BI__builtin_usubl_overflow:
12299     case Builtin::BI__builtin_usubll_overflow:
12300       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
12301                               : LHS.usub_ov(RHS, DidOverflow);
12302       break;
12303     case Builtin::BI__builtin_mul_overflow:
12304     case Builtin::BI__builtin_smul_overflow:
12305     case Builtin::BI__builtin_smull_overflow:
12306     case Builtin::BI__builtin_smulll_overflow:
12307     case Builtin::BI__builtin_umul_overflow:
12308     case Builtin::BI__builtin_umull_overflow:
12309     case Builtin::BI__builtin_umulll_overflow:
12310       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
12311                               : LHS.umul_ov(RHS, DidOverflow);
12312       break;
12313     }
12314 
12315     // In the case where multiple sizes are allowed, truncate and see if
12316     // the values are the same.
12317     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12318         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12319         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12320       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
12321       // since it will give us the behavior of a TruncOrSelf in the case where
12322       // its parameter <= its size.  We previously set Result to be at least the
12323       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
12324       // will work exactly like TruncOrSelf.
12325       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
12326       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
12327 
12328       if (!APSInt::isSameValue(Temp, Result))
12329         DidOverflow = true;
12330       Result = Temp;
12331     }
12332 
12333     APValue APV{Result};
12334     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
12335       return false;
12336     return Success(DidOverflow, E);
12337   }
12338   }
12339 }
12340 
12341 /// Determine whether this is a pointer past the end of the complete
12342 /// object referred to by the lvalue.
12343 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
12344                                             const LValue &LV) {
12345   // A null pointer can be viewed as being "past the end" but we don't
12346   // choose to look at it that way here.
12347   if (!LV.getLValueBase())
12348     return false;
12349 
12350   // If the designator is valid and refers to a subobject, we're not pointing
12351   // past the end.
12352   if (!LV.getLValueDesignator().Invalid &&
12353       !LV.getLValueDesignator().isOnePastTheEnd())
12354     return false;
12355 
12356   // A pointer to an incomplete type might be past-the-end if the type's size is
12357   // zero.  We cannot tell because the type is incomplete.
12358   QualType Ty = getType(LV.getLValueBase());
12359   if (Ty->isIncompleteType())
12360     return true;
12361 
12362   // We're a past-the-end pointer if we point to the byte after the object,
12363   // no matter what our type or path is.
12364   auto Size = Ctx.getTypeSizeInChars(Ty);
12365   return LV.getLValueOffset() == Size;
12366 }
12367 
12368 namespace {
12369 
12370 /// Data recursive integer evaluator of certain binary operators.
12371 ///
12372 /// We use a data recursive algorithm for binary operators so that we are able
12373 /// to handle extreme cases of chained binary operators without causing stack
12374 /// overflow.
12375 class DataRecursiveIntBinOpEvaluator {
12376   struct EvalResult {
12377     APValue Val;
12378     bool Failed;
12379 
12380     EvalResult() : Failed(false) { }
12381 
12382     void swap(EvalResult &RHS) {
12383       Val.swap(RHS.Val);
12384       Failed = RHS.Failed;
12385       RHS.Failed = false;
12386     }
12387   };
12388 
12389   struct Job {
12390     const Expr *E;
12391     EvalResult LHSResult; // meaningful only for binary operator expression.
12392     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
12393 
12394     Job() = default;
12395     Job(Job &&) = default;
12396 
12397     void startSpeculativeEval(EvalInfo &Info) {
12398       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
12399     }
12400 
12401   private:
12402     SpeculativeEvaluationRAII SpecEvalRAII;
12403   };
12404 
12405   SmallVector<Job, 16> Queue;
12406 
12407   IntExprEvaluator &IntEval;
12408   EvalInfo &Info;
12409   APValue &FinalResult;
12410 
12411 public:
12412   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
12413     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
12414 
12415   /// True if \param E is a binary operator that we are going to handle
12416   /// data recursively.
12417   /// We handle binary operators that are comma, logical, or that have operands
12418   /// with integral or enumeration type.
12419   static bool shouldEnqueue(const BinaryOperator *E) {
12420     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
12421            (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() &&
12422             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12423             E->getRHS()->getType()->isIntegralOrEnumerationType());
12424   }
12425 
12426   bool Traverse(const BinaryOperator *E) {
12427     enqueue(E);
12428     EvalResult PrevResult;
12429     while (!Queue.empty())
12430       process(PrevResult);
12431 
12432     if (PrevResult.Failed) return false;
12433 
12434     FinalResult.swap(PrevResult.Val);
12435     return true;
12436   }
12437 
12438 private:
12439   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
12440     return IntEval.Success(Value, E, Result);
12441   }
12442   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
12443     return IntEval.Success(Value, E, Result);
12444   }
12445   bool Error(const Expr *E) {
12446     return IntEval.Error(E);
12447   }
12448   bool Error(const Expr *E, diag::kind D) {
12449     return IntEval.Error(E, D);
12450   }
12451 
12452   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
12453     return Info.CCEDiag(E, D);
12454   }
12455 
12456   // Returns true if visiting the RHS is necessary, false otherwise.
12457   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12458                          bool &SuppressRHSDiags);
12459 
12460   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12461                   const BinaryOperator *E, APValue &Result);
12462 
12463   void EvaluateExpr(const Expr *E, EvalResult &Result) {
12464     Result.Failed = !Evaluate(Result.Val, Info, E);
12465     if (Result.Failed)
12466       Result.Val = APValue();
12467   }
12468 
12469   void process(EvalResult &Result);
12470 
12471   void enqueue(const Expr *E) {
12472     E = E->IgnoreParens();
12473     Queue.resize(Queue.size()+1);
12474     Queue.back().E = E;
12475     Queue.back().Kind = Job::AnyExprKind;
12476   }
12477 };
12478 
12479 }
12480 
12481 bool DataRecursiveIntBinOpEvaluator::
12482        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12483                          bool &SuppressRHSDiags) {
12484   if (E->getOpcode() == BO_Comma) {
12485     // Ignore LHS but note if we could not evaluate it.
12486     if (LHSResult.Failed)
12487       return Info.noteSideEffect();
12488     return true;
12489   }
12490 
12491   if (E->isLogicalOp()) {
12492     bool LHSAsBool;
12493     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
12494       // We were able to evaluate the LHS, see if we can get away with not
12495       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
12496       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
12497         Success(LHSAsBool, E, LHSResult.Val);
12498         return false; // Ignore RHS
12499       }
12500     } else {
12501       LHSResult.Failed = true;
12502 
12503       // Since we weren't able to evaluate the left hand side, it
12504       // might have had side effects.
12505       if (!Info.noteSideEffect())
12506         return false;
12507 
12508       // We can't evaluate the LHS; however, sometimes the result
12509       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12510       // Don't ignore RHS and suppress diagnostics from this arm.
12511       SuppressRHSDiags = true;
12512     }
12513 
12514     return true;
12515   }
12516 
12517   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12518          E->getRHS()->getType()->isIntegralOrEnumerationType());
12519 
12520   if (LHSResult.Failed && !Info.noteFailure())
12521     return false; // Ignore RHS;
12522 
12523   return true;
12524 }
12525 
12526 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
12527                                     bool IsSub) {
12528   // Compute the new offset in the appropriate width, wrapping at 64 bits.
12529   // FIXME: When compiling for a 32-bit target, we should use 32-bit
12530   // offsets.
12531   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
12532   CharUnits &Offset = LVal.getLValueOffset();
12533   uint64_t Offset64 = Offset.getQuantity();
12534   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
12535   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
12536                                          : Offset64 + Index64);
12537 }
12538 
12539 bool DataRecursiveIntBinOpEvaluator::
12540        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12541                   const BinaryOperator *E, APValue &Result) {
12542   if (E->getOpcode() == BO_Comma) {
12543     if (RHSResult.Failed)
12544       return false;
12545     Result = RHSResult.Val;
12546     return true;
12547   }
12548 
12549   if (E->isLogicalOp()) {
12550     bool lhsResult, rhsResult;
12551     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
12552     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
12553 
12554     if (LHSIsOK) {
12555       if (RHSIsOK) {
12556         if (E->getOpcode() == BO_LOr)
12557           return Success(lhsResult || rhsResult, E, Result);
12558         else
12559           return Success(lhsResult && rhsResult, E, Result);
12560       }
12561     } else {
12562       if (RHSIsOK) {
12563         // We can't evaluate the LHS; however, sometimes the result
12564         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12565         if (rhsResult == (E->getOpcode() == BO_LOr))
12566           return Success(rhsResult, E, Result);
12567       }
12568     }
12569 
12570     return false;
12571   }
12572 
12573   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12574          E->getRHS()->getType()->isIntegralOrEnumerationType());
12575 
12576   if (LHSResult.Failed || RHSResult.Failed)
12577     return false;
12578 
12579   const APValue &LHSVal = LHSResult.Val;
12580   const APValue &RHSVal = RHSResult.Val;
12581 
12582   // Handle cases like (unsigned long)&a + 4.
12583   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
12584     Result = LHSVal;
12585     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
12586     return true;
12587   }
12588 
12589   // Handle cases like 4 + (unsigned long)&a
12590   if (E->getOpcode() == BO_Add &&
12591       RHSVal.isLValue() && LHSVal.isInt()) {
12592     Result = RHSVal;
12593     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
12594     return true;
12595   }
12596 
12597   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
12598     // Handle (intptr_t)&&A - (intptr_t)&&B.
12599     if (!LHSVal.getLValueOffset().isZero() ||
12600         !RHSVal.getLValueOffset().isZero())
12601       return false;
12602     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
12603     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
12604     if (!LHSExpr || !RHSExpr)
12605       return false;
12606     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12607     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12608     if (!LHSAddrExpr || !RHSAddrExpr)
12609       return false;
12610     // Make sure both labels come from the same function.
12611     if (LHSAddrExpr->getLabel()->getDeclContext() !=
12612         RHSAddrExpr->getLabel()->getDeclContext())
12613       return false;
12614     Result = APValue(LHSAddrExpr, RHSAddrExpr);
12615     return true;
12616   }
12617 
12618   // All the remaining cases expect both operands to be an integer
12619   if (!LHSVal.isInt() || !RHSVal.isInt())
12620     return Error(E);
12621 
12622   // Set up the width and signedness manually, in case it can't be deduced
12623   // from the operation we're performing.
12624   // FIXME: Don't do this in the cases where we can deduce it.
12625   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
12626                E->getType()->isUnsignedIntegerOrEnumerationType());
12627   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
12628                          RHSVal.getInt(), Value))
12629     return false;
12630   return Success(Value, E, Result);
12631 }
12632 
12633 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
12634   Job &job = Queue.back();
12635 
12636   switch (job.Kind) {
12637     case Job::AnyExprKind: {
12638       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
12639         if (shouldEnqueue(Bop)) {
12640           job.Kind = Job::BinOpKind;
12641           enqueue(Bop->getLHS());
12642           return;
12643         }
12644       }
12645 
12646       EvaluateExpr(job.E, Result);
12647       Queue.pop_back();
12648       return;
12649     }
12650 
12651     case Job::BinOpKind: {
12652       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12653       bool SuppressRHSDiags = false;
12654       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
12655         Queue.pop_back();
12656         return;
12657       }
12658       if (SuppressRHSDiags)
12659         job.startSpeculativeEval(Info);
12660       job.LHSResult.swap(Result);
12661       job.Kind = Job::BinOpVisitedLHSKind;
12662       enqueue(Bop->getRHS());
12663       return;
12664     }
12665 
12666     case Job::BinOpVisitedLHSKind: {
12667       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12668       EvalResult RHS;
12669       RHS.swap(Result);
12670       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
12671       Queue.pop_back();
12672       return;
12673     }
12674   }
12675 
12676   llvm_unreachable("Invalid Job::Kind!");
12677 }
12678 
12679 namespace {
12680 enum class CmpResult {
12681   Unequal,
12682   Less,
12683   Equal,
12684   Greater,
12685   Unordered,
12686 };
12687 }
12688 
12689 template <class SuccessCB, class AfterCB>
12690 static bool
12691 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
12692                                  SuccessCB &&Success, AfterCB &&DoAfter) {
12693   assert(!E->isValueDependent());
12694   assert(E->isComparisonOp() && "expected comparison operator");
12695   assert((E->getOpcode() == BO_Cmp ||
12696           E->getType()->isIntegralOrEnumerationType()) &&
12697          "unsupported binary expression evaluation");
12698   auto Error = [&](const Expr *E) {
12699     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12700     return false;
12701   };
12702 
12703   bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
12704   bool IsEquality = E->isEqualityOp();
12705 
12706   QualType LHSTy = E->getLHS()->getType();
12707   QualType RHSTy = E->getRHS()->getType();
12708 
12709   if (LHSTy->isIntegralOrEnumerationType() &&
12710       RHSTy->isIntegralOrEnumerationType()) {
12711     APSInt LHS, RHS;
12712     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
12713     if (!LHSOK && !Info.noteFailure())
12714       return false;
12715     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
12716       return false;
12717     if (LHS < RHS)
12718       return Success(CmpResult::Less, E);
12719     if (LHS > RHS)
12720       return Success(CmpResult::Greater, E);
12721     return Success(CmpResult::Equal, E);
12722   }
12723 
12724   if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
12725     APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
12726     APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
12727 
12728     bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
12729     if (!LHSOK && !Info.noteFailure())
12730       return false;
12731     if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
12732       return false;
12733     if (LHSFX < RHSFX)
12734       return Success(CmpResult::Less, E);
12735     if (LHSFX > RHSFX)
12736       return Success(CmpResult::Greater, E);
12737     return Success(CmpResult::Equal, E);
12738   }
12739 
12740   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
12741     ComplexValue LHS, RHS;
12742     bool LHSOK;
12743     if (E->isAssignmentOp()) {
12744       LValue LV;
12745       EvaluateLValue(E->getLHS(), LV, Info);
12746       LHSOK = false;
12747     } else if (LHSTy->isRealFloatingType()) {
12748       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
12749       if (LHSOK) {
12750         LHS.makeComplexFloat();
12751         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
12752       }
12753     } else {
12754       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
12755     }
12756     if (!LHSOK && !Info.noteFailure())
12757       return false;
12758 
12759     if (E->getRHS()->getType()->isRealFloatingType()) {
12760       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
12761         return false;
12762       RHS.makeComplexFloat();
12763       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
12764     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
12765       return false;
12766 
12767     if (LHS.isComplexFloat()) {
12768       APFloat::cmpResult CR_r =
12769         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
12770       APFloat::cmpResult CR_i =
12771         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
12772       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
12773       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12774     } else {
12775       assert(IsEquality && "invalid complex comparison");
12776       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
12777                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
12778       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12779     }
12780   }
12781 
12782   if (LHSTy->isRealFloatingType() &&
12783       RHSTy->isRealFloatingType()) {
12784     APFloat RHS(0.0), LHS(0.0);
12785 
12786     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
12787     if (!LHSOK && !Info.noteFailure())
12788       return false;
12789 
12790     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
12791       return false;
12792 
12793     assert(E->isComparisonOp() && "Invalid binary operator!");
12794     llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
12795     if (!Info.InConstantContext &&
12796         APFloatCmpResult == APFloat::cmpUnordered &&
12797         E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
12798       // Note: Compares may raise invalid in some cases involving NaN or sNaN.
12799       Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
12800       return false;
12801     }
12802     auto GetCmpRes = [&]() {
12803       switch (APFloatCmpResult) {
12804       case APFloat::cmpEqual:
12805         return CmpResult::Equal;
12806       case APFloat::cmpLessThan:
12807         return CmpResult::Less;
12808       case APFloat::cmpGreaterThan:
12809         return CmpResult::Greater;
12810       case APFloat::cmpUnordered:
12811         return CmpResult::Unordered;
12812       }
12813       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
12814     };
12815     return Success(GetCmpRes(), E);
12816   }
12817 
12818   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
12819     LValue LHSValue, RHSValue;
12820 
12821     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12822     if (!LHSOK && !Info.noteFailure())
12823       return false;
12824 
12825     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12826       return false;
12827 
12828     // Reject differing bases from the normal codepath; we special-case
12829     // comparisons to null.
12830     if (!HasSameBase(LHSValue, RHSValue)) {
12831       // Inequalities and subtractions between unrelated pointers have
12832       // unspecified or undefined behavior.
12833       if (!IsEquality) {
12834         Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified);
12835         return false;
12836       }
12837       // A constant address may compare equal to the address of a symbol.
12838       // The one exception is that address of an object cannot compare equal
12839       // to a null pointer constant.
12840       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
12841           (!RHSValue.Base && !RHSValue.Offset.isZero()))
12842         return Error(E);
12843       // It's implementation-defined whether distinct literals will have
12844       // distinct addresses. In clang, the result of such a comparison is
12845       // unspecified, so it is not a constant expression. However, we do know
12846       // that the address of a literal will be non-null.
12847       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
12848           LHSValue.Base && RHSValue.Base)
12849         return Error(E);
12850       // We can't tell whether weak symbols will end up pointing to the same
12851       // object.
12852       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
12853         return Error(E);
12854       // We can't compare the address of the start of one object with the
12855       // past-the-end address of another object, per C++ DR1652.
12856       if ((LHSValue.Base && LHSValue.Offset.isZero() &&
12857            isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
12858           (RHSValue.Base && RHSValue.Offset.isZero() &&
12859            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
12860         return Error(E);
12861       // We can't tell whether an object is at the same address as another
12862       // zero sized object.
12863       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
12864           (LHSValue.Base && isZeroSized(RHSValue)))
12865         return Error(E);
12866       return Success(CmpResult::Unequal, E);
12867     }
12868 
12869     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12870     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12871 
12872     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12873     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12874 
12875     // C++11 [expr.rel]p3:
12876     //   Pointers to void (after pointer conversions) can be compared, with a
12877     //   result defined as follows: If both pointers represent the same
12878     //   address or are both the null pointer value, the result is true if the
12879     //   operator is <= or >= and false otherwise; otherwise the result is
12880     //   unspecified.
12881     // We interpret this as applying to pointers to *cv* void.
12882     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
12883       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
12884 
12885     // C++11 [expr.rel]p2:
12886     // - If two pointers point to non-static data members of the same object,
12887     //   or to subobjects or array elements fo such members, recursively, the
12888     //   pointer to the later declared member compares greater provided the
12889     //   two members have the same access control and provided their class is
12890     //   not a union.
12891     //   [...]
12892     // - Otherwise pointer comparisons are unspecified.
12893     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
12894       bool WasArrayIndex;
12895       unsigned Mismatch = FindDesignatorMismatch(
12896           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
12897       // At the point where the designators diverge, the comparison has a
12898       // specified value if:
12899       //  - we are comparing array indices
12900       //  - we are comparing fields of a union, or fields with the same access
12901       // Otherwise, the result is unspecified and thus the comparison is not a
12902       // constant expression.
12903       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
12904           Mismatch < RHSDesignator.Entries.size()) {
12905         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
12906         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
12907         if (!LF && !RF)
12908           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
12909         else if (!LF)
12910           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12911               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
12912               << RF->getParent() << RF;
12913         else if (!RF)
12914           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12915               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
12916               << LF->getParent() << LF;
12917         else if (!LF->getParent()->isUnion() &&
12918                  LF->getAccess() != RF->getAccess())
12919           Info.CCEDiag(E,
12920                        diag::note_constexpr_pointer_comparison_differing_access)
12921               << LF << LF->getAccess() << RF << RF->getAccess()
12922               << LF->getParent();
12923       }
12924     }
12925 
12926     // The comparison here must be unsigned, and performed with the same
12927     // width as the pointer.
12928     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
12929     uint64_t CompareLHS = LHSOffset.getQuantity();
12930     uint64_t CompareRHS = RHSOffset.getQuantity();
12931     assert(PtrSize <= 64 && "Unexpected pointer width");
12932     uint64_t Mask = ~0ULL >> (64 - PtrSize);
12933     CompareLHS &= Mask;
12934     CompareRHS &= Mask;
12935 
12936     // If there is a base and this is a relational operator, we can only
12937     // compare pointers within the object in question; otherwise, the result
12938     // depends on where the object is located in memory.
12939     if (!LHSValue.Base.isNull() && IsRelational) {
12940       QualType BaseTy = getType(LHSValue.Base);
12941       if (BaseTy->isIncompleteType())
12942         return Error(E);
12943       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
12944       uint64_t OffsetLimit = Size.getQuantity();
12945       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
12946         return Error(E);
12947     }
12948 
12949     if (CompareLHS < CompareRHS)
12950       return Success(CmpResult::Less, E);
12951     if (CompareLHS > CompareRHS)
12952       return Success(CmpResult::Greater, E);
12953     return Success(CmpResult::Equal, E);
12954   }
12955 
12956   if (LHSTy->isMemberPointerType()) {
12957     assert(IsEquality && "unexpected member pointer operation");
12958     assert(RHSTy->isMemberPointerType() && "invalid comparison");
12959 
12960     MemberPtr LHSValue, RHSValue;
12961 
12962     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
12963     if (!LHSOK && !Info.noteFailure())
12964       return false;
12965 
12966     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12967       return false;
12968 
12969     // C++11 [expr.eq]p2:
12970     //   If both operands are null, they compare equal. Otherwise if only one is
12971     //   null, they compare unequal.
12972     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
12973       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
12974       return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12975     }
12976 
12977     //   Otherwise if either is a pointer to a virtual member function, the
12978     //   result is unspecified.
12979     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
12980       if (MD->isVirtual())
12981         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12982     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
12983       if (MD->isVirtual())
12984         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12985 
12986     //   Otherwise they compare equal if and only if they would refer to the
12987     //   same member of the same most derived object or the same subobject if
12988     //   they were dereferenced with a hypothetical object of the associated
12989     //   class type.
12990     bool Equal = LHSValue == RHSValue;
12991     return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12992   }
12993 
12994   if (LHSTy->isNullPtrType()) {
12995     assert(E->isComparisonOp() && "unexpected nullptr operation");
12996     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
12997     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
12998     // are compared, the result is true of the operator is <=, >= or ==, and
12999     // false otherwise.
13000     return Success(CmpResult::Equal, E);
13001   }
13002 
13003   return DoAfter();
13004 }
13005 
13006 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
13007   if (!CheckLiteralType(Info, E))
13008     return false;
13009 
13010   auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
13011     ComparisonCategoryResult CCR;
13012     switch (CR) {
13013     case CmpResult::Unequal:
13014       llvm_unreachable("should never produce Unequal for three-way comparison");
13015     case CmpResult::Less:
13016       CCR = ComparisonCategoryResult::Less;
13017       break;
13018     case CmpResult::Equal:
13019       CCR = ComparisonCategoryResult::Equal;
13020       break;
13021     case CmpResult::Greater:
13022       CCR = ComparisonCategoryResult::Greater;
13023       break;
13024     case CmpResult::Unordered:
13025       CCR = ComparisonCategoryResult::Unordered;
13026       break;
13027     }
13028     // Evaluation succeeded. Lookup the information for the comparison category
13029     // type and fetch the VarDecl for the result.
13030     const ComparisonCategoryInfo &CmpInfo =
13031         Info.Ctx.CompCategories.getInfoForType(E->getType());
13032     const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
13033     // Check and evaluate the result as a constant expression.
13034     LValue LV;
13035     LV.set(VD);
13036     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
13037       return false;
13038     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
13039                                    ConstantExprKind::Normal);
13040   };
13041   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
13042     return ExprEvaluatorBaseTy::VisitBinCmp(E);
13043   });
13044 }
13045 
13046 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13047   // We don't support assignment in C. C++ assignments don't get here because
13048   // assignment is an lvalue in C++.
13049   if (E->isAssignmentOp()) {
13050     Error(E);
13051     if (!Info.noteFailure())
13052       return false;
13053   }
13054 
13055   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
13056     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
13057 
13058   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
13059           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
13060          "DataRecursiveIntBinOpEvaluator should have handled integral types");
13061 
13062   if (E->isComparisonOp()) {
13063     // Evaluate builtin binary comparisons by evaluating them as three-way
13064     // comparisons and then translating the result.
13065     auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
13066       assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
13067              "should only produce Unequal for equality comparisons");
13068       bool IsEqual   = CR == CmpResult::Equal,
13069            IsLess    = CR == CmpResult::Less,
13070            IsGreater = CR == CmpResult::Greater;
13071       auto Op = E->getOpcode();
13072       switch (Op) {
13073       default:
13074         llvm_unreachable("unsupported binary operator");
13075       case BO_EQ:
13076       case BO_NE:
13077         return Success(IsEqual == (Op == BO_EQ), E);
13078       case BO_LT:
13079         return Success(IsLess, E);
13080       case BO_GT:
13081         return Success(IsGreater, E);
13082       case BO_LE:
13083         return Success(IsEqual || IsLess, E);
13084       case BO_GE:
13085         return Success(IsEqual || IsGreater, E);
13086       }
13087     };
13088     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
13089       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13090     });
13091   }
13092 
13093   QualType LHSTy = E->getLHS()->getType();
13094   QualType RHSTy = E->getRHS()->getType();
13095 
13096   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
13097       E->getOpcode() == BO_Sub) {
13098     LValue LHSValue, RHSValue;
13099 
13100     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
13101     if (!LHSOK && !Info.noteFailure())
13102       return false;
13103 
13104     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13105       return false;
13106 
13107     // Reject differing bases from the normal codepath; we special-case
13108     // comparisons to null.
13109     if (!HasSameBase(LHSValue, RHSValue)) {
13110       // Handle &&A - &&B.
13111       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
13112         return Error(E);
13113       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
13114       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
13115       if (!LHSExpr || !RHSExpr)
13116         return Error(E);
13117       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
13118       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
13119       if (!LHSAddrExpr || !RHSAddrExpr)
13120         return Error(E);
13121       // Make sure both labels come from the same function.
13122       if (LHSAddrExpr->getLabel()->getDeclContext() !=
13123           RHSAddrExpr->getLabel()->getDeclContext())
13124         return Error(E);
13125       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
13126     }
13127     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
13128     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
13129 
13130     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
13131     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
13132 
13133     // C++11 [expr.add]p6:
13134     //   Unless both pointers point to elements of the same array object, or
13135     //   one past the last element of the array object, the behavior is
13136     //   undefined.
13137     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
13138         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
13139                                 RHSDesignator))
13140       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
13141 
13142     QualType Type = E->getLHS()->getType();
13143     QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
13144 
13145     CharUnits ElementSize;
13146     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
13147       return false;
13148 
13149     // As an extension, a type may have zero size (empty struct or union in
13150     // C, array of zero length). Pointer subtraction in such cases has
13151     // undefined behavior, so is not constant.
13152     if (ElementSize.isZero()) {
13153       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
13154           << ElementType;
13155       return false;
13156     }
13157 
13158     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
13159     // and produce incorrect results when it overflows. Such behavior
13160     // appears to be non-conforming, but is common, so perhaps we should
13161     // assume the standard intended for such cases to be undefined behavior
13162     // and check for them.
13163 
13164     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
13165     // overflow in the final conversion to ptrdiff_t.
13166     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
13167     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
13168     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
13169                     false);
13170     APSInt TrueResult = (LHS - RHS) / ElemSize;
13171     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
13172 
13173     if (Result.extend(65) != TrueResult &&
13174         !HandleOverflow(Info, E, TrueResult, E->getType()))
13175       return false;
13176     return Success(Result, E);
13177   }
13178 
13179   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13180 }
13181 
13182 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
13183 /// a result as the expression's type.
13184 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
13185                                     const UnaryExprOrTypeTraitExpr *E) {
13186   switch(E->getKind()) {
13187   case UETT_PreferredAlignOf:
13188   case UETT_AlignOf: {
13189     if (E->isArgumentType())
13190       return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
13191                      E);
13192     else
13193       return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
13194                      E);
13195   }
13196 
13197   case UETT_VecStep: {
13198     QualType Ty = E->getTypeOfArgument();
13199 
13200     if (Ty->isVectorType()) {
13201       unsigned n = Ty->castAs<VectorType>()->getNumElements();
13202 
13203       // The vec_step built-in functions that take a 3-component
13204       // vector return 4. (OpenCL 1.1 spec 6.11.12)
13205       if (n == 3)
13206         n = 4;
13207 
13208       return Success(n, E);
13209     } else
13210       return Success(1, E);
13211   }
13212 
13213   case UETT_SizeOf: {
13214     QualType SrcTy = E->getTypeOfArgument();
13215     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
13216     //   the result is the size of the referenced type."
13217     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
13218       SrcTy = Ref->getPointeeType();
13219 
13220     CharUnits Sizeof;
13221     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
13222       return false;
13223     return Success(Sizeof, E);
13224   }
13225   case UETT_OpenMPRequiredSimdAlign:
13226     assert(E->isArgumentType());
13227     return Success(
13228         Info.Ctx.toCharUnitsFromBits(
13229                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
13230             .getQuantity(),
13231         E);
13232   }
13233 
13234   llvm_unreachable("unknown expr/type trait");
13235 }
13236 
13237 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
13238   CharUnits Result;
13239   unsigned n = OOE->getNumComponents();
13240   if (n == 0)
13241     return Error(OOE);
13242   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
13243   for (unsigned i = 0; i != n; ++i) {
13244     OffsetOfNode ON = OOE->getComponent(i);
13245     switch (ON.getKind()) {
13246     case OffsetOfNode::Array: {
13247       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
13248       APSInt IdxResult;
13249       if (!EvaluateInteger(Idx, IdxResult, Info))
13250         return false;
13251       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
13252       if (!AT)
13253         return Error(OOE);
13254       CurrentType = AT->getElementType();
13255       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
13256       Result += IdxResult.getSExtValue() * ElementSize;
13257       break;
13258     }
13259 
13260     case OffsetOfNode::Field: {
13261       FieldDecl *MemberDecl = ON.getField();
13262       const RecordType *RT = CurrentType->getAs<RecordType>();
13263       if (!RT)
13264         return Error(OOE);
13265       RecordDecl *RD = RT->getDecl();
13266       if (RD->isInvalidDecl()) return false;
13267       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13268       unsigned i = MemberDecl->getFieldIndex();
13269       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
13270       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
13271       CurrentType = MemberDecl->getType().getNonReferenceType();
13272       break;
13273     }
13274 
13275     case OffsetOfNode::Identifier:
13276       llvm_unreachable("dependent __builtin_offsetof");
13277 
13278     case OffsetOfNode::Base: {
13279       CXXBaseSpecifier *BaseSpec = ON.getBase();
13280       if (BaseSpec->isVirtual())
13281         return Error(OOE);
13282 
13283       // Find the layout of the class whose base we are looking into.
13284       const RecordType *RT = CurrentType->getAs<RecordType>();
13285       if (!RT)
13286         return Error(OOE);
13287       RecordDecl *RD = RT->getDecl();
13288       if (RD->isInvalidDecl()) return false;
13289       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13290 
13291       // Find the base class itself.
13292       CurrentType = BaseSpec->getType();
13293       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
13294       if (!BaseRT)
13295         return Error(OOE);
13296 
13297       // Add the offset to the base.
13298       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
13299       break;
13300     }
13301     }
13302   }
13303   return Success(Result, OOE);
13304 }
13305 
13306 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13307   switch (E->getOpcode()) {
13308   default:
13309     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
13310     // See C99 6.6p3.
13311     return Error(E);
13312   case UO_Extension:
13313     // FIXME: Should extension allow i-c-e extension expressions in its scope?
13314     // If so, we could clear the diagnostic ID.
13315     return Visit(E->getSubExpr());
13316   case UO_Plus:
13317     // The result is just the value.
13318     return Visit(E->getSubExpr());
13319   case UO_Minus: {
13320     if (!Visit(E->getSubExpr()))
13321       return false;
13322     if (!Result.isInt()) return Error(E);
13323     const APSInt &Value = Result.getInt();
13324     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
13325         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
13326                         E->getType()))
13327       return false;
13328     return Success(-Value, E);
13329   }
13330   case UO_Not: {
13331     if (!Visit(E->getSubExpr()))
13332       return false;
13333     if (!Result.isInt()) return Error(E);
13334     return Success(~Result.getInt(), E);
13335   }
13336   case UO_LNot: {
13337     bool bres;
13338     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13339       return false;
13340     return Success(!bres, E);
13341   }
13342   }
13343 }
13344 
13345 /// HandleCast - This is used to evaluate implicit or explicit casts where the
13346 /// result type is integer.
13347 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
13348   const Expr *SubExpr = E->getSubExpr();
13349   QualType DestType = E->getType();
13350   QualType SrcType = SubExpr->getType();
13351 
13352   switch (E->getCastKind()) {
13353   case CK_BaseToDerived:
13354   case CK_DerivedToBase:
13355   case CK_UncheckedDerivedToBase:
13356   case CK_Dynamic:
13357   case CK_ToUnion:
13358   case CK_ArrayToPointerDecay:
13359   case CK_FunctionToPointerDecay:
13360   case CK_NullToPointer:
13361   case CK_NullToMemberPointer:
13362   case CK_BaseToDerivedMemberPointer:
13363   case CK_DerivedToBaseMemberPointer:
13364   case CK_ReinterpretMemberPointer:
13365   case CK_ConstructorConversion:
13366   case CK_IntegralToPointer:
13367   case CK_ToVoid:
13368   case CK_VectorSplat:
13369   case CK_IntegralToFloating:
13370   case CK_FloatingCast:
13371   case CK_CPointerToObjCPointerCast:
13372   case CK_BlockPointerToObjCPointerCast:
13373   case CK_AnyPointerToBlockPointerCast:
13374   case CK_ObjCObjectLValueCast:
13375   case CK_FloatingRealToComplex:
13376   case CK_FloatingComplexToReal:
13377   case CK_FloatingComplexCast:
13378   case CK_FloatingComplexToIntegralComplex:
13379   case CK_IntegralRealToComplex:
13380   case CK_IntegralComplexCast:
13381   case CK_IntegralComplexToFloatingComplex:
13382   case CK_BuiltinFnToFnPtr:
13383   case CK_ZeroToOCLOpaqueType:
13384   case CK_NonAtomicToAtomic:
13385   case CK_AddressSpaceConversion:
13386   case CK_IntToOCLSampler:
13387   case CK_FloatingToFixedPoint:
13388   case CK_FixedPointToFloating:
13389   case CK_FixedPointCast:
13390   case CK_IntegralToFixedPoint:
13391   case CK_MatrixCast:
13392     llvm_unreachable("invalid cast kind for integral value");
13393 
13394   case CK_BitCast:
13395   case CK_Dependent:
13396   case CK_LValueBitCast:
13397   case CK_ARCProduceObject:
13398   case CK_ARCConsumeObject:
13399   case CK_ARCReclaimReturnedObject:
13400   case CK_ARCExtendBlockObject:
13401   case CK_CopyAndAutoreleaseBlockObject:
13402     return Error(E);
13403 
13404   case CK_UserDefinedConversion:
13405   case CK_LValueToRValue:
13406   case CK_AtomicToNonAtomic:
13407   case CK_NoOp:
13408   case CK_LValueToRValueBitCast:
13409     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13410 
13411   case CK_MemberPointerToBoolean:
13412   case CK_PointerToBoolean:
13413   case CK_IntegralToBoolean:
13414   case CK_FloatingToBoolean:
13415   case CK_BooleanToSignedIntegral:
13416   case CK_FloatingComplexToBoolean:
13417   case CK_IntegralComplexToBoolean: {
13418     bool BoolResult;
13419     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
13420       return false;
13421     uint64_t IntResult = BoolResult;
13422     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
13423       IntResult = (uint64_t)-1;
13424     return Success(IntResult, E);
13425   }
13426 
13427   case CK_FixedPointToIntegral: {
13428     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
13429     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13430       return false;
13431     bool Overflowed;
13432     llvm::APSInt Result = Src.convertToInt(
13433         Info.Ctx.getIntWidth(DestType),
13434         DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
13435     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
13436       return false;
13437     return Success(Result, E);
13438   }
13439 
13440   case CK_FixedPointToBoolean: {
13441     // Unsigned padding does not affect this.
13442     APValue Val;
13443     if (!Evaluate(Val, Info, SubExpr))
13444       return false;
13445     return Success(Val.getFixedPoint().getBoolValue(), E);
13446   }
13447 
13448   case CK_IntegralCast: {
13449     if (!Visit(SubExpr))
13450       return false;
13451 
13452     if (!Result.isInt()) {
13453       // Allow casts of address-of-label differences if they are no-ops
13454       // or narrowing.  (The narrowing case isn't actually guaranteed to
13455       // be constant-evaluatable except in some narrow cases which are hard
13456       // to detect here.  We let it through on the assumption the user knows
13457       // what they are doing.)
13458       if (Result.isAddrLabelDiff())
13459         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
13460       // Only allow casts of lvalues if they are lossless.
13461       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
13462     }
13463 
13464     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
13465                                       Result.getInt()), E);
13466   }
13467 
13468   case CK_PointerToIntegral: {
13469     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
13470 
13471     LValue LV;
13472     if (!EvaluatePointer(SubExpr, LV, Info))
13473       return false;
13474 
13475     if (LV.getLValueBase()) {
13476       // Only allow based lvalue casts if they are lossless.
13477       // FIXME: Allow a larger integer size than the pointer size, and allow
13478       // narrowing back down to pointer width in subsequent integral casts.
13479       // FIXME: Check integer type's active bits, not its type size.
13480       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
13481         return Error(E);
13482 
13483       LV.Designator.setInvalid();
13484       LV.moveInto(Result);
13485       return true;
13486     }
13487 
13488     APSInt AsInt;
13489     APValue V;
13490     LV.moveInto(V);
13491     if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
13492       llvm_unreachable("Can't cast this!");
13493 
13494     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
13495   }
13496 
13497   case CK_IntegralComplexToReal: {
13498     ComplexValue C;
13499     if (!EvaluateComplex(SubExpr, C, Info))
13500       return false;
13501     return Success(C.getComplexIntReal(), E);
13502   }
13503 
13504   case CK_FloatingToIntegral: {
13505     APFloat F(0.0);
13506     if (!EvaluateFloat(SubExpr, F, Info))
13507       return false;
13508 
13509     APSInt Value;
13510     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
13511       return false;
13512     return Success(Value, E);
13513   }
13514   }
13515 
13516   llvm_unreachable("unknown cast resulting in integral value");
13517 }
13518 
13519 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13520   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13521     ComplexValue LV;
13522     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13523       return false;
13524     if (!LV.isComplexInt())
13525       return Error(E);
13526     return Success(LV.getComplexIntReal(), E);
13527   }
13528 
13529   return Visit(E->getSubExpr());
13530 }
13531 
13532 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13533   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
13534     ComplexValue LV;
13535     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13536       return false;
13537     if (!LV.isComplexInt())
13538       return Error(E);
13539     return Success(LV.getComplexIntImag(), E);
13540   }
13541 
13542   VisitIgnoredValue(E->getSubExpr());
13543   return Success(0, E);
13544 }
13545 
13546 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
13547   return Success(E->getPackLength(), E);
13548 }
13549 
13550 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
13551   return Success(E->getValue(), E);
13552 }
13553 
13554 bool IntExprEvaluator::VisitConceptSpecializationExpr(
13555        const ConceptSpecializationExpr *E) {
13556   return Success(E->isSatisfied(), E);
13557 }
13558 
13559 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
13560   return Success(E->isSatisfied(), E);
13561 }
13562 
13563 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13564   switch (E->getOpcode()) {
13565     default:
13566       // Invalid unary operators
13567       return Error(E);
13568     case UO_Plus:
13569       // The result is just the value.
13570       return Visit(E->getSubExpr());
13571     case UO_Minus: {
13572       if (!Visit(E->getSubExpr())) return false;
13573       if (!Result.isFixedPoint())
13574         return Error(E);
13575       bool Overflowed;
13576       APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
13577       if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
13578         return false;
13579       return Success(Negated, E);
13580     }
13581     case UO_LNot: {
13582       bool bres;
13583       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13584         return false;
13585       return Success(!bres, E);
13586     }
13587   }
13588 }
13589 
13590 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
13591   const Expr *SubExpr = E->getSubExpr();
13592   QualType DestType = E->getType();
13593   assert(DestType->isFixedPointType() &&
13594          "Expected destination type to be a fixed point type");
13595   auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
13596 
13597   switch (E->getCastKind()) {
13598   case CK_FixedPointCast: {
13599     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13600     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13601       return false;
13602     bool Overflowed;
13603     APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
13604     if (Overflowed) {
13605       if (Info.checkingForUndefinedBehavior())
13606         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13607                                          diag::warn_fixedpoint_constant_overflow)
13608           << Result.toString() << E->getType();
13609       if (!HandleOverflow(Info, E, Result, E->getType()))
13610         return false;
13611     }
13612     return Success(Result, E);
13613   }
13614   case CK_IntegralToFixedPoint: {
13615     APSInt Src;
13616     if (!EvaluateInteger(SubExpr, Src, Info))
13617       return false;
13618 
13619     bool Overflowed;
13620     APFixedPoint IntResult = APFixedPoint::getFromIntValue(
13621         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13622 
13623     if (Overflowed) {
13624       if (Info.checkingForUndefinedBehavior())
13625         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13626                                          diag::warn_fixedpoint_constant_overflow)
13627           << IntResult.toString() << E->getType();
13628       if (!HandleOverflow(Info, E, IntResult, E->getType()))
13629         return false;
13630     }
13631 
13632     return Success(IntResult, E);
13633   }
13634   case CK_FloatingToFixedPoint: {
13635     APFloat Src(0.0);
13636     if (!EvaluateFloat(SubExpr, Src, Info))
13637       return false;
13638 
13639     bool Overflowed;
13640     APFixedPoint Result = APFixedPoint::getFromFloatValue(
13641         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13642 
13643     if (Overflowed) {
13644       if (Info.checkingForUndefinedBehavior())
13645         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13646                                          diag::warn_fixedpoint_constant_overflow)
13647           << Result.toString() << E->getType();
13648       if (!HandleOverflow(Info, E, Result, E->getType()))
13649         return false;
13650     }
13651 
13652     return Success(Result, E);
13653   }
13654   case CK_NoOp:
13655   case CK_LValueToRValue:
13656     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13657   default:
13658     return Error(E);
13659   }
13660 }
13661 
13662 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13663   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13664     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13665 
13666   const Expr *LHS = E->getLHS();
13667   const Expr *RHS = E->getRHS();
13668   FixedPointSemantics ResultFXSema =
13669       Info.Ctx.getFixedPointSemantics(E->getType());
13670 
13671   APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
13672   if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
13673     return false;
13674   APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
13675   if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
13676     return false;
13677 
13678   bool OpOverflow = false, ConversionOverflow = false;
13679   APFixedPoint Result(LHSFX.getSemantics());
13680   switch (E->getOpcode()) {
13681   case BO_Add: {
13682     Result = LHSFX.add(RHSFX, &OpOverflow)
13683                   .convert(ResultFXSema, &ConversionOverflow);
13684     break;
13685   }
13686   case BO_Sub: {
13687     Result = LHSFX.sub(RHSFX, &OpOverflow)
13688                   .convert(ResultFXSema, &ConversionOverflow);
13689     break;
13690   }
13691   case BO_Mul: {
13692     Result = LHSFX.mul(RHSFX, &OpOverflow)
13693                   .convert(ResultFXSema, &ConversionOverflow);
13694     break;
13695   }
13696   case BO_Div: {
13697     if (RHSFX.getValue() == 0) {
13698       Info.FFDiag(E, diag::note_expr_divide_by_zero);
13699       return false;
13700     }
13701     Result = LHSFX.div(RHSFX, &OpOverflow)
13702                   .convert(ResultFXSema, &ConversionOverflow);
13703     break;
13704   }
13705   case BO_Shl:
13706   case BO_Shr: {
13707     FixedPointSemantics LHSSema = LHSFX.getSemantics();
13708     llvm::APSInt RHSVal = RHSFX.getValue();
13709 
13710     unsigned ShiftBW =
13711         LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
13712     unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
13713     // Embedded-C 4.1.6.2.2:
13714     //   The right operand must be nonnegative and less than the total number
13715     //   of (nonpadding) bits of the fixed-point operand ...
13716     if (RHSVal.isNegative())
13717       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
13718     else if (Amt != RHSVal)
13719       Info.CCEDiag(E, diag::note_constexpr_large_shift)
13720           << RHSVal << E->getType() << ShiftBW;
13721 
13722     if (E->getOpcode() == BO_Shl)
13723       Result = LHSFX.shl(Amt, &OpOverflow);
13724     else
13725       Result = LHSFX.shr(Amt, &OpOverflow);
13726     break;
13727   }
13728   default:
13729     return false;
13730   }
13731   if (OpOverflow || ConversionOverflow) {
13732     if (Info.checkingForUndefinedBehavior())
13733       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13734                                        diag::warn_fixedpoint_constant_overflow)
13735         << Result.toString() << E->getType();
13736     if (!HandleOverflow(Info, E, Result, E->getType()))
13737       return false;
13738   }
13739   return Success(Result, E);
13740 }
13741 
13742 //===----------------------------------------------------------------------===//
13743 // Float Evaluation
13744 //===----------------------------------------------------------------------===//
13745 
13746 namespace {
13747 class FloatExprEvaluator
13748   : public ExprEvaluatorBase<FloatExprEvaluator> {
13749   APFloat &Result;
13750 public:
13751   FloatExprEvaluator(EvalInfo &info, APFloat &result)
13752     : ExprEvaluatorBaseTy(info), Result(result) {}
13753 
13754   bool Success(const APValue &V, const Expr *e) {
13755     Result = V.getFloat();
13756     return true;
13757   }
13758 
13759   bool ZeroInitialization(const Expr *E) {
13760     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
13761     return true;
13762   }
13763 
13764   bool VisitCallExpr(const CallExpr *E);
13765 
13766   bool VisitUnaryOperator(const UnaryOperator *E);
13767   bool VisitBinaryOperator(const BinaryOperator *E);
13768   bool VisitFloatingLiteral(const FloatingLiteral *E);
13769   bool VisitCastExpr(const CastExpr *E);
13770 
13771   bool VisitUnaryReal(const UnaryOperator *E);
13772   bool VisitUnaryImag(const UnaryOperator *E);
13773 
13774   // FIXME: Missing: array subscript of vector, member of vector
13775 };
13776 } // end anonymous namespace
13777 
13778 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
13779   assert(!E->isValueDependent());
13780   assert(E->isPRValue() && E->getType()->isRealFloatingType());
13781   return FloatExprEvaluator(Info, Result).Visit(E);
13782 }
13783 
13784 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
13785                                   QualType ResultTy,
13786                                   const Expr *Arg,
13787                                   bool SNaN,
13788                                   llvm::APFloat &Result) {
13789   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
13790   if (!S) return false;
13791 
13792   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
13793 
13794   llvm::APInt fill;
13795 
13796   // Treat empty strings as if they were zero.
13797   if (S->getString().empty())
13798     fill = llvm::APInt(32, 0);
13799   else if (S->getString().getAsInteger(0, fill))
13800     return false;
13801 
13802   if (Context.getTargetInfo().isNan2008()) {
13803     if (SNaN)
13804       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13805     else
13806       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13807   } else {
13808     // Prior to IEEE 754-2008, architectures were allowed to choose whether
13809     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
13810     // a different encoding to what became a standard in 2008, and for pre-
13811     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
13812     // sNaN. This is now known as "legacy NaN" encoding.
13813     if (SNaN)
13814       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13815     else
13816       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13817   }
13818 
13819   return true;
13820 }
13821 
13822 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
13823   switch (E->getBuiltinCallee()) {
13824   default:
13825     return ExprEvaluatorBaseTy::VisitCallExpr(E);
13826 
13827   case Builtin::BI__builtin_huge_val:
13828   case Builtin::BI__builtin_huge_valf:
13829   case Builtin::BI__builtin_huge_vall:
13830   case Builtin::BI__builtin_huge_valf128:
13831   case Builtin::BI__builtin_inf:
13832   case Builtin::BI__builtin_inff:
13833   case Builtin::BI__builtin_infl:
13834   case Builtin::BI__builtin_inff128: {
13835     const llvm::fltSemantics &Sem =
13836       Info.Ctx.getFloatTypeSemantics(E->getType());
13837     Result = llvm::APFloat::getInf(Sem);
13838     return true;
13839   }
13840 
13841   case Builtin::BI__builtin_nans:
13842   case Builtin::BI__builtin_nansf:
13843   case Builtin::BI__builtin_nansl:
13844   case Builtin::BI__builtin_nansf128:
13845     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13846                                true, Result))
13847       return Error(E);
13848     return true;
13849 
13850   case Builtin::BI__builtin_nan:
13851   case Builtin::BI__builtin_nanf:
13852   case Builtin::BI__builtin_nanl:
13853   case Builtin::BI__builtin_nanf128:
13854     // If this is __builtin_nan() turn this into a nan, otherwise we
13855     // can't constant fold it.
13856     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13857                                false, Result))
13858       return Error(E);
13859     return true;
13860 
13861   case Builtin::BI__builtin_fabs:
13862   case Builtin::BI__builtin_fabsf:
13863   case Builtin::BI__builtin_fabsl:
13864   case Builtin::BI__builtin_fabsf128:
13865     // The C standard says "fabs raises no floating-point exceptions,
13866     // even if x is a signaling NaN. The returned value is independent of
13867     // the current rounding direction mode."  Therefore constant folding can
13868     // proceed without regard to the floating point settings.
13869     // Reference, WG14 N2478 F.10.4.3
13870     if (!EvaluateFloat(E->getArg(0), Result, Info))
13871       return false;
13872 
13873     if (Result.isNegative())
13874       Result.changeSign();
13875     return true;
13876 
13877   case Builtin::BI__arithmetic_fence:
13878     return EvaluateFloat(E->getArg(0), Result, Info);
13879 
13880   // FIXME: Builtin::BI__builtin_powi
13881   // FIXME: Builtin::BI__builtin_powif
13882   // FIXME: Builtin::BI__builtin_powil
13883 
13884   case Builtin::BI__builtin_copysign:
13885   case Builtin::BI__builtin_copysignf:
13886   case Builtin::BI__builtin_copysignl:
13887   case Builtin::BI__builtin_copysignf128: {
13888     APFloat RHS(0.);
13889     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
13890         !EvaluateFloat(E->getArg(1), RHS, Info))
13891       return false;
13892     Result.copySign(RHS);
13893     return true;
13894   }
13895   }
13896 }
13897 
13898 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13899   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13900     ComplexValue CV;
13901     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13902       return false;
13903     Result = CV.FloatReal;
13904     return true;
13905   }
13906 
13907   return Visit(E->getSubExpr());
13908 }
13909 
13910 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13911   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13912     ComplexValue CV;
13913     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13914       return false;
13915     Result = CV.FloatImag;
13916     return true;
13917   }
13918 
13919   VisitIgnoredValue(E->getSubExpr());
13920   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
13921   Result = llvm::APFloat::getZero(Sem);
13922   return true;
13923 }
13924 
13925 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13926   switch (E->getOpcode()) {
13927   default: return Error(E);
13928   case UO_Plus:
13929     return EvaluateFloat(E->getSubExpr(), Result, Info);
13930   case UO_Minus:
13931     // In C standard, WG14 N2478 F.3 p4
13932     // "the unary - raises no floating point exceptions,
13933     // even if the operand is signalling."
13934     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
13935       return false;
13936     Result.changeSign();
13937     return true;
13938   }
13939 }
13940 
13941 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13942   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13943     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13944 
13945   APFloat RHS(0.0);
13946   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
13947   if (!LHSOK && !Info.noteFailure())
13948     return false;
13949   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
13950          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
13951 }
13952 
13953 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
13954   Result = E->getValue();
13955   return true;
13956 }
13957 
13958 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
13959   const Expr* SubExpr = E->getSubExpr();
13960 
13961   switch (E->getCastKind()) {
13962   default:
13963     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13964 
13965   case CK_IntegralToFloating: {
13966     APSInt IntResult;
13967     const FPOptions FPO = E->getFPFeaturesInEffect(
13968                                   Info.Ctx.getLangOpts());
13969     return EvaluateInteger(SubExpr, IntResult, Info) &&
13970            HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
13971                                 IntResult, E->getType(), Result);
13972   }
13973 
13974   case CK_FixedPointToFloating: {
13975     APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13976     if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
13977       return false;
13978     Result =
13979         FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
13980     return true;
13981   }
13982 
13983   case CK_FloatingCast: {
13984     if (!Visit(SubExpr))
13985       return false;
13986     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
13987                                   Result);
13988   }
13989 
13990   case CK_FloatingComplexToReal: {
13991     ComplexValue V;
13992     if (!EvaluateComplex(SubExpr, V, Info))
13993       return false;
13994     Result = V.getComplexFloatReal();
13995     return true;
13996   }
13997   }
13998 }
13999 
14000 //===----------------------------------------------------------------------===//
14001 // Complex Evaluation (for float and integer)
14002 //===----------------------------------------------------------------------===//
14003 
14004 namespace {
14005 class ComplexExprEvaluator
14006   : public ExprEvaluatorBase<ComplexExprEvaluator> {
14007   ComplexValue &Result;
14008 
14009 public:
14010   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
14011     : ExprEvaluatorBaseTy(info), Result(Result) {}
14012 
14013   bool Success(const APValue &V, const Expr *e) {
14014     Result.setFrom(V);
14015     return true;
14016   }
14017 
14018   bool ZeroInitialization(const Expr *E);
14019 
14020   //===--------------------------------------------------------------------===//
14021   //                            Visitor Methods
14022   //===--------------------------------------------------------------------===//
14023 
14024   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
14025   bool VisitCastExpr(const CastExpr *E);
14026   bool VisitBinaryOperator(const BinaryOperator *E);
14027   bool VisitUnaryOperator(const UnaryOperator *E);
14028   bool VisitInitListExpr(const InitListExpr *E);
14029   bool VisitCallExpr(const CallExpr *E);
14030 };
14031 } // end anonymous namespace
14032 
14033 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
14034                             EvalInfo &Info) {
14035   assert(!E->isValueDependent());
14036   assert(E->isPRValue() && E->getType()->isAnyComplexType());
14037   return ComplexExprEvaluator(Info, Result).Visit(E);
14038 }
14039 
14040 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
14041   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
14042   if (ElemTy->isRealFloatingType()) {
14043     Result.makeComplexFloat();
14044     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
14045     Result.FloatReal = Zero;
14046     Result.FloatImag = Zero;
14047   } else {
14048     Result.makeComplexInt();
14049     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
14050     Result.IntReal = Zero;
14051     Result.IntImag = Zero;
14052   }
14053   return true;
14054 }
14055 
14056 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
14057   const Expr* SubExpr = E->getSubExpr();
14058 
14059   if (SubExpr->getType()->isRealFloatingType()) {
14060     Result.makeComplexFloat();
14061     APFloat &Imag = Result.FloatImag;
14062     if (!EvaluateFloat(SubExpr, Imag, Info))
14063       return false;
14064 
14065     Result.FloatReal = APFloat(Imag.getSemantics());
14066     return true;
14067   } else {
14068     assert(SubExpr->getType()->isIntegerType() &&
14069            "Unexpected imaginary literal.");
14070 
14071     Result.makeComplexInt();
14072     APSInt &Imag = Result.IntImag;
14073     if (!EvaluateInteger(SubExpr, Imag, Info))
14074       return false;
14075 
14076     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
14077     return true;
14078   }
14079 }
14080 
14081 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
14082 
14083   switch (E->getCastKind()) {
14084   case CK_BitCast:
14085   case CK_BaseToDerived:
14086   case CK_DerivedToBase:
14087   case CK_UncheckedDerivedToBase:
14088   case CK_Dynamic:
14089   case CK_ToUnion:
14090   case CK_ArrayToPointerDecay:
14091   case CK_FunctionToPointerDecay:
14092   case CK_NullToPointer:
14093   case CK_NullToMemberPointer:
14094   case CK_BaseToDerivedMemberPointer:
14095   case CK_DerivedToBaseMemberPointer:
14096   case CK_MemberPointerToBoolean:
14097   case CK_ReinterpretMemberPointer:
14098   case CK_ConstructorConversion:
14099   case CK_IntegralToPointer:
14100   case CK_PointerToIntegral:
14101   case CK_PointerToBoolean:
14102   case CK_ToVoid:
14103   case CK_VectorSplat:
14104   case CK_IntegralCast:
14105   case CK_BooleanToSignedIntegral:
14106   case CK_IntegralToBoolean:
14107   case CK_IntegralToFloating:
14108   case CK_FloatingToIntegral:
14109   case CK_FloatingToBoolean:
14110   case CK_FloatingCast:
14111   case CK_CPointerToObjCPointerCast:
14112   case CK_BlockPointerToObjCPointerCast:
14113   case CK_AnyPointerToBlockPointerCast:
14114   case CK_ObjCObjectLValueCast:
14115   case CK_FloatingComplexToReal:
14116   case CK_FloatingComplexToBoolean:
14117   case CK_IntegralComplexToReal:
14118   case CK_IntegralComplexToBoolean:
14119   case CK_ARCProduceObject:
14120   case CK_ARCConsumeObject:
14121   case CK_ARCReclaimReturnedObject:
14122   case CK_ARCExtendBlockObject:
14123   case CK_CopyAndAutoreleaseBlockObject:
14124   case CK_BuiltinFnToFnPtr:
14125   case CK_ZeroToOCLOpaqueType:
14126   case CK_NonAtomicToAtomic:
14127   case CK_AddressSpaceConversion:
14128   case CK_IntToOCLSampler:
14129   case CK_FloatingToFixedPoint:
14130   case CK_FixedPointToFloating:
14131   case CK_FixedPointCast:
14132   case CK_FixedPointToBoolean:
14133   case CK_FixedPointToIntegral:
14134   case CK_IntegralToFixedPoint:
14135   case CK_MatrixCast:
14136     llvm_unreachable("invalid cast kind for complex value");
14137 
14138   case CK_LValueToRValue:
14139   case CK_AtomicToNonAtomic:
14140   case CK_NoOp:
14141   case CK_LValueToRValueBitCast:
14142     return ExprEvaluatorBaseTy::VisitCastExpr(E);
14143 
14144   case CK_Dependent:
14145   case CK_LValueBitCast:
14146   case CK_UserDefinedConversion:
14147     return Error(E);
14148 
14149   case CK_FloatingRealToComplex: {
14150     APFloat &Real = Result.FloatReal;
14151     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
14152       return false;
14153 
14154     Result.makeComplexFloat();
14155     Result.FloatImag = APFloat(Real.getSemantics());
14156     return true;
14157   }
14158 
14159   case CK_FloatingComplexCast: {
14160     if (!Visit(E->getSubExpr()))
14161       return false;
14162 
14163     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14164     QualType From
14165       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14166 
14167     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
14168            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
14169   }
14170 
14171   case CK_FloatingComplexToIntegralComplex: {
14172     if (!Visit(E->getSubExpr()))
14173       return false;
14174 
14175     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14176     QualType From
14177       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14178     Result.makeComplexInt();
14179     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
14180                                 To, Result.IntReal) &&
14181            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
14182                                 To, Result.IntImag);
14183   }
14184 
14185   case CK_IntegralRealToComplex: {
14186     APSInt &Real = Result.IntReal;
14187     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
14188       return false;
14189 
14190     Result.makeComplexInt();
14191     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
14192     return true;
14193   }
14194 
14195   case CK_IntegralComplexCast: {
14196     if (!Visit(E->getSubExpr()))
14197       return false;
14198 
14199     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14200     QualType From
14201       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14202 
14203     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
14204     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
14205     return true;
14206   }
14207 
14208   case CK_IntegralComplexToFloatingComplex: {
14209     if (!Visit(E->getSubExpr()))
14210       return false;
14211 
14212     const FPOptions FPO = E->getFPFeaturesInEffect(
14213                                   Info.Ctx.getLangOpts());
14214     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14215     QualType From
14216       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14217     Result.makeComplexFloat();
14218     return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
14219                                 To, Result.FloatReal) &&
14220            HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
14221                                 To, Result.FloatImag);
14222   }
14223   }
14224 
14225   llvm_unreachable("unknown cast resulting in complex value");
14226 }
14227 
14228 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14229   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14230     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14231 
14232   // Track whether the LHS or RHS is real at the type system level. When this is
14233   // the case we can simplify our evaluation strategy.
14234   bool LHSReal = false, RHSReal = false;
14235 
14236   bool LHSOK;
14237   if (E->getLHS()->getType()->isRealFloatingType()) {
14238     LHSReal = true;
14239     APFloat &Real = Result.FloatReal;
14240     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
14241     if (LHSOK) {
14242       Result.makeComplexFloat();
14243       Result.FloatImag = APFloat(Real.getSemantics());
14244     }
14245   } else {
14246     LHSOK = Visit(E->getLHS());
14247   }
14248   if (!LHSOK && !Info.noteFailure())
14249     return false;
14250 
14251   ComplexValue RHS;
14252   if (E->getRHS()->getType()->isRealFloatingType()) {
14253     RHSReal = true;
14254     APFloat &Real = RHS.FloatReal;
14255     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
14256       return false;
14257     RHS.makeComplexFloat();
14258     RHS.FloatImag = APFloat(Real.getSemantics());
14259   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
14260     return false;
14261 
14262   assert(!(LHSReal && RHSReal) &&
14263          "Cannot have both operands of a complex operation be real.");
14264   switch (E->getOpcode()) {
14265   default: return Error(E);
14266   case BO_Add:
14267     if (Result.isComplexFloat()) {
14268       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
14269                                        APFloat::rmNearestTiesToEven);
14270       if (LHSReal)
14271         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14272       else if (!RHSReal)
14273         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
14274                                          APFloat::rmNearestTiesToEven);
14275     } else {
14276       Result.getComplexIntReal() += RHS.getComplexIntReal();
14277       Result.getComplexIntImag() += RHS.getComplexIntImag();
14278     }
14279     break;
14280   case BO_Sub:
14281     if (Result.isComplexFloat()) {
14282       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
14283                                             APFloat::rmNearestTiesToEven);
14284       if (LHSReal) {
14285         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14286         Result.getComplexFloatImag().changeSign();
14287       } else if (!RHSReal) {
14288         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
14289                                               APFloat::rmNearestTiesToEven);
14290       }
14291     } else {
14292       Result.getComplexIntReal() -= RHS.getComplexIntReal();
14293       Result.getComplexIntImag() -= RHS.getComplexIntImag();
14294     }
14295     break;
14296   case BO_Mul:
14297     if (Result.isComplexFloat()) {
14298       // This is an implementation of complex multiplication according to the
14299       // constraints laid out in C11 Annex G. The implementation uses the
14300       // following naming scheme:
14301       //   (a + ib) * (c + id)
14302       ComplexValue LHS = Result;
14303       APFloat &A = LHS.getComplexFloatReal();
14304       APFloat &B = LHS.getComplexFloatImag();
14305       APFloat &C = RHS.getComplexFloatReal();
14306       APFloat &D = RHS.getComplexFloatImag();
14307       APFloat &ResR = Result.getComplexFloatReal();
14308       APFloat &ResI = Result.getComplexFloatImag();
14309       if (LHSReal) {
14310         assert(!RHSReal && "Cannot have two real operands for a complex op!");
14311         ResR = A * C;
14312         ResI = A * D;
14313       } else if (RHSReal) {
14314         ResR = C * A;
14315         ResI = C * B;
14316       } else {
14317         // In the fully general case, we need to handle NaNs and infinities
14318         // robustly.
14319         APFloat AC = A * C;
14320         APFloat BD = B * D;
14321         APFloat AD = A * D;
14322         APFloat BC = B * C;
14323         ResR = AC - BD;
14324         ResI = AD + BC;
14325         if (ResR.isNaN() && ResI.isNaN()) {
14326           bool Recalc = false;
14327           if (A.isInfinity() || B.isInfinity()) {
14328             A = APFloat::copySign(
14329                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14330             B = APFloat::copySign(
14331                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14332             if (C.isNaN())
14333               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14334             if (D.isNaN())
14335               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14336             Recalc = true;
14337           }
14338           if (C.isInfinity() || D.isInfinity()) {
14339             C = APFloat::copySign(
14340                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14341             D = APFloat::copySign(
14342                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14343             if (A.isNaN())
14344               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14345             if (B.isNaN())
14346               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14347             Recalc = true;
14348           }
14349           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
14350                           AD.isInfinity() || BC.isInfinity())) {
14351             if (A.isNaN())
14352               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14353             if (B.isNaN())
14354               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14355             if (C.isNaN())
14356               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14357             if (D.isNaN())
14358               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14359             Recalc = true;
14360           }
14361           if (Recalc) {
14362             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
14363             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
14364           }
14365         }
14366       }
14367     } else {
14368       ComplexValue LHS = Result;
14369       Result.getComplexIntReal() =
14370         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
14371          LHS.getComplexIntImag() * RHS.getComplexIntImag());
14372       Result.getComplexIntImag() =
14373         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
14374          LHS.getComplexIntImag() * RHS.getComplexIntReal());
14375     }
14376     break;
14377   case BO_Div:
14378     if (Result.isComplexFloat()) {
14379       // This is an implementation of complex division according to the
14380       // constraints laid out in C11 Annex G. The implementation uses the
14381       // following naming scheme:
14382       //   (a + ib) / (c + id)
14383       ComplexValue LHS = Result;
14384       APFloat &A = LHS.getComplexFloatReal();
14385       APFloat &B = LHS.getComplexFloatImag();
14386       APFloat &C = RHS.getComplexFloatReal();
14387       APFloat &D = RHS.getComplexFloatImag();
14388       APFloat &ResR = Result.getComplexFloatReal();
14389       APFloat &ResI = Result.getComplexFloatImag();
14390       if (RHSReal) {
14391         ResR = A / C;
14392         ResI = B / C;
14393       } else {
14394         if (LHSReal) {
14395           // No real optimizations we can do here, stub out with zero.
14396           B = APFloat::getZero(A.getSemantics());
14397         }
14398         int DenomLogB = 0;
14399         APFloat MaxCD = maxnum(abs(C), abs(D));
14400         if (MaxCD.isFinite()) {
14401           DenomLogB = ilogb(MaxCD);
14402           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
14403           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
14404         }
14405         APFloat Denom = C * C + D * D;
14406         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
14407                       APFloat::rmNearestTiesToEven);
14408         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
14409                       APFloat::rmNearestTiesToEven);
14410         if (ResR.isNaN() && ResI.isNaN()) {
14411           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
14412             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
14413             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
14414           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
14415                      D.isFinite()) {
14416             A = APFloat::copySign(
14417                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14418             B = APFloat::copySign(
14419                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14420             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
14421             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
14422           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
14423             C = APFloat::copySign(
14424                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14425             D = APFloat::copySign(
14426                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14427             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
14428             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
14429           }
14430         }
14431       }
14432     } else {
14433       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
14434         return Error(E, diag::note_expr_divide_by_zero);
14435 
14436       ComplexValue LHS = Result;
14437       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
14438         RHS.getComplexIntImag() * RHS.getComplexIntImag();
14439       Result.getComplexIntReal() =
14440         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
14441          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
14442       Result.getComplexIntImag() =
14443         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
14444          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
14445     }
14446     break;
14447   }
14448 
14449   return true;
14450 }
14451 
14452 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14453   // Get the operand value into 'Result'.
14454   if (!Visit(E->getSubExpr()))
14455     return false;
14456 
14457   switch (E->getOpcode()) {
14458   default:
14459     return Error(E);
14460   case UO_Extension:
14461     return true;
14462   case UO_Plus:
14463     // The result is always just the subexpr.
14464     return true;
14465   case UO_Minus:
14466     if (Result.isComplexFloat()) {
14467       Result.getComplexFloatReal().changeSign();
14468       Result.getComplexFloatImag().changeSign();
14469     }
14470     else {
14471       Result.getComplexIntReal() = -Result.getComplexIntReal();
14472       Result.getComplexIntImag() = -Result.getComplexIntImag();
14473     }
14474     return true;
14475   case UO_Not:
14476     if (Result.isComplexFloat())
14477       Result.getComplexFloatImag().changeSign();
14478     else
14479       Result.getComplexIntImag() = -Result.getComplexIntImag();
14480     return true;
14481   }
14482 }
14483 
14484 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
14485   if (E->getNumInits() == 2) {
14486     if (E->getType()->isComplexType()) {
14487       Result.makeComplexFloat();
14488       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
14489         return false;
14490       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
14491         return false;
14492     } else {
14493       Result.makeComplexInt();
14494       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
14495         return false;
14496       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
14497         return false;
14498     }
14499     return true;
14500   }
14501   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
14502 }
14503 
14504 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
14505   switch (E->getBuiltinCallee()) {
14506   case Builtin::BI__builtin_complex:
14507     Result.makeComplexFloat();
14508     if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
14509       return false;
14510     if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
14511       return false;
14512     return true;
14513 
14514   default:
14515     break;
14516   }
14517 
14518   return ExprEvaluatorBaseTy::VisitCallExpr(E);
14519 }
14520 
14521 //===----------------------------------------------------------------------===//
14522 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
14523 // implicit conversion.
14524 //===----------------------------------------------------------------------===//
14525 
14526 namespace {
14527 class AtomicExprEvaluator :
14528     public ExprEvaluatorBase<AtomicExprEvaluator> {
14529   const LValue *This;
14530   APValue &Result;
14531 public:
14532   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
14533       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
14534 
14535   bool Success(const APValue &V, const Expr *E) {
14536     Result = V;
14537     return true;
14538   }
14539 
14540   bool ZeroInitialization(const Expr *E) {
14541     ImplicitValueInitExpr VIE(
14542         E->getType()->castAs<AtomicType>()->getValueType());
14543     // For atomic-qualified class (and array) types in C++, initialize the
14544     // _Atomic-wrapped subobject directly, in-place.
14545     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
14546                 : Evaluate(Result, Info, &VIE);
14547   }
14548 
14549   bool VisitCastExpr(const CastExpr *E) {
14550     switch (E->getCastKind()) {
14551     default:
14552       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14553     case CK_NonAtomicToAtomic:
14554       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
14555                   : Evaluate(Result, Info, E->getSubExpr());
14556     }
14557   }
14558 };
14559 } // end anonymous namespace
14560 
14561 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
14562                            EvalInfo &Info) {
14563   assert(!E->isValueDependent());
14564   assert(E->isPRValue() && E->getType()->isAtomicType());
14565   return AtomicExprEvaluator(Info, This, Result).Visit(E);
14566 }
14567 
14568 //===----------------------------------------------------------------------===//
14569 // Void expression evaluation, primarily for a cast to void on the LHS of a
14570 // comma operator
14571 //===----------------------------------------------------------------------===//
14572 
14573 namespace {
14574 class VoidExprEvaluator
14575   : public ExprEvaluatorBase<VoidExprEvaluator> {
14576 public:
14577   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
14578 
14579   bool Success(const APValue &V, const Expr *e) { return true; }
14580 
14581   bool ZeroInitialization(const Expr *E) { return true; }
14582 
14583   bool VisitCastExpr(const CastExpr *E) {
14584     switch (E->getCastKind()) {
14585     default:
14586       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14587     case CK_ToVoid:
14588       VisitIgnoredValue(E->getSubExpr());
14589       return true;
14590     }
14591   }
14592 
14593   bool VisitCallExpr(const CallExpr *E) {
14594     switch (E->getBuiltinCallee()) {
14595     case Builtin::BI__assume:
14596     case Builtin::BI__builtin_assume:
14597       // The argument is not evaluated!
14598       return true;
14599 
14600     case Builtin::BI__builtin_operator_delete:
14601       return HandleOperatorDeleteCall(Info, E);
14602 
14603     default:
14604       break;
14605     }
14606 
14607     return ExprEvaluatorBaseTy::VisitCallExpr(E);
14608   }
14609 
14610   bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
14611 };
14612 } // end anonymous namespace
14613 
14614 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
14615   // We cannot speculatively evaluate a delete expression.
14616   if (Info.SpeculativeEvaluationDepth)
14617     return false;
14618 
14619   FunctionDecl *OperatorDelete = E->getOperatorDelete();
14620   if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
14621     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14622         << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
14623     return false;
14624   }
14625 
14626   const Expr *Arg = E->getArgument();
14627 
14628   LValue Pointer;
14629   if (!EvaluatePointer(Arg, Pointer, Info))
14630     return false;
14631   if (Pointer.Designator.Invalid)
14632     return false;
14633 
14634   // Deleting a null pointer has no effect.
14635   if (Pointer.isNullPointer()) {
14636     // This is the only case where we need to produce an extension warning:
14637     // the only other way we can succeed is if we find a dynamic allocation,
14638     // and we will have warned when we allocated it in that case.
14639     if (!Info.getLangOpts().CPlusPlus20)
14640       Info.CCEDiag(E, diag::note_constexpr_new);
14641     return true;
14642   }
14643 
14644   Optional<DynAlloc *> Alloc = CheckDeleteKind(
14645       Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
14646   if (!Alloc)
14647     return false;
14648   QualType AllocType = Pointer.Base.getDynamicAllocType();
14649 
14650   // For the non-array case, the designator must be empty if the static type
14651   // does not have a virtual destructor.
14652   if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
14653       !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
14654     Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
14655         << Arg->getType()->getPointeeType() << AllocType;
14656     return false;
14657   }
14658 
14659   // For a class type with a virtual destructor, the selected operator delete
14660   // is the one looked up when building the destructor.
14661   if (!E->isArrayForm() && !E->isGlobalDelete()) {
14662     const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
14663     if (VirtualDelete &&
14664         !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
14665       Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14666           << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
14667       return false;
14668     }
14669   }
14670 
14671   if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
14672                          (*Alloc)->Value, AllocType))
14673     return false;
14674 
14675   if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
14676     // The element was already erased. This means the destructor call also
14677     // deleted the object.
14678     // FIXME: This probably results in undefined behavior before we get this
14679     // far, and should be diagnosed elsewhere first.
14680     Info.FFDiag(E, diag::note_constexpr_double_delete);
14681     return false;
14682   }
14683 
14684   return true;
14685 }
14686 
14687 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
14688   assert(!E->isValueDependent());
14689   assert(E->isPRValue() && E->getType()->isVoidType());
14690   return VoidExprEvaluator(Info).Visit(E);
14691 }
14692 
14693 //===----------------------------------------------------------------------===//
14694 // Top level Expr::EvaluateAsRValue method.
14695 //===----------------------------------------------------------------------===//
14696 
14697 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
14698   assert(!E->isValueDependent());
14699   // In C, function designators are not lvalues, but we evaluate them as if they
14700   // are.
14701   QualType T = E->getType();
14702   if (E->isGLValue() || T->isFunctionType()) {
14703     LValue LV;
14704     if (!EvaluateLValue(E, LV, Info))
14705       return false;
14706     LV.moveInto(Result);
14707   } else if (T->isVectorType()) {
14708     if (!EvaluateVector(E, Result, Info))
14709       return false;
14710   } else if (T->isIntegralOrEnumerationType()) {
14711     if (!IntExprEvaluator(Info, Result).Visit(E))
14712       return false;
14713   } else if (T->hasPointerRepresentation()) {
14714     LValue LV;
14715     if (!EvaluatePointer(E, LV, Info))
14716       return false;
14717     LV.moveInto(Result);
14718   } else if (T->isRealFloatingType()) {
14719     llvm::APFloat F(0.0);
14720     if (!EvaluateFloat(E, F, Info))
14721       return false;
14722     Result = APValue(F);
14723   } else if (T->isAnyComplexType()) {
14724     ComplexValue C;
14725     if (!EvaluateComplex(E, C, Info))
14726       return false;
14727     C.moveInto(Result);
14728   } else if (T->isFixedPointType()) {
14729     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
14730   } else if (T->isMemberPointerType()) {
14731     MemberPtr P;
14732     if (!EvaluateMemberPointer(E, P, Info))
14733       return false;
14734     P.moveInto(Result);
14735     return true;
14736   } else if (T->isArrayType()) {
14737     LValue LV;
14738     APValue &Value =
14739         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14740     if (!EvaluateArray(E, LV, Value, Info))
14741       return false;
14742     Result = Value;
14743   } else if (T->isRecordType()) {
14744     LValue LV;
14745     APValue &Value =
14746         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14747     if (!EvaluateRecord(E, LV, Value, Info))
14748       return false;
14749     Result = Value;
14750   } else if (T->isVoidType()) {
14751     if (!Info.getLangOpts().CPlusPlus11)
14752       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
14753         << E->getType();
14754     if (!EvaluateVoid(E, Info))
14755       return false;
14756   } else if (T->isAtomicType()) {
14757     QualType Unqual = T.getAtomicUnqualifiedType();
14758     if (Unqual->isArrayType() || Unqual->isRecordType()) {
14759       LValue LV;
14760       APValue &Value = Info.CurrentCall->createTemporary(
14761           E, Unqual, ScopeKind::FullExpression, LV);
14762       if (!EvaluateAtomic(E, &LV, Value, Info))
14763         return false;
14764     } else {
14765       if (!EvaluateAtomic(E, nullptr, Result, Info))
14766         return false;
14767     }
14768   } else if (Info.getLangOpts().CPlusPlus11) {
14769     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
14770     return false;
14771   } else {
14772     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
14773     return false;
14774   }
14775 
14776   return true;
14777 }
14778 
14779 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
14780 /// cases, the in-place evaluation is essential, since later initializers for
14781 /// an object can indirectly refer to subobjects which were initialized earlier.
14782 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
14783                             const Expr *E, bool AllowNonLiteralTypes) {
14784   assert(!E->isValueDependent());
14785 
14786   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
14787     return false;
14788 
14789   if (E->isPRValue()) {
14790     // Evaluate arrays and record types in-place, so that later initializers can
14791     // refer to earlier-initialized members of the object.
14792     QualType T = E->getType();
14793     if (T->isArrayType())
14794       return EvaluateArray(E, This, Result, Info);
14795     else if (T->isRecordType())
14796       return EvaluateRecord(E, This, Result, Info);
14797     else if (T->isAtomicType()) {
14798       QualType Unqual = T.getAtomicUnqualifiedType();
14799       if (Unqual->isArrayType() || Unqual->isRecordType())
14800         return EvaluateAtomic(E, &This, Result, Info);
14801     }
14802   }
14803 
14804   // For any other type, in-place evaluation is unimportant.
14805   return Evaluate(Result, Info, E);
14806 }
14807 
14808 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
14809 /// lvalue-to-rvalue cast if it is an lvalue.
14810 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
14811   assert(!E->isValueDependent());
14812   if (Info.EnableNewConstInterp) {
14813     if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
14814       return false;
14815   } else {
14816     if (E->getType().isNull())
14817       return false;
14818 
14819     if (!CheckLiteralType(Info, E))
14820       return false;
14821 
14822     if (!::Evaluate(Result, Info, E))
14823       return false;
14824 
14825     if (E->isGLValue()) {
14826       LValue LV;
14827       LV.setFrom(Info.Ctx, Result);
14828       if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
14829         return false;
14830     }
14831   }
14832 
14833   // Check this core constant expression is a constant expression.
14834   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
14835                                  ConstantExprKind::Normal) &&
14836          CheckMemoryLeaks(Info);
14837 }
14838 
14839 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
14840                                  const ASTContext &Ctx, bool &IsConst) {
14841   // Fast-path evaluations of integer literals, since we sometimes see files
14842   // containing vast quantities of these.
14843   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
14844     Result.Val = APValue(APSInt(L->getValue(),
14845                                 L->getType()->isUnsignedIntegerType()));
14846     IsConst = true;
14847     return true;
14848   }
14849 
14850   // This case should be rare, but we need to check it before we check on
14851   // the type below.
14852   if (Exp->getType().isNull()) {
14853     IsConst = false;
14854     return true;
14855   }
14856 
14857   // FIXME: Evaluating values of large array and record types can cause
14858   // performance problems. Only do so in C++11 for now.
14859   if (Exp->isPRValue() &&
14860       (Exp->getType()->isArrayType() || Exp->getType()->isRecordType()) &&
14861       !Ctx.getLangOpts().CPlusPlus11) {
14862     IsConst = false;
14863     return true;
14864   }
14865   return false;
14866 }
14867 
14868 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
14869                                       Expr::SideEffectsKind SEK) {
14870   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
14871          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
14872 }
14873 
14874 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
14875                              const ASTContext &Ctx, EvalInfo &Info) {
14876   assert(!E->isValueDependent());
14877   bool IsConst;
14878   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
14879     return IsConst;
14880 
14881   return EvaluateAsRValue(Info, E, Result.Val);
14882 }
14883 
14884 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
14885                           const ASTContext &Ctx,
14886                           Expr::SideEffectsKind AllowSideEffects,
14887                           EvalInfo &Info) {
14888   assert(!E->isValueDependent());
14889   if (!E->getType()->isIntegralOrEnumerationType())
14890     return false;
14891 
14892   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
14893       !ExprResult.Val.isInt() ||
14894       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14895     return false;
14896 
14897   return true;
14898 }
14899 
14900 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
14901                                  const ASTContext &Ctx,
14902                                  Expr::SideEffectsKind AllowSideEffects,
14903                                  EvalInfo &Info) {
14904   assert(!E->isValueDependent());
14905   if (!E->getType()->isFixedPointType())
14906     return false;
14907 
14908   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
14909     return false;
14910 
14911   if (!ExprResult.Val.isFixedPoint() ||
14912       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14913     return false;
14914 
14915   return true;
14916 }
14917 
14918 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
14919 /// any crazy technique (that has nothing to do with language standards) that
14920 /// we want to.  If this function returns true, it returns the folded constant
14921 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
14922 /// will be applied to the result.
14923 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
14924                             bool InConstantContext) const {
14925   assert(!isValueDependent() &&
14926          "Expression evaluator can't be called on a dependent expression.");
14927   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14928   Info.InConstantContext = InConstantContext;
14929   return ::EvaluateAsRValue(this, Result, Ctx, Info);
14930 }
14931 
14932 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
14933                                       bool InConstantContext) const {
14934   assert(!isValueDependent() &&
14935          "Expression evaluator can't be called on a dependent expression.");
14936   EvalResult Scratch;
14937   return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
14938          HandleConversionToBool(Scratch.Val, Result);
14939 }
14940 
14941 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
14942                          SideEffectsKind AllowSideEffects,
14943                          bool InConstantContext) const {
14944   assert(!isValueDependent() &&
14945          "Expression evaluator can't be called on a dependent expression.");
14946   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14947   Info.InConstantContext = InConstantContext;
14948   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
14949 }
14950 
14951 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
14952                                 SideEffectsKind AllowSideEffects,
14953                                 bool InConstantContext) const {
14954   assert(!isValueDependent() &&
14955          "Expression evaluator can't be called on a dependent expression.");
14956   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14957   Info.InConstantContext = InConstantContext;
14958   return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
14959 }
14960 
14961 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
14962                            SideEffectsKind AllowSideEffects,
14963                            bool InConstantContext) const {
14964   assert(!isValueDependent() &&
14965          "Expression evaluator can't be called on a dependent expression.");
14966 
14967   if (!getType()->isRealFloatingType())
14968     return false;
14969 
14970   EvalResult ExprResult;
14971   if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
14972       !ExprResult.Val.isFloat() ||
14973       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14974     return false;
14975 
14976   Result = ExprResult.Val.getFloat();
14977   return true;
14978 }
14979 
14980 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
14981                             bool InConstantContext) const {
14982   assert(!isValueDependent() &&
14983          "Expression evaluator can't be called on a dependent expression.");
14984 
14985   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
14986   Info.InConstantContext = InConstantContext;
14987   LValue LV;
14988   CheckedTemporaries CheckedTemps;
14989   if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
14990       Result.HasSideEffects ||
14991       !CheckLValueConstantExpression(Info, getExprLoc(),
14992                                      Ctx.getLValueReferenceType(getType()), LV,
14993                                      ConstantExprKind::Normal, CheckedTemps))
14994     return false;
14995 
14996   LV.moveInto(Result.Val);
14997   return true;
14998 }
14999 
15000 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base,
15001                                 APValue DestroyedValue, QualType Type,
15002                                 SourceLocation Loc, Expr::EvalStatus &EStatus,
15003                                 bool IsConstantDestruction) {
15004   EvalInfo Info(Ctx, EStatus,
15005                 IsConstantDestruction ? EvalInfo::EM_ConstantExpression
15006                                       : EvalInfo::EM_ConstantFold);
15007   Info.setEvaluatingDecl(Base, DestroyedValue,
15008                          EvalInfo::EvaluatingDeclKind::Dtor);
15009   Info.InConstantContext = IsConstantDestruction;
15010 
15011   LValue LVal;
15012   LVal.set(Base);
15013 
15014   if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
15015       EStatus.HasSideEffects)
15016     return false;
15017 
15018   if (!Info.discardCleanups())
15019     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15020 
15021   return true;
15022 }
15023 
15024 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx,
15025                                   ConstantExprKind Kind) const {
15026   assert(!isValueDependent() &&
15027          "Expression evaluator can't be called on a dependent expression.");
15028 
15029   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
15030   EvalInfo Info(Ctx, Result, EM);
15031   Info.InConstantContext = true;
15032 
15033   // The type of the object we're initializing is 'const T' for a class NTTP.
15034   QualType T = getType();
15035   if (Kind == ConstantExprKind::ClassTemplateArgument)
15036     T.addConst();
15037 
15038   // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
15039   // represent the result of the evaluation. CheckConstantExpression ensures
15040   // this doesn't escape.
15041   MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
15042   APValue::LValueBase Base(&BaseMTE);
15043 
15044   Info.setEvaluatingDecl(Base, Result.Val);
15045   LValue LVal;
15046   LVal.set(Base);
15047 
15048   if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || Result.HasSideEffects)
15049     return false;
15050 
15051   if (!Info.discardCleanups())
15052     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15053 
15054   if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
15055                                Result.Val, Kind))
15056     return false;
15057   if (!CheckMemoryLeaks(Info))
15058     return false;
15059 
15060   // If this is a class template argument, it's required to have constant
15061   // destruction too.
15062   if (Kind == ConstantExprKind::ClassTemplateArgument &&
15063       (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result,
15064                             true) ||
15065        Result.HasSideEffects)) {
15066     // FIXME: Prefix a note to indicate that the problem is lack of constant
15067     // destruction.
15068     return false;
15069   }
15070 
15071   return true;
15072 }
15073 
15074 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
15075                                  const VarDecl *VD,
15076                                  SmallVectorImpl<PartialDiagnosticAt> &Notes,
15077                                  bool IsConstantInitialization) const {
15078   assert(!isValueDependent() &&
15079          "Expression evaluator can't be called on a dependent expression.");
15080 
15081   // FIXME: Evaluating initializers for large array and record types can cause
15082   // performance problems. Only do so in C++11 for now.
15083   if (isPRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
15084       !Ctx.getLangOpts().CPlusPlus11)
15085     return false;
15086 
15087   Expr::EvalStatus EStatus;
15088   EStatus.Diag = &Notes;
15089 
15090   EvalInfo Info(Ctx, EStatus,
15091                 (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11)
15092                     ? EvalInfo::EM_ConstantExpression
15093                     : EvalInfo::EM_ConstantFold);
15094   Info.setEvaluatingDecl(VD, Value);
15095   Info.InConstantContext = IsConstantInitialization;
15096 
15097   SourceLocation DeclLoc = VD->getLocation();
15098   QualType DeclTy = VD->getType();
15099 
15100   if (Info.EnableNewConstInterp) {
15101     auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
15102     if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
15103       return false;
15104   } else {
15105     LValue LVal;
15106     LVal.set(VD);
15107 
15108     if (!EvaluateInPlace(Value, Info, LVal, this,
15109                          /*AllowNonLiteralTypes=*/true) ||
15110         EStatus.HasSideEffects)
15111       return false;
15112 
15113     // At this point, any lifetime-extended temporaries are completely
15114     // initialized.
15115     Info.performLifetimeExtension();
15116 
15117     if (!Info.discardCleanups())
15118       llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15119   }
15120   return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
15121                                  ConstantExprKind::Normal) &&
15122          CheckMemoryLeaks(Info);
15123 }
15124 
15125 bool VarDecl::evaluateDestruction(
15126     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
15127   Expr::EvalStatus EStatus;
15128   EStatus.Diag = &Notes;
15129 
15130   // Only treat the destruction as constant destruction if we formally have
15131   // constant initialization (or are usable in a constant expression).
15132   bool IsConstantDestruction = hasConstantInitialization();
15133 
15134   // Make a copy of the value for the destructor to mutate, if we know it.
15135   // Otherwise, treat the value as default-initialized; if the destructor works
15136   // anyway, then the destruction is constant (and must be essentially empty).
15137   APValue DestroyedValue;
15138   if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
15139     DestroyedValue = *getEvaluatedValue();
15140   else if (!getDefaultInitValue(getType(), DestroyedValue))
15141     return false;
15142 
15143   if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
15144                            getType(), getLocation(), EStatus,
15145                            IsConstantDestruction) ||
15146       EStatus.HasSideEffects)
15147     return false;
15148 
15149   ensureEvaluatedStmt()->HasConstantDestruction = true;
15150   return true;
15151 }
15152 
15153 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
15154 /// constant folded, but discard the result.
15155 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
15156   assert(!isValueDependent() &&
15157          "Expression evaluator can't be called on a dependent expression.");
15158 
15159   EvalResult Result;
15160   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
15161          !hasUnacceptableSideEffect(Result, SEK);
15162 }
15163 
15164 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
15165                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
15166   assert(!isValueDependent() &&
15167          "Expression evaluator can't be called on a dependent expression.");
15168 
15169   EvalResult EVResult;
15170   EVResult.Diag = Diag;
15171   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15172   Info.InConstantContext = true;
15173 
15174   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
15175   (void)Result;
15176   assert(Result && "Could not evaluate expression");
15177   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
15178 
15179   return EVResult.Val.getInt();
15180 }
15181 
15182 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
15183     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
15184   assert(!isValueDependent() &&
15185          "Expression evaluator can't be called on a dependent expression.");
15186 
15187   EvalResult EVResult;
15188   EVResult.Diag = Diag;
15189   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15190   Info.InConstantContext = true;
15191   Info.CheckingForUndefinedBehavior = true;
15192 
15193   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
15194   (void)Result;
15195   assert(Result && "Could not evaluate expression");
15196   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
15197 
15198   return EVResult.Val.getInt();
15199 }
15200 
15201 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
15202   assert(!isValueDependent() &&
15203          "Expression evaluator can't be called on a dependent expression.");
15204 
15205   bool IsConst;
15206   EvalResult EVResult;
15207   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
15208     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15209     Info.CheckingForUndefinedBehavior = true;
15210     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
15211   }
15212 }
15213 
15214 bool Expr::EvalResult::isGlobalLValue() const {
15215   assert(Val.isLValue());
15216   return IsGlobalLValue(Val.getLValueBase());
15217 }
15218 
15219 /// isIntegerConstantExpr - this recursive routine will test if an expression is
15220 /// an integer constant expression.
15221 
15222 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
15223 /// comma, etc
15224 
15225 // CheckICE - This function does the fundamental ICE checking: the returned
15226 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
15227 // and a (possibly null) SourceLocation indicating the location of the problem.
15228 //
15229 // Note that to reduce code duplication, this helper does no evaluation
15230 // itself; the caller checks whether the expression is evaluatable, and
15231 // in the rare cases where CheckICE actually cares about the evaluated
15232 // value, it calls into Evaluate.
15233 
15234 namespace {
15235 
15236 enum ICEKind {
15237   /// This expression is an ICE.
15238   IK_ICE,
15239   /// This expression is not an ICE, but if it isn't evaluated, it's
15240   /// a legal subexpression for an ICE. This return value is used to handle
15241   /// the comma operator in C99 mode, and non-constant subexpressions.
15242   IK_ICEIfUnevaluated,
15243   /// This expression is not an ICE, and is not a legal subexpression for one.
15244   IK_NotICE
15245 };
15246 
15247 struct ICEDiag {
15248   ICEKind Kind;
15249   SourceLocation Loc;
15250 
15251   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
15252 };
15253 
15254 }
15255 
15256 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
15257 
15258 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
15259 
15260 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
15261   Expr::EvalResult EVResult;
15262   Expr::EvalStatus Status;
15263   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15264 
15265   Info.InConstantContext = true;
15266   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
15267       !EVResult.Val.isInt())
15268     return ICEDiag(IK_NotICE, E->getBeginLoc());
15269 
15270   return NoDiag();
15271 }
15272 
15273 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
15274   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
15275   if (!E->getType()->isIntegralOrEnumerationType())
15276     return ICEDiag(IK_NotICE, E->getBeginLoc());
15277 
15278   switch (E->getStmtClass()) {
15279 #define ABSTRACT_STMT(Node)
15280 #define STMT(Node, Base) case Expr::Node##Class:
15281 #define EXPR(Node, Base)
15282 #include "clang/AST/StmtNodes.inc"
15283   case Expr::PredefinedExprClass:
15284   case Expr::FloatingLiteralClass:
15285   case Expr::ImaginaryLiteralClass:
15286   case Expr::StringLiteralClass:
15287   case Expr::ArraySubscriptExprClass:
15288   case Expr::MatrixSubscriptExprClass:
15289   case Expr::OMPArraySectionExprClass:
15290   case Expr::OMPArrayShapingExprClass:
15291   case Expr::OMPIteratorExprClass:
15292   case Expr::MemberExprClass:
15293   case Expr::CompoundAssignOperatorClass:
15294   case Expr::CompoundLiteralExprClass:
15295   case Expr::ExtVectorElementExprClass:
15296   case Expr::DesignatedInitExprClass:
15297   case Expr::ArrayInitLoopExprClass:
15298   case Expr::ArrayInitIndexExprClass:
15299   case Expr::NoInitExprClass:
15300   case Expr::DesignatedInitUpdateExprClass:
15301   case Expr::ImplicitValueInitExprClass:
15302   case Expr::ParenListExprClass:
15303   case Expr::VAArgExprClass:
15304   case Expr::AddrLabelExprClass:
15305   case Expr::StmtExprClass:
15306   case Expr::CXXMemberCallExprClass:
15307   case Expr::CUDAKernelCallExprClass:
15308   case Expr::CXXAddrspaceCastExprClass:
15309   case Expr::CXXDynamicCastExprClass:
15310   case Expr::CXXTypeidExprClass:
15311   case Expr::CXXUuidofExprClass:
15312   case Expr::MSPropertyRefExprClass:
15313   case Expr::MSPropertySubscriptExprClass:
15314   case Expr::CXXNullPtrLiteralExprClass:
15315   case Expr::UserDefinedLiteralClass:
15316   case Expr::CXXThisExprClass:
15317   case Expr::CXXThrowExprClass:
15318   case Expr::CXXNewExprClass:
15319   case Expr::CXXDeleteExprClass:
15320   case Expr::CXXPseudoDestructorExprClass:
15321   case Expr::UnresolvedLookupExprClass:
15322   case Expr::TypoExprClass:
15323   case Expr::RecoveryExprClass:
15324   case Expr::DependentScopeDeclRefExprClass:
15325   case Expr::CXXConstructExprClass:
15326   case Expr::CXXInheritedCtorInitExprClass:
15327   case Expr::CXXStdInitializerListExprClass:
15328   case Expr::CXXBindTemporaryExprClass:
15329   case Expr::ExprWithCleanupsClass:
15330   case Expr::CXXTemporaryObjectExprClass:
15331   case Expr::CXXUnresolvedConstructExprClass:
15332   case Expr::CXXDependentScopeMemberExprClass:
15333   case Expr::UnresolvedMemberExprClass:
15334   case Expr::ObjCStringLiteralClass:
15335   case Expr::ObjCBoxedExprClass:
15336   case Expr::ObjCArrayLiteralClass:
15337   case Expr::ObjCDictionaryLiteralClass:
15338   case Expr::ObjCEncodeExprClass:
15339   case Expr::ObjCMessageExprClass:
15340   case Expr::ObjCSelectorExprClass:
15341   case Expr::ObjCProtocolExprClass:
15342   case Expr::ObjCIvarRefExprClass:
15343   case Expr::ObjCPropertyRefExprClass:
15344   case Expr::ObjCSubscriptRefExprClass:
15345   case Expr::ObjCIsaExprClass:
15346   case Expr::ObjCAvailabilityCheckExprClass:
15347   case Expr::ShuffleVectorExprClass:
15348   case Expr::ConvertVectorExprClass:
15349   case Expr::BlockExprClass:
15350   case Expr::NoStmtClass:
15351   case Expr::OpaqueValueExprClass:
15352   case Expr::PackExpansionExprClass:
15353   case Expr::SubstNonTypeTemplateParmPackExprClass:
15354   case Expr::FunctionParmPackExprClass:
15355   case Expr::AsTypeExprClass:
15356   case Expr::ObjCIndirectCopyRestoreExprClass:
15357   case Expr::MaterializeTemporaryExprClass:
15358   case Expr::PseudoObjectExprClass:
15359   case Expr::AtomicExprClass:
15360   case Expr::LambdaExprClass:
15361   case Expr::CXXFoldExprClass:
15362   case Expr::CoawaitExprClass:
15363   case Expr::DependentCoawaitExprClass:
15364   case Expr::CoyieldExprClass:
15365   case Expr::SYCLUniqueStableNameExprClass:
15366     return ICEDiag(IK_NotICE, E->getBeginLoc());
15367 
15368   case Expr::InitListExprClass: {
15369     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
15370     // form "T x = { a };" is equivalent to "T x = a;".
15371     // Unless we're initializing a reference, T is a scalar as it is known to be
15372     // of integral or enumeration type.
15373     if (E->isPRValue())
15374       if (cast<InitListExpr>(E)->getNumInits() == 1)
15375         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
15376     return ICEDiag(IK_NotICE, E->getBeginLoc());
15377   }
15378 
15379   case Expr::SizeOfPackExprClass:
15380   case Expr::GNUNullExprClass:
15381   case Expr::SourceLocExprClass:
15382     return NoDiag();
15383 
15384   case Expr::SubstNonTypeTemplateParmExprClass:
15385     return
15386       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
15387 
15388   case Expr::ConstantExprClass:
15389     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
15390 
15391   case Expr::ParenExprClass:
15392     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
15393   case Expr::GenericSelectionExprClass:
15394     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
15395   case Expr::IntegerLiteralClass:
15396   case Expr::FixedPointLiteralClass:
15397   case Expr::CharacterLiteralClass:
15398   case Expr::ObjCBoolLiteralExprClass:
15399   case Expr::CXXBoolLiteralExprClass:
15400   case Expr::CXXScalarValueInitExprClass:
15401   case Expr::TypeTraitExprClass:
15402   case Expr::ConceptSpecializationExprClass:
15403   case Expr::RequiresExprClass:
15404   case Expr::ArrayTypeTraitExprClass:
15405   case Expr::ExpressionTraitExprClass:
15406   case Expr::CXXNoexceptExprClass:
15407     return NoDiag();
15408   case Expr::CallExprClass:
15409   case Expr::CXXOperatorCallExprClass: {
15410     // C99 6.6/3 allows function calls within unevaluated subexpressions of
15411     // constant expressions, but they can never be ICEs because an ICE cannot
15412     // contain an operand of (pointer to) function type.
15413     const CallExpr *CE = cast<CallExpr>(E);
15414     if (CE->getBuiltinCallee())
15415       return CheckEvalInICE(E, Ctx);
15416     return ICEDiag(IK_NotICE, E->getBeginLoc());
15417   }
15418   case Expr::CXXRewrittenBinaryOperatorClass:
15419     return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
15420                     Ctx);
15421   case Expr::DeclRefExprClass: {
15422     const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
15423     if (isa<EnumConstantDecl>(D))
15424       return NoDiag();
15425 
15426     // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
15427     // integer variables in constant expressions:
15428     //
15429     // C++ 7.1.5.1p2
15430     //   A variable of non-volatile const-qualified integral or enumeration
15431     //   type initialized by an ICE can be used in ICEs.
15432     //
15433     // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
15434     // that mode, use of reference variables should not be allowed.
15435     const VarDecl *VD = dyn_cast<VarDecl>(D);
15436     if (VD && VD->isUsableInConstantExpressions(Ctx) &&
15437         !VD->getType()->isReferenceType())
15438       return NoDiag();
15439 
15440     return ICEDiag(IK_NotICE, E->getBeginLoc());
15441   }
15442   case Expr::UnaryOperatorClass: {
15443     const UnaryOperator *Exp = cast<UnaryOperator>(E);
15444     switch (Exp->getOpcode()) {
15445     case UO_PostInc:
15446     case UO_PostDec:
15447     case UO_PreInc:
15448     case UO_PreDec:
15449     case UO_AddrOf:
15450     case UO_Deref:
15451     case UO_Coawait:
15452       // C99 6.6/3 allows increment and decrement within unevaluated
15453       // subexpressions of constant expressions, but they can never be ICEs
15454       // because an ICE cannot contain an lvalue operand.
15455       return ICEDiag(IK_NotICE, E->getBeginLoc());
15456     case UO_Extension:
15457     case UO_LNot:
15458     case UO_Plus:
15459     case UO_Minus:
15460     case UO_Not:
15461     case UO_Real:
15462     case UO_Imag:
15463       return CheckICE(Exp->getSubExpr(), Ctx);
15464     }
15465     llvm_unreachable("invalid unary operator class");
15466   }
15467   case Expr::OffsetOfExprClass: {
15468     // Note that per C99, offsetof must be an ICE. And AFAIK, using
15469     // EvaluateAsRValue matches the proposed gcc behavior for cases like
15470     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
15471     // compliance: we should warn earlier for offsetof expressions with
15472     // array subscripts that aren't ICEs, and if the array subscripts
15473     // are ICEs, the value of the offsetof must be an integer constant.
15474     return CheckEvalInICE(E, Ctx);
15475   }
15476   case Expr::UnaryExprOrTypeTraitExprClass: {
15477     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
15478     if ((Exp->getKind() ==  UETT_SizeOf) &&
15479         Exp->getTypeOfArgument()->isVariableArrayType())
15480       return ICEDiag(IK_NotICE, E->getBeginLoc());
15481     return NoDiag();
15482   }
15483   case Expr::BinaryOperatorClass: {
15484     const BinaryOperator *Exp = cast<BinaryOperator>(E);
15485     switch (Exp->getOpcode()) {
15486     case BO_PtrMemD:
15487     case BO_PtrMemI:
15488     case BO_Assign:
15489     case BO_MulAssign:
15490     case BO_DivAssign:
15491     case BO_RemAssign:
15492     case BO_AddAssign:
15493     case BO_SubAssign:
15494     case BO_ShlAssign:
15495     case BO_ShrAssign:
15496     case BO_AndAssign:
15497     case BO_XorAssign:
15498     case BO_OrAssign:
15499       // C99 6.6/3 allows assignments within unevaluated subexpressions of
15500       // constant expressions, but they can never be ICEs because an ICE cannot
15501       // contain an lvalue operand.
15502       return ICEDiag(IK_NotICE, E->getBeginLoc());
15503 
15504     case BO_Mul:
15505     case BO_Div:
15506     case BO_Rem:
15507     case BO_Add:
15508     case BO_Sub:
15509     case BO_Shl:
15510     case BO_Shr:
15511     case BO_LT:
15512     case BO_GT:
15513     case BO_LE:
15514     case BO_GE:
15515     case BO_EQ:
15516     case BO_NE:
15517     case BO_And:
15518     case BO_Xor:
15519     case BO_Or:
15520     case BO_Comma:
15521     case BO_Cmp: {
15522       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15523       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15524       if (Exp->getOpcode() == BO_Div ||
15525           Exp->getOpcode() == BO_Rem) {
15526         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
15527         // we don't evaluate one.
15528         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
15529           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
15530           if (REval == 0)
15531             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15532           if (REval.isSigned() && REval.isAllOnes()) {
15533             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
15534             if (LEval.isMinSignedValue())
15535               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15536           }
15537         }
15538       }
15539       if (Exp->getOpcode() == BO_Comma) {
15540         if (Ctx.getLangOpts().C99) {
15541           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
15542           // if it isn't evaluated.
15543           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
15544             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15545         } else {
15546           // In both C89 and C++, commas in ICEs are illegal.
15547           return ICEDiag(IK_NotICE, E->getBeginLoc());
15548         }
15549       }
15550       return Worst(LHSResult, RHSResult);
15551     }
15552     case BO_LAnd:
15553     case BO_LOr: {
15554       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15555       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15556       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
15557         // Rare case where the RHS has a comma "side-effect"; we need
15558         // to actually check the condition to see whether the side
15559         // with the comma is evaluated.
15560         if ((Exp->getOpcode() == BO_LAnd) !=
15561             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
15562           return RHSResult;
15563         return NoDiag();
15564       }
15565 
15566       return Worst(LHSResult, RHSResult);
15567     }
15568     }
15569     llvm_unreachable("invalid binary operator kind");
15570   }
15571   case Expr::ImplicitCastExprClass:
15572   case Expr::CStyleCastExprClass:
15573   case Expr::CXXFunctionalCastExprClass:
15574   case Expr::CXXStaticCastExprClass:
15575   case Expr::CXXReinterpretCastExprClass:
15576   case Expr::CXXConstCastExprClass:
15577   case Expr::ObjCBridgedCastExprClass: {
15578     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
15579     if (isa<ExplicitCastExpr>(E)) {
15580       if (const FloatingLiteral *FL
15581             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
15582         unsigned DestWidth = Ctx.getIntWidth(E->getType());
15583         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
15584         APSInt IgnoredVal(DestWidth, !DestSigned);
15585         bool Ignored;
15586         // If the value does not fit in the destination type, the behavior is
15587         // undefined, so we are not required to treat it as a constant
15588         // expression.
15589         if (FL->getValue().convertToInteger(IgnoredVal,
15590                                             llvm::APFloat::rmTowardZero,
15591                                             &Ignored) & APFloat::opInvalidOp)
15592           return ICEDiag(IK_NotICE, E->getBeginLoc());
15593         return NoDiag();
15594       }
15595     }
15596     switch (cast<CastExpr>(E)->getCastKind()) {
15597     case CK_LValueToRValue:
15598     case CK_AtomicToNonAtomic:
15599     case CK_NonAtomicToAtomic:
15600     case CK_NoOp:
15601     case CK_IntegralToBoolean:
15602     case CK_IntegralCast:
15603       return CheckICE(SubExpr, Ctx);
15604     default:
15605       return ICEDiag(IK_NotICE, E->getBeginLoc());
15606     }
15607   }
15608   case Expr::BinaryConditionalOperatorClass: {
15609     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
15610     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
15611     if (CommonResult.Kind == IK_NotICE) return CommonResult;
15612     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15613     if (FalseResult.Kind == IK_NotICE) return FalseResult;
15614     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
15615     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
15616         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
15617     return FalseResult;
15618   }
15619   case Expr::ConditionalOperatorClass: {
15620     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
15621     // If the condition (ignoring parens) is a __builtin_constant_p call,
15622     // then only the true side is actually considered in an integer constant
15623     // expression, and it is fully evaluated.  This is an important GNU
15624     // extension.  See GCC PR38377 for discussion.
15625     if (const CallExpr *CallCE
15626         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
15627       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
15628         return CheckEvalInICE(E, Ctx);
15629     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
15630     if (CondResult.Kind == IK_NotICE)
15631       return CondResult;
15632 
15633     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
15634     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15635 
15636     if (TrueResult.Kind == IK_NotICE)
15637       return TrueResult;
15638     if (FalseResult.Kind == IK_NotICE)
15639       return FalseResult;
15640     if (CondResult.Kind == IK_ICEIfUnevaluated)
15641       return CondResult;
15642     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
15643       return NoDiag();
15644     // Rare case where the diagnostics depend on which side is evaluated
15645     // Note that if we get here, CondResult is 0, and at least one of
15646     // TrueResult and FalseResult is non-zero.
15647     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
15648       return FalseResult;
15649     return TrueResult;
15650   }
15651   case Expr::CXXDefaultArgExprClass:
15652     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
15653   case Expr::CXXDefaultInitExprClass:
15654     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
15655   case Expr::ChooseExprClass: {
15656     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
15657   }
15658   case Expr::BuiltinBitCastExprClass: {
15659     if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
15660       return ICEDiag(IK_NotICE, E->getBeginLoc());
15661     return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
15662   }
15663   }
15664 
15665   llvm_unreachable("Invalid StmtClass!");
15666 }
15667 
15668 /// Evaluate an expression as a C++11 integral constant expression.
15669 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
15670                                                     const Expr *E,
15671                                                     llvm::APSInt *Value,
15672                                                     SourceLocation *Loc) {
15673   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15674     if (Loc) *Loc = E->getExprLoc();
15675     return false;
15676   }
15677 
15678   APValue Result;
15679   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
15680     return false;
15681 
15682   if (!Result.isInt()) {
15683     if (Loc) *Loc = E->getExprLoc();
15684     return false;
15685   }
15686 
15687   if (Value) *Value = Result.getInt();
15688   return true;
15689 }
15690 
15691 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
15692                                  SourceLocation *Loc) const {
15693   assert(!isValueDependent() &&
15694          "Expression evaluator can't be called on a dependent expression.");
15695 
15696   if (Ctx.getLangOpts().CPlusPlus11)
15697     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
15698 
15699   ICEDiag D = CheckICE(this, Ctx);
15700   if (D.Kind != IK_ICE) {
15701     if (Loc) *Loc = D.Loc;
15702     return false;
15703   }
15704   return true;
15705 }
15706 
15707 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx,
15708                                                     SourceLocation *Loc,
15709                                                     bool isEvaluated) const {
15710   if (isValueDependent()) {
15711     // Expression evaluator can't succeed on a dependent expression.
15712     return None;
15713   }
15714 
15715   APSInt Value;
15716 
15717   if (Ctx.getLangOpts().CPlusPlus11) {
15718     if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc))
15719       return Value;
15720     return None;
15721   }
15722 
15723   if (!isIntegerConstantExpr(Ctx, Loc))
15724     return None;
15725 
15726   // The only possible side-effects here are due to UB discovered in the
15727   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
15728   // required to treat the expression as an ICE, so we produce the folded
15729   // value.
15730   EvalResult ExprResult;
15731   Expr::EvalStatus Status;
15732   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
15733   Info.InConstantContext = true;
15734 
15735   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
15736     llvm_unreachable("ICE cannot be evaluated!");
15737 
15738   return ExprResult.Val.getInt();
15739 }
15740 
15741 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
15742   assert(!isValueDependent() &&
15743          "Expression evaluator can't be called on a dependent expression.");
15744 
15745   return CheckICE(this, Ctx).Kind == IK_ICE;
15746 }
15747 
15748 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
15749                                SourceLocation *Loc) const {
15750   assert(!isValueDependent() &&
15751          "Expression evaluator can't be called on a dependent expression.");
15752 
15753   // We support this checking in C++98 mode in order to diagnose compatibility
15754   // issues.
15755   assert(Ctx.getLangOpts().CPlusPlus);
15756 
15757   // Build evaluation settings.
15758   Expr::EvalStatus Status;
15759   SmallVector<PartialDiagnosticAt, 8> Diags;
15760   Status.Diag = &Diags;
15761   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15762 
15763   APValue Scratch;
15764   bool IsConstExpr =
15765       ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
15766       // FIXME: We don't produce a diagnostic for this, but the callers that
15767       // call us on arbitrary full-expressions should generally not care.
15768       Info.discardCleanups() && !Status.HasSideEffects;
15769 
15770   if (!Diags.empty()) {
15771     IsConstExpr = false;
15772     if (Loc) *Loc = Diags[0].first;
15773   } else if (!IsConstExpr) {
15774     // FIXME: This shouldn't happen.
15775     if (Loc) *Loc = getExprLoc();
15776   }
15777 
15778   return IsConstExpr;
15779 }
15780 
15781 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
15782                                     const FunctionDecl *Callee,
15783                                     ArrayRef<const Expr*> Args,
15784                                     const Expr *This) const {
15785   assert(!isValueDependent() &&
15786          "Expression evaluator can't be called on a dependent expression.");
15787 
15788   Expr::EvalStatus Status;
15789   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
15790   Info.InConstantContext = true;
15791 
15792   LValue ThisVal;
15793   const LValue *ThisPtr = nullptr;
15794   if (This) {
15795 #ifndef NDEBUG
15796     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
15797     assert(MD && "Don't provide `this` for non-methods.");
15798     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
15799 #endif
15800     if (!This->isValueDependent() &&
15801         EvaluateObjectArgument(Info, This, ThisVal) &&
15802         !Info.EvalStatus.HasSideEffects)
15803       ThisPtr = &ThisVal;
15804 
15805     // Ignore any side-effects from a failed evaluation. This is safe because
15806     // they can't interfere with any other argument evaluation.
15807     Info.EvalStatus.HasSideEffects = false;
15808   }
15809 
15810   CallRef Call = Info.CurrentCall->createCall(Callee);
15811   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
15812        I != E; ++I) {
15813     unsigned Idx = I - Args.begin();
15814     if (Idx >= Callee->getNumParams())
15815       break;
15816     const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
15817     if ((*I)->isValueDependent() ||
15818         !EvaluateCallArg(PVD, *I, Call, Info) ||
15819         Info.EvalStatus.HasSideEffects) {
15820       // If evaluation fails, throw away the argument entirely.
15821       if (APValue *Slot = Info.getParamSlot(Call, PVD))
15822         *Slot = APValue();
15823     }
15824 
15825     // Ignore any side-effects from a failed evaluation. This is safe because
15826     // they can't interfere with any other argument evaluation.
15827     Info.EvalStatus.HasSideEffects = false;
15828   }
15829 
15830   // Parameter cleanups happen in the caller and are not part of this
15831   // evaluation.
15832   Info.discardCleanups();
15833   Info.EvalStatus.HasSideEffects = false;
15834 
15835   // Build fake call to Callee.
15836   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call);
15837   // FIXME: Missing ExprWithCleanups in enable_if conditions?
15838   FullExpressionRAII Scope(Info);
15839   return Evaluate(Value, Info, this) && Scope.destroy() &&
15840          !Info.EvalStatus.HasSideEffects;
15841 }
15842 
15843 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
15844                                    SmallVectorImpl<
15845                                      PartialDiagnosticAt> &Diags) {
15846   // FIXME: It would be useful to check constexpr function templates, but at the
15847   // moment the constant expression evaluator cannot cope with the non-rigorous
15848   // ASTs which we build for dependent expressions.
15849   if (FD->isDependentContext())
15850     return true;
15851 
15852   Expr::EvalStatus Status;
15853   Status.Diag = &Diags;
15854 
15855   EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
15856   Info.InConstantContext = true;
15857   Info.CheckingPotentialConstantExpression = true;
15858 
15859   // The constexpr VM attempts to compile all methods to bytecode here.
15860   if (Info.EnableNewConstInterp) {
15861     Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
15862     return Diags.empty();
15863   }
15864 
15865   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
15866   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
15867 
15868   // Fabricate an arbitrary expression on the stack and pretend that it
15869   // is a temporary being used as the 'this' pointer.
15870   LValue This;
15871   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
15872   This.set({&VIE, Info.CurrentCall->Index});
15873 
15874   ArrayRef<const Expr*> Args;
15875 
15876   APValue Scratch;
15877   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
15878     // Evaluate the call as a constant initializer, to allow the construction
15879     // of objects of non-literal types.
15880     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
15881     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
15882   } else {
15883     SourceLocation Loc = FD->getLocation();
15884     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
15885                        Args, CallRef(), FD->getBody(), Info, Scratch, nullptr);
15886   }
15887 
15888   return Diags.empty();
15889 }
15890 
15891 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
15892                                               const FunctionDecl *FD,
15893                                               SmallVectorImpl<
15894                                                 PartialDiagnosticAt> &Diags) {
15895   assert(!E->isValueDependent() &&
15896          "Expression evaluator can't be called on a dependent expression.");
15897 
15898   Expr::EvalStatus Status;
15899   Status.Diag = &Diags;
15900 
15901   EvalInfo Info(FD->getASTContext(), Status,
15902                 EvalInfo::EM_ConstantExpressionUnevaluated);
15903   Info.InConstantContext = true;
15904   Info.CheckingPotentialConstantExpression = true;
15905 
15906   // Fabricate a call stack frame to give the arguments a plausible cover story.
15907   CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef());
15908 
15909   APValue ResultScratch;
15910   Evaluate(ResultScratch, Info, E);
15911   return Diags.empty();
15912 }
15913 
15914 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
15915                                  unsigned Type) const {
15916   if (!getType()->isPointerType())
15917     return false;
15918 
15919   Expr::EvalStatus Status;
15920   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
15921   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
15922 }
15923 
15924 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
15925                                   EvalInfo &Info) {
15926   if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
15927     return false;
15928 
15929   LValue String;
15930 
15931   if (!EvaluatePointer(E, String, Info))
15932     return false;
15933 
15934   QualType CharTy = E->getType()->getPointeeType();
15935 
15936   // Fast path: if it's a string literal, search the string value.
15937   if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
15938           String.getLValueBase().dyn_cast<const Expr *>())) {
15939     StringRef Str = S->getBytes();
15940     int64_t Off = String.Offset.getQuantity();
15941     if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
15942         S->getCharByteWidth() == 1 &&
15943         // FIXME: Add fast-path for wchar_t too.
15944         Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
15945       Str = Str.substr(Off);
15946 
15947       StringRef::size_type Pos = Str.find(0);
15948       if (Pos != StringRef::npos)
15949         Str = Str.substr(0, Pos);
15950 
15951       Result = Str.size();
15952       return true;
15953     }
15954 
15955     // Fall through to slow path.
15956   }
15957 
15958   // Slow path: scan the bytes of the string looking for the terminating 0.
15959   for (uint64_t Strlen = 0; /**/; ++Strlen) {
15960     APValue Char;
15961     if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
15962         !Char.isInt())
15963       return false;
15964     if (!Char.getInt()) {
15965       Result = Strlen;
15966       return true;
15967     }
15968     if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
15969       return false;
15970   }
15971 }
15972 
15973 bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
15974   Expr::EvalStatus Status;
15975   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
15976   return EvaluateBuiltinStrLen(this, Result, Info);
15977 }
15978