1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Expr constant evaluator.
10 //
11 // Constant expression evaluation produces four main results:
12 //
13 //  * A success/failure flag indicating whether constant folding was successful.
14 //    This is the 'bool' return value used by most of the code in this file. A
15 //    'false' return value indicates that constant folding has failed, and any
16 //    appropriate diagnostic has already been produced.
17 //
18 //  * An evaluated result, valid only if constant folding has not failed.
19 //
20 //  * A flag indicating if evaluation encountered (unevaluated) side-effects.
21 //    These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
22 //    where it is possible to determine the evaluated result regardless.
23 //
24 //  * A set of notes indicating why the evaluation was not a constant expression
25 //    (under the C++11 / C++1y rules only, at the moment), or, if folding failed
26 //    too, why the expression could not be folded.
27 //
28 // If we are checking for a potential constant expression, failure to constant
29 // fold a potential constant sub-expression will be indicated by a 'false'
30 // return value (the expression could not be folded) and no diagnostic (the
31 // expression is not necessarily non-constant).
32 //
33 //===----------------------------------------------------------------------===//
34 
35 #include "Interp/Context.h"
36 #include "Interp/Frame.h"
37 #include "Interp/State.h"
38 #include "clang/AST/APValue.h"
39 #include "clang/AST/ASTContext.h"
40 #include "clang/AST/ASTDiagnostic.h"
41 #include "clang/AST/ASTLambda.h"
42 #include "clang/AST/Attr.h"
43 #include "clang/AST/CXXInheritance.h"
44 #include "clang/AST/CharUnits.h"
45 #include "clang/AST/CurrentSourceLocExprScope.h"
46 #include "clang/AST/Expr.h"
47 #include "clang/AST/OSLog.h"
48 #include "clang/AST/OptionalDiagnostic.h"
49 #include "clang/AST/RecordLayout.h"
50 #include "clang/AST/StmtVisitor.h"
51 #include "clang/AST/TypeLoc.h"
52 #include "clang/Basic/Builtins.h"
53 #include "clang/Basic/TargetInfo.h"
54 #include "llvm/ADT/APFixedPoint.h"
55 #include "llvm/ADT/Optional.h"
56 #include "llvm/ADT/SmallBitVector.h"
57 #include "llvm/Support/Debug.h"
58 #include "llvm/Support/SaveAndRestore.h"
59 #include "llvm/Support/raw_ostream.h"
60 #include <cstring>
61 #include <functional>
62 
63 #define DEBUG_TYPE "exprconstant"
64 
65 using namespace clang;
66 using llvm::APFixedPoint;
67 using llvm::APInt;
68 using llvm::APSInt;
69 using llvm::APFloat;
70 using llvm::FixedPointSemantics;
71 using llvm::Optional;
72 
73 namespace {
74   struct LValue;
75   class CallStackFrame;
76   class EvalInfo;
77 
78   using SourceLocExprScopeGuard =
79       CurrentSourceLocExprScope::SourceLocExprScopeGuard;
80 
81   static QualType getType(APValue::LValueBase B) {
82     return B.getType();
83   }
84 
85   /// Get an LValue path entry, which is known to not be an array index, as a
86   /// field declaration.
87   static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
88     return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
89   }
90   /// Get an LValue path entry, which is known to not be an array index, as a
91   /// base class declaration.
92   static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
93     return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
94   }
95   /// Determine whether this LValue path entry for a base class names a virtual
96   /// base class.
97   static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
98     return E.getAsBaseOrMember().getInt();
99   }
100 
101   /// Given an expression, determine the type used to store the result of
102   /// evaluating that expression.
103   static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
104     if (E->isPRValue())
105       return E->getType();
106     return Ctx.getLValueReferenceType(E->getType());
107   }
108 
109   /// Given a CallExpr, try to get the alloc_size attribute. May return null.
110   static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
111     if (const FunctionDecl *DirectCallee = CE->getDirectCallee())
112       return DirectCallee->getAttr<AllocSizeAttr>();
113     if (const Decl *IndirectCallee = CE->getCalleeDecl())
114       return IndirectCallee->getAttr<AllocSizeAttr>();
115     return nullptr;
116   }
117 
118   /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
119   /// This will look through a single cast.
120   ///
121   /// Returns null if we couldn't unwrap a function with alloc_size.
122   static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
123     if (!E->getType()->isPointerType())
124       return nullptr;
125 
126     E = E->IgnoreParens();
127     // If we're doing a variable assignment from e.g. malloc(N), there will
128     // probably be a cast of some kind. In exotic cases, we might also see a
129     // top-level ExprWithCleanups. Ignore them either way.
130     if (const auto *FE = dyn_cast<FullExpr>(E))
131       E = FE->getSubExpr()->IgnoreParens();
132 
133     if (const auto *Cast = dyn_cast<CastExpr>(E))
134       E = Cast->getSubExpr()->IgnoreParens();
135 
136     if (const auto *CE = dyn_cast<CallExpr>(E))
137       return getAllocSizeAttr(CE) ? CE : nullptr;
138     return nullptr;
139   }
140 
141   /// Determines whether or not the given Base contains a call to a function
142   /// with the alloc_size attribute.
143   static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
144     const auto *E = Base.dyn_cast<const Expr *>();
145     return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
146   }
147 
148   /// Determines whether the given kind of constant expression is only ever
149   /// used for name mangling. If so, it's permitted to reference things that we
150   /// can't generate code for (in particular, dllimported functions).
151   static bool isForManglingOnly(ConstantExprKind Kind) {
152     switch (Kind) {
153     case ConstantExprKind::Normal:
154     case ConstantExprKind::ClassTemplateArgument:
155     case ConstantExprKind::ImmediateInvocation:
156       // Note that non-type template arguments of class type are emitted as
157       // template parameter objects.
158       return false;
159 
160     case ConstantExprKind::NonClassTemplateArgument:
161       return true;
162     }
163     llvm_unreachable("unknown ConstantExprKind");
164   }
165 
166   static bool isTemplateArgument(ConstantExprKind Kind) {
167     switch (Kind) {
168     case ConstantExprKind::Normal:
169     case ConstantExprKind::ImmediateInvocation:
170       return false;
171 
172     case ConstantExprKind::ClassTemplateArgument:
173     case ConstantExprKind::NonClassTemplateArgument:
174       return true;
175     }
176     llvm_unreachable("unknown ConstantExprKind");
177   }
178 
179   /// The bound to claim that an array of unknown bound has.
180   /// The value in MostDerivedArraySize is undefined in this case. So, set it
181   /// to an arbitrary value that's likely to loudly break things if it's used.
182   static const uint64_t AssumedSizeForUnsizedArray =
183       std::numeric_limits<uint64_t>::max() / 2;
184 
185   /// Determines if an LValue with the given LValueBase will have an unsized
186   /// array in its designator.
187   /// Find the path length and type of the most-derived subobject in the given
188   /// path, and find the size of the containing array, if any.
189   static unsigned
190   findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
191                            ArrayRef<APValue::LValuePathEntry> Path,
192                            uint64_t &ArraySize, QualType &Type, bool &IsArray,
193                            bool &FirstEntryIsUnsizedArray) {
194     // This only accepts LValueBases from APValues, and APValues don't support
195     // arrays that lack size info.
196     assert(!isBaseAnAllocSizeCall(Base) &&
197            "Unsized arrays shouldn't appear here");
198     unsigned MostDerivedLength = 0;
199     Type = getType(Base);
200 
201     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
202       if (Type->isArrayType()) {
203         const ArrayType *AT = Ctx.getAsArrayType(Type);
204         Type = AT->getElementType();
205         MostDerivedLength = I + 1;
206         IsArray = true;
207 
208         if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
209           ArraySize = CAT->getSize().getZExtValue();
210         } else {
211           assert(I == 0 && "unexpected unsized array designator");
212           FirstEntryIsUnsizedArray = true;
213           ArraySize = AssumedSizeForUnsizedArray;
214         }
215       } else if (Type->isAnyComplexType()) {
216         const ComplexType *CT = Type->castAs<ComplexType>();
217         Type = CT->getElementType();
218         ArraySize = 2;
219         MostDerivedLength = I + 1;
220         IsArray = true;
221       } else if (const FieldDecl *FD = getAsField(Path[I])) {
222         Type = FD->getType();
223         ArraySize = 0;
224         MostDerivedLength = I + 1;
225         IsArray = false;
226       } else {
227         // Path[I] describes a base class.
228         ArraySize = 0;
229         IsArray = false;
230       }
231     }
232     return MostDerivedLength;
233   }
234 
235   /// A path from a glvalue to a subobject of that glvalue.
236   struct SubobjectDesignator {
237     /// True if the subobject was named in a manner not supported by C++11. Such
238     /// lvalues can still be folded, but they are not core constant expressions
239     /// and we cannot perform lvalue-to-rvalue conversions on them.
240     unsigned Invalid : 1;
241 
242     /// Is this a pointer one past the end of an object?
243     unsigned IsOnePastTheEnd : 1;
244 
245     /// Indicator of whether the first entry is an unsized array.
246     unsigned FirstEntryIsAnUnsizedArray : 1;
247 
248     /// Indicator of whether the most-derived object is an array element.
249     unsigned MostDerivedIsArrayElement : 1;
250 
251     /// The length of the path to the most-derived object of which this is a
252     /// subobject.
253     unsigned MostDerivedPathLength : 28;
254 
255     /// The size of the array of which the most-derived object is an element.
256     /// This will always be 0 if the most-derived object is not an array
257     /// element. 0 is not an indicator of whether or not the most-derived object
258     /// is an array, however, because 0-length arrays are allowed.
259     ///
260     /// If the current array is an unsized array, the value of this is
261     /// undefined.
262     uint64_t MostDerivedArraySize;
263 
264     /// The type of the most derived object referred to by this address.
265     QualType MostDerivedType;
266 
267     typedef APValue::LValuePathEntry PathEntry;
268 
269     /// The entries on the path from the glvalue to the designated subobject.
270     SmallVector<PathEntry, 8> Entries;
271 
272     SubobjectDesignator() : Invalid(true) {}
273 
274     explicit SubobjectDesignator(QualType T)
275         : Invalid(false), IsOnePastTheEnd(false),
276           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
277           MostDerivedPathLength(0), MostDerivedArraySize(0),
278           MostDerivedType(T) {}
279 
280     SubobjectDesignator(ASTContext &Ctx, const APValue &V)
281         : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
282           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
283           MostDerivedPathLength(0), MostDerivedArraySize(0) {
284       assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
285       if (!Invalid) {
286         IsOnePastTheEnd = V.isLValueOnePastTheEnd();
287         ArrayRef<PathEntry> VEntries = V.getLValuePath();
288         Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
289         if (V.getLValueBase()) {
290           bool IsArray = false;
291           bool FirstIsUnsizedArray = false;
292           MostDerivedPathLength = findMostDerivedSubobject(
293               Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
294               MostDerivedType, IsArray, FirstIsUnsizedArray);
295           MostDerivedIsArrayElement = IsArray;
296           FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
297         }
298       }
299     }
300 
301     void truncate(ASTContext &Ctx, APValue::LValueBase Base,
302                   unsigned NewLength) {
303       if (Invalid)
304         return;
305 
306       assert(Base && "cannot truncate path for null pointer");
307       assert(NewLength <= Entries.size() && "not a truncation");
308 
309       if (NewLength == Entries.size())
310         return;
311       Entries.resize(NewLength);
312 
313       bool IsArray = false;
314       bool FirstIsUnsizedArray = false;
315       MostDerivedPathLength = findMostDerivedSubobject(
316           Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
317           FirstIsUnsizedArray);
318       MostDerivedIsArrayElement = IsArray;
319       FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
320     }
321 
322     void setInvalid() {
323       Invalid = true;
324       Entries.clear();
325     }
326 
327     /// Determine whether the most derived subobject is an array without a
328     /// known bound.
329     bool isMostDerivedAnUnsizedArray() const {
330       assert(!Invalid && "Calling this makes no sense on invalid designators");
331       return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
332     }
333 
334     /// Determine what the most derived array's size is. Results in an assertion
335     /// failure if the most derived array lacks a size.
336     uint64_t getMostDerivedArraySize() const {
337       assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
338       return MostDerivedArraySize;
339     }
340 
341     /// Determine whether this is a one-past-the-end pointer.
342     bool isOnePastTheEnd() const {
343       assert(!Invalid);
344       if (IsOnePastTheEnd)
345         return true;
346       if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
347           Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
348               MostDerivedArraySize)
349         return true;
350       return false;
351     }
352 
353     /// Get the range of valid index adjustments in the form
354     ///   {maximum value that can be subtracted from this pointer,
355     ///    maximum value that can be added to this pointer}
356     std::pair<uint64_t, uint64_t> validIndexAdjustments() {
357       if (Invalid || isMostDerivedAnUnsizedArray())
358         return {0, 0};
359 
360       // [expr.add]p4: For the purposes of these operators, a pointer to a
361       // nonarray object behaves the same as a pointer to the first element of
362       // an array of length one with the type of the object as its element type.
363       bool IsArray = MostDerivedPathLength == Entries.size() &&
364                      MostDerivedIsArrayElement;
365       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
366                                     : (uint64_t)IsOnePastTheEnd;
367       uint64_t ArraySize =
368           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
369       return {ArrayIndex, ArraySize - ArrayIndex};
370     }
371 
372     /// Check that this refers to a valid subobject.
373     bool isValidSubobject() const {
374       if (Invalid)
375         return false;
376       return !isOnePastTheEnd();
377     }
378     /// Check that this refers to a valid subobject, and if not, produce a
379     /// relevant diagnostic and set the designator as invalid.
380     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
381 
382     /// Get the type of the designated object.
383     QualType getType(ASTContext &Ctx) const {
384       assert(!Invalid && "invalid designator has no subobject type");
385       return MostDerivedPathLength == Entries.size()
386                  ? MostDerivedType
387                  : Ctx.getRecordType(getAsBaseClass(Entries.back()));
388     }
389 
390     /// Update this designator to refer to the first element within this array.
391     void addArrayUnchecked(const ConstantArrayType *CAT) {
392       Entries.push_back(PathEntry::ArrayIndex(0));
393 
394       // This is a most-derived object.
395       MostDerivedType = CAT->getElementType();
396       MostDerivedIsArrayElement = true;
397       MostDerivedArraySize = CAT->getSize().getZExtValue();
398       MostDerivedPathLength = Entries.size();
399     }
400     /// Update this designator to refer to the first element within the array of
401     /// elements of type T. This is an array of unknown size.
402     void addUnsizedArrayUnchecked(QualType ElemTy) {
403       Entries.push_back(PathEntry::ArrayIndex(0));
404 
405       MostDerivedType = ElemTy;
406       MostDerivedIsArrayElement = true;
407       // The value in MostDerivedArraySize is undefined in this case. So, set it
408       // to an arbitrary value that's likely to loudly break things if it's
409       // used.
410       MostDerivedArraySize = AssumedSizeForUnsizedArray;
411       MostDerivedPathLength = Entries.size();
412     }
413     /// Update this designator to refer to the given base or member of this
414     /// object.
415     void addDeclUnchecked(const Decl *D, bool Virtual = false) {
416       Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
417 
418       // If this isn't a base class, it's a new most-derived object.
419       if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
420         MostDerivedType = FD->getType();
421         MostDerivedIsArrayElement = false;
422         MostDerivedArraySize = 0;
423         MostDerivedPathLength = Entries.size();
424       }
425     }
426     /// Update this designator to refer to the given complex component.
427     void addComplexUnchecked(QualType EltTy, bool Imag) {
428       Entries.push_back(PathEntry::ArrayIndex(Imag));
429 
430       // This is technically a most-derived object, though in practice this
431       // is unlikely to matter.
432       MostDerivedType = EltTy;
433       MostDerivedIsArrayElement = true;
434       MostDerivedArraySize = 2;
435       MostDerivedPathLength = Entries.size();
436     }
437     void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
438     void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
439                                    const APSInt &N);
440     /// Add N to the address of this subobject.
441     void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
442       if (Invalid || !N) return;
443       uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
444       if (isMostDerivedAnUnsizedArray()) {
445         diagnoseUnsizedArrayPointerArithmetic(Info, E);
446         // Can't verify -- trust that the user is doing the right thing (or if
447         // not, trust that the caller will catch the bad behavior).
448         // FIXME: Should we reject if this overflows, at least?
449         Entries.back() = PathEntry::ArrayIndex(
450             Entries.back().getAsArrayIndex() + TruncatedN);
451         return;
452       }
453 
454       // [expr.add]p4: For the purposes of these operators, a pointer to a
455       // nonarray object behaves the same as a pointer to the first element of
456       // an array of length one with the type of the object as its element type.
457       bool IsArray = MostDerivedPathLength == Entries.size() &&
458                      MostDerivedIsArrayElement;
459       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
460                                     : (uint64_t)IsOnePastTheEnd;
461       uint64_t ArraySize =
462           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
463 
464       if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
465         // Calculate the actual index in a wide enough type, so we can include
466         // it in the note.
467         N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
468         (llvm::APInt&)N += ArrayIndex;
469         assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
470         diagnosePointerArithmetic(Info, E, N);
471         setInvalid();
472         return;
473       }
474 
475       ArrayIndex += TruncatedN;
476       assert(ArrayIndex <= ArraySize &&
477              "bounds check succeeded for out-of-bounds index");
478 
479       if (IsArray)
480         Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
481       else
482         IsOnePastTheEnd = (ArrayIndex != 0);
483     }
484   };
485 
486   /// A scope at the end of which an object can need to be destroyed.
487   enum class ScopeKind {
488     Block,
489     FullExpression,
490     Call
491   };
492 
493   /// A reference to a particular call and its arguments.
494   struct CallRef {
495     CallRef() : OrigCallee(), CallIndex(0), Version() {}
496     CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
497         : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
498 
499     explicit operator bool() const { return OrigCallee; }
500 
501     /// Get the parameter that the caller initialized, corresponding to the
502     /// given parameter in the callee.
503     const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
504       return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
505                         : PVD;
506     }
507 
508     /// The callee at the point where the arguments were evaluated. This might
509     /// be different from the actual callee (a different redeclaration, or a
510     /// virtual override), but this function's parameters are the ones that
511     /// appear in the parameter map.
512     const FunctionDecl *OrigCallee;
513     /// The call index of the frame that holds the argument values.
514     unsigned CallIndex;
515     /// The version of the parameters corresponding to this call.
516     unsigned Version;
517   };
518 
519   /// A stack frame in the constexpr call stack.
520   class CallStackFrame : public interp::Frame {
521   public:
522     EvalInfo &Info;
523 
524     /// Parent - The caller of this stack frame.
525     CallStackFrame *Caller;
526 
527     /// Callee - The function which was called.
528     const FunctionDecl *Callee;
529 
530     /// This - The binding for the this pointer in this call, if any.
531     const LValue *This;
532 
533     /// Information on how to find the arguments to this call. Our arguments
534     /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
535     /// key and this value as the version.
536     CallRef Arguments;
537 
538     /// Source location information about the default argument or default
539     /// initializer expression we're evaluating, if any.
540     CurrentSourceLocExprScope CurSourceLocExprScope;
541 
542     // Note that we intentionally use std::map here so that references to
543     // values are stable.
544     typedef std::pair<const void *, unsigned> MapKeyTy;
545     typedef std::map<MapKeyTy, APValue> MapTy;
546     /// Temporaries - Temporary lvalues materialized within this stack frame.
547     MapTy Temporaries;
548 
549     /// CallLoc - The location of the call expression for this call.
550     SourceLocation CallLoc;
551 
552     /// Index - The call index of this call.
553     unsigned Index;
554 
555     /// The stack of integers for tracking version numbers for temporaries.
556     SmallVector<unsigned, 2> TempVersionStack = {1};
557     unsigned CurTempVersion = TempVersionStack.back();
558 
559     unsigned getTempVersion() const { return TempVersionStack.back(); }
560 
561     void pushTempVersion() {
562       TempVersionStack.push_back(++CurTempVersion);
563     }
564 
565     void popTempVersion() {
566       TempVersionStack.pop_back();
567     }
568 
569     CallRef createCall(const FunctionDecl *Callee) {
570       return {Callee, Index, ++CurTempVersion};
571     }
572 
573     // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
574     // on the overall stack usage of deeply-recursing constexpr evaluations.
575     // (We should cache this map rather than recomputing it repeatedly.)
576     // But let's try this and see how it goes; we can look into caching the map
577     // as a later change.
578 
579     /// LambdaCaptureFields - Mapping from captured variables/this to
580     /// corresponding data members in the closure class.
581     llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
582     FieldDecl *LambdaThisCaptureField;
583 
584     CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
585                    const FunctionDecl *Callee, const LValue *This,
586                    CallRef Arguments);
587     ~CallStackFrame();
588 
589     // Return the temporary for Key whose version number is Version.
590     APValue *getTemporary(const void *Key, unsigned Version) {
591       MapKeyTy KV(Key, Version);
592       auto LB = Temporaries.lower_bound(KV);
593       if (LB != Temporaries.end() && LB->first == KV)
594         return &LB->second;
595       // Pair (Key,Version) wasn't found in the map. Check that no elements
596       // in the map have 'Key' as their key.
597       assert((LB == Temporaries.end() || LB->first.first != Key) &&
598              (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
599              "Element with key 'Key' found in map");
600       return nullptr;
601     }
602 
603     // Return the current temporary for Key in the map.
604     APValue *getCurrentTemporary(const void *Key) {
605       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
606       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
607         return &std::prev(UB)->second;
608       return nullptr;
609     }
610 
611     // Return the version number of the current temporary for Key.
612     unsigned getCurrentTemporaryVersion(const void *Key) const {
613       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
614       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
615         return std::prev(UB)->first.second;
616       return 0;
617     }
618 
619     /// Allocate storage for an object of type T in this stack frame.
620     /// Populates LV with a handle to the created object. Key identifies
621     /// the temporary within the stack frame, and must not be reused without
622     /// bumping the temporary version number.
623     template<typename KeyT>
624     APValue &createTemporary(const KeyT *Key, QualType T,
625                              ScopeKind Scope, LValue &LV);
626 
627     /// Allocate storage for a parameter of a function call made in this frame.
628     APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
629 
630     void describe(llvm::raw_ostream &OS) override;
631 
632     Frame *getCaller() const override { return Caller; }
633     SourceLocation getCallLocation() const override { return CallLoc; }
634     const FunctionDecl *getCallee() const override { return Callee; }
635 
636     bool isStdFunction() const {
637       for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
638         if (DC->isStdNamespace())
639           return true;
640       return false;
641     }
642 
643   private:
644     APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
645                          ScopeKind Scope);
646   };
647 
648   /// Temporarily override 'this'.
649   class ThisOverrideRAII {
650   public:
651     ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
652         : Frame(Frame), OldThis(Frame.This) {
653       if (Enable)
654         Frame.This = NewThis;
655     }
656     ~ThisOverrideRAII() {
657       Frame.This = OldThis;
658     }
659   private:
660     CallStackFrame &Frame;
661     const LValue *OldThis;
662   };
663 }
664 
665 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
666                               const LValue &This, QualType ThisType);
667 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
668                               APValue::LValueBase LVBase, APValue &Value,
669                               QualType T);
670 
671 namespace {
672   /// A cleanup, and a flag indicating whether it is lifetime-extended.
673   class Cleanup {
674     llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
675     APValue::LValueBase Base;
676     QualType T;
677 
678   public:
679     Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
680             ScopeKind Scope)
681         : Value(Val, Scope), Base(Base), T(T) {}
682 
683     /// Determine whether this cleanup should be performed at the end of the
684     /// given kind of scope.
685     bool isDestroyedAtEndOf(ScopeKind K) const {
686       return (int)Value.getInt() >= (int)K;
687     }
688     bool endLifetime(EvalInfo &Info, bool RunDestructors) {
689       if (RunDestructors) {
690         SourceLocation Loc;
691         if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
692           Loc = VD->getLocation();
693         else if (const Expr *E = Base.dyn_cast<const Expr*>())
694           Loc = E->getExprLoc();
695         return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
696       }
697       *Value.getPointer() = APValue();
698       return true;
699     }
700 
701     bool hasSideEffect() {
702       return T.isDestructedType();
703     }
704   };
705 
706   /// A reference to an object whose construction we are currently evaluating.
707   struct ObjectUnderConstruction {
708     APValue::LValueBase Base;
709     ArrayRef<APValue::LValuePathEntry> Path;
710     friend bool operator==(const ObjectUnderConstruction &LHS,
711                            const ObjectUnderConstruction &RHS) {
712       return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
713     }
714     friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
715       return llvm::hash_combine(Obj.Base, Obj.Path);
716     }
717   };
718   enum class ConstructionPhase {
719     None,
720     Bases,
721     AfterBases,
722     AfterFields,
723     Destroying,
724     DestroyingBases
725   };
726 }
727 
728 namespace llvm {
729 template<> struct DenseMapInfo<ObjectUnderConstruction> {
730   using Base = DenseMapInfo<APValue::LValueBase>;
731   static ObjectUnderConstruction getEmptyKey() {
732     return {Base::getEmptyKey(), {}}; }
733   static ObjectUnderConstruction getTombstoneKey() {
734     return {Base::getTombstoneKey(), {}};
735   }
736   static unsigned getHashValue(const ObjectUnderConstruction &Object) {
737     return hash_value(Object);
738   }
739   static bool isEqual(const ObjectUnderConstruction &LHS,
740                       const ObjectUnderConstruction &RHS) {
741     return LHS == RHS;
742   }
743 };
744 }
745 
746 namespace {
747   /// A dynamically-allocated heap object.
748   struct DynAlloc {
749     /// The value of this heap-allocated object.
750     APValue Value;
751     /// The allocating expression; used for diagnostics. Either a CXXNewExpr
752     /// or a CallExpr (the latter is for direct calls to operator new inside
753     /// std::allocator<T>::allocate).
754     const Expr *AllocExpr = nullptr;
755 
756     enum Kind {
757       New,
758       ArrayNew,
759       StdAllocator
760     };
761 
762     /// Get the kind of the allocation. This must match between allocation
763     /// and deallocation.
764     Kind getKind() const {
765       if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
766         return NE->isArray() ? ArrayNew : New;
767       assert(isa<CallExpr>(AllocExpr));
768       return StdAllocator;
769     }
770   };
771 
772   struct DynAllocOrder {
773     bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
774       return L.getIndex() < R.getIndex();
775     }
776   };
777 
778   /// EvalInfo - This is a private struct used by the evaluator to capture
779   /// information about a subexpression as it is folded.  It retains information
780   /// about the AST context, but also maintains information about the folded
781   /// expression.
782   ///
783   /// If an expression could be evaluated, it is still possible it is not a C
784   /// "integer constant expression" or constant expression.  If not, this struct
785   /// captures information about how and why not.
786   ///
787   /// One bit of information passed *into* the request for constant folding
788   /// indicates whether the subexpression is "evaluated" or not according to C
789   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
790   /// evaluate the expression regardless of what the RHS is, but C only allows
791   /// certain things in certain situations.
792   class EvalInfo : public interp::State {
793   public:
794     ASTContext &Ctx;
795 
796     /// EvalStatus - Contains information about the evaluation.
797     Expr::EvalStatus &EvalStatus;
798 
799     /// CurrentCall - The top of the constexpr call stack.
800     CallStackFrame *CurrentCall;
801 
802     /// CallStackDepth - The number of calls in the call stack right now.
803     unsigned CallStackDepth;
804 
805     /// NextCallIndex - The next call index to assign.
806     unsigned NextCallIndex;
807 
808     /// StepsLeft - The remaining number of evaluation steps we're permitted
809     /// to perform. This is essentially a limit for the number of statements
810     /// we will evaluate.
811     unsigned StepsLeft;
812 
813     /// Enable the experimental new constant interpreter. If an expression is
814     /// not supported by the interpreter, an error is triggered.
815     bool EnableNewConstInterp;
816 
817     /// BottomFrame - The frame in which evaluation started. This must be
818     /// initialized after CurrentCall and CallStackDepth.
819     CallStackFrame BottomFrame;
820 
821     /// A stack of values whose lifetimes end at the end of some surrounding
822     /// evaluation frame.
823     llvm::SmallVector<Cleanup, 16> CleanupStack;
824 
825     /// EvaluatingDecl - This is the declaration whose initializer is being
826     /// evaluated, if any.
827     APValue::LValueBase EvaluatingDecl;
828 
829     enum class EvaluatingDeclKind {
830       None,
831       /// We're evaluating the construction of EvaluatingDecl.
832       Ctor,
833       /// We're evaluating the destruction of EvaluatingDecl.
834       Dtor,
835     };
836     EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
837 
838     /// EvaluatingDeclValue - This is the value being constructed for the
839     /// declaration whose initializer is being evaluated, if any.
840     APValue *EvaluatingDeclValue;
841 
842     /// Set of objects that are currently being constructed.
843     llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
844         ObjectsUnderConstruction;
845 
846     /// Current heap allocations, along with the location where each was
847     /// allocated. We use std::map here because we need stable addresses
848     /// for the stored APValues.
849     std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
850 
851     /// The number of heap allocations performed so far in this evaluation.
852     unsigned NumHeapAllocs = 0;
853 
854     struct EvaluatingConstructorRAII {
855       EvalInfo &EI;
856       ObjectUnderConstruction Object;
857       bool DidInsert;
858       EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
859                                 bool HasBases)
860           : EI(EI), Object(Object) {
861         DidInsert =
862             EI.ObjectsUnderConstruction
863                 .insert({Object, HasBases ? ConstructionPhase::Bases
864                                           : ConstructionPhase::AfterBases})
865                 .second;
866       }
867       void finishedConstructingBases() {
868         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
869       }
870       void finishedConstructingFields() {
871         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
872       }
873       ~EvaluatingConstructorRAII() {
874         if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
875       }
876     };
877 
878     struct EvaluatingDestructorRAII {
879       EvalInfo &EI;
880       ObjectUnderConstruction Object;
881       bool DidInsert;
882       EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
883           : EI(EI), Object(Object) {
884         DidInsert = EI.ObjectsUnderConstruction
885                         .insert({Object, ConstructionPhase::Destroying})
886                         .second;
887       }
888       void startedDestroyingBases() {
889         EI.ObjectsUnderConstruction[Object] =
890             ConstructionPhase::DestroyingBases;
891       }
892       ~EvaluatingDestructorRAII() {
893         if (DidInsert)
894           EI.ObjectsUnderConstruction.erase(Object);
895       }
896     };
897 
898     ConstructionPhase
899     isEvaluatingCtorDtor(APValue::LValueBase Base,
900                          ArrayRef<APValue::LValuePathEntry> Path) {
901       return ObjectsUnderConstruction.lookup({Base, Path});
902     }
903 
904     /// If we're currently speculatively evaluating, the outermost call stack
905     /// depth at which we can mutate state, otherwise 0.
906     unsigned SpeculativeEvaluationDepth = 0;
907 
908     /// The current array initialization index, if we're performing array
909     /// initialization.
910     uint64_t ArrayInitIndex = -1;
911 
912     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
913     /// notes attached to it will also be stored, otherwise they will not be.
914     bool HasActiveDiagnostic;
915 
916     /// Have we emitted a diagnostic explaining why we couldn't constant
917     /// fold (not just why it's not strictly a constant expression)?
918     bool HasFoldFailureDiagnostic;
919 
920     /// Whether or not we're in a context where the front end requires a
921     /// constant value.
922     bool InConstantContext;
923 
924     /// Whether we're checking that an expression is a potential constant
925     /// expression. If so, do not fail on constructs that could become constant
926     /// later on (such as a use of an undefined global).
927     bool CheckingPotentialConstantExpression = false;
928 
929     /// Whether we're checking for an expression that has undefined behavior.
930     /// If so, we will produce warnings if we encounter an operation that is
931     /// always undefined.
932     ///
933     /// Note that we still need to evaluate the expression normally when this
934     /// is set; this is used when evaluating ICEs in C.
935     bool CheckingForUndefinedBehavior = false;
936 
937     enum EvaluationMode {
938       /// Evaluate as a constant expression. Stop if we find that the expression
939       /// is not a constant expression.
940       EM_ConstantExpression,
941 
942       /// Evaluate as a constant expression. Stop if we find that the expression
943       /// is not a constant expression. Some expressions can be retried in the
944       /// optimizer if we don't constant fold them here, but in an unevaluated
945       /// context we try to fold them immediately since the optimizer never
946       /// gets a chance to look at it.
947       EM_ConstantExpressionUnevaluated,
948 
949       /// Fold the expression to a constant. Stop if we hit a side-effect that
950       /// we can't model.
951       EM_ConstantFold,
952 
953       /// Evaluate in any way we know how. Don't worry about side-effects that
954       /// can't be modeled.
955       EM_IgnoreSideEffects,
956     } EvalMode;
957 
958     /// Are we checking whether the expression is a potential constant
959     /// expression?
960     bool checkingPotentialConstantExpression() const override  {
961       return CheckingPotentialConstantExpression;
962     }
963 
964     /// Are we checking an expression for overflow?
965     // FIXME: We should check for any kind of undefined or suspicious behavior
966     // in such constructs, not just overflow.
967     bool checkingForUndefinedBehavior() const override {
968       return CheckingForUndefinedBehavior;
969     }
970 
971     EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
972         : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
973           CallStackDepth(0), NextCallIndex(1),
974           StepsLeft(C.getLangOpts().ConstexprStepLimit),
975           EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
976           BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()),
977           EvaluatingDecl((const ValueDecl *)nullptr),
978           EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
979           HasFoldFailureDiagnostic(false), InConstantContext(false),
980           EvalMode(Mode) {}
981 
982     ~EvalInfo() {
983       discardCleanups();
984     }
985 
986     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
987                            EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
988       EvaluatingDecl = Base;
989       IsEvaluatingDecl = EDK;
990       EvaluatingDeclValue = &Value;
991     }
992 
993     bool CheckCallLimit(SourceLocation Loc) {
994       // Don't perform any constexpr calls (other than the call we're checking)
995       // when checking a potential constant expression.
996       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
997         return false;
998       if (NextCallIndex == 0) {
999         // NextCallIndex has wrapped around.
1000         FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
1001         return false;
1002       }
1003       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
1004         return true;
1005       FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
1006         << getLangOpts().ConstexprCallDepth;
1007       return false;
1008     }
1009 
1010     std::pair<CallStackFrame *, unsigned>
1011     getCallFrameAndDepth(unsigned CallIndex) {
1012       assert(CallIndex && "no call index in getCallFrameAndDepth");
1013       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1014       // be null in this loop.
1015       unsigned Depth = CallStackDepth;
1016       CallStackFrame *Frame = CurrentCall;
1017       while (Frame->Index > CallIndex) {
1018         Frame = Frame->Caller;
1019         --Depth;
1020       }
1021       if (Frame->Index == CallIndex)
1022         return {Frame, Depth};
1023       return {nullptr, 0};
1024     }
1025 
1026     bool nextStep(const Stmt *S) {
1027       if (!StepsLeft) {
1028         FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1029         return false;
1030       }
1031       --StepsLeft;
1032       return true;
1033     }
1034 
1035     APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1036 
1037     Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) {
1038       Optional<DynAlloc*> Result;
1039       auto It = HeapAllocs.find(DA);
1040       if (It != HeapAllocs.end())
1041         Result = &It->second;
1042       return Result;
1043     }
1044 
1045     /// Get the allocated storage for the given parameter of the given call.
1046     APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1047       CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1048       return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1049                    : nullptr;
1050     }
1051 
1052     /// Information about a stack frame for std::allocator<T>::[de]allocate.
1053     struct StdAllocatorCaller {
1054       unsigned FrameIndex;
1055       QualType ElemType;
1056       explicit operator bool() const { return FrameIndex != 0; };
1057     };
1058 
1059     StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1060       for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1061            Call = Call->Caller) {
1062         const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1063         if (!MD)
1064           continue;
1065         const IdentifierInfo *FnII = MD->getIdentifier();
1066         if (!FnII || !FnII->isStr(FnName))
1067           continue;
1068 
1069         const auto *CTSD =
1070             dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1071         if (!CTSD)
1072           continue;
1073 
1074         const IdentifierInfo *ClassII = CTSD->getIdentifier();
1075         const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1076         if (CTSD->isInStdNamespace() && ClassII &&
1077             ClassII->isStr("allocator") && TAL.size() >= 1 &&
1078             TAL[0].getKind() == TemplateArgument::Type)
1079           return {Call->Index, TAL[0].getAsType()};
1080       }
1081 
1082       return {};
1083     }
1084 
1085     void performLifetimeExtension() {
1086       // Disable the cleanups for lifetime-extended temporaries.
1087       CleanupStack.erase(std::remove_if(CleanupStack.begin(),
1088                                         CleanupStack.end(),
1089                                         [](Cleanup &C) {
1090                                           return !C.isDestroyedAtEndOf(
1091                                               ScopeKind::FullExpression);
1092                                         }),
1093                          CleanupStack.end());
1094      }
1095 
1096     /// Throw away any remaining cleanups at the end of evaluation. If any
1097     /// cleanups would have had a side-effect, note that as an unmodeled
1098     /// side-effect and return false. Otherwise, return true.
1099     bool discardCleanups() {
1100       for (Cleanup &C : CleanupStack) {
1101         if (C.hasSideEffect() && !noteSideEffect()) {
1102           CleanupStack.clear();
1103           return false;
1104         }
1105       }
1106       CleanupStack.clear();
1107       return true;
1108     }
1109 
1110   private:
1111     interp::Frame *getCurrentFrame() override { return CurrentCall; }
1112     const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1113 
1114     bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1115     void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1116 
1117     void setFoldFailureDiagnostic(bool Flag) override {
1118       HasFoldFailureDiagnostic = Flag;
1119     }
1120 
1121     Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1122 
1123     ASTContext &getCtx() const override { return Ctx; }
1124 
1125     // If we have a prior diagnostic, it will be noting that the expression
1126     // isn't a constant expression. This diagnostic is more important,
1127     // unless we require this evaluation to produce a constant expression.
1128     //
1129     // FIXME: We might want to show both diagnostics to the user in
1130     // EM_ConstantFold mode.
1131     bool hasPriorDiagnostic() override {
1132       if (!EvalStatus.Diag->empty()) {
1133         switch (EvalMode) {
1134         case EM_ConstantFold:
1135         case EM_IgnoreSideEffects:
1136           if (!HasFoldFailureDiagnostic)
1137             break;
1138           // We've already failed to fold something. Keep that diagnostic.
1139           LLVM_FALLTHROUGH;
1140         case EM_ConstantExpression:
1141         case EM_ConstantExpressionUnevaluated:
1142           setActiveDiagnostic(false);
1143           return true;
1144         }
1145       }
1146       return false;
1147     }
1148 
1149     unsigned getCallStackDepth() override { return CallStackDepth; }
1150 
1151   public:
1152     /// Should we continue evaluation after encountering a side-effect that we
1153     /// couldn't model?
1154     bool keepEvaluatingAfterSideEffect() {
1155       switch (EvalMode) {
1156       case EM_IgnoreSideEffects:
1157         return true;
1158 
1159       case EM_ConstantExpression:
1160       case EM_ConstantExpressionUnevaluated:
1161       case EM_ConstantFold:
1162         // By default, assume any side effect might be valid in some other
1163         // evaluation of this expression from a different context.
1164         return checkingPotentialConstantExpression() ||
1165                checkingForUndefinedBehavior();
1166       }
1167       llvm_unreachable("Missed EvalMode case");
1168     }
1169 
1170     /// Note that we have had a side-effect, and determine whether we should
1171     /// keep evaluating.
1172     bool noteSideEffect() {
1173       EvalStatus.HasSideEffects = true;
1174       return keepEvaluatingAfterSideEffect();
1175     }
1176 
1177     /// Should we continue evaluation after encountering undefined behavior?
1178     bool keepEvaluatingAfterUndefinedBehavior() {
1179       switch (EvalMode) {
1180       case EM_IgnoreSideEffects:
1181       case EM_ConstantFold:
1182         return true;
1183 
1184       case EM_ConstantExpression:
1185       case EM_ConstantExpressionUnevaluated:
1186         return checkingForUndefinedBehavior();
1187       }
1188       llvm_unreachable("Missed EvalMode case");
1189     }
1190 
1191     /// Note that we hit something that was technically undefined behavior, but
1192     /// that we can evaluate past it (such as signed overflow or floating-point
1193     /// division by zero.)
1194     bool noteUndefinedBehavior() override {
1195       EvalStatus.HasUndefinedBehavior = true;
1196       return keepEvaluatingAfterUndefinedBehavior();
1197     }
1198 
1199     /// Should we continue evaluation as much as possible after encountering a
1200     /// construct which can't be reduced to a value?
1201     bool keepEvaluatingAfterFailure() const override {
1202       if (!StepsLeft)
1203         return false;
1204 
1205       switch (EvalMode) {
1206       case EM_ConstantExpression:
1207       case EM_ConstantExpressionUnevaluated:
1208       case EM_ConstantFold:
1209       case EM_IgnoreSideEffects:
1210         return checkingPotentialConstantExpression() ||
1211                checkingForUndefinedBehavior();
1212       }
1213       llvm_unreachable("Missed EvalMode case");
1214     }
1215 
1216     /// Notes that we failed to evaluate an expression that other expressions
1217     /// directly depend on, and determine if we should keep evaluating. This
1218     /// should only be called if we actually intend to keep evaluating.
1219     ///
1220     /// Call noteSideEffect() instead if we may be able to ignore the value that
1221     /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1222     ///
1223     /// (Foo(), 1)      // use noteSideEffect
1224     /// (Foo() || true) // use noteSideEffect
1225     /// Foo() + 1       // use noteFailure
1226     LLVM_NODISCARD bool noteFailure() {
1227       // Failure when evaluating some expression often means there is some
1228       // subexpression whose evaluation was skipped. Therefore, (because we
1229       // don't track whether we skipped an expression when unwinding after an
1230       // evaluation failure) every evaluation failure that bubbles up from a
1231       // subexpression implies that a side-effect has potentially happened. We
1232       // skip setting the HasSideEffects flag to true until we decide to
1233       // continue evaluating after that point, which happens here.
1234       bool KeepGoing = keepEvaluatingAfterFailure();
1235       EvalStatus.HasSideEffects |= KeepGoing;
1236       return KeepGoing;
1237     }
1238 
1239     class ArrayInitLoopIndex {
1240       EvalInfo &Info;
1241       uint64_t OuterIndex;
1242 
1243     public:
1244       ArrayInitLoopIndex(EvalInfo &Info)
1245           : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1246         Info.ArrayInitIndex = 0;
1247       }
1248       ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1249 
1250       operator uint64_t&() { return Info.ArrayInitIndex; }
1251     };
1252   };
1253 
1254   /// Object used to treat all foldable expressions as constant expressions.
1255   struct FoldConstant {
1256     EvalInfo &Info;
1257     bool Enabled;
1258     bool HadNoPriorDiags;
1259     EvalInfo::EvaluationMode OldMode;
1260 
1261     explicit FoldConstant(EvalInfo &Info, bool Enabled)
1262       : Info(Info),
1263         Enabled(Enabled),
1264         HadNoPriorDiags(Info.EvalStatus.Diag &&
1265                         Info.EvalStatus.Diag->empty() &&
1266                         !Info.EvalStatus.HasSideEffects),
1267         OldMode(Info.EvalMode) {
1268       if (Enabled)
1269         Info.EvalMode = EvalInfo::EM_ConstantFold;
1270     }
1271     void keepDiagnostics() { Enabled = false; }
1272     ~FoldConstant() {
1273       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1274           !Info.EvalStatus.HasSideEffects)
1275         Info.EvalStatus.Diag->clear();
1276       Info.EvalMode = OldMode;
1277     }
1278   };
1279 
1280   /// RAII object used to set the current evaluation mode to ignore
1281   /// side-effects.
1282   struct IgnoreSideEffectsRAII {
1283     EvalInfo &Info;
1284     EvalInfo::EvaluationMode OldMode;
1285     explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1286         : Info(Info), OldMode(Info.EvalMode) {
1287       Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1288     }
1289 
1290     ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1291   };
1292 
1293   /// RAII object used to optionally suppress diagnostics and side-effects from
1294   /// a speculative evaluation.
1295   class SpeculativeEvaluationRAII {
1296     EvalInfo *Info = nullptr;
1297     Expr::EvalStatus OldStatus;
1298     unsigned OldSpeculativeEvaluationDepth;
1299 
1300     void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1301       Info = Other.Info;
1302       OldStatus = Other.OldStatus;
1303       OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1304       Other.Info = nullptr;
1305     }
1306 
1307     void maybeRestoreState() {
1308       if (!Info)
1309         return;
1310 
1311       Info->EvalStatus = OldStatus;
1312       Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1313     }
1314 
1315   public:
1316     SpeculativeEvaluationRAII() = default;
1317 
1318     SpeculativeEvaluationRAII(
1319         EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1320         : Info(&Info), OldStatus(Info.EvalStatus),
1321           OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1322       Info.EvalStatus.Diag = NewDiag;
1323       Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1324     }
1325 
1326     SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1327     SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1328       moveFromAndCancel(std::move(Other));
1329     }
1330 
1331     SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1332       maybeRestoreState();
1333       moveFromAndCancel(std::move(Other));
1334       return *this;
1335     }
1336 
1337     ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1338   };
1339 
1340   /// RAII object wrapping a full-expression or block scope, and handling
1341   /// the ending of the lifetime of temporaries created within it.
1342   template<ScopeKind Kind>
1343   class ScopeRAII {
1344     EvalInfo &Info;
1345     unsigned OldStackSize;
1346   public:
1347     ScopeRAII(EvalInfo &Info)
1348         : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1349       // Push a new temporary version. This is needed to distinguish between
1350       // temporaries created in different iterations of a loop.
1351       Info.CurrentCall->pushTempVersion();
1352     }
1353     bool destroy(bool RunDestructors = true) {
1354       bool OK = cleanup(Info, RunDestructors, OldStackSize);
1355       OldStackSize = -1U;
1356       return OK;
1357     }
1358     ~ScopeRAII() {
1359       if (OldStackSize != -1U)
1360         destroy(false);
1361       // Body moved to a static method to encourage the compiler to inline away
1362       // instances of this class.
1363       Info.CurrentCall->popTempVersion();
1364     }
1365   private:
1366     static bool cleanup(EvalInfo &Info, bool RunDestructors,
1367                         unsigned OldStackSize) {
1368       assert(OldStackSize <= Info.CleanupStack.size() &&
1369              "running cleanups out of order?");
1370 
1371       // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1372       // for a full-expression scope.
1373       bool Success = true;
1374       for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1375         if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1376           if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1377             Success = false;
1378             break;
1379           }
1380         }
1381       }
1382 
1383       // Compact any retained cleanups.
1384       auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1385       if (Kind != ScopeKind::Block)
1386         NewEnd =
1387             std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1388               return C.isDestroyedAtEndOf(Kind);
1389             });
1390       Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1391       return Success;
1392     }
1393   };
1394   typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1395   typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1396   typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1397 }
1398 
1399 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1400                                          CheckSubobjectKind CSK) {
1401   if (Invalid)
1402     return false;
1403   if (isOnePastTheEnd()) {
1404     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1405       << CSK;
1406     setInvalid();
1407     return false;
1408   }
1409   // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1410   // must actually be at least one array element; even a VLA cannot have a
1411   // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1412   return true;
1413 }
1414 
1415 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1416                                                                 const Expr *E) {
1417   Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1418   // Do not set the designator as invalid: we can represent this situation,
1419   // and correct handling of __builtin_object_size requires us to do so.
1420 }
1421 
1422 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1423                                                     const Expr *E,
1424                                                     const APSInt &N) {
1425   // If we're complaining, we must be able to statically determine the size of
1426   // the most derived array.
1427   if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1428     Info.CCEDiag(E, diag::note_constexpr_array_index)
1429       << N << /*array*/ 0
1430       << static_cast<unsigned>(getMostDerivedArraySize());
1431   else
1432     Info.CCEDiag(E, diag::note_constexpr_array_index)
1433       << N << /*non-array*/ 1;
1434   setInvalid();
1435 }
1436 
1437 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1438                                const FunctionDecl *Callee, const LValue *This,
1439                                CallRef Call)
1440     : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1441       Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1442   Info.CurrentCall = this;
1443   ++Info.CallStackDepth;
1444 }
1445 
1446 CallStackFrame::~CallStackFrame() {
1447   assert(Info.CurrentCall == this && "calls retired out of order");
1448   --Info.CallStackDepth;
1449   Info.CurrentCall = Caller;
1450 }
1451 
1452 static bool isRead(AccessKinds AK) {
1453   return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1454 }
1455 
1456 static bool isModification(AccessKinds AK) {
1457   switch (AK) {
1458   case AK_Read:
1459   case AK_ReadObjectRepresentation:
1460   case AK_MemberCall:
1461   case AK_DynamicCast:
1462   case AK_TypeId:
1463     return false;
1464   case AK_Assign:
1465   case AK_Increment:
1466   case AK_Decrement:
1467   case AK_Construct:
1468   case AK_Destroy:
1469     return true;
1470   }
1471   llvm_unreachable("unknown access kind");
1472 }
1473 
1474 static bool isAnyAccess(AccessKinds AK) {
1475   return isRead(AK) || isModification(AK);
1476 }
1477 
1478 /// Is this an access per the C++ definition?
1479 static bool isFormalAccess(AccessKinds AK) {
1480   return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
1481 }
1482 
1483 /// Is this kind of axcess valid on an indeterminate object value?
1484 static bool isValidIndeterminateAccess(AccessKinds AK) {
1485   switch (AK) {
1486   case AK_Read:
1487   case AK_Increment:
1488   case AK_Decrement:
1489     // These need the object's value.
1490     return false;
1491 
1492   case AK_ReadObjectRepresentation:
1493   case AK_Assign:
1494   case AK_Construct:
1495   case AK_Destroy:
1496     // Construction and destruction don't need the value.
1497     return true;
1498 
1499   case AK_MemberCall:
1500   case AK_DynamicCast:
1501   case AK_TypeId:
1502     // These aren't really meaningful on scalars.
1503     return true;
1504   }
1505   llvm_unreachable("unknown access kind");
1506 }
1507 
1508 namespace {
1509   struct ComplexValue {
1510   private:
1511     bool IsInt;
1512 
1513   public:
1514     APSInt IntReal, IntImag;
1515     APFloat FloatReal, FloatImag;
1516 
1517     ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1518 
1519     void makeComplexFloat() { IsInt = false; }
1520     bool isComplexFloat() const { return !IsInt; }
1521     APFloat &getComplexFloatReal() { return FloatReal; }
1522     APFloat &getComplexFloatImag() { return FloatImag; }
1523 
1524     void makeComplexInt() { IsInt = true; }
1525     bool isComplexInt() const { return IsInt; }
1526     APSInt &getComplexIntReal() { return IntReal; }
1527     APSInt &getComplexIntImag() { return IntImag; }
1528 
1529     void moveInto(APValue &v) const {
1530       if (isComplexFloat())
1531         v = APValue(FloatReal, FloatImag);
1532       else
1533         v = APValue(IntReal, IntImag);
1534     }
1535     void setFrom(const APValue &v) {
1536       assert(v.isComplexFloat() || v.isComplexInt());
1537       if (v.isComplexFloat()) {
1538         makeComplexFloat();
1539         FloatReal = v.getComplexFloatReal();
1540         FloatImag = v.getComplexFloatImag();
1541       } else {
1542         makeComplexInt();
1543         IntReal = v.getComplexIntReal();
1544         IntImag = v.getComplexIntImag();
1545       }
1546     }
1547   };
1548 
1549   struct LValue {
1550     APValue::LValueBase Base;
1551     CharUnits Offset;
1552     SubobjectDesignator Designator;
1553     bool IsNullPtr : 1;
1554     bool InvalidBase : 1;
1555 
1556     const APValue::LValueBase getLValueBase() const { return Base; }
1557     CharUnits &getLValueOffset() { return Offset; }
1558     const CharUnits &getLValueOffset() const { return Offset; }
1559     SubobjectDesignator &getLValueDesignator() { return Designator; }
1560     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1561     bool isNullPointer() const { return IsNullPtr;}
1562 
1563     unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1564     unsigned getLValueVersion() const { return Base.getVersion(); }
1565 
1566     void moveInto(APValue &V) const {
1567       if (Designator.Invalid)
1568         V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1569       else {
1570         assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1571         V = APValue(Base, Offset, Designator.Entries,
1572                     Designator.IsOnePastTheEnd, IsNullPtr);
1573       }
1574     }
1575     void setFrom(ASTContext &Ctx, const APValue &V) {
1576       assert(V.isLValue() && "Setting LValue from a non-LValue?");
1577       Base = V.getLValueBase();
1578       Offset = V.getLValueOffset();
1579       InvalidBase = false;
1580       Designator = SubobjectDesignator(Ctx, V);
1581       IsNullPtr = V.isNullPointer();
1582     }
1583 
1584     void set(APValue::LValueBase B, bool BInvalid = false) {
1585 #ifndef NDEBUG
1586       // We only allow a few types of invalid bases. Enforce that here.
1587       if (BInvalid) {
1588         const auto *E = B.get<const Expr *>();
1589         assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1590                "Unexpected type of invalid base");
1591       }
1592 #endif
1593 
1594       Base = B;
1595       Offset = CharUnits::fromQuantity(0);
1596       InvalidBase = BInvalid;
1597       Designator = SubobjectDesignator(getType(B));
1598       IsNullPtr = false;
1599     }
1600 
1601     void setNull(ASTContext &Ctx, QualType PointerTy) {
1602       Base = (const ValueDecl *)nullptr;
1603       Offset =
1604           CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
1605       InvalidBase = false;
1606       Designator = SubobjectDesignator(PointerTy->getPointeeType());
1607       IsNullPtr = true;
1608     }
1609 
1610     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1611       set(B, true);
1612     }
1613 
1614     std::string toString(ASTContext &Ctx, QualType T) const {
1615       APValue Printable;
1616       moveInto(Printable);
1617       return Printable.getAsString(Ctx, T);
1618     }
1619 
1620   private:
1621     // Check that this LValue is not based on a null pointer. If it is, produce
1622     // a diagnostic and mark the designator as invalid.
1623     template <typename GenDiagType>
1624     bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1625       if (Designator.Invalid)
1626         return false;
1627       if (IsNullPtr) {
1628         GenDiag();
1629         Designator.setInvalid();
1630         return false;
1631       }
1632       return true;
1633     }
1634 
1635   public:
1636     bool checkNullPointer(EvalInfo &Info, const Expr *E,
1637                           CheckSubobjectKind CSK) {
1638       return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1639         Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1640       });
1641     }
1642 
1643     bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1644                                        AccessKinds AK) {
1645       return checkNullPointerDiagnosingWith([&Info, E, AK] {
1646         Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1647       });
1648     }
1649 
1650     // Check this LValue refers to an object. If not, set the designator to be
1651     // invalid and emit a diagnostic.
1652     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1653       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1654              Designator.checkSubobject(Info, E, CSK);
1655     }
1656 
1657     void addDecl(EvalInfo &Info, const Expr *E,
1658                  const Decl *D, bool Virtual = false) {
1659       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1660         Designator.addDeclUnchecked(D, Virtual);
1661     }
1662     void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1663       if (!Designator.Entries.empty()) {
1664         Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1665         Designator.setInvalid();
1666         return;
1667       }
1668       if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1669         assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1670         Designator.FirstEntryIsAnUnsizedArray = true;
1671         Designator.addUnsizedArrayUnchecked(ElemTy);
1672       }
1673     }
1674     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1675       if (checkSubobject(Info, E, CSK_ArrayToPointer))
1676         Designator.addArrayUnchecked(CAT);
1677     }
1678     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1679       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1680         Designator.addComplexUnchecked(EltTy, Imag);
1681     }
1682     void clearIsNullPointer() {
1683       IsNullPtr = false;
1684     }
1685     void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1686                               const APSInt &Index, CharUnits ElementSize) {
1687       // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1688       // but we're not required to diagnose it and it's valid in C++.)
1689       if (!Index)
1690         return;
1691 
1692       // Compute the new offset in the appropriate width, wrapping at 64 bits.
1693       // FIXME: When compiling for a 32-bit target, we should use 32-bit
1694       // offsets.
1695       uint64_t Offset64 = Offset.getQuantity();
1696       uint64_t ElemSize64 = ElementSize.getQuantity();
1697       uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1698       Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1699 
1700       if (checkNullPointer(Info, E, CSK_ArrayIndex))
1701         Designator.adjustIndex(Info, E, Index);
1702       clearIsNullPointer();
1703     }
1704     void adjustOffset(CharUnits N) {
1705       Offset += N;
1706       if (N.getQuantity())
1707         clearIsNullPointer();
1708     }
1709   };
1710 
1711   struct MemberPtr {
1712     MemberPtr() {}
1713     explicit MemberPtr(const ValueDecl *Decl) :
1714       DeclAndIsDerivedMember(Decl, false), Path() {}
1715 
1716     /// The member or (direct or indirect) field referred to by this member
1717     /// pointer, or 0 if this is a null member pointer.
1718     const ValueDecl *getDecl() const {
1719       return DeclAndIsDerivedMember.getPointer();
1720     }
1721     /// Is this actually a member of some type derived from the relevant class?
1722     bool isDerivedMember() const {
1723       return DeclAndIsDerivedMember.getInt();
1724     }
1725     /// Get the class which the declaration actually lives in.
1726     const CXXRecordDecl *getContainingRecord() const {
1727       return cast<CXXRecordDecl>(
1728           DeclAndIsDerivedMember.getPointer()->getDeclContext());
1729     }
1730 
1731     void moveInto(APValue &V) const {
1732       V = APValue(getDecl(), isDerivedMember(), Path);
1733     }
1734     void setFrom(const APValue &V) {
1735       assert(V.isMemberPointer());
1736       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1737       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1738       Path.clear();
1739       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1740       Path.insert(Path.end(), P.begin(), P.end());
1741     }
1742 
1743     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1744     /// whether the member is a member of some class derived from the class type
1745     /// of the member pointer.
1746     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1747     /// Path - The path of base/derived classes from the member declaration's
1748     /// class (exclusive) to the class type of the member pointer (inclusive).
1749     SmallVector<const CXXRecordDecl*, 4> Path;
1750 
1751     /// Perform a cast towards the class of the Decl (either up or down the
1752     /// hierarchy).
1753     bool castBack(const CXXRecordDecl *Class) {
1754       assert(!Path.empty());
1755       const CXXRecordDecl *Expected;
1756       if (Path.size() >= 2)
1757         Expected = Path[Path.size() - 2];
1758       else
1759         Expected = getContainingRecord();
1760       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1761         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1762         // if B does not contain the original member and is not a base or
1763         // derived class of the class containing the original member, the result
1764         // of the cast is undefined.
1765         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1766         // (D::*). We consider that to be a language defect.
1767         return false;
1768       }
1769       Path.pop_back();
1770       return true;
1771     }
1772     /// Perform a base-to-derived member pointer cast.
1773     bool castToDerived(const CXXRecordDecl *Derived) {
1774       if (!getDecl())
1775         return true;
1776       if (!isDerivedMember()) {
1777         Path.push_back(Derived);
1778         return true;
1779       }
1780       if (!castBack(Derived))
1781         return false;
1782       if (Path.empty())
1783         DeclAndIsDerivedMember.setInt(false);
1784       return true;
1785     }
1786     /// Perform a derived-to-base member pointer cast.
1787     bool castToBase(const CXXRecordDecl *Base) {
1788       if (!getDecl())
1789         return true;
1790       if (Path.empty())
1791         DeclAndIsDerivedMember.setInt(true);
1792       if (isDerivedMember()) {
1793         Path.push_back(Base);
1794         return true;
1795       }
1796       return castBack(Base);
1797     }
1798   };
1799 
1800   /// Compare two member pointers, which are assumed to be of the same type.
1801   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1802     if (!LHS.getDecl() || !RHS.getDecl())
1803       return !LHS.getDecl() && !RHS.getDecl();
1804     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1805       return false;
1806     return LHS.Path == RHS.Path;
1807   }
1808 }
1809 
1810 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1811 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1812                             const LValue &This, const Expr *E,
1813                             bool AllowNonLiteralTypes = false);
1814 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1815                            bool InvalidBaseOK = false);
1816 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1817                             bool InvalidBaseOK = false);
1818 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1819                                   EvalInfo &Info);
1820 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1821 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1822 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1823                                     EvalInfo &Info);
1824 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1825 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1826 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1827                            EvalInfo &Info);
1828 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1829 
1830 /// Evaluate an integer or fixed point expression into an APResult.
1831 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1832                                         EvalInfo &Info);
1833 
1834 /// Evaluate only a fixed point expression into an APResult.
1835 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1836                                EvalInfo &Info);
1837 
1838 //===----------------------------------------------------------------------===//
1839 // Misc utilities
1840 //===----------------------------------------------------------------------===//
1841 
1842 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1843 /// preserving its value (by extending by up to one bit as needed).
1844 static void negateAsSigned(APSInt &Int) {
1845   if (Int.isUnsigned() || Int.isMinSignedValue()) {
1846     Int = Int.extend(Int.getBitWidth() + 1);
1847     Int.setIsSigned(true);
1848   }
1849   Int = -Int;
1850 }
1851 
1852 template<typename KeyT>
1853 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1854                                          ScopeKind Scope, LValue &LV) {
1855   unsigned Version = getTempVersion();
1856   APValue::LValueBase Base(Key, Index, Version);
1857   LV.set(Base);
1858   return createLocal(Base, Key, T, Scope);
1859 }
1860 
1861 /// Allocate storage for a parameter of a function call made in this frame.
1862 APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1863                                      LValue &LV) {
1864   assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1865   APValue::LValueBase Base(PVD, Index, Args.Version);
1866   LV.set(Base);
1867   // We always destroy parameters at the end of the call, even if we'd allow
1868   // them to live to the end of the full-expression at runtime, in order to
1869   // give portable results and match other compilers.
1870   return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1871 }
1872 
1873 APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1874                                      QualType T, ScopeKind Scope) {
1875   assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1876   unsigned Version = Base.getVersion();
1877   APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1878   assert(Result.isAbsent() && "local created multiple times");
1879 
1880   // If we're creating a local immediately in the operand of a speculative
1881   // evaluation, don't register a cleanup to be run outside the speculative
1882   // evaluation context, since we won't actually be able to initialize this
1883   // object.
1884   if (Index <= Info.SpeculativeEvaluationDepth) {
1885     if (T.isDestructedType())
1886       Info.noteSideEffect();
1887   } else {
1888     Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1889   }
1890   return Result;
1891 }
1892 
1893 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1894   if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1895     FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1896     return nullptr;
1897   }
1898 
1899   DynamicAllocLValue DA(NumHeapAllocs++);
1900   LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1901   auto Result = HeapAllocs.emplace(std::piecewise_construct,
1902                                    std::forward_as_tuple(DA), std::tuple<>());
1903   assert(Result.second && "reused a heap alloc index?");
1904   Result.first->second.AllocExpr = E;
1905   return &Result.first->second.Value;
1906 }
1907 
1908 /// Produce a string describing the given constexpr call.
1909 void CallStackFrame::describe(raw_ostream &Out) {
1910   unsigned ArgIndex = 0;
1911   bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1912                       !isa<CXXConstructorDecl>(Callee) &&
1913                       cast<CXXMethodDecl>(Callee)->isInstance();
1914 
1915   if (!IsMemberCall)
1916     Out << *Callee << '(';
1917 
1918   if (This && IsMemberCall) {
1919     APValue Val;
1920     This->moveInto(Val);
1921     Val.printPretty(Out, Info.Ctx,
1922                     This->Designator.MostDerivedType);
1923     // FIXME: Add parens around Val if needed.
1924     Out << "->" << *Callee << '(';
1925     IsMemberCall = false;
1926   }
1927 
1928   for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1929        E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
1930     if (ArgIndex > (unsigned)IsMemberCall)
1931       Out << ", ";
1932 
1933     const ParmVarDecl *Param = *I;
1934     APValue *V = Info.getParamSlot(Arguments, Param);
1935     if (V)
1936       V->printPretty(Out, Info.Ctx, Param->getType());
1937     else
1938       Out << "<...>";
1939 
1940     if (ArgIndex == 0 && IsMemberCall)
1941       Out << "->" << *Callee << '(';
1942   }
1943 
1944   Out << ')';
1945 }
1946 
1947 /// Evaluate an expression to see if it had side-effects, and discard its
1948 /// result.
1949 /// \return \c true if the caller should keep evaluating.
1950 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1951   assert(!E->isValueDependent());
1952   APValue Scratch;
1953   if (!Evaluate(Scratch, Info, E))
1954     // We don't need the value, but we might have skipped a side effect here.
1955     return Info.noteSideEffect();
1956   return true;
1957 }
1958 
1959 /// Should this call expression be treated as a string literal?
1960 static bool IsStringLiteralCall(const CallExpr *E) {
1961   unsigned Builtin = E->getBuiltinCallee();
1962   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1963           Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1964 }
1965 
1966 static bool IsGlobalLValue(APValue::LValueBase B) {
1967   // C++11 [expr.const]p3 An address constant expression is a prvalue core
1968   // constant expression of pointer type that evaluates to...
1969 
1970   // ... a null pointer value, or a prvalue core constant expression of type
1971   // std::nullptr_t.
1972   if (!B) return true;
1973 
1974   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1975     // ... the address of an object with static storage duration,
1976     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1977       return VD->hasGlobalStorage();
1978     if (isa<TemplateParamObjectDecl>(D))
1979       return true;
1980     // ... the address of a function,
1981     // ... the address of a GUID [MS extension],
1982     return isa<FunctionDecl>(D) || isa<MSGuidDecl>(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 IsStringLiteralCall(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   case Expr::ImplicitValueInitExprClass:
2018     // FIXME:
2019     // We can never form an lvalue with an implicit value initialization as its
2020     // base through expression evaluation, so these only appear in one case: the
2021     // implicit variable declaration we invent when checking whether a constexpr
2022     // constructor can produce a constant expression. We must assume that such
2023     // an expression might be a global lvalue.
2024     return true;
2025   }
2026 }
2027 
2028 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2029   return LVal.Base.dyn_cast<const ValueDecl*>();
2030 }
2031 
2032 static bool IsLiteralLValue(const LValue &Value) {
2033   if (Value.getLValueCallIndex())
2034     return false;
2035   const Expr *E = Value.Base.dyn_cast<const Expr*>();
2036   return E && !isa<MaterializeTemporaryExpr>(E);
2037 }
2038 
2039 static bool IsWeakLValue(const LValue &Value) {
2040   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2041   return Decl && Decl->isWeak();
2042 }
2043 
2044 static bool isZeroSized(const LValue &Value) {
2045   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2046   if (Decl && isa<VarDecl>(Decl)) {
2047     QualType Ty = Decl->getType();
2048     if (Ty->isArrayType())
2049       return Ty->isIncompleteType() ||
2050              Decl->getASTContext().getTypeSize(Ty) == 0;
2051   }
2052   return false;
2053 }
2054 
2055 static bool HasSameBase(const LValue &A, const LValue &B) {
2056   if (!A.getLValueBase())
2057     return !B.getLValueBase();
2058   if (!B.getLValueBase())
2059     return false;
2060 
2061   if (A.getLValueBase().getOpaqueValue() !=
2062       B.getLValueBase().getOpaqueValue())
2063     return false;
2064 
2065   return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2066          A.getLValueVersion() == B.getLValueVersion();
2067 }
2068 
2069 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2070   assert(Base && "no location for a null lvalue");
2071   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2072 
2073   // For a parameter, find the corresponding call stack frame (if it still
2074   // exists), and point at the parameter of the function definition we actually
2075   // invoked.
2076   if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2077     unsigned Idx = PVD->getFunctionScopeIndex();
2078     for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2079       if (F->Arguments.CallIndex == Base.getCallIndex() &&
2080           F->Arguments.Version == Base.getVersion() && F->Callee &&
2081           Idx < F->Callee->getNumParams()) {
2082         VD = F->Callee->getParamDecl(Idx);
2083         break;
2084       }
2085     }
2086   }
2087 
2088   if (VD)
2089     Info.Note(VD->getLocation(), diag::note_declared_at);
2090   else if (const Expr *E = Base.dyn_cast<const Expr*>())
2091     Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2092   else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2093     // FIXME: Produce a note for dangling pointers too.
2094     if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA))
2095       Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2096                 diag::note_constexpr_dynamic_alloc_here);
2097   }
2098   // We have no information to show for a typeid(T) object.
2099 }
2100 
2101 enum class CheckEvaluationResultKind {
2102   ConstantExpression,
2103   FullyInitialized,
2104 };
2105 
2106 /// Materialized temporaries that we've already checked to determine if they're
2107 /// initializsed by a constant expression.
2108 using CheckedTemporaries =
2109     llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
2110 
2111 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2112                                   EvalInfo &Info, SourceLocation DiagLoc,
2113                                   QualType Type, const APValue &Value,
2114                                   ConstantExprKind Kind,
2115                                   SourceLocation SubobjectLoc,
2116                                   CheckedTemporaries &CheckedTemps);
2117 
2118 /// Check that this reference or pointer core constant expression is a valid
2119 /// value for an address or reference constant expression. Return true if we
2120 /// can fold this expression, whether or not it's a constant expression.
2121 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2122                                           QualType Type, const LValue &LVal,
2123                                           ConstantExprKind Kind,
2124                                           CheckedTemporaries &CheckedTemps) {
2125   bool IsReferenceType = Type->isReferenceType();
2126 
2127   APValue::LValueBase Base = LVal.getLValueBase();
2128   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2129 
2130   const Expr *BaseE = Base.dyn_cast<const Expr *>();
2131   const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2132 
2133   // Additional restrictions apply in a template argument. We only enforce the
2134   // C++20 restrictions here; additional syntactic and semantic restrictions
2135   // are applied elsewhere.
2136   if (isTemplateArgument(Kind)) {
2137     int InvalidBaseKind = -1;
2138     StringRef Ident;
2139     if (Base.is<TypeInfoLValue>())
2140       InvalidBaseKind = 0;
2141     else if (isa_and_nonnull<StringLiteral>(BaseE))
2142       InvalidBaseKind = 1;
2143     else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2144              isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2145       InvalidBaseKind = 2;
2146     else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2147       InvalidBaseKind = 3;
2148       Ident = PE->getIdentKindName();
2149     }
2150 
2151     if (InvalidBaseKind != -1) {
2152       Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2153           << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2154           << Ident;
2155       return false;
2156     }
2157   }
2158 
2159   if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD)) {
2160     if (FD->isConsteval()) {
2161       Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2162           << !Type->isAnyPointerType();
2163       Info.Note(FD->getLocation(), diag::note_declared_at);
2164       return false;
2165     }
2166   }
2167 
2168   // Check that the object is a global. Note that the fake 'this' object we
2169   // manufacture when checking potential constant expressions is conservatively
2170   // assumed to be global here.
2171   if (!IsGlobalLValue(Base)) {
2172     if (Info.getLangOpts().CPlusPlus11) {
2173       const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2174       Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2175         << IsReferenceType << !Designator.Entries.empty()
2176         << !!VD << VD;
2177 
2178       auto *VarD = dyn_cast_or_null<VarDecl>(VD);
2179       if (VarD && VarD->isConstexpr()) {
2180         // Non-static local constexpr variables have unintuitive semantics:
2181         //   constexpr int a = 1;
2182         //   constexpr const int *p = &a;
2183         // ... is invalid because the address of 'a' is not constant. Suggest
2184         // adding a 'static' in this case.
2185         Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2186             << VarD
2187             << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2188       } else {
2189         NoteLValueLocation(Info, Base);
2190       }
2191     } else {
2192       Info.FFDiag(Loc);
2193     }
2194     // Don't allow references to temporaries to escape.
2195     return false;
2196   }
2197   assert((Info.checkingPotentialConstantExpression() ||
2198           LVal.getLValueCallIndex() == 0) &&
2199          "have call index for global lvalue");
2200 
2201   if (Base.is<DynamicAllocLValue>()) {
2202     Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2203         << IsReferenceType << !Designator.Entries.empty();
2204     NoteLValueLocation(Info, Base);
2205     return false;
2206   }
2207 
2208   if (BaseVD) {
2209     if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2210       // Check if this is a thread-local variable.
2211       if (Var->getTLSKind())
2212         // FIXME: Diagnostic!
2213         return false;
2214 
2215       // A dllimport variable never acts like a constant, unless we're
2216       // evaluating a value for use only in name mangling.
2217       if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2218         // FIXME: Diagnostic!
2219         return false;
2220     }
2221     if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2222       // __declspec(dllimport) must be handled very carefully:
2223       // We must never initialize an expression with the thunk in C++.
2224       // Doing otherwise would allow the same id-expression to yield
2225       // different addresses for the same function in different translation
2226       // units.  However, this means that we must dynamically initialize the
2227       // expression with the contents of the import address table at runtime.
2228       //
2229       // The C language has no notion of ODR; furthermore, it has no notion of
2230       // dynamic initialization.  This means that we are permitted to
2231       // perform initialization with the address of the thunk.
2232       if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2233           FD->hasAttr<DLLImportAttr>())
2234         // FIXME: Diagnostic!
2235         return false;
2236     }
2237   } else if (const auto *MTE =
2238                  dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2239     if (CheckedTemps.insert(MTE).second) {
2240       QualType TempType = getType(Base);
2241       if (TempType.isDestructedType()) {
2242         Info.FFDiag(MTE->getExprLoc(),
2243                     diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2244             << TempType;
2245         return false;
2246       }
2247 
2248       APValue *V = MTE->getOrCreateValue(false);
2249       assert(V && "evasluation result refers to uninitialised temporary");
2250       if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2251                                  Info, MTE->getExprLoc(), TempType, *V,
2252                                  Kind, SourceLocation(), CheckedTemps))
2253         return false;
2254     }
2255   }
2256 
2257   // Allow address constant expressions to be past-the-end pointers. This is
2258   // an extension: the standard requires them to point to an object.
2259   if (!IsReferenceType)
2260     return true;
2261 
2262   // A reference constant expression must refer to an object.
2263   if (!Base) {
2264     // FIXME: diagnostic
2265     Info.CCEDiag(Loc);
2266     return true;
2267   }
2268 
2269   // Does this refer one past the end of some object?
2270   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2271     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2272       << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2273     NoteLValueLocation(Info, Base);
2274   }
2275 
2276   return true;
2277 }
2278 
2279 /// Member pointers are constant expressions unless they point to a
2280 /// non-virtual dllimport member function.
2281 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2282                                                  SourceLocation Loc,
2283                                                  QualType Type,
2284                                                  const APValue &Value,
2285                                                  ConstantExprKind Kind) {
2286   const ValueDecl *Member = Value.getMemberPointerDecl();
2287   const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2288   if (!FD)
2289     return true;
2290   if (FD->isConsteval()) {
2291     Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2292     Info.Note(FD->getLocation(), diag::note_declared_at);
2293     return false;
2294   }
2295   return isForManglingOnly(Kind) || FD->isVirtual() ||
2296          !FD->hasAttr<DLLImportAttr>();
2297 }
2298 
2299 /// Check that this core constant expression is of literal type, and if not,
2300 /// produce an appropriate diagnostic.
2301 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2302                              const LValue *This = nullptr) {
2303   if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2304     return true;
2305 
2306   // C++1y: A constant initializer for an object o [...] may also invoke
2307   // constexpr constructors for o and its subobjects even if those objects
2308   // are of non-literal class types.
2309   //
2310   // C++11 missed this detail for aggregates, so classes like this:
2311   //   struct foo_t { union { int i; volatile int j; } u; };
2312   // are not (obviously) initializable like so:
2313   //   __attribute__((__require_constant_initialization__))
2314   //   static const foo_t x = {{0}};
2315   // because "i" is a subobject with non-literal initialization (due to the
2316   // volatile member of the union). See:
2317   //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2318   // Therefore, we use the C++1y behavior.
2319   if (This && Info.EvaluatingDecl == This->getLValueBase())
2320     return true;
2321 
2322   // Prvalue constant expressions must be of literal types.
2323   if (Info.getLangOpts().CPlusPlus11)
2324     Info.FFDiag(E, diag::note_constexpr_nonliteral)
2325       << E->getType();
2326   else
2327     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2328   return false;
2329 }
2330 
2331 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2332                                   EvalInfo &Info, SourceLocation DiagLoc,
2333                                   QualType Type, const APValue &Value,
2334                                   ConstantExprKind Kind,
2335                                   SourceLocation SubobjectLoc,
2336                                   CheckedTemporaries &CheckedTemps) {
2337   if (!Value.hasValue()) {
2338     Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2339       << true << Type;
2340     if (SubobjectLoc.isValid())
2341       Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2342     return false;
2343   }
2344 
2345   // We allow _Atomic(T) to be initialized from anything that T can be
2346   // initialized from.
2347   if (const AtomicType *AT = Type->getAs<AtomicType>())
2348     Type = AT->getValueType();
2349 
2350   // Core issue 1454: For a literal constant expression of array or class type,
2351   // each subobject of its value shall have been initialized by a constant
2352   // expression.
2353   if (Value.isArray()) {
2354     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2355     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2356       if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2357                                  Value.getArrayInitializedElt(I), Kind,
2358                                  SubobjectLoc, CheckedTemps))
2359         return false;
2360     }
2361     if (!Value.hasArrayFiller())
2362       return true;
2363     return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2364                                  Value.getArrayFiller(), Kind, SubobjectLoc,
2365                                  CheckedTemps);
2366   }
2367   if (Value.isUnion() && Value.getUnionField()) {
2368     return CheckEvaluationResult(
2369         CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2370         Value.getUnionValue(), Kind, Value.getUnionField()->getLocation(),
2371         CheckedTemps);
2372   }
2373   if (Value.isStruct()) {
2374     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2375     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2376       unsigned BaseIndex = 0;
2377       for (const CXXBaseSpecifier &BS : CD->bases()) {
2378         if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2379                                    Value.getStructBase(BaseIndex), Kind,
2380                                    BS.getBeginLoc(), CheckedTemps))
2381           return false;
2382         ++BaseIndex;
2383       }
2384     }
2385     for (const auto *I : RD->fields()) {
2386       if (I->isUnnamedBitfield())
2387         continue;
2388 
2389       if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2390                                  Value.getStructField(I->getFieldIndex()),
2391                                  Kind, I->getLocation(), CheckedTemps))
2392         return false;
2393     }
2394   }
2395 
2396   if (Value.isLValue() &&
2397       CERK == CheckEvaluationResultKind::ConstantExpression) {
2398     LValue LVal;
2399     LVal.setFrom(Info.Ctx, Value);
2400     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2401                                          CheckedTemps);
2402   }
2403 
2404   if (Value.isMemberPointer() &&
2405       CERK == CheckEvaluationResultKind::ConstantExpression)
2406     return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2407 
2408   // Everything else is fine.
2409   return true;
2410 }
2411 
2412 /// Check that this core constant expression value is a valid value for a
2413 /// constant expression. If not, report an appropriate diagnostic. Does not
2414 /// check that the expression is of literal type.
2415 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2416                                     QualType Type, const APValue &Value,
2417                                     ConstantExprKind Kind) {
2418   // Nothing to check for a constant expression of type 'cv void'.
2419   if (Type->isVoidType())
2420     return true;
2421 
2422   CheckedTemporaries CheckedTemps;
2423   return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2424                                Info, DiagLoc, Type, Value, Kind,
2425                                SourceLocation(), CheckedTemps);
2426 }
2427 
2428 /// Check that this evaluated value is fully-initialized and can be loaded by
2429 /// an lvalue-to-rvalue conversion.
2430 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2431                                   QualType Type, const APValue &Value) {
2432   CheckedTemporaries CheckedTemps;
2433   return CheckEvaluationResult(
2434       CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2435       ConstantExprKind::Normal, SourceLocation(), CheckedTemps);
2436 }
2437 
2438 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2439 /// "the allocated storage is deallocated within the evaluation".
2440 static bool CheckMemoryLeaks(EvalInfo &Info) {
2441   if (!Info.HeapAllocs.empty()) {
2442     // We can still fold to a constant despite a compile-time memory leak,
2443     // so long as the heap allocation isn't referenced in the result (we check
2444     // that in CheckConstantExpression).
2445     Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2446                  diag::note_constexpr_memory_leak)
2447         << unsigned(Info.HeapAllocs.size() - 1);
2448   }
2449   return true;
2450 }
2451 
2452 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2453   // A null base expression indicates a null pointer.  These are always
2454   // evaluatable, and they are false unless the offset is zero.
2455   if (!Value.getLValueBase()) {
2456     Result = !Value.getLValueOffset().isZero();
2457     return true;
2458   }
2459 
2460   // We have a non-null base.  These are generally known to be true, but if it's
2461   // a weak declaration it can be null at runtime.
2462   Result = true;
2463   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2464   return !Decl || !Decl->isWeak();
2465 }
2466 
2467 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2468   switch (Val.getKind()) {
2469   case APValue::None:
2470   case APValue::Indeterminate:
2471     return false;
2472   case APValue::Int:
2473     Result = Val.getInt().getBoolValue();
2474     return true;
2475   case APValue::FixedPoint:
2476     Result = Val.getFixedPoint().getBoolValue();
2477     return true;
2478   case APValue::Float:
2479     Result = !Val.getFloat().isZero();
2480     return true;
2481   case APValue::ComplexInt:
2482     Result = Val.getComplexIntReal().getBoolValue() ||
2483              Val.getComplexIntImag().getBoolValue();
2484     return true;
2485   case APValue::ComplexFloat:
2486     Result = !Val.getComplexFloatReal().isZero() ||
2487              !Val.getComplexFloatImag().isZero();
2488     return true;
2489   case APValue::LValue:
2490     return EvalPointerValueAsBool(Val, Result);
2491   case APValue::MemberPointer:
2492     Result = Val.getMemberPointerDecl();
2493     return true;
2494   case APValue::Vector:
2495   case APValue::Array:
2496   case APValue::Struct:
2497   case APValue::Union:
2498   case APValue::AddrLabelDiff:
2499     return false;
2500   }
2501 
2502   llvm_unreachable("unknown APValue kind");
2503 }
2504 
2505 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2506                                        EvalInfo &Info) {
2507   assert(!E->isValueDependent());
2508   assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2509   APValue Val;
2510   if (!Evaluate(Val, Info, E))
2511     return false;
2512   return HandleConversionToBool(Val, Result);
2513 }
2514 
2515 template<typename T>
2516 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2517                            const T &SrcValue, QualType DestType) {
2518   Info.CCEDiag(E, diag::note_constexpr_overflow)
2519     << SrcValue << DestType;
2520   return Info.noteUndefinedBehavior();
2521 }
2522 
2523 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2524                                  QualType SrcType, const APFloat &Value,
2525                                  QualType DestType, APSInt &Result) {
2526   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2527   // Determine whether we are converting to unsigned or signed.
2528   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2529 
2530   Result = APSInt(DestWidth, !DestSigned);
2531   bool ignored;
2532   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2533       & APFloat::opInvalidOp)
2534     return HandleOverflow(Info, E, Value, DestType);
2535   return true;
2536 }
2537 
2538 /// Get rounding mode used for evaluation of the specified expression.
2539 /// \param[out] DynamicRM Is set to true is the requested rounding mode is
2540 ///                       dynamic.
2541 /// If rounding mode is unknown at compile time, still try to evaluate the
2542 /// expression. If the result is exact, it does not depend on rounding mode.
2543 /// So return "tonearest" mode instead of "dynamic".
2544 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E,
2545                                                 bool &DynamicRM) {
2546   llvm::RoundingMode RM =
2547       E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2548   DynamicRM = (RM == llvm::RoundingMode::Dynamic);
2549   if (DynamicRM)
2550     RM = llvm::RoundingMode::NearestTiesToEven;
2551   return RM;
2552 }
2553 
2554 /// Check if the given evaluation result is allowed for constant evaluation.
2555 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2556                                      APFloat::opStatus St) {
2557   // In a constant context, assume that any dynamic rounding mode or FP
2558   // exception state matches the default floating-point environment.
2559   if (Info.InConstantContext)
2560     return true;
2561 
2562   FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2563   if ((St & APFloat::opInexact) &&
2564       FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2565     // Inexact result means that it depends on rounding mode. If the requested
2566     // mode is dynamic, the evaluation cannot be made in compile time.
2567     Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2568     return false;
2569   }
2570 
2571   if ((St != APFloat::opOK) &&
2572       (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2573        FPO.getFPExceptionMode() != LangOptions::FPE_Ignore ||
2574        FPO.getAllowFEnvAccess())) {
2575     Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2576     return false;
2577   }
2578 
2579   if ((St & APFloat::opStatus::opInvalidOp) &&
2580       FPO.getFPExceptionMode() != LangOptions::FPE_Ignore) {
2581     // There is no usefully definable result.
2582     Info.FFDiag(E);
2583     return false;
2584   }
2585 
2586   // FIXME: if:
2587   // - evaluation triggered other FP exception, and
2588   // - exception mode is not "ignore", and
2589   // - the expression being evaluated is not a part of global variable
2590   //   initializer,
2591   // the evaluation probably need to be rejected.
2592   return true;
2593 }
2594 
2595 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2596                                    QualType SrcType, QualType DestType,
2597                                    APFloat &Result) {
2598   assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E));
2599   bool DynamicRM;
2600   llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM);
2601   APFloat::opStatus St;
2602   APFloat Value = Result;
2603   bool ignored;
2604   St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2605   return checkFloatingPointResult(Info, E, St);
2606 }
2607 
2608 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2609                                  QualType DestType, QualType SrcType,
2610                                  const APSInt &Value) {
2611   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2612   // Figure out if this is a truncate, extend or noop cast.
2613   // If the input is signed, do a sign extend, noop, or truncate.
2614   APSInt Result = Value.extOrTrunc(DestWidth);
2615   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2616   if (DestType->isBooleanType())
2617     Result = Value.getBoolValue();
2618   return Result;
2619 }
2620 
2621 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2622                                  const FPOptions FPO,
2623                                  QualType SrcType, const APSInt &Value,
2624                                  QualType DestType, APFloat &Result) {
2625   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2626   APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(),
2627        APFloat::rmNearestTiesToEven);
2628   if (!Info.InConstantContext && St != llvm::APFloatBase::opOK &&
2629       FPO.isFPConstrained()) {
2630     Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2631     return false;
2632   }
2633   return true;
2634 }
2635 
2636 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2637                                   APValue &Value, const FieldDecl *FD) {
2638   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2639 
2640   if (!Value.isInt()) {
2641     // Trying to store a pointer-cast-to-integer into a bitfield.
2642     // FIXME: In this case, we should provide the diagnostic for casting
2643     // a pointer to an integer.
2644     assert(Value.isLValue() && "integral value neither int nor lvalue?");
2645     Info.FFDiag(E);
2646     return false;
2647   }
2648 
2649   APSInt &Int = Value.getInt();
2650   unsigned OldBitWidth = Int.getBitWidth();
2651   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2652   if (NewBitWidth < OldBitWidth)
2653     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2654   return true;
2655 }
2656 
2657 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2658                                   llvm::APInt &Res) {
2659   APValue SVal;
2660   if (!Evaluate(SVal, Info, E))
2661     return false;
2662   if (SVal.isInt()) {
2663     Res = SVal.getInt();
2664     return true;
2665   }
2666   if (SVal.isFloat()) {
2667     Res = SVal.getFloat().bitcastToAPInt();
2668     return true;
2669   }
2670   if (SVal.isVector()) {
2671     QualType VecTy = E->getType();
2672     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2673     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2674     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2675     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2676     Res = llvm::APInt::getNullValue(VecSize);
2677     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2678       APValue &Elt = SVal.getVectorElt(i);
2679       llvm::APInt EltAsInt;
2680       if (Elt.isInt()) {
2681         EltAsInt = Elt.getInt();
2682       } else if (Elt.isFloat()) {
2683         EltAsInt = Elt.getFloat().bitcastToAPInt();
2684       } else {
2685         // Don't try to handle vectors of anything other than int or float
2686         // (not sure if it's possible to hit this case).
2687         Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2688         return false;
2689       }
2690       unsigned BaseEltSize = EltAsInt.getBitWidth();
2691       if (BigEndian)
2692         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2693       else
2694         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2695     }
2696     return true;
2697   }
2698   // Give up if the input isn't an int, float, or vector.  For example, we
2699   // reject "(v4i16)(intptr_t)&a".
2700   Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2701   return false;
2702 }
2703 
2704 /// Perform the given integer operation, which is known to need at most BitWidth
2705 /// bits, and check for overflow in the original type (if that type was not an
2706 /// unsigned type).
2707 template<typename Operation>
2708 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2709                                  const APSInt &LHS, const APSInt &RHS,
2710                                  unsigned BitWidth, Operation Op,
2711                                  APSInt &Result) {
2712   if (LHS.isUnsigned()) {
2713     Result = Op(LHS, RHS);
2714     return true;
2715   }
2716 
2717   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2718   Result = Value.trunc(LHS.getBitWidth());
2719   if (Result.extend(BitWidth) != Value) {
2720     if (Info.checkingForUndefinedBehavior())
2721       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2722                                        diag::warn_integer_constant_overflow)
2723           << toString(Result, 10) << E->getType();
2724     return HandleOverflow(Info, E, Value, E->getType());
2725   }
2726   return true;
2727 }
2728 
2729 /// Perform the given binary integer operation.
2730 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2731                               BinaryOperatorKind Opcode, APSInt RHS,
2732                               APSInt &Result) {
2733   switch (Opcode) {
2734   default:
2735     Info.FFDiag(E);
2736     return false;
2737   case BO_Mul:
2738     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2739                                 std::multiplies<APSInt>(), Result);
2740   case BO_Add:
2741     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2742                                 std::plus<APSInt>(), Result);
2743   case BO_Sub:
2744     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2745                                 std::minus<APSInt>(), Result);
2746   case BO_And: Result = LHS & RHS; return true;
2747   case BO_Xor: Result = LHS ^ RHS; return true;
2748   case BO_Or:  Result = LHS | RHS; return true;
2749   case BO_Div:
2750   case BO_Rem:
2751     if (RHS == 0) {
2752       Info.FFDiag(E, diag::note_expr_divide_by_zero);
2753       return false;
2754     }
2755     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2756     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2757     // this operation and gives the two's complement result.
2758     if (RHS.isNegative() && RHS.isAllOnesValue() &&
2759         LHS.isSigned() && LHS.isMinSignedValue())
2760       return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2761                             E->getType());
2762     return true;
2763   case BO_Shl: {
2764     if (Info.getLangOpts().OpenCL)
2765       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2766       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2767                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2768                     RHS.isUnsigned());
2769     else if (RHS.isSigned() && RHS.isNegative()) {
2770       // During constant-folding, a negative shift is an opposite shift. Such
2771       // a shift is not a constant expression.
2772       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2773       RHS = -RHS;
2774       goto shift_right;
2775     }
2776   shift_left:
2777     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2778     // the shifted type.
2779     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2780     if (SA != RHS) {
2781       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2782         << RHS << E->getType() << LHS.getBitWidth();
2783     } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2784       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2785       // operand, and must not overflow the corresponding unsigned type.
2786       // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2787       // E1 x 2^E2 module 2^N.
2788       if (LHS.isNegative())
2789         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2790       else if (LHS.countLeadingZeros() < SA)
2791         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2792     }
2793     Result = LHS << SA;
2794     return true;
2795   }
2796   case BO_Shr: {
2797     if (Info.getLangOpts().OpenCL)
2798       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2799       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2800                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2801                     RHS.isUnsigned());
2802     else if (RHS.isSigned() && RHS.isNegative()) {
2803       // During constant-folding, a negative shift is an opposite shift. Such a
2804       // shift is not a constant expression.
2805       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2806       RHS = -RHS;
2807       goto shift_left;
2808     }
2809   shift_right:
2810     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2811     // shifted type.
2812     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2813     if (SA != RHS)
2814       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2815         << RHS << E->getType() << LHS.getBitWidth();
2816     Result = LHS >> SA;
2817     return true;
2818   }
2819 
2820   case BO_LT: Result = LHS < RHS; return true;
2821   case BO_GT: Result = LHS > RHS; return true;
2822   case BO_LE: Result = LHS <= RHS; return true;
2823   case BO_GE: Result = LHS >= RHS; return true;
2824   case BO_EQ: Result = LHS == RHS; return true;
2825   case BO_NE: Result = LHS != RHS; return true;
2826   case BO_Cmp:
2827     llvm_unreachable("BO_Cmp should be handled elsewhere");
2828   }
2829 }
2830 
2831 /// Perform the given binary floating-point operation, in-place, on LHS.
2832 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2833                                   APFloat &LHS, BinaryOperatorKind Opcode,
2834                                   const APFloat &RHS) {
2835   bool DynamicRM;
2836   llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM);
2837   APFloat::opStatus St;
2838   switch (Opcode) {
2839   default:
2840     Info.FFDiag(E);
2841     return false;
2842   case BO_Mul:
2843     St = LHS.multiply(RHS, RM);
2844     break;
2845   case BO_Add:
2846     St = LHS.add(RHS, RM);
2847     break;
2848   case BO_Sub:
2849     St = LHS.subtract(RHS, RM);
2850     break;
2851   case BO_Div:
2852     // [expr.mul]p4:
2853     //   If the second operand of / or % is zero the behavior is undefined.
2854     if (RHS.isZero())
2855       Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2856     St = LHS.divide(RHS, RM);
2857     break;
2858   }
2859 
2860   // [expr.pre]p4:
2861   //   If during the evaluation of an expression, the result is not
2862   //   mathematically defined [...], the behavior is undefined.
2863   // FIXME: C++ rules require us to not conform to IEEE 754 here.
2864   if (LHS.isNaN()) {
2865     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2866     return Info.noteUndefinedBehavior();
2867   }
2868 
2869   return checkFloatingPointResult(Info, E, St);
2870 }
2871 
2872 static bool handleLogicalOpForVector(const APInt &LHSValue,
2873                                      BinaryOperatorKind Opcode,
2874                                      const APInt &RHSValue, APInt &Result) {
2875   bool LHS = (LHSValue != 0);
2876   bool RHS = (RHSValue != 0);
2877 
2878   if (Opcode == BO_LAnd)
2879     Result = LHS && RHS;
2880   else
2881     Result = LHS || RHS;
2882   return true;
2883 }
2884 static bool handleLogicalOpForVector(const APFloat &LHSValue,
2885                                      BinaryOperatorKind Opcode,
2886                                      const APFloat &RHSValue, APInt &Result) {
2887   bool LHS = !LHSValue.isZero();
2888   bool RHS = !RHSValue.isZero();
2889 
2890   if (Opcode == BO_LAnd)
2891     Result = LHS && RHS;
2892   else
2893     Result = LHS || RHS;
2894   return true;
2895 }
2896 
2897 static bool handleLogicalOpForVector(const APValue &LHSValue,
2898                                      BinaryOperatorKind Opcode,
2899                                      const APValue &RHSValue, APInt &Result) {
2900   // The result is always an int type, however operands match the first.
2901   if (LHSValue.getKind() == APValue::Int)
2902     return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2903                                     RHSValue.getInt(), Result);
2904   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2905   return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2906                                   RHSValue.getFloat(), Result);
2907 }
2908 
2909 template <typename APTy>
2910 static bool
2911 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
2912                                const APTy &RHSValue, APInt &Result) {
2913   switch (Opcode) {
2914   default:
2915     llvm_unreachable("unsupported binary operator");
2916   case BO_EQ:
2917     Result = (LHSValue == RHSValue);
2918     break;
2919   case BO_NE:
2920     Result = (LHSValue != RHSValue);
2921     break;
2922   case BO_LT:
2923     Result = (LHSValue < RHSValue);
2924     break;
2925   case BO_GT:
2926     Result = (LHSValue > RHSValue);
2927     break;
2928   case BO_LE:
2929     Result = (LHSValue <= RHSValue);
2930     break;
2931   case BO_GE:
2932     Result = (LHSValue >= RHSValue);
2933     break;
2934   }
2935 
2936   return true;
2937 }
2938 
2939 static bool handleCompareOpForVector(const APValue &LHSValue,
2940                                      BinaryOperatorKind Opcode,
2941                                      const APValue &RHSValue, APInt &Result) {
2942   // The result is always an int type, however operands match the first.
2943   if (LHSValue.getKind() == APValue::Int)
2944     return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
2945                                           RHSValue.getInt(), Result);
2946   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2947   return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
2948                                         RHSValue.getFloat(), Result);
2949 }
2950 
2951 // Perform binary operations for vector types, in place on the LHS.
2952 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
2953                                     BinaryOperatorKind Opcode,
2954                                     APValue &LHSValue,
2955                                     const APValue &RHSValue) {
2956   assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
2957          "Operation not supported on vector types");
2958 
2959   const auto *VT = E->getType()->castAs<VectorType>();
2960   unsigned NumElements = VT->getNumElements();
2961   QualType EltTy = VT->getElementType();
2962 
2963   // In the cases (typically C as I've observed) where we aren't evaluating
2964   // constexpr but are checking for cases where the LHS isn't yet evaluatable,
2965   // just give up.
2966   if (!LHSValue.isVector()) {
2967     assert(LHSValue.isLValue() &&
2968            "A vector result that isn't a vector OR uncalculated LValue");
2969     Info.FFDiag(E);
2970     return false;
2971   }
2972 
2973   assert(LHSValue.getVectorLength() == NumElements &&
2974          RHSValue.getVectorLength() == NumElements && "Different vector sizes");
2975 
2976   SmallVector<APValue, 4> ResultElements;
2977 
2978   for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
2979     APValue LHSElt = LHSValue.getVectorElt(EltNum);
2980     APValue RHSElt = RHSValue.getVectorElt(EltNum);
2981 
2982     if (EltTy->isIntegerType()) {
2983       APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
2984                        EltTy->isUnsignedIntegerType()};
2985       bool Success = true;
2986 
2987       if (BinaryOperator::isLogicalOp(Opcode))
2988         Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
2989       else if (BinaryOperator::isComparisonOp(Opcode))
2990         Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
2991       else
2992         Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
2993                                     RHSElt.getInt(), EltResult);
2994 
2995       if (!Success) {
2996         Info.FFDiag(E);
2997         return false;
2998       }
2999       ResultElements.emplace_back(EltResult);
3000 
3001     } else if (EltTy->isFloatingType()) {
3002       assert(LHSElt.getKind() == APValue::Float &&
3003              RHSElt.getKind() == APValue::Float &&
3004              "Mismatched LHS/RHS/Result Type");
3005       APFloat LHSFloat = LHSElt.getFloat();
3006 
3007       if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3008                                  RHSElt.getFloat())) {
3009         Info.FFDiag(E);
3010         return false;
3011       }
3012 
3013       ResultElements.emplace_back(LHSFloat);
3014     }
3015   }
3016 
3017   LHSValue = APValue(ResultElements.data(), ResultElements.size());
3018   return true;
3019 }
3020 
3021 /// Cast an lvalue referring to a base subobject to a derived class, by
3022 /// truncating the lvalue's path to the given length.
3023 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3024                                const RecordDecl *TruncatedType,
3025                                unsigned TruncatedElements) {
3026   SubobjectDesignator &D = Result.Designator;
3027 
3028   // Check we actually point to a derived class object.
3029   if (TruncatedElements == D.Entries.size())
3030     return true;
3031   assert(TruncatedElements >= D.MostDerivedPathLength &&
3032          "not casting to a derived class");
3033   if (!Result.checkSubobject(Info, E, CSK_Derived))
3034     return false;
3035 
3036   // Truncate the path to the subobject, and remove any derived-to-base offsets.
3037   const RecordDecl *RD = TruncatedType;
3038   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3039     if (RD->isInvalidDecl()) return false;
3040     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3041     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3042     if (isVirtualBaseClass(D.Entries[I]))
3043       Result.Offset -= Layout.getVBaseClassOffset(Base);
3044     else
3045       Result.Offset -= Layout.getBaseClassOffset(Base);
3046     RD = Base;
3047   }
3048   D.Entries.resize(TruncatedElements);
3049   return true;
3050 }
3051 
3052 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3053                                    const CXXRecordDecl *Derived,
3054                                    const CXXRecordDecl *Base,
3055                                    const ASTRecordLayout *RL = nullptr) {
3056   if (!RL) {
3057     if (Derived->isInvalidDecl()) return false;
3058     RL = &Info.Ctx.getASTRecordLayout(Derived);
3059   }
3060 
3061   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3062   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3063   return true;
3064 }
3065 
3066 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3067                              const CXXRecordDecl *DerivedDecl,
3068                              const CXXBaseSpecifier *Base) {
3069   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3070 
3071   if (!Base->isVirtual())
3072     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3073 
3074   SubobjectDesignator &D = Obj.Designator;
3075   if (D.Invalid)
3076     return false;
3077 
3078   // Extract most-derived object and corresponding type.
3079   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3080   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3081     return false;
3082 
3083   // Find the virtual base class.
3084   if (DerivedDecl->isInvalidDecl()) return false;
3085   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3086   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3087   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3088   return true;
3089 }
3090 
3091 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3092                                  QualType Type, LValue &Result) {
3093   for (CastExpr::path_const_iterator PathI = E->path_begin(),
3094                                      PathE = E->path_end();
3095        PathI != PathE; ++PathI) {
3096     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3097                           *PathI))
3098       return false;
3099     Type = (*PathI)->getType();
3100   }
3101   return true;
3102 }
3103 
3104 /// Cast an lvalue referring to a derived class to a known base subobject.
3105 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3106                             const CXXRecordDecl *DerivedRD,
3107                             const CXXRecordDecl *BaseRD) {
3108   CXXBasePaths Paths(/*FindAmbiguities=*/false,
3109                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
3110   if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3111     llvm_unreachable("Class must be derived from the passed in base class!");
3112 
3113   for (CXXBasePathElement &Elem : Paths.front())
3114     if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3115       return false;
3116   return true;
3117 }
3118 
3119 /// Update LVal to refer to the given field, which must be a member of the type
3120 /// currently described by LVal.
3121 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3122                                const FieldDecl *FD,
3123                                const ASTRecordLayout *RL = nullptr) {
3124   if (!RL) {
3125     if (FD->getParent()->isInvalidDecl()) return false;
3126     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3127   }
3128 
3129   unsigned I = FD->getFieldIndex();
3130   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3131   LVal.addDecl(Info, E, FD);
3132   return true;
3133 }
3134 
3135 /// Update LVal to refer to the given indirect field.
3136 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3137                                        LValue &LVal,
3138                                        const IndirectFieldDecl *IFD) {
3139   for (const auto *C : IFD->chain())
3140     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3141       return false;
3142   return true;
3143 }
3144 
3145 /// Get the size of the given type in char units.
3146 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
3147                          QualType Type, CharUnits &Size) {
3148   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3149   // extension.
3150   if (Type->isVoidType() || Type->isFunctionType()) {
3151     Size = CharUnits::One();
3152     return true;
3153   }
3154 
3155   if (Type->isDependentType()) {
3156     Info.FFDiag(Loc);
3157     return false;
3158   }
3159 
3160   if (!Type->isConstantSizeType()) {
3161     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3162     // FIXME: Better diagnostic.
3163     Info.FFDiag(Loc);
3164     return false;
3165   }
3166 
3167   Size = Info.Ctx.getTypeSizeInChars(Type);
3168   return true;
3169 }
3170 
3171 /// Update a pointer value to model pointer arithmetic.
3172 /// \param Info - Information about the ongoing evaluation.
3173 /// \param E - The expression being evaluated, for diagnostic purposes.
3174 /// \param LVal - The pointer value to be updated.
3175 /// \param EltTy - The pointee type represented by LVal.
3176 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3177 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3178                                         LValue &LVal, QualType EltTy,
3179                                         APSInt Adjustment) {
3180   CharUnits SizeOfPointee;
3181   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3182     return false;
3183 
3184   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3185   return true;
3186 }
3187 
3188 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3189                                         LValue &LVal, QualType EltTy,
3190                                         int64_t Adjustment) {
3191   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3192                                      APSInt::get(Adjustment));
3193 }
3194 
3195 /// Update an lvalue to refer to a component of a complex number.
3196 /// \param Info - Information about the ongoing evaluation.
3197 /// \param LVal - The lvalue to be updated.
3198 /// \param EltTy - The complex number's component type.
3199 /// \param Imag - False for the real component, true for the imaginary.
3200 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3201                                        LValue &LVal, QualType EltTy,
3202                                        bool Imag) {
3203   if (Imag) {
3204     CharUnits SizeOfComponent;
3205     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3206       return false;
3207     LVal.Offset += SizeOfComponent;
3208   }
3209   LVal.addComplex(Info, E, EltTy, Imag);
3210   return true;
3211 }
3212 
3213 /// Try to evaluate the initializer for a variable declaration.
3214 ///
3215 /// \param Info   Information about the ongoing evaluation.
3216 /// \param E      An expression to be used when printing diagnostics.
3217 /// \param VD     The variable whose initializer should be obtained.
3218 /// \param Version The version of the variable within the frame.
3219 /// \param Frame  The frame in which the variable was created. Must be null
3220 ///               if this variable is not local to the evaluation.
3221 /// \param Result Filled in with a pointer to the value of the variable.
3222 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3223                                 const VarDecl *VD, CallStackFrame *Frame,
3224                                 unsigned Version, APValue *&Result) {
3225   APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3226 
3227   // If this is a local variable, dig out its value.
3228   if (Frame) {
3229     Result = Frame->getTemporary(VD, Version);
3230     if (Result)
3231       return true;
3232 
3233     if (!isa<ParmVarDecl>(VD)) {
3234       // Assume variables referenced within a lambda's call operator that were
3235       // not declared within the call operator are captures and during checking
3236       // of a potential constant expression, assume they are unknown constant
3237       // expressions.
3238       assert(isLambdaCallOperator(Frame->Callee) &&
3239              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3240              "missing value for local variable");
3241       if (Info.checkingPotentialConstantExpression())
3242         return false;
3243       // FIXME: This diagnostic is bogus; we do support captures. Is this code
3244       // still reachable at all?
3245       Info.FFDiag(E->getBeginLoc(),
3246                   diag::note_unimplemented_constexpr_lambda_feature_ast)
3247           << "captures not currently allowed";
3248       return false;
3249     }
3250   }
3251 
3252   // If we're currently evaluating the initializer of this declaration, use that
3253   // in-flight value.
3254   if (Info.EvaluatingDecl == Base) {
3255     Result = Info.EvaluatingDeclValue;
3256     return true;
3257   }
3258 
3259   if (isa<ParmVarDecl>(VD)) {
3260     // Assume parameters of a potential constant expression are usable in
3261     // constant expressions.
3262     if (!Info.checkingPotentialConstantExpression() ||
3263         !Info.CurrentCall->Callee ||
3264         !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3265       if (Info.getLangOpts().CPlusPlus11) {
3266         Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3267             << VD;
3268         NoteLValueLocation(Info, Base);
3269       } else {
3270         Info.FFDiag(E);
3271       }
3272     }
3273     return false;
3274   }
3275 
3276   // Dig out the initializer, and use the declaration which it's attached to.
3277   // FIXME: We should eventually check whether the variable has a reachable
3278   // initializing declaration.
3279   const Expr *Init = VD->getAnyInitializer(VD);
3280   if (!Init) {
3281     // Don't diagnose during potential constant expression checking; an
3282     // initializer might be added later.
3283     if (!Info.checkingPotentialConstantExpression()) {
3284       Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3285         << VD;
3286       NoteLValueLocation(Info, Base);
3287     }
3288     return false;
3289   }
3290 
3291   if (Init->isValueDependent()) {
3292     // The DeclRefExpr is not value-dependent, but the variable it refers to
3293     // has a value-dependent initializer. This should only happen in
3294     // constant-folding cases, where the variable is not actually of a suitable
3295     // type for use in a constant expression (otherwise the DeclRefExpr would
3296     // have been value-dependent too), so diagnose that.
3297     assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3298     if (!Info.checkingPotentialConstantExpression()) {
3299       Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3300                          ? diag::note_constexpr_ltor_non_constexpr
3301                          : diag::note_constexpr_ltor_non_integral, 1)
3302           << VD << VD->getType();
3303       NoteLValueLocation(Info, Base);
3304     }
3305     return false;
3306   }
3307 
3308   // Check that we can fold the initializer. In C++, we will have already done
3309   // this in the cases where it matters for conformance.
3310   SmallVector<PartialDiagnosticAt, 8> Notes;
3311   if (!VD->evaluateValue(Notes)) {
3312     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
3313               Notes.size() + 1) << VD;
3314     NoteLValueLocation(Info, Base);
3315     Info.addNotes(Notes);
3316     return false;
3317   }
3318 
3319   // Check that the variable is actually usable in constant expressions. For a
3320   // const integral variable or a reference, we might have a non-constant
3321   // initializer that we can nonetheless evaluate the initializer for. Such
3322   // variables are not usable in constant expressions. In C++98, the
3323   // initializer also syntactically needs to be an ICE.
3324   //
3325   // FIXME: We don't diagnose cases that aren't potentially usable in constant
3326   // expressions here; doing so would regress diagnostics for things like
3327   // reading from a volatile constexpr variable.
3328   if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3329        VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||
3330       ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3331        !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3332     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3333     NoteLValueLocation(Info, Base);
3334   }
3335 
3336   // Never use the initializer of a weak variable, not even for constant
3337   // folding. We can't be sure that this is the definition that will be used.
3338   if (VD->isWeak()) {
3339     Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3340     NoteLValueLocation(Info, Base);
3341     return false;
3342   }
3343 
3344   Result = VD->getEvaluatedValue();
3345   return true;
3346 }
3347 
3348 /// Get the base index of the given base class within an APValue representing
3349 /// the given derived class.
3350 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3351                              const CXXRecordDecl *Base) {
3352   Base = Base->getCanonicalDecl();
3353   unsigned Index = 0;
3354   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3355          E = Derived->bases_end(); I != E; ++I, ++Index) {
3356     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3357       return Index;
3358   }
3359 
3360   llvm_unreachable("base class missing from derived class's bases list");
3361 }
3362 
3363 /// Extract the value of a character from a string literal.
3364 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3365                                             uint64_t Index) {
3366   assert(!isa<SourceLocExpr>(Lit) &&
3367          "SourceLocExpr should have already been converted to a StringLiteral");
3368 
3369   // FIXME: Support MakeStringConstant
3370   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3371     std::string Str;
3372     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3373     assert(Index <= Str.size() && "Index too large");
3374     return APSInt::getUnsigned(Str.c_str()[Index]);
3375   }
3376 
3377   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3378     Lit = PE->getFunctionName();
3379   const StringLiteral *S = cast<StringLiteral>(Lit);
3380   const ConstantArrayType *CAT =
3381       Info.Ctx.getAsConstantArrayType(S->getType());
3382   assert(CAT && "string literal isn't an array");
3383   QualType CharType = CAT->getElementType();
3384   assert(CharType->isIntegerType() && "unexpected character type");
3385 
3386   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3387                CharType->isUnsignedIntegerType());
3388   if (Index < S->getLength())
3389     Value = S->getCodeUnit(Index);
3390   return Value;
3391 }
3392 
3393 // Expand a string literal into an array of characters.
3394 //
3395 // FIXME: This is inefficient; we should probably introduce something similar
3396 // to the LLVM ConstantDataArray to make this cheaper.
3397 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3398                                 APValue &Result,
3399                                 QualType AllocType = QualType()) {
3400   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3401       AllocType.isNull() ? S->getType() : AllocType);
3402   assert(CAT && "string literal isn't an array");
3403   QualType CharType = CAT->getElementType();
3404   assert(CharType->isIntegerType() && "unexpected character type");
3405 
3406   unsigned Elts = CAT->getSize().getZExtValue();
3407   Result = APValue(APValue::UninitArray(),
3408                    std::min(S->getLength(), Elts), Elts);
3409   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3410                CharType->isUnsignedIntegerType());
3411   if (Result.hasArrayFiller())
3412     Result.getArrayFiller() = APValue(Value);
3413   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3414     Value = S->getCodeUnit(I);
3415     Result.getArrayInitializedElt(I) = APValue(Value);
3416   }
3417 }
3418 
3419 // Expand an array so that it has more than Index filled elements.
3420 static void expandArray(APValue &Array, unsigned Index) {
3421   unsigned Size = Array.getArraySize();
3422   assert(Index < Size);
3423 
3424   // Always at least double the number of elements for which we store a value.
3425   unsigned OldElts = Array.getArrayInitializedElts();
3426   unsigned NewElts = std::max(Index+1, OldElts * 2);
3427   NewElts = std::min(Size, std::max(NewElts, 8u));
3428 
3429   // Copy the data across.
3430   APValue NewValue(APValue::UninitArray(), NewElts, Size);
3431   for (unsigned I = 0; I != OldElts; ++I)
3432     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3433   for (unsigned I = OldElts; I != NewElts; ++I)
3434     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3435   if (NewValue.hasArrayFiller())
3436     NewValue.getArrayFiller() = Array.getArrayFiller();
3437   Array.swap(NewValue);
3438 }
3439 
3440 /// Determine whether a type would actually be read by an lvalue-to-rvalue
3441 /// conversion. If it's of class type, we may assume that the copy operation
3442 /// is trivial. Note that this is never true for a union type with fields
3443 /// (because the copy always "reads" the active member) and always true for
3444 /// a non-class type.
3445 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3446 static bool isReadByLvalueToRvalueConversion(QualType T) {
3447   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3448   return !RD || isReadByLvalueToRvalueConversion(RD);
3449 }
3450 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3451   // FIXME: A trivial copy of a union copies the object representation, even if
3452   // the union is empty.
3453   if (RD->isUnion())
3454     return !RD->field_empty();
3455   if (RD->isEmpty())
3456     return false;
3457 
3458   for (auto *Field : RD->fields())
3459     if (!Field->isUnnamedBitfield() &&
3460         isReadByLvalueToRvalueConversion(Field->getType()))
3461       return true;
3462 
3463   for (auto &BaseSpec : RD->bases())
3464     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3465       return true;
3466 
3467   return false;
3468 }
3469 
3470 /// Diagnose an attempt to read from any unreadable field within the specified
3471 /// type, which might be a class type.
3472 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3473                                   QualType T) {
3474   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3475   if (!RD)
3476     return false;
3477 
3478   if (!RD->hasMutableFields())
3479     return false;
3480 
3481   for (auto *Field : RD->fields()) {
3482     // If we're actually going to read this field in some way, then it can't
3483     // be mutable. If we're in a union, then assigning to a mutable field
3484     // (even an empty one) can change the active member, so that's not OK.
3485     // FIXME: Add core issue number for the union case.
3486     if (Field->isMutable() &&
3487         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3488       Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3489       Info.Note(Field->getLocation(), diag::note_declared_at);
3490       return true;
3491     }
3492 
3493     if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3494       return true;
3495   }
3496 
3497   for (auto &BaseSpec : RD->bases())
3498     if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3499       return true;
3500 
3501   // All mutable fields were empty, and thus not actually read.
3502   return false;
3503 }
3504 
3505 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3506                                         APValue::LValueBase Base,
3507                                         bool MutableSubobject = false) {
3508   // A temporary or transient heap allocation we created.
3509   if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3510     return true;
3511 
3512   switch (Info.IsEvaluatingDecl) {
3513   case EvalInfo::EvaluatingDeclKind::None:
3514     return false;
3515 
3516   case EvalInfo::EvaluatingDeclKind::Ctor:
3517     // The variable whose initializer we're evaluating.
3518     if (Info.EvaluatingDecl == Base)
3519       return true;
3520 
3521     // A temporary lifetime-extended by the variable whose initializer we're
3522     // evaluating.
3523     if (auto *BaseE = Base.dyn_cast<const Expr *>())
3524       if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3525         return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3526     return false;
3527 
3528   case EvalInfo::EvaluatingDeclKind::Dtor:
3529     // C++2a [expr.const]p6:
3530     //   [during constant destruction] the lifetime of a and its non-mutable
3531     //   subobjects (but not its mutable subobjects) [are] considered to start
3532     //   within e.
3533     if (MutableSubobject || Base != Info.EvaluatingDecl)
3534       return false;
3535     // FIXME: We can meaningfully extend this to cover non-const objects, but
3536     // we will need special handling: we should be able to access only
3537     // subobjects of such objects that are themselves declared const.
3538     QualType T = getType(Base);
3539     return T.isConstQualified() || T->isReferenceType();
3540   }
3541 
3542   llvm_unreachable("unknown evaluating decl kind");
3543 }
3544 
3545 namespace {
3546 /// A handle to a complete object (an object that is not a subobject of
3547 /// another object).
3548 struct CompleteObject {
3549   /// The identity of the object.
3550   APValue::LValueBase Base;
3551   /// The value of the complete object.
3552   APValue *Value;
3553   /// The type of the complete object.
3554   QualType Type;
3555 
3556   CompleteObject() : Value(nullptr) {}
3557   CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3558       : Base(Base), Value(Value), Type(Type) {}
3559 
3560   bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3561     // If this isn't a "real" access (eg, if it's just accessing the type
3562     // info), allow it. We assume the type doesn't change dynamically for
3563     // subobjects of constexpr objects (even though we'd hit UB here if it
3564     // did). FIXME: Is this right?
3565     if (!isAnyAccess(AK))
3566       return true;
3567 
3568     // In C++14 onwards, it is permitted to read a mutable member whose
3569     // lifetime began within the evaluation.
3570     // FIXME: Should we also allow this in C++11?
3571     if (!Info.getLangOpts().CPlusPlus14)
3572       return false;
3573     return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3574   }
3575 
3576   explicit operator bool() const { return !Type.isNull(); }
3577 };
3578 } // end anonymous namespace
3579 
3580 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3581                                  bool IsMutable = false) {
3582   // C++ [basic.type.qualifier]p1:
3583   // - A const object is an object of type const T or a non-mutable subobject
3584   //   of a const object.
3585   if (ObjType.isConstQualified() && !IsMutable)
3586     SubobjType.addConst();
3587   // - A volatile object is an object of type const T or a subobject of a
3588   //   volatile object.
3589   if (ObjType.isVolatileQualified())
3590     SubobjType.addVolatile();
3591   return SubobjType;
3592 }
3593 
3594 /// Find the designated sub-object of an rvalue.
3595 template<typename SubobjectHandler>
3596 typename SubobjectHandler::result_type
3597 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3598               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3599   if (Sub.Invalid)
3600     // A diagnostic will have already been produced.
3601     return handler.failed();
3602   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3603     if (Info.getLangOpts().CPlusPlus11)
3604       Info.FFDiag(E, Sub.isOnePastTheEnd()
3605                          ? diag::note_constexpr_access_past_end
3606                          : diag::note_constexpr_access_unsized_array)
3607           << handler.AccessKind;
3608     else
3609       Info.FFDiag(E);
3610     return handler.failed();
3611   }
3612 
3613   APValue *O = Obj.Value;
3614   QualType ObjType = Obj.Type;
3615   const FieldDecl *LastField = nullptr;
3616   const FieldDecl *VolatileField = nullptr;
3617 
3618   // Walk the designator's path to find the subobject.
3619   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3620     // Reading an indeterminate value is undefined, but assigning over one is OK.
3621     if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3622         (O->isIndeterminate() &&
3623          !isValidIndeterminateAccess(handler.AccessKind))) {
3624       if (!Info.checkingPotentialConstantExpression())
3625         Info.FFDiag(E, diag::note_constexpr_access_uninit)
3626             << handler.AccessKind << O->isIndeterminate();
3627       return handler.failed();
3628     }
3629 
3630     // C++ [class.ctor]p5, C++ [class.dtor]p5:
3631     //    const and volatile semantics are not applied on an object under
3632     //    {con,de}struction.
3633     if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3634         ObjType->isRecordType() &&
3635         Info.isEvaluatingCtorDtor(
3636             Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3637                                          Sub.Entries.begin() + I)) !=
3638                           ConstructionPhase::None) {
3639       ObjType = Info.Ctx.getCanonicalType(ObjType);
3640       ObjType.removeLocalConst();
3641       ObjType.removeLocalVolatile();
3642     }
3643 
3644     // If this is our last pass, check that the final object type is OK.
3645     if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3646       // Accesses to volatile objects are prohibited.
3647       if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3648         if (Info.getLangOpts().CPlusPlus) {
3649           int DiagKind;
3650           SourceLocation Loc;
3651           const NamedDecl *Decl = nullptr;
3652           if (VolatileField) {
3653             DiagKind = 2;
3654             Loc = VolatileField->getLocation();
3655             Decl = VolatileField;
3656           } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3657             DiagKind = 1;
3658             Loc = VD->getLocation();
3659             Decl = VD;
3660           } else {
3661             DiagKind = 0;
3662             if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3663               Loc = E->getExprLoc();
3664           }
3665           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3666               << handler.AccessKind << DiagKind << Decl;
3667           Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3668         } else {
3669           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3670         }
3671         return handler.failed();
3672       }
3673 
3674       // If we are reading an object of class type, there may still be more
3675       // things we need to check: if there are any mutable subobjects, we
3676       // cannot perform this read. (This only happens when performing a trivial
3677       // copy or assignment.)
3678       if (ObjType->isRecordType() &&
3679           !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3680           diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3681         return handler.failed();
3682     }
3683 
3684     if (I == N) {
3685       if (!handler.found(*O, ObjType))
3686         return false;
3687 
3688       // If we modified a bit-field, truncate it to the right width.
3689       if (isModification(handler.AccessKind) &&
3690           LastField && LastField->isBitField() &&
3691           !truncateBitfieldValue(Info, E, *O, LastField))
3692         return false;
3693 
3694       return true;
3695     }
3696 
3697     LastField = nullptr;
3698     if (ObjType->isArrayType()) {
3699       // Next subobject is an array element.
3700       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3701       assert(CAT && "vla in literal type?");
3702       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3703       if (CAT->getSize().ule(Index)) {
3704         // Note, it should not be possible to form a pointer with a valid
3705         // designator which points more than one past the end of the array.
3706         if (Info.getLangOpts().CPlusPlus11)
3707           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3708             << handler.AccessKind;
3709         else
3710           Info.FFDiag(E);
3711         return handler.failed();
3712       }
3713 
3714       ObjType = CAT->getElementType();
3715 
3716       if (O->getArrayInitializedElts() > Index)
3717         O = &O->getArrayInitializedElt(Index);
3718       else if (!isRead(handler.AccessKind)) {
3719         expandArray(*O, Index);
3720         O = &O->getArrayInitializedElt(Index);
3721       } else
3722         O = &O->getArrayFiller();
3723     } else if (ObjType->isAnyComplexType()) {
3724       // Next subobject is a complex number.
3725       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3726       if (Index > 1) {
3727         if (Info.getLangOpts().CPlusPlus11)
3728           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3729             << handler.AccessKind;
3730         else
3731           Info.FFDiag(E);
3732         return handler.failed();
3733       }
3734 
3735       ObjType = getSubobjectType(
3736           ObjType, ObjType->castAs<ComplexType>()->getElementType());
3737 
3738       assert(I == N - 1 && "extracting subobject of scalar?");
3739       if (O->isComplexInt()) {
3740         return handler.found(Index ? O->getComplexIntImag()
3741                                    : O->getComplexIntReal(), ObjType);
3742       } else {
3743         assert(O->isComplexFloat());
3744         return handler.found(Index ? O->getComplexFloatImag()
3745                                    : O->getComplexFloatReal(), ObjType);
3746       }
3747     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3748       if (Field->isMutable() &&
3749           !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3750         Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3751           << handler.AccessKind << Field;
3752         Info.Note(Field->getLocation(), diag::note_declared_at);
3753         return handler.failed();
3754       }
3755 
3756       // Next subobject is a class, struct or union field.
3757       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3758       if (RD->isUnion()) {
3759         const FieldDecl *UnionField = O->getUnionField();
3760         if (!UnionField ||
3761             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3762           if (I == N - 1 && handler.AccessKind == AK_Construct) {
3763             // Placement new onto an inactive union member makes it active.
3764             O->setUnion(Field, APValue());
3765           } else {
3766             // FIXME: If O->getUnionValue() is absent, report that there's no
3767             // active union member rather than reporting the prior active union
3768             // member. We'll need to fix nullptr_t to not use APValue() as its
3769             // representation first.
3770             Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3771                 << handler.AccessKind << Field << !UnionField << UnionField;
3772             return handler.failed();
3773           }
3774         }
3775         O = &O->getUnionValue();
3776       } else
3777         O = &O->getStructField(Field->getFieldIndex());
3778 
3779       ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3780       LastField = Field;
3781       if (Field->getType().isVolatileQualified())
3782         VolatileField = Field;
3783     } else {
3784       // Next subobject is a base class.
3785       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3786       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3787       O = &O->getStructBase(getBaseIndex(Derived, Base));
3788 
3789       ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3790     }
3791   }
3792 }
3793 
3794 namespace {
3795 struct ExtractSubobjectHandler {
3796   EvalInfo &Info;
3797   const Expr *E;
3798   APValue &Result;
3799   const AccessKinds AccessKind;
3800 
3801   typedef bool result_type;
3802   bool failed() { return false; }
3803   bool found(APValue &Subobj, QualType SubobjType) {
3804     Result = Subobj;
3805     if (AccessKind == AK_ReadObjectRepresentation)
3806       return true;
3807     return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3808   }
3809   bool found(APSInt &Value, QualType SubobjType) {
3810     Result = APValue(Value);
3811     return true;
3812   }
3813   bool found(APFloat &Value, QualType SubobjType) {
3814     Result = APValue(Value);
3815     return true;
3816   }
3817 };
3818 } // end anonymous namespace
3819 
3820 /// Extract the designated sub-object of an rvalue.
3821 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3822                              const CompleteObject &Obj,
3823                              const SubobjectDesignator &Sub, APValue &Result,
3824                              AccessKinds AK = AK_Read) {
3825   assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3826   ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3827   return findSubobject(Info, E, Obj, Sub, Handler);
3828 }
3829 
3830 namespace {
3831 struct ModifySubobjectHandler {
3832   EvalInfo &Info;
3833   APValue &NewVal;
3834   const Expr *E;
3835 
3836   typedef bool result_type;
3837   static const AccessKinds AccessKind = AK_Assign;
3838 
3839   bool checkConst(QualType QT) {
3840     // Assigning to a const object has undefined behavior.
3841     if (QT.isConstQualified()) {
3842       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3843       return false;
3844     }
3845     return true;
3846   }
3847 
3848   bool failed() { return false; }
3849   bool found(APValue &Subobj, QualType SubobjType) {
3850     if (!checkConst(SubobjType))
3851       return false;
3852     // We've been given ownership of NewVal, so just swap it in.
3853     Subobj.swap(NewVal);
3854     return true;
3855   }
3856   bool found(APSInt &Value, QualType SubobjType) {
3857     if (!checkConst(SubobjType))
3858       return false;
3859     if (!NewVal.isInt()) {
3860       // Maybe trying to write a cast pointer value into a complex?
3861       Info.FFDiag(E);
3862       return false;
3863     }
3864     Value = NewVal.getInt();
3865     return true;
3866   }
3867   bool found(APFloat &Value, QualType SubobjType) {
3868     if (!checkConst(SubobjType))
3869       return false;
3870     Value = NewVal.getFloat();
3871     return true;
3872   }
3873 };
3874 } // end anonymous namespace
3875 
3876 const AccessKinds ModifySubobjectHandler::AccessKind;
3877 
3878 /// Update the designated sub-object of an rvalue to the given value.
3879 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3880                             const CompleteObject &Obj,
3881                             const SubobjectDesignator &Sub,
3882                             APValue &NewVal) {
3883   ModifySubobjectHandler Handler = { Info, NewVal, E };
3884   return findSubobject(Info, E, Obj, Sub, Handler);
3885 }
3886 
3887 /// Find the position where two subobject designators diverge, or equivalently
3888 /// the length of the common initial subsequence.
3889 static unsigned FindDesignatorMismatch(QualType ObjType,
3890                                        const SubobjectDesignator &A,
3891                                        const SubobjectDesignator &B,
3892                                        bool &WasArrayIndex) {
3893   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3894   for (/**/; I != N; ++I) {
3895     if (!ObjType.isNull() &&
3896         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3897       // Next subobject is an array element.
3898       if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3899         WasArrayIndex = true;
3900         return I;
3901       }
3902       if (ObjType->isAnyComplexType())
3903         ObjType = ObjType->castAs<ComplexType>()->getElementType();
3904       else
3905         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3906     } else {
3907       if (A.Entries[I].getAsBaseOrMember() !=
3908           B.Entries[I].getAsBaseOrMember()) {
3909         WasArrayIndex = false;
3910         return I;
3911       }
3912       if (const FieldDecl *FD = getAsField(A.Entries[I]))
3913         // Next subobject is a field.
3914         ObjType = FD->getType();
3915       else
3916         // Next subobject is a base class.
3917         ObjType = QualType();
3918     }
3919   }
3920   WasArrayIndex = false;
3921   return I;
3922 }
3923 
3924 /// Determine whether the given subobject designators refer to elements of the
3925 /// same array object.
3926 static bool AreElementsOfSameArray(QualType ObjType,
3927                                    const SubobjectDesignator &A,
3928                                    const SubobjectDesignator &B) {
3929   if (A.Entries.size() != B.Entries.size())
3930     return false;
3931 
3932   bool IsArray = A.MostDerivedIsArrayElement;
3933   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3934     // A is a subobject of the array element.
3935     return false;
3936 
3937   // If A (and B) designates an array element, the last entry will be the array
3938   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3939   // of length 1' case, and the entire path must match.
3940   bool WasArrayIndex;
3941   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3942   return CommonLength >= A.Entries.size() - IsArray;
3943 }
3944 
3945 /// Find the complete object to which an LValue refers.
3946 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3947                                          AccessKinds AK, const LValue &LVal,
3948                                          QualType LValType) {
3949   if (LVal.InvalidBase) {
3950     Info.FFDiag(E);
3951     return CompleteObject();
3952   }
3953 
3954   if (!LVal.Base) {
3955     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3956     return CompleteObject();
3957   }
3958 
3959   CallStackFrame *Frame = nullptr;
3960   unsigned Depth = 0;
3961   if (LVal.getLValueCallIndex()) {
3962     std::tie(Frame, Depth) =
3963         Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3964     if (!Frame) {
3965       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3966         << AK << LVal.Base.is<const ValueDecl*>();
3967       NoteLValueLocation(Info, LVal.Base);
3968       return CompleteObject();
3969     }
3970   }
3971 
3972   bool IsAccess = isAnyAccess(AK);
3973 
3974   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3975   // is not a constant expression (even if the object is non-volatile). We also
3976   // apply this rule to C++98, in order to conform to the expected 'volatile'
3977   // semantics.
3978   if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
3979     if (Info.getLangOpts().CPlusPlus)
3980       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3981         << AK << LValType;
3982     else
3983       Info.FFDiag(E);
3984     return CompleteObject();
3985   }
3986 
3987   // Compute value storage location and type of base object.
3988   APValue *BaseVal = nullptr;
3989   QualType BaseType = getType(LVal.Base);
3990 
3991   if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
3992       lifetimeStartedInEvaluation(Info, LVal.Base)) {
3993     // This is the object whose initializer we're evaluating, so its lifetime
3994     // started in the current evaluation.
3995     BaseVal = Info.EvaluatingDeclValue;
3996   } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
3997     // Allow reading from a GUID declaration.
3998     if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
3999       if (isModification(AK)) {
4000         // All the remaining cases do not permit modification of the object.
4001         Info.FFDiag(E, diag::note_constexpr_modify_global);
4002         return CompleteObject();
4003       }
4004       APValue &V = GD->getAsAPValue();
4005       if (V.isAbsent()) {
4006         Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4007             << GD->getType();
4008         return CompleteObject();
4009       }
4010       return CompleteObject(LVal.Base, &V, GD->getType());
4011     }
4012 
4013     // Allow reading from template parameter objects.
4014     if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4015       if (isModification(AK)) {
4016         Info.FFDiag(E, diag::note_constexpr_modify_global);
4017         return CompleteObject();
4018       }
4019       return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4020                             TPO->getType());
4021     }
4022 
4023     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4024     // In C++11, constexpr, non-volatile variables initialized with constant
4025     // expressions are constant expressions too. Inside constexpr functions,
4026     // parameters are constant expressions even if they're non-const.
4027     // In C++1y, objects local to a constant expression (those with a Frame) are
4028     // both readable and writable inside constant expressions.
4029     // In C, such things can also be folded, although they are not ICEs.
4030     const VarDecl *VD = dyn_cast<VarDecl>(D);
4031     if (VD) {
4032       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4033         VD = VDef;
4034     }
4035     if (!VD || VD->isInvalidDecl()) {
4036       Info.FFDiag(E);
4037       return CompleteObject();
4038     }
4039 
4040     bool IsConstant = BaseType.isConstant(Info.Ctx);
4041 
4042     // Unless we're looking at a local variable or argument in a constexpr call,
4043     // the variable we're reading must be const.
4044     if (!Frame) {
4045       if (IsAccess && isa<ParmVarDecl>(VD)) {
4046         // Access of a parameter that's not associated with a frame isn't going
4047         // to work out, but we can leave it to evaluateVarDeclInit to provide a
4048         // suitable diagnostic.
4049       } else if (Info.getLangOpts().CPlusPlus14 &&
4050                  lifetimeStartedInEvaluation(Info, LVal.Base)) {
4051         // OK, we can read and modify an object if we're in the process of
4052         // evaluating its initializer, because its lifetime began in this
4053         // evaluation.
4054       } else if (isModification(AK)) {
4055         // All the remaining cases do not permit modification of the object.
4056         Info.FFDiag(E, diag::note_constexpr_modify_global);
4057         return CompleteObject();
4058       } else if (VD->isConstexpr()) {
4059         // OK, we can read this variable.
4060       } else if (BaseType->isIntegralOrEnumerationType()) {
4061         if (!IsConstant) {
4062           if (!IsAccess)
4063             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4064           if (Info.getLangOpts().CPlusPlus) {
4065             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4066             Info.Note(VD->getLocation(), diag::note_declared_at);
4067           } else {
4068             Info.FFDiag(E);
4069           }
4070           return CompleteObject();
4071         }
4072       } else if (!IsAccess) {
4073         return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4074       } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
4075                  BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4076         // This variable might end up being constexpr. Don't diagnose it yet.
4077       } else if (IsConstant) {
4078         // Keep evaluating to see what we can do. In particular, we support
4079         // folding of const floating-point types, in order to make static const
4080         // data members of such types (supported as an extension) more useful.
4081         if (Info.getLangOpts().CPlusPlus) {
4082           Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4083                               ? diag::note_constexpr_ltor_non_constexpr
4084                               : diag::note_constexpr_ltor_non_integral, 1)
4085               << VD << BaseType;
4086           Info.Note(VD->getLocation(), diag::note_declared_at);
4087         } else {
4088           Info.CCEDiag(E);
4089         }
4090       } else {
4091         // Never allow reading a non-const value.
4092         if (Info.getLangOpts().CPlusPlus) {
4093           Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4094                              ? diag::note_constexpr_ltor_non_constexpr
4095                              : diag::note_constexpr_ltor_non_integral, 1)
4096               << VD << BaseType;
4097           Info.Note(VD->getLocation(), diag::note_declared_at);
4098         } else {
4099           Info.FFDiag(E);
4100         }
4101         return CompleteObject();
4102       }
4103     }
4104 
4105     if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
4106       return CompleteObject();
4107   } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4108     Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
4109     if (!Alloc) {
4110       Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4111       return CompleteObject();
4112     }
4113     return CompleteObject(LVal.Base, &(*Alloc)->Value,
4114                           LVal.Base.getDynamicAllocType());
4115   } else {
4116     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4117 
4118     if (!Frame) {
4119       if (const MaterializeTemporaryExpr *MTE =
4120               dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4121         assert(MTE->getStorageDuration() == SD_Static &&
4122                "should have a frame for a non-global materialized temporary");
4123 
4124         // C++20 [expr.const]p4: [DR2126]
4125         //   An object or reference is usable in constant expressions if it is
4126         //   - a temporary object of non-volatile const-qualified literal type
4127         //     whose lifetime is extended to that of a variable that is usable
4128         //     in constant expressions
4129         //
4130         // C++20 [expr.const]p5:
4131         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4132         //   - a non-volatile glvalue that refers to an object that is usable
4133         //     in constant expressions, or
4134         //   - a non-volatile glvalue of literal type that refers to a
4135         //     non-volatile object whose lifetime began within the evaluation
4136         //     of E;
4137         //
4138         // C++11 misses the 'began within the evaluation of e' check and
4139         // instead allows all temporaries, including things like:
4140         //   int &&r = 1;
4141         //   int x = ++r;
4142         //   constexpr int k = r;
4143         // Therefore we use the C++14-onwards rules in C++11 too.
4144         //
4145         // Note that temporaries whose lifetimes began while evaluating a
4146         // variable's constructor are not usable while evaluating the
4147         // corresponding destructor, not even if they're of const-qualified
4148         // types.
4149         if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4150             !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4151           if (!IsAccess)
4152             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4153           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4154           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4155           return CompleteObject();
4156         }
4157 
4158         BaseVal = MTE->getOrCreateValue(false);
4159         assert(BaseVal && "got reference to unevaluated temporary");
4160       } else {
4161         if (!IsAccess)
4162           return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4163         APValue Val;
4164         LVal.moveInto(Val);
4165         Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4166             << AK
4167             << Val.getAsString(Info.Ctx,
4168                                Info.Ctx.getLValueReferenceType(LValType));
4169         NoteLValueLocation(Info, LVal.Base);
4170         return CompleteObject();
4171       }
4172     } else {
4173       BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4174       assert(BaseVal && "missing value for temporary");
4175     }
4176   }
4177 
4178   // In C++14, we can't safely access any mutable state when we might be
4179   // evaluating after an unmodeled side effect. Parameters are modeled as state
4180   // in the caller, but aren't visible once the call returns, so they can be
4181   // modified in a speculatively-evaluated call.
4182   //
4183   // FIXME: Not all local state is mutable. Allow local constant subobjects
4184   // to be read here (but take care with 'mutable' fields).
4185   unsigned VisibleDepth = Depth;
4186   if (llvm::isa_and_nonnull<ParmVarDecl>(
4187           LVal.Base.dyn_cast<const ValueDecl *>()))
4188     ++VisibleDepth;
4189   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4190        Info.EvalStatus.HasSideEffects) ||
4191       (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4192     return CompleteObject();
4193 
4194   return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4195 }
4196 
4197 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4198 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4199 /// glvalue referred to by an entity of reference type.
4200 ///
4201 /// \param Info - Information about the ongoing evaluation.
4202 /// \param Conv - The expression for which we are performing the conversion.
4203 ///               Used for diagnostics.
4204 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4205 ///               case of a non-class type).
4206 /// \param LVal - The glvalue on which we are attempting to perform this action.
4207 /// \param RVal - The produced value will be placed here.
4208 /// \param WantObjectRepresentation - If true, we're looking for the object
4209 ///               representation rather than the value, and in particular,
4210 ///               there is no requirement that the result be fully initialized.
4211 static bool
4212 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
4213                                const LValue &LVal, APValue &RVal,
4214                                bool WantObjectRepresentation = false) {
4215   if (LVal.Designator.Invalid)
4216     return false;
4217 
4218   // Check for special cases where there is no existing APValue to look at.
4219   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4220 
4221   AccessKinds AK =
4222       WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4223 
4224   if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4225     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4226       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4227       // initializer until now for such expressions. Such an expression can't be
4228       // an ICE in C, so this only matters for fold.
4229       if (Type.isVolatileQualified()) {
4230         Info.FFDiag(Conv);
4231         return false;
4232       }
4233       APValue Lit;
4234       if (!Evaluate(Lit, Info, CLE->getInitializer()))
4235         return false;
4236       CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4237       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4238     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4239       // Special-case character extraction so we don't have to construct an
4240       // APValue for the whole string.
4241       assert(LVal.Designator.Entries.size() <= 1 &&
4242              "Can only read characters from string literals");
4243       if (LVal.Designator.Entries.empty()) {
4244         // Fail for now for LValue to RValue conversion of an array.
4245         // (This shouldn't show up in C/C++, but it could be triggered by a
4246         // weird EvaluateAsRValue call from a tool.)
4247         Info.FFDiag(Conv);
4248         return false;
4249       }
4250       if (LVal.Designator.isOnePastTheEnd()) {
4251         if (Info.getLangOpts().CPlusPlus11)
4252           Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4253         else
4254           Info.FFDiag(Conv);
4255         return false;
4256       }
4257       uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4258       RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4259       return true;
4260     }
4261   }
4262 
4263   CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4264   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4265 }
4266 
4267 /// Perform an assignment of Val to LVal. Takes ownership of Val.
4268 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4269                              QualType LValType, APValue &Val) {
4270   if (LVal.Designator.Invalid)
4271     return false;
4272 
4273   if (!Info.getLangOpts().CPlusPlus14) {
4274     Info.FFDiag(E);
4275     return false;
4276   }
4277 
4278   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4279   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4280 }
4281 
4282 namespace {
4283 struct CompoundAssignSubobjectHandler {
4284   EvalInfo &Info;
4285   const CompoundAssignOperator *E;
4286   QualType PromotedLHSType;
4287   BinaryOperatorKind Opcode;
4288   const APValue &RHS;
4289 
4290   static const AccessKinds AccessKind = AK_Assign;
4291 
4292   typedef bool result_type;
4293 
4294   bool checkConst(QualType QT) {
4295     // Assigning to a const object has undefined behavior.
4296     if (QT.isConstQualified()) {
4297       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4298       return false;
4299     }
4300     return true;
4301   }
4302 
4303   bool failed() { return false; }
4304   bool found(APValue &Subobj, QualType SubobjType) {
4305     switch (Subobj.getKind()) {
4306     case APValue::Int:
4307       return found(Subobj.getInt(), SubobjType);
4308     case APValue::Float:
4309       return found(Subobj.getFloat(), SubobjType);
4310     case APValue::ComplexInt:
4311     case APValue::ComplexFloat:
4312       // FIXME: Implement complex compound assignment.
4313       Info.FFDiag(E);
4314       return false;
4315     case APValue::LValue:
4316       return foundPointer(Subobj, SubobjType);
4317     case APValue::Vector:
4318       return foundVector(Subobj, SubobjType);
4319     default:
4320       // FIXME: can this happen?
4321       Info.FFDiag(E);
4322       return false;
4323     }
4324   }
4325 
4326   bool foundVector(APValue &Value, QualType SubobjType) {
4327     if (!checkConst(SubobjType))
4328       return false;
4329 
4330     if (!SubobjType->isVectorType()) {
4331       Info.FFDiag(E);
4332       return false;
4333     }
4334     return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4335   }
4336 
4337   bool found(APSInt &Value, QualType SubobjType) {
4338     if (!checkConst(SubobjType))
4339       return false;
4340 
4341     if (!SubobjType->isIntegerType()) {
4342       // We don't support compound assignment on integer-cast-to-pointer
4343       // values.
4344       Info.FFDiag(E);
4345       return false;
4346     }
4347 
4348     if (RHS.isInt()) {
4349       APSInt LHS =
4350           HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4351       if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4352         return false;
4353       Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4354       return true;
4355     } else if (RHS.isFloat()) {
4356       const FPOptions FPO = E->getFPFeaturesInEffect(
4357                                     Info.Ctx.getLangOpts());
4358       APFloat FValue(0.0);
4359       return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4360                                   PromotedLHSType, FValue) &&
4361              handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4362              HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4363                                   Value);
4364     }
4365 
4366     Info.FFDiag(E);
4367     return false;
4368   }
4369   bool found(APFloat &Value, QualType SubobjType) {
4370     return checkConst(SubobjType) &&
4371            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4372                                   Value) &&
4373            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4374            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4375   }
4376   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4377     if (!checkConst(SubobjType))
4378       return false;
4379 
4380     QualType PointeeType;
4381     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4382       PointeeType = PT->getPointeeType();
4383 
4384     if (PointeeType.isNull() || !RHS.isInt() ||
4385         (Opcode != BO_Add && Opcode != BO_Sub)) {
4386       Info.FFDiag(E);
4387       return false;
4388     }
4389 
4390     APSInt Offset = RHS.getInt();
4391     if (Opcode == BO_Sub)
4392       negateAsSigned(Offset);
4393 
4394     LValue LVal;
4395     LVal.setFrom(Info.Ctx, Subobj);
4396     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4397       return false;
4398     LVal.moveInto(Subobj);
4399     return true;
4400   }
4401 };
4402 } // end anonymous namespace
4403 
4404 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4405 
4406 /// Perform a compound assignment of LVal <op>= RVal.
4407 static bool handleCompoundAssignment(EvalInfo &Info,
4408                                      const CompoundAssignOperator *E,
4409                                      const LValue &LVal, QualType LValType,
4410                                      QualType PromotedLValType,
4411                                      BinaryOperatorKind Opcode,
4412                                      const APValue &RVal) {
4413   if (LVal.Designator.Invalid)
4414     return false;
4415 
4416   if (!Info.getLangOpts().CPlusPlus14) {
4417     Info.FFDiag(E);
4418     return false;
4419   }
4420 
4421   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4422   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4423                                              RVal };
4424   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4425 }
4426 
4427 namespace {
4428 struct IncDecSubobjectHandler {
4429   EvalInfo &Info;
4430   const UnaryOperator *E;
4431   AccessKinds AccessKind;
4432   APValue *Old;
4433 
4434   typedef bool result_type;
4435 
4436   bool checkConst(QualType QT) {
4437     // Assigning to a const object has undefined behavior.
4438     if (QT.isConstQualified()) {
4439       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4440       return false;
4441     }
4442     return true;
4443   }
4444 
4445   bool failed() { return false; }
4446   bool found(APValue &Subobj, QualType SubobjType) {
4447     // Stash the old value. Also clear Old, so we don't clobber it later
4448     // if we're post-incrementing a complex.
4449     if (Old) {
4450       *Old = Subobj;
4451       Old = nullptr;
4452     }
4453 
4454     switch (Subobj.getKind()) {
4455     case APValue::Int:
4456       return found(Subobj.getInt(), SubobjType);
4457     case APValue::Float:
4458       return found(Subobj.getFloat(), SubobjType);
4459     case APValue::ComplexInt:
4460       return found(Subobj.getComplexIntReal(),
4461                    SubobjType->castAs<ComplexType>()->getElementType()
4462                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4463     case APValue::ComplexFloat:
4464       return found(Subobj.getComplexFloatReal(),
4465                    SubobjType->castAs<ComplexType>()->getElementType()
4466                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4467     case APValue::LValue:
4468       return foundPointer(Subobj, SubobjType);
4469     default:
4470       // FIXME: can this happen?
4471       Info.FFDiag(E);
4472       return false;
4473     }
4474   }
4475   bool found(APSInt &Value, QualType SubobjType) {
4476     if (!checkConst(SubobjType))
4477       return false;
4478 
4479     if (!SubobjType->isIntegerType()) {
4480       // We don't support increment / decrement on integer-cast-to-pointer
4481       // values.
4482       Info.FFDiag(E);
4483       return false;
4484     }
4485 
4486     if (Old) *Old = APValue(Value);
4487 
4488     // bool arithmetic promotes to int, and the conversion back to bool
4489     // doesn't reduce mod 2^n, so special-case it.
4490     if (SubobjType->isBooleanType()) {
4491       if (AccessKind == AK_Increment)
4492         Value = 1;
4493       else
4494         Value = !Value;
4495       return true;
4496     }
4497 
4498     bool WasNegative = Value.isNegative();
4499     if (AccessKind == AK_Increment) {
4500       ++Value;
4501 
4502       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4503         APSInt ActualValue(Value, /*IsUnsigned*/true);
4504         return HandleOverflow(Info, E, ActualValue, SubobjType);
4505       }
4506     } else {
4507       --Value;
4508 
4509       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4510         unsigned BitWidth = Value.getBitWidth();
4511         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4512         ActualValue.setBit(BitWidth);
4513         return HandleOverflow(Info, E, ActualValue, SubobjType);
4514       }
4515     }
4516     return true;
4517   }
4518   bool found(APFloat &Value, QualType SubobjType) {
4519     if (!checkConst(SubobjType))
4520       return false;
4521 
4522     if (Old) *Old = APValue(Value);
4523 
4524     APFloat One(Value.getSemantics(), 1);
4525     if (AccessKind == AK_Increment)
4526       Value.add(One, APFloat::rmNearestTiesToEven);
4527     else
4528       Value.subtract(One, APFloat::rmNearestTiesToEven);
4529     return true;
4530   }
4531   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4532     if (!checkConst(SubobjType))
4533       return false;
4534 
4535     QualType PointeeType;
4536     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4537       PointeeType = PT->getPointeeType();
4538     else {
4539       Info.FFDiag(E);
4540       return false;
4541     }
4542 
4543     LValue LVal;
4544     LVal.setFrom(Info.Ctx, Subobj);
4545     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4546                                      AccessKind == AK_Increment ? 1 : -1))
4547       return false;
4548     LVal.moveInto(Subobj);
4549     return true;
4550   }
4551 };
4552 } // end anonymous namespace
4553 
4554 /// Perform an increment or decrement on LVal.
4555 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4556                          QualType LValType, bool IsIncrement, APValue *Old) {
4557   if (LVal.Designator.Invalid)
4558     return false;
4559 
4560   if (!Info.getLangOpts().CPlusPlus14) {
4561     Info.FFDiag(E);
4562     return false;
4563   }
4564 
4565   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4566   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4567   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4568   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4569 }
4570 
4571 /// Build an lvalue for the object argument of a member function call.
4572 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4573                                    LValue &This) {
4574   if (Object->getType()->isPointerType() && Object->isPRValue())
4575     return EvaluatePointer(Object, This, Info);
4576 
4577   if (Object->isGLValue())
4578     return EvaluateLValue(Object, This, Info);
4579 
4580   if (Object->getType()->isLiteralType(Info.Ctx))
4581     return EvaluateTemporary(Object, This, Info);
4582 
4583   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4584   return false;
4585 }
4586 
4587 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
4588 /// lvalue referring to the result.
4589 ///
4590 /// \param Info - Information about the ongoing evaluation.
4591 /// \param LV - An lvalue referring to the base of the member pointer.
4592 /// \param RHS - The member pointer expression.
4593 /// \param IncludeMember - Specifies whether the member itself is included in
4594 ///        the resulting LValue subobject designator. This is not possible when
4595 ///        creating a bound member function.
4596 /// \return The field or method declaration to which the member pointer refers,
4597 ///         or 0 if evaluation fails.
4598 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4599                                                   QualType LVType,
4600                                                   LValue &LV,
4601                                                   const Expr *RHS,
4602                                                   bool IncludeMember = true) {
4603   MemberPtr MemPtr;
4604   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4605     return nullptr;
4606 
4607   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4608   // member value, the behavior is undefined.
4609   if (!MemPtr.getDecl()) {
4610     // FIXME: Specific diagnostic.
4611     Info.FFDiag(RHS);
4612     return nullptr;
4613   }
4614 
4615   if (MemPtr.isDerivedMember()) {
4616     // This is a member of some derived class. Truncate LV appropriately.
4617     // The end of the derived-to-base path for the base object must match the
4618     // derived-to-base path for the member pointer.
4619     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4620         LV.Designator.Entries.size()) {
4621       Info.FFDiag(RHS);
4622       return nullptr;
4623     }
4624     unsigned PathLengthToMember =
4625         LV.Designator.Entries.size() - MemPtr.Path.size();
4626     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4627       const CXXRecordDecl *LVDecl = getAsBaseClass(
4628           LV.Designator.Entries[PathLengthToMember + I]);
4629       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4630       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4631         Info.FFDiag(RHS);
4632         return nullptr;
4633       }
4634     }
4635 
4636     // Truncate the lvalue to the appropriate derived class.
4637     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4638                             PathLengthToMember))
4639       return nullptr;
4640   } else if (!MemPtr.Path.empty()) {
4641     // Extend the LValue path with the member pointer's path.
4642     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4643                                   MemPtr.Path.size() + IncludeMember);
4644 
4645     // Walk down to the appropriate base class.
4646     if (const PointerType *PT = LVType->getAs<PointerType>())
4647       LVType = PT->getPointeeType();
4648     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4649     assert(RD && "member pointer access on non-class-type expression");
4650     // The first class in the path is that of the lvalue.
4651     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4652       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4653       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4654         return nullptr;
4655       RD = Base;
4656     }
4657     // Finally cast to the class containing the member.
4658     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4659                                 MemPtr.getContainingRecord()))
4660       return nullptr;
4661   }
4662 
4663   // Add the member. Note that we cannot build bound member functions here.
4664   if (IncludeMember) {
4665     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4666       if (!HandleLValueMember(Info, RHS, LV, FD))
4667         return nullptr;
4668     } else if (const IndirectFieldDecl *IFD =
4669                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4670       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4671         return nullptr;
4672     } else {
4673       llvm_unreachable("can't construct reference to bound member function");
4674     }
4675   }
4676 
4677   return MemPtr.getDecl();
4678 }
4679 
4680 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4681                                                   const BinaryOperator *BO,
4682                                                   LValue &LV,
4683                                                   bool IncludeMember = true) {
4684   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4685 
4686   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4687     if (Info.noteFailure()) {
4688       MemberPtr MemPtr;
4689       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4690     }
4691     return nullptr;
4692   }
4693 
4694   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4695                                    BO->getRHS(), IncludeMember);
4696 }
4697 
4698 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4699 /// the provided lvalue, which currently refers to the base object.
4700 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4701                                     LValue &Result) {
4702   SubobjectDesignator &D = Result.Designator;
4703   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4704     return false;
4705 
4706   QualType TargetQT = E->getType();
4707   if (const PointerType *PT = TargetQT->getAs<PointerType>())
4708     TargetQT = PT->getPointeeType();
4709 
4710   // Check this cast lands within the final derived-to-base subobject path.
4711   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4712     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4713       << D.MostDerivedType << TargetQT;
4714     return false;
4715   }
4716 
4717   // Check the type of the final cast. We don't need to check the path,
4718   // since a cast can only be formed if the path is unique.
4719   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4720   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4721   const CXXRecordDecl *FinalType;
4722   if (NewEntriesSize == D.MostDerivedPathLength)
4723     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4724   else
4725     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4726   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4727     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4728       << D.MostDerivedType << TargetQT;
4729     return false;
4730   }
4731 
4732   // Truncate the lvalue to the appropriate derived class.
4733   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4734 }
4735 
4736 /// Get the value to use for a default-initialized object of type T.
4737 /// Return false if it encounters something invalid.
4738 static bool getDefaultInitValue(QualType T, APValue &Result) {
4739   bool Success = true;
4740   if (auto *RD = T->getAsCXXRecordDecl()) {
4741     if (RD->isInvalidDecl()) {
4742       Result = APValue();
4743       return false;
4744     }
4745     if (RD->isUnion()) {
4746       Result = APValue((const FieldDecl *)nullptr);
4747       return true;
4748     }
4749     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4750                      std::distance(RD->field_begin(), RD->field_end()));
4751 
4752     unsigned Index = 0;
4753     for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4754                                                   End = RD->bases_end();
4755          I != End; ++I, ++Index)
4756       Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index));
4757 
4758     for (const auto *I : RD->fields()) {
4759       if (I->isUnnamedBitfield())
4760         continue;
4761       Success &= getDefaultInitValue(I->getType(),
4762                                      Result.getStructField(I->getFieldIndex()));
4763     }
4764     return Success;
4765   }
4766 
4767   if (auto *AT =
4768           dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4769     Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4770     if (Result.hasArrayFiller())
4771       Success &=
4772           getDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
4773 
4774     return Success;
4775   }
4776 
4777   Result = APValue::IndeterminateValue();
4778   return true;
4779 }
4780 
4781 namespace {
4782 enum EvalStmtResult {
4783   /// Evaluation failed.
4784   ESR_Failed,
4785   /// Hit a 'return' statement.
4786   ESR_Returned,
4787   /// Evaluation succeeded.
4788   ESR_Succeeded,
4789   /// Hit a 'continue' statement.
4790   ESR_Continue,
4791   /// Hit a 'break' statement.
4792   ESR_Break,
4793   /// Still scanning for 'case' or 'default' statement.
4794   ESR_CaseNotFound
4795 };
4796 }
4797 
4798 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4799   // We don't need to evaluate the initializer for a static local.
4800   if (!VD->hasLocalStorage())
4801     return true;
4802 
4803   LValue Result;
4804   APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
4805                                                    ScopeKind::Block, Result);
4806 
4807   const Expr *InitE = VD->getInit();
4808   if (!InitE) {
4809     if (VD->getType()->isDependentType())
4810       return Info.noteSideEffect();
4811     return getDefaultInitValue(VD->getType(), Val);
4812   }
4813   if (InitE->isValueDependent())
4814     return false;
4815 
4816   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4817     // Wipe out any partially-computed value, to allow tracking that this
4818     // evaluation failed.
4819     Val = APValue();
4820     return false;
4821   }
4822 
4823   return true;
4824 }
4825 
4826 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4827   bool OK = true;
4828 
4829   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4830     OK &= EvaluateVarDecl(Info, VD);
4831 
4832   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4833     for (auto *BD : DD->bindings())
4834       if (auto *VD = BD->getHoldingVar())
4835         OK &= EvaluateDecl(Info, VD);
4836 
4837   return OK;
4838 }
4839 
4840 static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
4841   assert(E->isValueDependent());
4842   if (Info.noteSideEffect())
4843     return true;
4844   assert(E->containsErrors() && "valid value-dependent expression should never "
4845                                 "reach invalid code path.");
4846   return false;
4847 }
4848 
4849 /// Evaluate a condition (either a variable declaration or an expression).
4850 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4851                          const Expr *Cond, bool &Result) {
4852   if (Cond->isValueDependent())
4853     return false;
4854   FullExpressionRAII Scope(Info);
4855   if (CondDecl && !EvaluateDecl(Info, CondDecl))
4856     return false;
4857   if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4858     return false;
4859   return Scope.destroy();
4860 }
4861 
4862 namespace {
4863 /// A location where the result (returned value) of evaluating a
4864 /// statement should be stored.
4865 struct StmtResult {
4866   /// The APValue that should be filled in with the returned value.
4867   APValue &Value;
4868   /// The location containing the result, if any (used to support RVO).
4869   const LValue *Slot;
4870 };
4871 
4872 struct TempVersionRAII {
4873   CallStackFrame &Frame;
4874 
4875   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4876     Frame.pushTempVersion();
4877   }
4878 
4879   ~TempVersionRAII() {
4880     Frame.popTempVersion();
4881   }
4882 };
4883 
4884 }
4885 
4886 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4887                                    const Stmt *S,
4888                                    const SwitchCase *SC = nullptr);
4889 
4890 /// Evaluate the body of a loop, and translate the result as appropriate.
4891 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4892                                        const Stmt *Body,
4893                                        const SwitchCase *Case = nullptr) {
4894   BlockScopeRAII Scope(Info);
4895 
4896   EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4897   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4898     ESR = ESR_Failed;
4899 
4900   switch (ESR) {
4901   case ESR_Break:
4902     return ESR_Succeeded;
4903   case ESR_Succeeded:
4904   case ESR_Continue:
4905     return ESR_Continue;
4906   case ESR_Failed:
4907   case ESR_Returned:
4908   case ESR_CaseNotFound:
4909     return ESR;
4910   }
4911   llvm_unreachable("Invalid EvalStmtResult!");
4912 }
4913 
4914 /// Evaluate a switch statement.
4915 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4916                                      const SwitchStmt *SS) {
4917   BlockScopeRAII Scope(Info);
4918 
4919   // Evaluate the switch condition.
4920   APSInt Value;
4921   {
4922     if (const Stmt *Init = SS->getInit()) {
4923       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4924       if (ESR != ESR_Succeeded) {
4925         if (ESR != ESR_Failed && !Scope.destroy())
4926           ESR = ESR_Failed;
4927         return ESR;
4928       }
4929     }
4930 
4931     FullExpressionRAII CondScope(Info);
4932     if (SS->getConditionVariable() &&
4933         !EvaluateDecl(Info, SS->getConditionVariable()))
4934       return ESR_Failed;
4935     if (!EvaluateInteger(SS->getCond(), Value, Info))
4936       return ESR_Failed;
4937     if (!CondScope.destroy())
4938       return ESR_Failed;
4939   }
4940 
4941   // Find the switch case corresponding to the value of the condition.
4942   // FIXME: Cache this lookup.
4943   const SwitchCase *Found = nullptr;
4944   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4945        SC = SC->getNextSwitchCase()) {
4946     if (isa<DefaultStmt>(SC)) {
4947       Found = SC;
4948       continue;
4949     }
4950 
4951     const CaseStmt *CS = cast<CaseStmt>(SC);
4952     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4953     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4954                               : LHS;
4955     if (LHS <= Value && Value <= RHS) {
4956       Found = SC;
4957       break;
4958     }
4959   }
4960 
4961   if (!Found)
4962     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4963 
4964   // Search the switch body for the switch case and evaluate it from there.
4965   EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
4966   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4967     return ESR_Failed;
4968 
4969   switch (ESR) {
4970   case ESR_Break:
4971     return ESR_Succeeded;
4972   case ESR_Succeeded:
4973   case ESR_Continue:
4974   case ESR_Failed:
4975   case ESR_Returned:
4976     return ESR;
4977   case ESR_CaseNotFound:
4978     // This can only happen if the switch case is nested within a statement
4979     // expression. We have no intention of supporting that.
4980     Info.FFDiag(Found->getBeginLoc(),
4981                 diag::note_constexpr_stmt_expr_unsupported);
4982     return ESR_Failed;
4983   }
4984   llvm_unreachable("Invalid EvalStmtResult!");
4985 }
4986 
4987 // Evaluate a statement.
4988 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4989                                    const Stmt *S, const SwitchCase *Case) {
4990   if (!Info.nextStep(S))
4991     return ESR_Failed;
4992 
4993   // If we're hunting down a 'case' or 'default' label, recurse through
4994   // substatements until we hit the label.
4995   if (Case) {
4996     switch (S->getStmtClass()) {
4997     case Stmt::CompoundStmtClass:
4998       // FIXME: Precompute which substatement of a compound statement we
4999       // would jump to, and go straight there rather than performing a
5000       // linear scan each time.
5001     case Stmt::LabelStmtClass:
5002     case Stmt::AttributedStmtClass:
5003     case Stmt::DoStmtClass:
5004       break;
5005 
5006     case Stmt::CaseStmtClass:
5007     case Stmt::DefaultStmtClass:
5008       if (Case == S)
5009         Case = nullptr;
5010       break;
5011 
5012     case Stmt::IfStmtClass: {
5013       // FIXME: Precompute which side of an 'if' we would jump to, and go
5014       // straight there rather than scanning both sides.
5015       const IfStmt *IS = cast<IfStmt>(S);
5016 
5017       // Wrap the evaluation in a block scope, in case it's a DeclStmt
5018       // preceded by our switch label.
5019       BlockScopeRAII Scope(Info);
5020 
5021       // Step into the init statement in case it brings an (uninitialized)
5022       // variable into scope.
5023       if (const Stmt *Init = IS->getInit()) {
5024         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5025         if (ESR != ESR_CaseNotFound) {
5026           assert(ESR != ESR_Succeeded);
5027           return ESR;
5028         }
5029       }
5030 
5031       // Condition variable must be initialized if it exists.
5032       // FIXME: We can skip evaluating the body if there's a condition
5033       // variable, as there can't be any case labels within it.
5034       // (The same is true for 'for' statements.)
5035 
5036       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5037       if (ESR == ESR_Failed)
5038         return ESR;
5039       if (ESR != ESR_CaseNotFound)
5040         return Scope.destroy() ? ESR : ESR_Failed;
5041       if (!IS->getElse())
5042         return ESR_CaseNotFound;
5043 
5044       ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5045       if (ESR == ESR_Failed)
5046         return ESR;
5047       if (ESR != ESR_CaseNotFound)
5048         return Scope.destroy() ? ESR : ESR_Failed;
5049       return ESR_CaseNotFound;
5050     }
5051 
5052     case Stmt::WhileStmtClass: {
5053       EvalStmtResult ESR =
5054           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5055       if (ESR != ESR_Continue)
5056         return ESR;
5057       break;
5058     }
5059 
5060     case Stmt::ForStmtClass: {
5061       const ForStmt *FS = cast<ForStmt>(S);
5062       BlockScopeRAII Scope(Info);
5063 
5064       // Step into the init statement in case it brings an (uninitialized)
5065       // variable into scope.
5066       if (const Stmt *Init = FS->getInit()) {
5067         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5068         if (ESR != ESR_CaseNotFound) {
5069           assert(ESR != ESR_Succeeded);
5070           return ESR;
5071         }
5072       }
5073 
5074       EvalStmtResult ESR =
5075           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5076       if (ESR != ESR_Continue)
5077         return ESR;
5078       if (const auto *Inc = FS->getInc()) {
5079         if (Inc->isValueDependent()) {
5080           if (!EvaluateDependentExpr(Inc, Info))
5081             return ESR_Failed;
5082         } else {
5083           FullExpressionRAII IncScope(Info);
5084           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5085             return ESR_Failed;
5086         }
5087       }
5088       break;
5089     }
5090 
5091     case Stmt::DeclStmtClass: {
5092       // Start the lifetime of any uninitialized variables we encounter. They
5093       // might be used by the selected branch of the switch.
5094       const DeclStmt *DS = cast<DeclStmt>(S);
5095       for (const auto *D : DS->decls()) {
5096         if (const auto *VD = dyn_cast<VarDecl>(D)) {
5097           if (VD->hasLocalStorage() && !VD->getInit())
5098             if (!EvaluateVarDecl(Info, VD))
5099               return ESR_Failed;
5100           // FIXME: If the variable has initialization that can't be jumped
5101           // over, bail out of any immediately-surrounding compound-statement
5102           // too. There can't be any case labels here.
5103         }
5104       }
5105       return ESR_CaseNotFound;
5106     }
5107 
5108     default:
5109       return ESR_CaseNotFound;
5110     }
5111   }
5112 
5113   switch (S->getStmtClass()) {
5114   default:
5115     if (const Expr *E = dyn_cast<Expr>(S)) {
5116       if (E->isValueDependent()) {
5117         if (!EvaluateDependentExpr(E, Info))
5118           return ESR_Failed;
5119       } else {
5120         // Don't bother evaluating beyond an expression-statement which couldn't
5121         // be evaluated.
5122         // FIXME: Do we need the FullExpressionRAII object here?
5123         // VisitExprWithCleanups should create one when necessary.
5124         FullExpressionRAII Scope(Info);
5125         if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5126           return ESR_Failed;
5127       }
5128       return ESR_Succeeded;
5129     }
5130 
5131     Info.FFDiag(S->getBeginLoc());
5132     return ESR_Failed;
5133 
5134   case Stmt::NullStmtClass:
5135     return ESR_Succeeded;
5136 
5137   case Stmt::DeclStmtClass: {
5138     const DeclStmt *DS = cast<DeclStmt>(S);
5139     for (const auto *D : DS->decls()) {
5140       // Each declaration initialization is its own full-expression.
5141       FullExpressionRAII Scope(Info);
5142       if (!EvaluateDecl(Info, D) && !Info.noteFailure())
5143         return ESR_Failed;
5144       if (!Scope.destroy())
5145         return ESR_Failed;
5146     }
5147     return ESR_Succeeded;
5148   }
5149 
5150   case Stmt::ReturnStmtClass: {
5151     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5152     FullExpressionRAII Scope(Info);
5153     if (RetExpr && RetExpr->isValueDependent()) {
5154       EvaluateDependentExpr(RetExpr, Info);
5155       // We know we returned, but we don't know what the value is.
5156       return ESR_Failed;
5157     }
5158     if (RetExpr &&
5159         !(Result.Slot
5160               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5161               : Evaluate(Result.Value, Info, RetExpr)))
5162       return ESR_Failed;
5163     return Scope.destroy() ? ESR_Returned : ESR_Failed;
5164   }
5165 
5166   case Stmt::CompoundStmtClass: {
5167     BlockScopeRAII Scope(Info);
5168 
5169     const CompoundStmt *CS = cast<CompoundStmt>(S);
5170     for (const auto *BI : CS->body()) {
5171       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5172       if (ESR == ESR_Succeeded)
5173         Case = nullptr;
5174       else if (ESR != ESR_CaseNotFound) {
5175         if (ESR != ESR_Failed && !Scope.destroy())
5176           return ESR_Failed;
5177         return ESR;
5178       }
5179     }
5180     if (Case)
5181       return ESR_CaseNotFound;
5182     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5183   }
5184 
5185   case Stmt::IfStmtClass: {
5186     const IfStmt *IS = cast<IfStmt>(S);
5187 
5188     // Evaluate the condition, as either a var decl or as an expression.
5189     BlockScopeRAII Scope(Info);
5190     if (const Stmt *Init = IS->getInit()) {
5191       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5192       if (ESR != ESR_Succeeded) {
5193         if (ESR != ESR_Failed && !Scope.destroy())
5194           return ESR_Failed;
5195         return ESR;
5196       }
5197     }
5198     bool Cond;
5199     if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
5200       return ESR_Failed;
5201 
5202     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5203       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5204       if (ESR != ESR_Succeeded) {
5205         if (ESR != ESR_Failed && !Scope.destroy())
5206           return ESR_Failed;
5207         return ESR;
5208       }
5209     }
5210     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5211   }
5212 
5213   case Stmt::WhileStmtClass: {
5214     const WhileStmt *WS = cast<WhileStmt>(S);
5215     while (true) {
5216       BlockScopeRAII Scope(Info);
5217       bool Continue;
5218       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5219                         Continue))
5220         return ESR_Failed;
5221       if (!Continue)
5222         break;
5223 
5224       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5225       if (ESR != ESR_Continue) {
5226         if (ESR != ESR_Failed && !Scope.destroy())
5227           return ESR_Failed;
5228         return ESR;
5229       }
5230       if (!Scope.destroy())
5231         return ESR_Failed;
5232     }
5233     return ESR_Succeeded;
5234   }
5235 
5236   case Stmt::DoStmtClass: {
5237     const DoStmt *DS = cast<DoStmt>(S);
5238     bool Continue;
5239     do {
5240       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5241       if (ESR != ESR_Continue)
5242         return ESR;
5243       Case = nullptr;
5244 
5245       if (DS->getCond()->isValueDependent()) {
5246         EvaluateDependentExpr(DS->getCond(), Info);
5247         // Bailout as we don't know whether to keep going or terminate the loop.
5248         return ESR_Failed;
5249       }
5250       FullExpressionRAII CondScope(Info);
5251       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5252           !CondScope.destroy())
5253         return ESR_Failed;
5254     } while (Continue);
5255     return ESR_Succeeded;
5256   }
5257 
5258   case Stmt::ForStmtClass: {
5259     const ForStmt *FS = cast<ForStmt>(S);
5260     BlockScopeRAII ForScope(Info);
5261     if (FS->getInit()) {
5262       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5263       if (ESR != ESR_Succeeded) {
5264         if (ESR != ESR_Failed && !ForScope.destroy())
5265           return ESR_Failed;
5266         return ESR;
5267       }
5268     }
5269     while (true) {
5270       BlockScopeRAII IterScope(Info);
5271       bool Continue = true;
5272       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5273                                          FS->getCond(), Continue))
5274         return ESR_Failed;
5275       if (!Continue)
5276         break;
5277 
5278       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5279       if (ESR != ESR_Continue) {
5280         if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5281           return ESR_Failed;
5282         return ESR;
5283       }
5284 
5285       if (const auto *Inc = FS->getInc()) {
5286         if (Inc->isValueDependent()) {
5287           if (!EvaluateDependentExpr(Inc, Info))
5288             return ESR_Failed;
5289         } else {
5290           FullExpressionRAII IncScope(Info);
5291           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5292             return ESR_Failed;
5293         }
5294       }
5295 
5296       if (!IterScope.destroy())
5297         return ESR_Failed;
5298     }
5299     return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5300   }
5301 
5302   case Stmt::CXXForRangeStmtClass: {
5303     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5304     BlockScopeRAII Scope(Info);
5305 
5306     // Evaluate the init-statement if present.
5307     if (FS->getInit()) {
5308       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5309       if (ESR != ESR_Succeeded) {
5310         if (ESR != ESR_Failed && !Scope.destroy())
5311           return ESR_Failed;
5312         return ESR;
5313       }
5314     }
5315 
5316     // Initialize the __range variable.
5317     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5318     if (ESR != ESR_Succeeded) {
5319       if (ESR != ESR_Failed && !Scope.destroy())
5320         return ESR_Failed;
5321       return ESR;
5322     }
5323 
5324     // Create the __begin and __end iterators.
5325     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5326     if (ESR != ESR_Succeeded) {
5327       if (ESR != ESR_Failed && !Scope.destroy())
5328         return ESR_Failed;
5329       return ESR;
5330     }
5331     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5332     if (ESR != ESR_Succeeded) {
5333       if (ESR != ESR_Failed && !Scope.destroy())
5334         return ESR_Failed;
5335       return ESR;
5336     }
5337 
5338     while (true) {
5339       // Condition: __begin != __end.
5340       {
5341         if (FS->getCond()->isValueDependent()) {
5342           EvaluateDependentExpr(FS->getCond(), Info);
5343           // We don't know whether to keep going or terminate the loop.
5344           return ESR_Failed;
5345         }
5346         bool Continue = true;
5347         FullExpressionRAII CondExpr(Info);
5348         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5349           return ESR_Failed;
5350         if (!Continue)
5351           break;
5352       }
5353 
5354       // User's variable declaration, initialized by *__begin.
5355       BlockScopeRAII InnerScope(Info);
5356       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5357       if (ESR != ESR_Succeeded) {
5358         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5359           return ESR_Failed;
5360         return ESR;
5361       }
5362 
5363       // Loop body.
5364       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5365       if (ESR != ESR_Continue) {
5366         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5367           return ESR_Failed;
5368         return ESR;
5369       }
5370       if (FS->getInc()->isValueDependent()) {
5371         if (!EvaluateDependentExpr(FS->getInc(), Info))
5372           return ESR_Failed;
5373       } else {
5374         // Increment: ++__begin
5375         if (!EvaluateIgnoredValue(Info, FS->getInc()))
5376           return ESR_Failed;
5377       }
5378 
5379       if (!InnerScope.destroy())
5380         return ESR_Failed;
5381     }
5382 
5383     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5384   }
5385 
5386   case Stmt::SwitchStmtClass:
5387     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5388 
5389   case Stmt::ContinueStmtClass:
5390     return ESR_Continue;
5391 
5392   case Stmt::BreakStmtClass:
5393     return ESR_Break;
5394 
5395   case Stmt::LabelStmtClass:
5396     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5397 
5398   case Stmt::AttributedStmtClass:
5399     // As a general principle, C++11 attributes can be ignored without
5400     // any semantic impact.
5401     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
5402                         Case);
5403 
5404   case Stmt::CaseStmtClass:
5405   case Stmt::DefaultStmtClass:
5406     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5407   case Stmt::CXXTryStmtClass:
5408     // Evaluate try blocks by evaluating all sub statements.
5409     return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5410   }
5411 }
5412 
5413 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5414 /// default constructor. If so, we'll fold it whether or not it's marked as
5415 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
5416 /// so we need special handling.
5417 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5418                                            const CXXConstructorDecl *CD,
5419                                            bool IsValueInitialization) {
5420   if (!CD->isTrivial() || !CD->isDefaultConstructor())
5421     return false;
5422 
5423   // Value-initialization does not call a trivial default constructor, so such a
5424   // call is a core constant expression whether or not the constructor is
5425   // constexpr.
5426   if (!CD->isConstexpr() && !IsValueInitialization) {
5427     if (Info.getLangOpts().CPlusPlus11) {
5428       // FIXME: If DiagDecl is an implicitly-declared special member function,
5429       // we should be much more explicit about why it's not constexpr.
5430       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5431         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5432       Info.Note(CD->getLocation(), diag::note_declared_at);
5433     } else {
5434       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5435     }
5436   }
5437   return true;
5438 }
5439 
5440 /// CheckConstexprFunction - Check that a function can be called in a constant
5441 /// expression.
5442 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5443                                    const FunctionDecl *Declaration,
5444                                    const FunctionDecl *Definition,
5445                                    const Stmt *Body) {
5446   // Potential constant expressions can contain calls to declared, but not yet
5447   // defined, constexpr functions.
5448   if (Info.checkingPotentialConstantExpression() && !Definition &&
5449       Declaration->isConstexpr())
5450     return false;
5451 
5452   // Bail out if the function declaration itself is invalid.  We will
5453   // have produced a relevant diagnostic while parsing it, so just
5454   // note the problematic sub-expression.
5455   if (Declaration->isInvalidDecl()) {
5456     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5457     return false;
5458   }
5459 
5460   // DR1872: An instantiated virtual constexpr function can't be called in a
5461   // constant expression (prior to C++20). We can still constant-fold such a
5462   // call.
5463   if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5464       cast<CXXMethodDecl>(Declaration)->isVirtual())
5465     Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5466 
5467   if (Definition && Definition->isInvalidDecl()) {
5468     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5469     return false;
5470   }
5471 
5472   // Can we evaluate this function call?
5473   if (Definition && Definition->isConstexpr() && Body)
5474     return true;
5475 
5476   if (Info.getLangOpts().CPlusPlus11) {
5477     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5478 
5479     // If this function is not constexpr because it is an inherited
5480     // non-constexpr constructor, diagnose that directly.
5481     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5482     if (CD && CD->isInheritingConstructor()) {
5483       auto *Inherited = CD->getInheritedConstructor().getConstructor();
5484       if (!Inherited->isConstexpr())
5485         DiagDecl = CD = Inherited;
5486     }
5487 
5488     // FIXME: If DiagDecl is an implicitly-declared special member function
5489     // or an inheriting constructor, we should be much more explicit about why
5490     // it's not constexpr.
5491     if (CD && CD->isInheritingConstructor())
5492       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5493         << CD->getInheritedConstructor().getConstructor()->getParent();
5494     else
5495       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5496         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5497     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5498   } else {
5499     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5500   }
5501   return false;
5502 }
5503 
5504 namespace {
5505 struct CheckDynamicTypeHandler {
5506   AccessKinds AccessKind;
5507   typedef bool result_type;
5508   bool failed() { return false; }
5509   bool found(APValue &Subobj, QualType SubobjType) { return true; }
5510   bool found(APSInt &Value, QualType SubobjType) { return true; }
5511   bool found(APFloat &Value, QualType SubobjType) { return true; }
5512 };
5513 } // end anonymous namespace
5514 
5515 /// Check that we can access the notional vptr of an object / determine its
5516 /// dynamic type.
5517 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5518                              AccessKinds AK, bool Polymorphic) {
5519   if (This.Designator.Invalid)
5520     return false;
5521 
5522   CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5523 
5524   if (!Obj)
5525     return false;
5526 
5527   if (!Obj.Value) {
5528     // The object is not usable in constant expressions, so we can't inspect
5529     // its value to see if it's in-lifetime or what the active union members
5530     // are. We can still check for a one-past-the-end lvalue.
5531     if (This.Designator.isOnePastTheEnd() ||
5532         This.Designator.isMostDerivedAnUnsizedArray()) {
5533       Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5534                          ? diag::note_constexpr_access_past_end
5535                          : diag::note_constexpr_access_unsized_array)
5536           << AK;
5537       return false;
5538     } else if (Polymorphic) {
5539       // Conservatively refuse to perform a polymorphic operation if we would
5540       // not be able to read a notional 'vptr' value.
5541       APValue Val;
5542       This.moveInto(Val);
5543       QualType StarThisType =
5544           Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5545       Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5546           << AK << Val.getAsString(Info.Ctx, StarThisType);
5547       return false;
5548     }
5549     return true;
5550   }
5551 
5552   CheckDynamicTypeHandler Handler{AK};
5553   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5554 }
5555 
5556 /// Check that the pointee of the 'this' pointer in a member function call is
5557 /// either within its lifetime or in its period of construction or destruction.
5558 static bool
5559 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5560                                      const LValue &This,
5561                                      const CXXMethodDecl *NamedMember) {
5562   return checkDynamicType(
5563       Info, E, This,
5564       isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5565 }
5566 
5567 struct DynamicType {
5568   /// The dynamic class type of the object.
5569   const CXXRecordDecl *Type;
5570   /// The corresponding path length in the lvalue.
5571   unsigned PathLength;
5572 };
5573 
5574 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5575                                              unsigned PathLength) {
5576   assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5577       Designator.Entries.size() && "invalid path length");
5578   return (PathLength == Designator.MostDerivedPathLength)
5579              ? Designator.MostDerivedType->getAsCXXRecordDecl()
5580              : getAsBaseClass(Designator.Entries[PathLength - 1]);
5581 }
5582 
5583 /// Determine the dynamic type of an object.
5584 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
5585                                                 LValue &This, AccessKinds AK) {
5586   // If we don't have an lvalue denoting an object of class type, there is no
5587   // meaningful dynamic type. (We consider objects of non-class type to have no
5588   // dynamic type.)
5589   if (!checkDynamicType(Info, E, This, AK, true))
5590     return None;
5591 
5592   // Refuse to compute a dynamic type in the presence of virtual bases. This
5593   // shouldn't happen other than in constant-folding situations, since literal
5594   // types can't have virtual bases.
5595   //
5596   // Note that consumers of DynamicType assume that the type has no virtual
5597   // bases, and will need modifications if this restriction is relaxed.
5598   const CXXRecordDecl *Class =
5599       This.Designator.MostDerivedType->getAsCXXRecordDecl();
5600   if (!Class || Class->getNumVBases()) {
5601     Info.FFDiag(E);
5602     return None;
5603   }
5604 
5605   // FIXME: For very deep class hierarchies, it might be beneficial to use a
5606   // binary search here instead. But the overwhelmingly common case is that
5607   // we're not in the middle of a constructor, so it probably doesn't matter
5608   // in practice.
5609   ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5610   for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5611        PathLength <= Path.size(); ++PathLength) {
5612     switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5613                                       Path.slice(0, PathLength))) {
5614     case ConstructionPhase::Bases:
5615     case ConstructionPhase::DestroyingBases:
5616       // We're constructing or destroying a base class. This is not the dynamic
5617       // type.
5618       break;
5619 
5620     case ConstructionPhase::None:
5621     case ConstructionPhase::AfterBases:
5622     case ConstructionPhase::AfterFields:
5623     case ConstructionPhase::Destroying:
5624       // We've finished constructing the base classes and not yet started
5625       // destroying them again, so this is the dynamic type.
5626       return DynamicType{getBaseClassType(This.Designator, PathLength),
5627                          PathLength};
5628     }
5629   }
5630 
5631   // CWG issue 1517: we're constructing a base class of the object described by
5632   // 'This', so that object has not yet begun its period of construction and
5633   // any polymorphic operation on it results in undefined behavior.
5634   Info.FFDiag(E);
5635   return None;
5636 }
5637 
5638 /// Perform virtual dispatch.
5639 static const CXXMethodDecl *HandleVirtualDispatch(
5640     EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5641     llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5642   Optional<DynamicType> DynType = ComputeDynamicType(
5643       Info, E, This,
5644       isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5645   if (!DynType)
5646     return nullptr;
5647 
5648   // Find the final overrider. It must be declared in one of the classes on the
5649   // path from the dynamic type to the static type.
5650   // FIXME: If we ever allow literal types to have virtual base classes, that
5651   // won't be true.
5652   const CXXMethodDecl *Callee = Found;
5653   unsigned PathLength = DynType->PathLength;
5654   for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5655     const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5656     const CXXMethodDecl *Overrider =
5657         Found->getCorrespondingMethodDeclaredInClass(Class, false);
5658     if (Overrider) {
5659       Callee = Overrider;
5660       break;
5661     }
5662   }
5663 
5664   // C++2a [class.abstract]p6:
5665   //   the effect of making a virtual call to a pure virtual function [...] is
5666   //   undefined
5667   if (Callee->isPure()) {
5668     Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5669     Info.Note(Callee->getLocation(), diag::note_declared_at);
5670     return nullptr;
5671   }
5672 
5673   // If necessary, walk the rest of the path to determine the sequence of
5674   // covariant adjustment steps to apply.
5675   if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5676                                        Found->getReturnType())) {
5677     CovariantAdjustmentPath.push_back(Callee->getReturnType());
5678     for (unsigned CovariantPathLength = PathLength + 1;
5679          CovariantPathLength != This.Designator.Entries.size();
5680          ++CovariantPathLength) {
5681       const CXXRecordDecl *NextClass =
5682           getBaseClassType(This.Designator, CovariantPathLength);
5683       const CXXMethodDecl *Next =
5684           Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5685       if (Next && !Info.Ctx.hasSameUnqualifiedType(
5686                       Next->getReturnType(), CovariantAdjustmentPath.back()))
5687         CovariantAdjustmentPath.push_back(Next->getReturnType());
5688     }
5689     if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5690                                          CovariantAdjustmentPath.back()))
5691       CovariantAdjustmentPath.push_back(Found->getReturnType());
5692   }
5693 
5694   // Perform 'this' adjustment.
5695   if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5696     return nullptr;
5697 
5698   return Callee;
5699 }
5700 
5701 /// Perform the adjustment from a value returned by a virtual function to
5702 /// a value of the statically expected type, which may be a pointer or
5703 /// reference to a base class of the returned type.
5704 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5705                                             APValue &Result,
5706                                             ArrayRef<QualType> Path) {
5707   assert(Result.isLValue() &&
5708          "unexpected kind of APValue for covariant return");
5709   if (Result.isNullPointer())
5710     return true;
5711 
5712   LValue LVal;
5713   LVal.setFrom(Info.Ctx, Result);
5714 
5715   const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5716   for (unsigned I = 1; I != Path.size(); ++I) {
5717     const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5718     assert(OldClass && NewClass && "unexpected kind of covariant return");
5719     if (OldClass != NewClass &&
5720         !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5721       return false;
5722     OldClass = NewClass;
5723   }
5724 
5725   LVal.moveInto(Result);
5726   return true;
5727 }
5728 
5729 /// Determine whether \p Base, which is known to be a direct base class of
5730 /// \p Derived, is a public base class.
5731 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5732                               const CXXRecordDecl *Base) {
5733   for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5734     auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5735     if (BaseClass && declaresSameEntity(BaseClass, Base))
5736       return BaseSpec.getAccessSpecifier() == AS_public;
5737   }
5738   llvm_unreachable("Base is not a direct base of Derived");
5739 }
5740 
5741 /// Apply the given dynamic cast operation on the provided lvalue.
5742 ///
5743 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
5744 /// to find a suitable target subobject.
5745 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5746                               LValue &Ptr) {
5747   // We can't do anything with a non-symbolic pointer value.
5748   SubobjectDesignator &D = Ptr.Designator;
5749   if (D.Invalid)
5750     return false;
5751 
5752   // C++ [expr.dynamic.cast]p6:
5753   //   If v is a null pointer value, the result is a null pointer value.
5754   if (Ptr.isNullPointer() && !E->isGLValue())
5755     return true;
5756 
5757   // For all the other cases, we need the pointer to point to an object within
5758   // its lifetime / period of construction / destruction, and we need to know
5759   // its dynamic type.
5760   Optional<DynamicType> DynType =
5761       ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5762   if (!DynType)
5763     return false;
5764 
5765   // C++ [expr.dynamic.cast]p7:
5766   //   If T is "pointer to cv void", then the result is a pointer to the most
5767   //   derived object
5768   if (E->getType()->isVoidPointerType())
5769     return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5770 
5771   const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5772   assert(C && "dynamic_cast target is not void pointer nor class");
5773   CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5774 
5775   auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5776     // C++ [expr.dynamic.cast]p9:
5777     if (!E->isGLValue()) {
5778       //   The value of a failed cast to pointer type is the null pointer value
5779       //   of the required result type.
5780       Ptr.setNull(Info.Ctx, E->getType());
5781       return true;
5782     }
5783 
5784     //   A failed cast to reference type throws [...] std::bad_cast.
5785     unsigned DiagKind;
5786     if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5787                    DynType->Type->isDerivedFrom(C)))
5788       DiagKind = 0;
5789     else if (!Paths || Paths->begin() == Paths->end())
5790       DiagKind = 1;
5791     else if (Paths->isAmbiguous(CQT))
5792       DiagKind = 2;
5793     else {
5794       assert(Paths->front().Access != AS_public && "why did the cast fail?");
5795       DiagKind = 3;
5796     }
5797     Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5798         << DiagKind << Ptr.Designator.getType(Info.Ctx)
5799         << Info.Ctx.getRecordType(DynType->Type)
5800         << E->getType().getUnqualifiedType();
5801     return false;
5802   };
5803 
5804   // Runtime check, phase 1:
5805   //   Walk from the base subobject towards the derived object looking for the
5806   //   target type.
5807   for (int PathLength = Ptr.Designator.Entries.size();
5808        PathLength >= (int)DynType->PathLength; --PathLength) {
5809     const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5810     if (declaresSameEntity(Class, C))
5811       return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5812     // We can only walk across public inheritance edges.
5813     if (PathLength > (int)DynType->PathLength &&
5814         !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5815                            Class))
5816       return RuntimeCheckFailed(nullptr);
5817   }
5818 
5819   // Runtime check, phase 2:
5820   //   Search the dynamic type for an unambiguous public base of type C.
5821   CXXBasePaths Paths(/*FindAmbiguities=*/true,
5822                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
5823   if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5824       Paths.front().Access == AS_public) {
5825     // Downcast to the dynamic type...
5826     if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5827       return false;
5828     // ... then upcast to the chosen base class subobject.
5829     for (CXXBasePathElement &Elem : Paths.front())
5830       if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5831         return false;
5832     return true;
5833   }
5834 
5835   // Otherwise, the runtime check fails.
5836   return RuntimeCheckFailed(&Paths);
5837 }
5838 
5839 namespace {
5840 struct StartLifetimeOfUnionMemberHandler {
5841   EvalInfo &Info;
5842   const Expr *LHSExpr;
5843   const FieldDecl *Field;
5844   bool DuringInit;
5845   bool Failed = false;
5846   static const AccessKinds AccessKind = AK_Assign;
5847 
5848   typedef bool result_type;
5849   bool failed() { return Failed; }
5850   bool found(APValue &Subobj, QualType SubobjType) {
5851     // We are supposed to perform no initialization but begin the lifetime of
5852     // the object. We interpret that as meaning to do what default
5853     // initialization of the object would do if all constructors involved were
5854     // trivial:
5855     //  * All base, non-variant member, and array element subobjects' lifetimes
5856     //    begin
5857     //  * No variant members' lifetimes begin
5858     //  * All scalar subobjects whose lifetimes begin have indeterminate values
5859     assert(SubobjType->isUnionType());
5860     if (declaresSameEntity(Subobj.getUnionField(), Field)) {
5861       // This union member is already active. If it's also in-lifetime, there's
5862       // nothing to do.
5863       if (Subobj.getUnionValue().hasValue())
5864         return true;
5865     } else if (DuringInit) {
5866       // We're currently in the process of initializing a different union
5867       // member.  If we carried on, that initialization would attempt to
5868       // store to an inactive union member, resulting in undefined behavior.
5869       Info.FFDiag(LHSExpr,
5870                   diag::note_constexpr_union_member_change_during_init);
5871       return false;
5872     }
5873     APValue Result;
5874     Failed = !getDefaultInitValue(Field->getType(), Result);
5875     Subobj.setUnion(Field, Result);
5876     return true;
5877   }
5878   bool found(APSInt &Value, QualType SubobjType) {
5879     llvm_unreachable("wrong value kind for union object");
5880   }
5881   bool found(APFloat &Value, QualType SubobjType) {
5882     llvm_unreachable("wrong value kind for union object");
5883   }
5884 };
5885 } // end anonymous namespace
5886 
5887 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5888 
5889 /// Handle a builtin simple-assignment or a call to a trivial assignment
5890 /// operator whose left-hand side might involve a union member access. If it
5891 /// does, implicitly start the lifetime of any accessed union elements per
5892 /// C++20 [class.union]5.
5893 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5894                                           const LValue &LHS) {
5895   if (LHS.InvalidBase || LHS.Designator.Invalid)
5896     return false;
5897 
5898   llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5899   // C++ [class.union]p5:
5900   //   define the set S(E) of subexpressions of E as follows:
5901   unsigned PathLength = LHS.Designator.Entries.size();
5902   for (const Expr *E = LHSExpr; E != nullptr;) {
5903     //   -- If E is of the form A.B, S(E) contains the elements of S(A)...
5904     if (auto *ME = dyn_cast<MemberExpr>(E)) {
5905       auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5906       // Note that we can't implicitly start the lifetime of a reference,
5907       // so we don't need to proceed any further if we reach one.
5908       if (!FD || FD->getType()->isReferenceType())
5909         break;
5910 
5911       //    ... and also contains A.B if B names a union member ...
5912       if (FD->getParent()->isUnion()) {
5913         //    ... of a non-class, non-array type, or of a class type with a
5914         //    trivial default constructor that is not deleted, or an array of
5915         //    such types.
5916         auto *RD =
5917             FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5918         if (!RD || RD->hasTrivialDefaultConstructor())
5919           UnionPathLengths.push_back({PathLength - 1, FD});
5920       }
5921 
5922       E = ME->getBase();
5923       --PathLength;
5924       assert(declaresSameEntity(FD,
5925                                 LHS.Designator.Entries[PathLength]
5926                                     .getAsBaseOrMember().getPointer()));
5927 
5928       //   -- If E is of the form A[B] and is interpreted as a built-in array
5929       //      subscripting operator, S(E) is [S(the array operand, if any)].
5930     } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5931       // Step over an ArrayToPointerDecay implicit cast.
5932       auto *Base = ASE->getBase()->IgnoreImplicit();
5933       if (!Base->getType()->isArrayType())
5934         break;
5935 
5936       E = Base;
5937       --PathLength;
5938 
5939     } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5940       // Step over a derived-to-base conversion.
5941       E = ICE->getSubExpr();
5942       if (ICE->getCastKind() == CK_NoOp)
5943         continue;
5944       if (ICE->getCastKind() != CK_DerivedToBase &&
5945           ICE->getCastKind() != CK_UncheckedDerivedToBase)
5946         break;
5947       // Walk path backwards as we walk up from the base to the derived class.
5948       for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
5949         --PathLength;
5950         (void)Elt;
5951         assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
5952                                   LHS.Designator.Entries[PathLength]
5953                                       .getAsBaseOrMember().getPointer()));
5954       }
5955 
5956     //   -- Otherwise, S(E) is empty.
5957     } else {
5958       break;
5959     }
5960   }
5961 
5962   // Common case: no unions' lifetimes are started.
5963   if (UnionPathLengths.empty())
5964     return true;
5965 
5966   //   if modification of X [would access an inactive union member], an object
5967   //   of the type of X is implicitly created
5968   CompleteObject Obj =
5969       findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
5970   if (!Obj)
5971     return false;
5972   for (std::pair<unsigned, const FieldDecl *> LengthAndField :
5973            llvm::reverse(UnionPathLengths)) {
5974     // Form a designator for the union object.
5975     SubobjectDesignator D = LHS.Designator;
5976     D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
5977 
5978     bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
5979                       ConstructionPhase::AfterBases;
5980     StartLifetimeOfUnionMemberHandler StartLifetime{
5981         Info, LHSExpr, LengthAndField.second, DuringInit};
5982     if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
5983       return false;
5984   }
5985 
5986   return true;
5987 }
5988 
5989 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
5990                             CallRef Call, EvalInfo &Info,
5991                             bool NonNull = false) {
5992   LValue LV;
5993   // Create the parameter slot and register its destruction. For a vararg
5994   // argument, create a temporary.
5995   // FIXME: For calling conventions that destroy parameters in the callee,
5996   // should we consider performing destruction when the function returns
5997   // instead?
5998   APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
5999                    : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6000                                                        ScopeKind::Call, LV);
6001   if (!EvaluateInPlace(V, Info, LV, Arg))
6002     return false;
6003 
6004   // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6005   // undefined behavior, so is non-constant.
6006   if (NonNull && V.isLValue() && V.isNullPointer()) {
6007     Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6008     return false;
6009   }
6010 
6011   return true;
6012 }
6013 
6014 /// Evaluate the arguments to a function call.
6015 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6016                          EvalInfo &Info, const FunctionDecl *Callee,
6017                          bool RightToLeft = false) {
6018   bool Success = true;
6019   llvm::SmallBitVector ForbiddenNullArgs;
6020   if (Callee->hasAttr<NonNullAttr>()) {
6021     ForbiddenNullArgs.resize(Args.size());
6022     for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6023       if (!Attr->args_size()) {
6024         ForbiddenNullArgs.set();
6025         break;
6026       } else
6027         for (auto Idx : Attr->args()) {
6028           unsigned ASTIdx = Idx.getASTIndex();
6029           if (ASTIdx >= Args.size())
6030             continue;
6031           ForbiddenNullArgs[ASTIdx] = 1;
6032         }
6033     }
6034   }
6035   for (unsigned I = 0; I < Args.size(); I++) {
6036     unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6037     const ParmVarDecl *PVD =
6038         Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6039     bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6040     if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) {
6041       // If we're checking for a potential constant expression, evaluate all
6042       // initializers even if some of them fail.
6043       if (!Info.noteFailure())
6044         return false;
6045       Success = false;
6046     }
6047   }
6048   return Success;
6049 }
6050 
6051 /// Perform a trivial copy from Param, which is the parameter of a copy or move
6052 /// constructor or assignment operator.
6053 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6054                               const Expr *E, APValue &Result,
6055                               bool CopyObjectRepresentation) {
6056   // Find the reference argument.
6057   CallStackFrame *Frame = Info.CurrentCall;
6058   APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6059   if (!RefValue) {
6060     Info.FFDiag(E);
6061     return false;
6062   }
6063 
6064   // Copy out the contents of the RHS object.
6065   LValue RefLValue;
6066   RefLValue.setFrom(Info.Ctx, *RefValue);
6067   return handleLValueToRValueConversion(
6068       Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6069       CopyObjectRepresentation);
6070 }
6071 
6072 /// Evaluate a function call.
6073 static bool HandleFunctionCall(SourceLocation CallLoc,
6074                                const FunctionDecl *Callee, const LValue *This,
6075                                ArrayRef<const Expr *> Args, CallRef Call,
6076                                const Stmt *Body, EvalInfo &Info,
6077                                APValue &Result, const LValue *ResultSlot) {
6078   if (!Info.CheckCallLimit(CallLoc))
6079     return false;
6080 
6081   CallStackFrame Frame(Info, CallLoc, Callee, This, Call);
6082 
6083   // For a trivial copy or move assignment, perform an APValue copy. This is
6084   // essential for unions, where the operations performed by the assignment
6085   // operator cannot be represented as statements.
6086   //
6087   // Skip this for non-union classes with no fields; in that case, the defaulted
6088   // copy/move does not actually read the object.
6089   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6090   if (MD && MD->isDefaulted() &&
6091       (MD->getParent()->isUnion() ||
6092        (MD->isTrivial() &&
6093         isReadByLvalueToRvalueConversion(MD->getParent())))) {
6094     assert(This &&
6095            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
6096     APValue RHSValue;
6097     if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6098                            MD->getParent()->isUnion()))
6099       return false;
6100     if (Info.getLangOpts().CPlusPlus20 && MD->isTrivial() &&
6101         !HandleUnionActiveMemberChange(Info, Args[0], *This))
6102       return false;
6103     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
6104                           RHSValue))
6105       return false;
6106     This->moveInto(Result);
6107     return true;
6108   } else if (MD && isLambdaCallOperator(MD)) {
6109     // We're in a lambda; determine the lambda capture field maps unless we're
6110     // just constexpr checking a lambda's call operator. constexpr checking is
6111     // done before the captures have been added to the closure object (unless
6112     // we're inferring constexpr-ness), so we don't have access to them in this
6113     // case. But since we don't need the captures to constexpr check, we can
6114     // just ignore them.
6115     if (!Info.checkingPotentialConstantExpression())
6116       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6117                                         Frame.LambdaThisCaptureField);
6118   }
6119 
6120   StmtResult Ret = {Result, ResultSlot};
6121   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6122   if (ESR == ESR_Succeeded) {
6123     if (Callee->getReturnType()->isVoidType())
6124       return true;
6125     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6126   }
6127   return ESR == ESR_Returned;
6128 }
6129 
6130 /// Evaluate a constructor call.
6131 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6132                                   CallRef Call,
6133                                   const CXXConstructorDecl *Definition,
6134                                   EvalInfo &Info, APValue &Result) {
6135   SourceLocation CallLoc = E->getExprLoc();
6136   if (!Info.CheckCallLimit(CallLoc))
6137     return false;
6138 
6139   const CXXRecordDecl *RD = Definition->getParent();
6140   if (RD->getNumVBases()) {
6141     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6142     return false;
6143   }
6144 
6145   EvalInfo::EvaluatingConstructorRAII EvalObj(
6146       Info,
6147       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6148       RD->getNumBases());
6149   CallStackFrame Frame(Info, CallLoc, Definition, &This, Call);
6150 
6151   // FIXME: Creating an APValue just to hold a nonexistent return value is
6152   // wasteful.
6153   APValue RetVal;
6154   StmtResult Ret = {RetVal, nullptr};
6155 
6156   // If it's a delegating constructor, delegate.
6157   if (Definition->isDelegatingConstructor()) {
6158     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
6159     if ((*I)->getInit()->isValueDependent()) {
6160       if (!EvaluateDependentExpr((*I)->getInit(), Info))
6161         return false;
6162     } else {
6163       FullExpressionRAII InitScope(Info);
6164       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6165           !InitScope.destroy())
6166         return false;
6167     }
6168     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6169   }
6170 
6171   // For a trivial copy or move constructor, perform an APValue copy. This is
6172   // essential for unions (or classes with anonymous union members), where the
6173   // operations performed by the constructor cannot be represented by
6174   // ctor-initializers.
6175   //
6176   // Skip this for empty non-union classes; we should not perform an
6177   // lvalue-to-rvalue conversion on them because their copy constructor does not
6178   // actually read them.
6179   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6180       (Definition->getParent()->isUnion() ||
6181        (Definition->isTrivial() &&
6182         isReadByLvalueToRvalueConversion(Definition->getParent())))) {
6183     return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6184                              Definition->getParent()->isUnion());
6185   }
6186 
6187   // Reserve space for the struct members.
6188   if (!Result.hasValue()) {
6189     if (!RD->isUnion())
6190       Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6191                        std::distance(RD->field_begin(), RD->field_end()));
6192     else
6193       // A union starts with no active member.
6194       Result = APValue((const FieldDecl*)nullptr);
6195   }
6196 
6197   if (RD->isInvalidDecl()) return false;
6198   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6199 
6200   // A scope for temporaries lifetime-extended by reference members.
6201   BlockScopeRAII LifetimeExtendedScope(Info);
6202 
6203   bool Success = true;
6204   unsigned BasesSeen = 0;
6205 #ifndef NDEBUG
6206   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
6207 #endif
6208   CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
6209   auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6210     // We might be initializing the same field again if this is an indirect
6211     // field initialization.
6212     if (FieldIt == RD->field_end() ||
6213         FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6214       assert(Indirect && "fields out of order?");
6215       return;
6216     }
6217 
6218     // Default-initialize any fields with no explicit initializer.
6219     for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6220       assert(FieldIt != RD->field_end() && "missing field?");
6221       if (!FieldIt->isUnnamedBitfield())
6222         Success &= getDefaultInitValue(
6223             FieldIt->getType(),
6224             Result.getStructField(FieldIt->getFieldIndex()));
6225     }
6226     ++FieldIt;
6227   };
6228   for (const auto *I : Definition->inits()) {
6229     LValue Subobject = This;
6230     LValue SubobjectParent = This;
6231     APValue *Value = &Result;
6232 
6233     // Determine the subobject to initialize.
6234     FieldDecl *FD = nullptr;
6235     if (I->isBaseInitializer()) {
6236       QualType BaseType(I->getBaseClass(), 0);
6237 #ifndef NDEBUG
6238       // Non-virtual base classes are initialized in the order in the class
6239       // definition. We have already checked for virtual base classes.
6240       assert(!BaseIt->isVirtual() && "virtual base for literal type");
6241       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
6242              "base class initializers not in expected order");
6243       ++BaseIt;
6244 #endif
6245       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6246                                   BaseType->getAsCXXRecordDecl(), &Layout))
6247         return false;
6248       Value = &Result.getStructBase(BasesSeen++);
6249     } else if ((FD = I->getMember())) {
6250       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6251         return false;
6252       if (RD->isUnion()) {
6253         Result = APValue(FD);
6254         Value = &Result.getUnionValue();
6255       } else {
6256         SkipToField(FD, false);
6257         Value = &Result.getStructField(FD->getFieldIndex());
6258       }
6259     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6260       // Walk the indirect field decl's chain to find the object to initialize,
6261       // and make sure we've initialized every step along it.
6262       auto IndirectFieldChain = IFD->chain();
6263       for (auto *C : IndirectFieldChain) {
6264         FD = cast<FieldDecl>(C);
6265         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6266         // Switch the union field if it differs. This happens if we had
6267         // preceding zero-initialization, and we're now initializing a union
6268         // subobject other than the first.
6269         // FIXME: In this case, the values of the other subobjects are
6270         // specified, since zero-initialization sets all padding bits to zero.
6271         if (!Value->hasValue() ||
6272             (Value->isUnion() && Value->getUnionField() != FD)) {
6273           if (CD->isUnion())
6274             *Value = APValue(FD);
6275           else
6276             // FIXME: This immediately starts the lifetime of all members of
6277             // an anonymous struct. It would be preferable to strictly start
6278             // member lifetime in initialization order.
6279             Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
6280         }
6281         // Store Subobject as its parent before updating it for the last element
6282         // in the chain.
6283         if (C == IndirectFieldChain.back())
6284           SubobjectParent = Subobject;
6285         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6286           return false;
6287         if (CD->isUnion())
6288           Value = &Value->getUnionValue();
6289         else {
6290           if (C == IndirectFieldChain.front() && !RD->isUnion())
6291             SkipToField(FD, true);
6292           Value = &Value->getStructField(FD->getFieldIndex());
6293         }
6294       }
6295     } else {
6296       llvm_unreachable("unknown base initializer kind");
6297     }
6298 
6299     // Need to override This for implicit field initializers as in this case
6300     // This refers to innermost anonymous struct/union containing initializer,
6301     // not to currently constructed class.
6302     const Expr *Init = I->getInit();
6303     if (Init->isValueDependent()) {
6304       if (!EvaluateDependentExpr(Init, Info))
6305         return false;
6306     } else {
6307       ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6308                                     isa<CXXDefaultInitExpr>(Init));
6309       FullExpressionRAII InitScope(Info);
6310       if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6311           (FD && FD->isBitField() &&
6312            !truncateBitfieldValue(Info, Init, *Value, FD))) {
6313         // If we're checking for a potential constant expression, evaluate all
6314         // initializers even if some of them fail.
6315         if (!Info.noteFailure())
6316           return false;
6317         Success = false;
6318       }
6319     }
6320 
6321     // This is the point at which the dynamic type of the object becomes this
6322     // class type.
6323     if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6324       EvalObj.finishedConstructingBases();
6325   }
6326 
6327   // Default-initialize any remaining fields.
6328   if (!RD->isUnion()) {
6329     for (; FieldIt != RD->field_end(); ++FieldIt) {
6330       if (!FieldIt->isUnnamedBitfield())
6331         Success &= getDefaultInitValue(
6332             FieldIt->getType(),
6333             Result.getStructField(FieldIt->getFieldIndex()));
6334     }
6335   }
6336 
6337   EvalObj.finishedConstructingFields();
6338 
6339   return Success &&
6340          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6341          LifetimeExtendedScope.destroy();
6342 }
6343 
6344 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6345                                   ArrayRef<const Expr*> Args,
6346                                   const CXXConstructorDecl *Definition,
6347                                   EvalInfo &Info, APValue &Result) {
6348   CallScopeRAII CallScope(Info);
6349   CallRef Call = Info.CurrentCall->createCall(Definition);
6350   if (!EvaluateArgs(Args, Call, Info, Definition))
6351     return false;
6352 
6353   return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6354          CallScope.destroy();
6355 }
6356 
6357 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
6358                                   const LValue &This, APValue &Value,
6359                                   QualType T) {
6360   // Objects can only be destroyed while they're within their lifetimes.
6361   // FIXME: We have no representation for whether an object of type nullptr_t
6362   // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6363   // as indeterminate instead?
6364   if (Value.isAbsent() && !T->isNullPtrType()) {
6365     APValue Printable;
6366     This.moveInto(Printable);
6367     Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
6368       << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6369     return false;
6370   }
6371 
6372   // Invent an expression for location purposes.
6373   // FIXME: We shouldn't need to do this.
6374   OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_PRValue);
6375 
6376   // For arrays, destroy elements right-to-left.
6377   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6378     uint64_t Size = CAT->getSize().getZExtValue();
6379     QualType ElemT = CAT->getElementType();
6380 
6381     LValue ElemLV = This;
6382     ElemLV.addArray(Info, &LocE, CAT);
6383     if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6384       return false;
6385 
6386     // Ensure that we have actual array elements available to destroy; the
6387     // destructors might mutate the value, so we can't run them on the array
6388     // filler.
6389     if (Size && Size > Value.getArrayInitializedElts())
6390       expandArray(Value, Value.getArraySize() - 1);
6391 
6392     for (; Size != 0; --Size) {
6393       APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6394       if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6395           !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
6396         return false;
6397     }
6398 
6399     // End the lifetime of this array now.
6400     Value = APValue();
6401     return true;
6402   }
6403 
6404   const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6405   if (!RD) {
6406     if (T.isDestructedType()) {
6407       Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
6408       return false;
6409     }
6410 
6411     Value = APValue();
6412     return true;
6413   }
6414 
6415   if (RD->getNumVBases()) {
6416     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6417     return false;
6418   }
6419 
6420   const CXXDestructorDecl *DD = RD->getDestructor();
6421   if (!DD && !RD->hasTrivialDestructor()) {
6422     Info.FFDiag(CallLoc);
6423     return false;
6424   }
6425 
6426   if (!DD || DD->isTrivial() ||
6427       (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6428     // A trivial destructor just ends the lifetime of the object. Check for
6429     // this case before checking for a body, because we might not bother
6430     // building a body for a trivial destructor. Note that it doesn't matter
6431     // whether the destructor is constexpr in this case; all trivial
6432     // destructors are constexpr.
6433     //
6434     // If an anonymous union would be destroyed, some enclosing destructor must
6435     // have been explicitly defined, and the anonymous union destruction should
6436     // have no effect.
6437     Value = APValue();
6438     return true;
6439   }
6440 
6441   if (!Info.CheckCallLimit(CallLoc))
6442     return false;
6443 
6444   const FunctionDecl *Definition = nullptr;
6445   const Stmt *Body = DD->getBody(Definition);
6446 
6447   if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
6448     return false;
6449 
6450   CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef());
6451 
6452   // We're now in the period of destruction of this object.
6453   unsigned BasesLeft = RD->getNumBases();
6454   EvalInfo::EvaluatingDestructorRAII EvalObj(
6455       Info,
6456       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6457   if (!EvalObj.DidInsert) {
6458     // C++2a [class.dtor]p19:
6459     //   the behavior is undefined if the destructor is invoked for an object
6460     //   whose lifetime has ended
6461     // (Note that formally the lifetime ends when the period of destruction
6462     // begins, even though certain uses of the object remain valid until the
6463     // period of destruction ends.)
6464     Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
6465     return false;
6466   }
6467 
6468   // FIXME: Creating an APValue just to hold a nonexistent return value is
6469   // wasteful.
6470   APValue RetVal;
6471   StmtResult Ret = {RetVal, nullptr};
6472   if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6473     return false;
6474 
6475   // A union destructor does not implicitly destroy its members.
6476   if (RD->isUnion())
6477     return true;
6478 
6479   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6480 
6481   // We don't have a good way to iterate fields in reverse, so collect all the
6482   // fields first and then walk them backwards.
6483   SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
6484   for (const FieldDecl *FD : llvm::reverse(Fields)) {
6485     if (FD->isUnnamedBitfield())
6486       continue;
6487 
6488     LValue Subobject = This;
6489     if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6490       return false;
6491 
6492     APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6493     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6494                                FD->getType()))
6495       return false;
6496   }
6497 
6498   if (BasesLeft != 0)
6499     EvalObj.startedDestroyingBases();
6500 
6501   // Destroy base classes in reverse order.
6502   for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6503     --BasesLeft;
6504 
6505     QualType BaseType = Base.getType();
6506     LValue Subobject = This;
6507     if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
6508                                 BaseType->getAsCXXRecordDecl(), &Layout))
6509       return false;
6510 
6511     APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
6512     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6513                                BaseType))
6514       return false;
6515   }
6516   assert(BasesLeft == 0 && "NumBases was wrong?");
6517 
6518   // The period of destruction ends now. The object is gone.
6519   Value = APValue();
6520   return true;
6521 }
6522 
6523 namespace {
6524 struct DestroyObjectHandler {
6525   EvalInfo &Info;
6526   const Expr *E;
6527   const LValue &This;
6528   const AccessKinds AccessKind;
6529 
6530   typedef bool result_type;
6531   bool failed() { return false; }
6532   bool found(APValue &Subobj, QualType SubobjType) {
6533     return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
6534                                  SubobjType);
6535   }
6536   bool found(APSInt &Value, QualType SubobjType) {
6537     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6538     return false;
6539   }
6540   bool found(APFloat &Value, QualType SubobjType) {
6541     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6542     return false;
6543   }
6544 };
6545 }
6546 
6547 /// Perform a destructor or pseudo-destructor call on the given object, which
6548 /// might in general not be a complete object.
6549 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6550                               const LValue &This, QualType ThisType) {
6551   CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6552   DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6553   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6554 }
6555 
6556 /// Destroy and end the lifetime of the given complete object.
6557 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6558                               APValue::LValueBase LVBase, APValue &Value,
6559                               QualType T) {
6560   // If we've had an unmodeled side-effect, we can't rely on mutable state
6561   // (such as the object we're about to destroy) being correct.
6562   if (Info.EvalStatus.HasSideEffects)
6563     return false;
6564 
6565   LValue LV;
6566   LV.set({LVBase});
6567   return HandleDestructionImpl(Info, Loc, LV, Value, T);
6568 }
6569 
6570 /// Perform a call to 'perator new' or to `__builtin_operator_new'.
6571 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6572                                   LValue &Result) {
6573   if (Info.checkingPotentialConstantExpression() ||
6574       Info.SpeculativeEvaluationDepth)
6575     return false;
6576 
6577   // This is permitted only within a call to std::allocator<T>::allocate.
6578   auto Caller = Info.getStdAllocatorCaller("allocate");
6579   if (!Caller) {
6580     Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
6581                                      ? diag::note_constexpr_new_untyped
6582                                      : diag::note_constexpr_new);
6583     return false;
6584   }
6585 
6586   QualType ElemType = Caller.ElemType;
6587   if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6588     Info.FFDiag(E->getExprLoc(),
6589                 diag::note_constexpr_new_not_complete_object_type)
6590         << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6591     return false;
6592   }
6593 
6594   APSInt ByteSize;
6595   if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6596     return false;
6597   bool IsNothrow = false;
6598   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6599     EvaluateIgnoredValue(Info, E->getArg(I));
6600     IsNothrow |= E->getType()->isNothrowT();
6601   }
6602 
6603   CharUnits ElemSize;
6604   if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6605     return false;
6606   APInt Size, Remainder;
6607   APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6608   APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6609   if (Remainder != 0) {
6610     // This likely indicates a bug in the implementation of 'std::allocator'.
6611     Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6612         << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6613     return false;
6614   }
6615 
6616   if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
6617     if (IsNothrow) {
6618       Result.setNull(Info.Ctx, E->getType());
6619       return true;
6620     }
6621 
6622     Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
6623     return false;
6624   }
6625 
6626   QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
6627                                                      ArrayType::Normal, 0);
6628   APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6629   *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6630   Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6631   return true;
6632 }
6633 
6634 static bool hasVirtualDestructor(QualType T) {
6635   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6636     if (CXXDestructorDecl *DD = RD->getDestructor())
6637       return DD->isVirtual();
6638   return false;
6639 }
6640 
6641 static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6642   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6643     if (CXXDestructorDecl *DD = RD->getDestructor())
6644       return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6645   return nullptr;
6646 }
6647 
6648 /// Check that the given object is a suitable pointer to a heap allocation that
6649 /// still exists and is of the right kind for the purpose of a deletion.
6650 ///
6651 /// On success, returns the heap allocation to deallocate. On failure, produces
6652 /// a diagnostic and returns None.
6653 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6654                                             const LValue &Pointer,
6655                                             DynAlloc::Kind DeallocKind) {
6656   auto PointerAsString = [&] {
6657     return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6658   };
6659 
6660   DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6661   if (!DA) {
6662     Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6663         << PointerAsString();
6664     if (Pointer.Base)
6665       NoteLValueLocation(Info, Pointer.Base);
6666     return None;
6667   }
6668 
6669   Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6670   if (!Alloc) {
6671     Info.FFDiag(E, diag::note_constexpr_double_delete);
6672     return None;
6673   }
6674 
6675   QualType AllocType = Pointer.Base.getDynamicAllocType();
6676   if (DeallocKind != (*Alloc)->getKind()) {
6677     Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6678         << DeallocKind << (*Alloc)->getKind() << AllocType;
6679     NoteLValueLocation(Info, Pointer.Base);
6680     return None;
6681   }
6682 
6683   bool Subobject = false;
6684   if (DeallocKind == DynAlloc::New) {
6685     Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6686                 Pointer.Designator.isOnePastTheEnd();
6687   } else {
6688     Subobject = Pointer.Designator.Entries.size() != 1 ||
6689                 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6690   }
6691   if (Subobject) {
6692     Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6693         << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6694     return None;
6695   }
6696 
6697   return Alloc;
6698 }
6699 
6700 // Perform a call to 'operator delete' or '__builtin_operator_delete'.
6701 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6702   if (Info.checkingPotentialConstantExpression() ||
6703       Info.SpeculativeEvaluationDepth)
6704     return false;
6705 
6706   // This is permitted only within a call to std::allocator<T>::deallocate.
6707   if (!Info.getStdAllocatorCaller("deallocate")) {
6708     Info.FFDiag(E->getExprLoc());
6709     return true;
6710   }
6711 
6712   LValue Pointer;
6713   if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6714     return false;
6715   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6716     EvaluateIgnoredValue(Info, E->getArg(I));
6717 
6718   if (Pointer.Designator.Invalid)
6719     return false;
6720 
6721   // Deleting a null pointer would have no effect, but it's not permitted by
6722   // std::allocator<T>::deallocate's contract.
6723   if (Pointer.isNullPointer()) {
6724     Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
6725     return true;
6726   }
6727 
6728   if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6729     return false;
6730 
6731   Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6732   return true;
6733 }
6734 
6735 //===----------------------------------------------------------------------===//
6736 // Generic Evaluation
6737 //===----------------------------------------------------------------------===//
6738 namespace {
6739 
6740 class BitCastBuffer {
6741   // FIXME: We're going to need bit-level granularity when we support
6742   // bit-fields.
6743   // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6744   // we don't support a host or target where that is the case. Still, we should
6745   // use a more generic type in case we ever do.
6746   SmallVector<Optional<unsigned char>, 32> Bytes;
6747 
6748   static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6749                 "Need at least 8 bit unsigned char");
6750 
6751   bool TargetIsLittleEndian;
6752 
6753 public:
6754   BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6755       : Bytes(Width.getQuantity()),
6756         TargetIsLittleEndian(TargetIsLittleEndian) {}
6757 
6758   LLVM_NODISCARD
6759   bool readObject(CharUnits Offset, CharUnits Width,
6760                   SmallVectorImpl<unsigned char> &Output) const {
6761     for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6762       // If a byte of an integer is uninitialized, then the whole integer is
6763       // uninitalized.
6764       if (!Bytes[I.getQuantity()])
6765         return false;
6766       Output.push_back(*Bytes[I.getQuantity()]);
6767     }
6768     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6769       std::reverse(Output.begin(), Output.end());
6770     return true;
6771   }
6772 
6773   void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6774     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6775       std::reverse(Input.begin(), Input.end());
6776 
6777     size_t Index = 0;
6778     for (unsigned char Byte : Input) {
6779       assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
6780       Bytes[Offset.getQuantity() + Index] = Byte;
6781       ++Index;
6782     }
6783   }
6784 
6785   size_t size() { return Bytes.size(); }
6786 };
6787 
6788 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6789 /// target would represent the value at runtime.
6790 class APValueToBufferConverter {
6791   EvalInfo &Info;
6792   BitCastBuffer Buffer;
6793   const CastExpr *BCE;
6794 
6795   APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6796                            const CastExpr *BCE)
6797       : Info(Info),
6798         Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6799         BCE(BCE) {}
6800 
6801   bool visit(const APValue &Val, QualType Ty) {
6802     return visit(Val, Ty, CharUnits::fromQuantity(0));
6803   }
6804 
6805   // Write out Val with type Ty into Buffer starting at Offset.
6806   bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6807     assert((size_t)Offset.getQuantity() <= Buffer.size());
6808 
6809     // As a special case, nullptr_t has an indeterminate value.
6810     if (Ty->isNullPtrType())
6811       return true;
6812 
6813     // Dig through Src to find the byte at SrcOffset.
6814     switch (Val.getKind()) {
6815     case APValue::Indeterminate:
6816     case APValue::None:
6817       return true;
6818 
6819     case APValue::Int:
6820       return visitInt(Val.getInt(), Ty, Offset);
6821     case APValue::Float:
6822       return visitFloat(Val.getFloat(), Ty, Offset);
6823     case APValue::Array:
6824       return visitArray(Val, Ty, Offset);
6825     case APValue::Struct:
6826       return visitRecord(Val, Ty, Offset);
6827 
6828     case APValue::ComplexInt:
6829     case APValue::ComplexFloat:
6830     case APValue::Vector:
6831     case APValue::FixedPoint:
6832       // FIXME: We should support these.
6833 
6834     case APValue::Union:
6835     case APValue::MemberPointer:
6836     case APValue::AddrLabelDiff: {
6837       Info.FFDiag(BCE->getBeginLoc(),
6838                   diag::note_constexpr_bit_cast_unsupported_type)
6839           << Ty;
6840       return false;
6841     }
6842 
6843     case APValue::LValue:
6844       llvm_unreachable("LValue subobject in bit_cast?");
6845     }
6846     llvm_unreachable("Unhandled APValue::ValueKind");
6847   }
6848 
6849   bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
6850     const RecordDecl *RD = Ty->getAsRecordDecl();
6851     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6852 
6853     // Visit the base classes.
6854     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6855       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6856         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6857         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6858 
6859         if (!visitRecord(Val.getStructBase(I), BS.getType(),
6860                          Layout.getBaseClassOffset(BaseDecl) + Offset))
6861           return false;
6862       }
6863     }
6864 
6865     // Visit the fields.
6866     unsigned FieldIdx = 0;
6867     for (FieldDecl *FD : RD->fields()) {
6868       if (FD->isBitField()) {
6869         Info.FFDiag(BCE->getBeginLoc(),
6870                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6871         return false;
6872       }
6873 
6874       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6875 
6876       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
6877              "only bit-fields can have sub-char alignment");
6878       CharUnits FieldOffset =
6879           Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
6880       QualType FieldTy = FD->getType();
6881       if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
6882         return false;
6883       ++FieldIdx;
6884     }
6885 
6886     return true;
6887   }
6888 
6889   bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
6890     const auto *CAT =
6891         dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
6892     if (!CAT)
6893       return false;
6894 
6895     CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
6896     unsigned NumInitializedElts = Val.getArrayInitializedElts();
6897     unsigned ArraySize = Val.getArraySize();
6898     // First, initialize the initialized elements.
6899     for (unsigned I = 0; I != NumInitializedElts; ++I) {
6900       const APValue &SubObj = Val.getArrayInitializedElt(I);
6901       if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
6902         return false;
6903     }
6904 
6905     // Next, initialize the rest of the array using the filler.
6906     if (Val.hasArrayFiller()) {
6907       const APValue &Filler = Val.getArrayFiller();
6908       for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
6909         if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
6910           return false;
6911       }
6912     }
6913 
6914     return true;
6915   }
6916 
6917   bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
6918     APSInt AdjustedVal = Val;
6919     unsigned Width = AdjustedVal.getBitWidth();
6920     if (Ty->isBooleanType()) {
6921       Width = Info.Ctx.getTypeSize(Ty);
6922       AdjustedVal = AdjustedVal.extend(Width);
6923     }
6924 
6925     SmallVector<unsigned char, 8> Bytes(Width / 8);
6926     llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
6927     Buffer.writeObject(Offset, Bytes);
6928     return true;
6929   }
6930 
6931   bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
6932     APSInt AsInt(Val.bitcastToAPInt());
6933     return visitInt(AsInt, Ty, Offset);
6934   }
6935 
6936 public:
6937   static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
6938                                          const CastExpr *BCE) {
6939     CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
6940     APValueToBufferConverter Converter(Info, DstSize, BCE);
6941     if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
6942       return None;
6943     return Converter.Buffer;
6944   }
6945 };
6946 
6947 /// Write an BitCastBuffer into an APValue.
6948 class BufferToAPValueConverter {
6949   EvalInfo &Info;
6950   const BitCastBuffer &Buffer;
6951   const CastExpr *BCE;
6952 
6953   BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
6954                            const CastExpr *BCE)
6955       : Info(Info), Buffer(Buffer), BCE(BCE) {}
6956 
6957   // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
6958   // with an invalid type, so anything left is a deficiency on our part (FIXME).
6959   // Ideally this will be unreachable.
6960   llvm::NoneType unsupportedType(QualType Ty) {
6961     Info.FFDiag(BCE->getBeginLoc(),
6962                 diag::note_constexpr_bit_cast_unsupported_type)
6963         << Ty;
6964     return None;
6965   }
6966 
6967   llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) {
6968     Info.FFDiag(BCE->getBeginLoc(),
6969                 diag::note_constexpr_bit_cast_unrepresentable_value)
6970         << Ty << toString(Val, /*Radix=*/10);
6971     return None;
6972   }
6973 
6974   Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
6975                           const EnumType *EnumSugar = nullptr) {
6976     if (T->isNullPtrType()) {
6977       uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
6978       return APValue((Expr *)nullptr,
6979                      /*Offset=*/CharUnits::fromQuantity(NullValue),
6980                      APValue::NoLValuePath{}, /*IsNullPtr=*/true);
6981     }
6982 
6983     CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
6984 
6985     // Work around floating point types that contain unused padding bytes. This
6986     // is really just `long double` on x86, which is the only fundamental type
6987     // with padding bytes.
6988     if (T->isRealFloatingType()) {
6989       const llvm::fltSemantics &Semantics =
6990           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
6991       unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
6992       assert(NumBits % 8 == 0);
6993       CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
6994       if (NumBytes != SizeOf)
6995         SizeOf = NumBytes;
6996     }
6997 
6998     SmallVector<uint8_t, 8> Bytes;
6999     if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
7000       // If this is std::byte or unsigned char, then its okay to store an
7001       // indeterminate value.
7002       bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
7003       bool IsUChar =
7004           !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
7005                          T->isSpecificBuiltinType(BuiltinType::Char_U));
7006       if (!IsStdByte && !IsUChar) {
7007         QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
7008         Info.FFDiag(BCE->getExprLoc(),
7009                     diag::note_constexpr_bit_cast_indet_dest)
7010             << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
7011         return None;
7012       }
7013 
7014       return APValue::IndeterminateValue();
7015     }
7016 
7017     APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
7018     llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
7019 
7020     if (T->isIntegralOrEnumerationType()) {
7021       Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7022 
7023       unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
7024       if (IntWidth != Val.getBitWidth()) {
7025         APSInt Truncated = Val.trunc(IntWidth);
7026         if (Truncated.extend(Val.getBitWidth()) != Val)
7027           return unrepresentableValue(QualType(T, 0), Val);
7028         Val = Truncated;
7029       }
7030 
7031       return APValue(Val);
7032     }
7033 
7034     if (T->isRealFloatingType()) {
7035       const llvm::fltSemantics &Semantics =
7036           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7037       return APValue(APFloat(Semantics, Val));
7038     }
7039 
7040     return unsupportedType(QualType(T, 0));
7041   }
7042 
7043   Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7044     const RecordDecl *RD = RTy->getAsRecordDecl();
7045     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7046 
7047     unsigned NumBases = 0;
7048     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7049       NumBases = CXXRD->getNumBases();
7050 
7051     APValue ResultVal(APValue::UninitStruct(), NumBases,
7052                       std::distance(RD->field_begin(), RD->field_end()));
7053 
7054     // Visit the base classes.
7055     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7056       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7057         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7058         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7059         if (BaseDecl->isEmpty() ||
7060             Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
7061           continue;
7062 
7063         Optional<APValue> SubObj = visitType(
7064             BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7065         if (!SubObj)
7066           return None;
7067         ResultVal.getStructBase(I) = *SubObj;
7068       }
7069     }
7070 
7071     // Visit the fields.
7072     unsigned FieldIdx = 0;
7073     for (FieldDecl *FD : RD->fields()) {
7074       // FIXME: We don't currently support bit-fields. A lot of the logic for
7075       // this is in CodeGen, so we need to factor it around.
7076       if (FD->isBitField()) {
7077         Info.FFDiag(BCE->getBeginLoc(),
7078                     diag::note_constexpr_bit_cast_unsupported_bitfield);
7079         return None;
7080       }
7081 
7082       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7083       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
7084 
7085       CharUnits FieldOffset =
7086           CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7087           Offset;
7088       QualType FieldTy = FD->getType();
7089       Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7090       if (!SubObj)
7091         return None;
7092       ResultVal.getStructField(FieldIdx) = *SubObj;
7093       ++FieldIdx;
7094     }
7095 
7096     return ResultVal;
7097   }
7098 
7099   Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7100     QualType RepresentationType = Ty->getDecl()->getIntegerType();
7101     assert(!RepresentationType.isNull() &&
7102            "enum forward decl should be caught by Sema");
7103     const auto *AsBuiltin =
7104         RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7105     // Recurse into the underlying type. Treat std::byte transparently as
7106     // unsigned char.
7107     return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7108   }
7109 
7110   Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7111     size_t Size = Ty->getSize().getLimitedValue();
7112     CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7113 
7114     APValue ArrayValue(APValue::UninitArray(), Size, Size);
7115     for (size_t I = 0; I != Size; ++I) {
7116       Optional<APValue> ElementValue =
7117           visitType(Ty->getElementType(), Offset + I * ElementWidth);
7118       if (!ElementValue)
7119         return None;
7120       ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7121     }
7122 
7123     return ArrayValue;
7124   }
7125 
7126   Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7127     return unsupportedType(QualType(Ty, 0));
7128   }
7129 
7130   Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7131     QualType Can = Ty.getCanonicalType();
7132 
7133     switch (Can->getTypeClass()) {
7134 #define TYPE(Class, Base)                                                      \
7135   case Type::Class:                                                            \
7136     return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7137 #define ABSTRACT_TYPE(Class, Base)
7138 #define NON_CANONICAL_TYPE(Class, Base)                                        \
7139   case Type::Class:                                                            \
7140     llvm_unreachable("non-canonical type should be impossible!");
7141 #define DEPENDENT_TYPE(Class, Base)                                            \
7142   case Type::Class:                                                            \
7143     llvm_unreachable(                                                          \
7144         "dependent types aren't supported in the constant evaluator!");
7145 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)                            \
7146   case Type::Class:                                                            \
7147     llvm_unreachable("either dependent or not canonical!");
7148 #include "clang/AST/TypeNodes.inc"
7149     }
7150     llvm_unreachable("Unhandled Type::TypeClass");
7151   }
7152 
7153 public:
7154   // Pull out a full value of type DstType.
7155   static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7156                                    const CastExpr *BCE) {
7157     BufferToAPValueConverter Converter(Info, Buffer, BCE);
7158     return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7159   }
7160 };
7161 
7162 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7163                                                  QualType Ty, EvalInfo *Info,
7164                                                  const ASTContext &Ctx,
7165                                                  bool CheckingDest) {
7166   Ty = Ty.getCanonicalType();
7167 
7168   auto diag = [&](int Reason) {
7169     if (Info)
7170       Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7171           << CheckingDest << (Reason == 4) << Reason;
7172     return false;
7173   };
7174   auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7175     if (Info)
7176       Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7177           << NoteTy << Construct << Ty;
7178     return false;
7179   };
7180 
7181   if (Ty->isUnionType())
7182     return diag(0);
7183   if (Ty->isPointerType())
7184     return diag(1);
7185   if (Ty->isMemberPointerType())
7186     return diag(2);
7187   if (Ty.isVolatileQualified())
7188     return diag(3);
7189 
7190   if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7191     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7192       for (CXXBaseSpecifier &BS : CXXRD->bases())
7193         if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7194                                                   CheckingDest))
7195           return note(1, BS.getType(), BS.getBeginLoc());
7196     }
7197     for (FieldDecl *FD : Record->fields()) {
7198       if (FD->getType()->isReferenceType())
7199         return diag(4);
7200       if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7201                                                 CheckingDest))
7202         return note(0, FD->getType(), FD->getBeginLoc());
7203     }
7204   }
7205 
7206   if (Ty->isArrayType() &&
7207       !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7208                                             Info, Ctx, CheckingDest))
7209     return false;
7210 
7211   return true;
7212 }
7213 
7214 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
7215                                              const ASTContext &Ctx,
7216                                              const CastExpr *BCE) {
7217   bool DestOK = checkBitCastConstexprEligibilityType(
7218       BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
7219   bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
7220                                 BCE->getBeginLoc(),
7221                                 BCE->getSubExpr()->getType(), Info, Ctx, false);
7222   return SourceOK;
7223 }
7224 
7225 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7226                                         APValue &SourceValue,
7227                                         const CastExpr *BCE) {
7228   assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7229          "no host or target supports non 8-bit chars");
7230   assert(SourceValue.isLValue() &&
7231          "LValueToRValueBitcast requires an lvalue operand!");
7232 
7233   if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
7234     return false;
7235 
7236   LValue SourceLValue;
7237   APValue SourceRValue;
7238   SourceLValue.setFrom(Info.Ctx, SourceValue);
7239   if (!handleLValueToRValueConversion(
7240           Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
7241           SourceRValue, /*WantObjectRepresentation=*/true))
7242     return false;
7243 
7244   // Read out SourceValue into a char buffer.
7245   Optional<BitCastBuffer> Buffer =
7246       APValueToBufferConverter::convert(Info, SourceRValue, BCE);
7247   if (!Buffer)
7248     return false;
7249 
7250   // Write out the buffer into a new APValue.
7251   Optional<APValue> MaybeDestValue =
7252       BufferToAPValueConverter::convert(Info, *Buffer, BCE);
7253   if (!MaybeDestValue)
7254     return false;
7255 
7256   DestValue = std::move(*MaybeDestValue);
7257   return true;
7258 }
7259 
7260 template <class Derived>
7261 class ExprEvaluatorBase
7262   : public ConstStmtVisitor<Derived, bool> {
7263 private:
7264   Derived &getDerived() { return static_cast<Derived&>(*this); }
7265   bool DerivedSuccess(const APValue &V, const Expr *E) {
7266     return getDerived().Success(V, E);
7267   }
7268   bool DerivedZeroInitialization(const Expr *E) {
7269     return getDerived().ZeroInitialization(E);
7270   }
7271 
7272   // Check whether a conditional operator with a non-constant condition is a
7273   // potential constant expression. If neither arm is a potential constant
7274   // expression, then the conditional operator is not either.
7275   template<typename ConditionalOperator>
7276   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7277     assert(Info.checkingPotentialConstantExpression());
7278 
7279     // Speculatively evaluate both arms.
7280     SmallVector<PartialDiagnosticAt, 8> Diag;
7281     {
7282       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7283       StmtVisitorTy::Visit(E->getFalseExpr());
7284       if (Diag.empty())
7285         return;
7286     }
7287 
7288     {
7289       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7290       Diag.clear();
7291       StmtVisitorTy::Visit(E->getTrueExpr());
7292       if (Diag.empty())
7293         return;
7294     }
7295 
7296     Error(E, diag::note_constexpr_conditional_never_const);
7297   }
7298 
7299 
7300   template<typename ConditionalOperator>
7301   bool HandleConditionalOperator(const ConditionalOperator *E) {
7302     bool BoolResult;
7303     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7304       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7305         CheckPotentialConstantConditional(E);
7306         return false;
7307       }
7308       if (Info.noteFailure()) {
7309         StmtVisitorTy::Visit(E->getTrueExpr());
7310         StmtVisitorTy::Visit(E->getFalseExpr());
7311       }
7312       return false;
7313     }
7314 
7315     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
7316     return StmtVisitorTy::Visit(EvalExpr);
7317   }
7318 
7319 protected:
7320   EvalInfo &Info;
7321   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
7322   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
7323 
7324   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7325     return Info.CCEDiag(E, D);
7326   }
7327 
7328   bool ZeroInitialization(const Expr *E) { return Error(E); }
7329 
7330 public:
7331   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
7332 
7333   EvalInfo &getEvalInfo() { return Info; }
7334 
7335   /// Report an evaluation error. This should only be called when an error is
7336   /// first discovered. When propagating an error, just return false.
7337   bool Error(const Expr *E, diag::kind D) {
7338     Info.FFDiag(E, D);
7339     return false;
7340   }
7341   bool Error(const Expr *E) {
7342     return Error(E, diag::note_invalid_subexpr_in_const_expr);
7343   }
7344 
7345   bool VisitStmt(const Stmt *) {
7346     llvm_unreachable("Expression evaluator should not be called on stmts");
7347   }
7348   bool VisitExpr(const Expr *E) {
7349     return Error(E);
7350   }
7351 
7352   bool VisitConstantExpr(const ConstantExpr *E) {
7353     if (E->hasAPValueResult())
7354       return DerivedSuccess(E->getAPValueResult(), E);
7355 
7356     return StmtVisitorTy::Visit(E->getSubExpr());
7357   }
7358 
7359   bool VisitParenExpr(const ParenExpr *E)
7360     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7361   bool VisitUnaryExtension(const UnaryOperator *E)
7362     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7363   bool VisitUnaryPlus(const UnaryOperator *E)
7364     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7365   bool VisitChooseExpr(const ChooseExpr *E)
7366     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
7367   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
7368     { return StmtVisitorTy::Visit(E->getResultExpr()); }
7369   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
7370     { return StmtVisitorTy::Visit(E->getReplacement()); }
7371   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7372     TempVersionRAII RAII(*Info.CurrentCall);
7373     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7374     return StmtVisitorTy::Visit(E->getExpr());
7375   }
7376   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7377     TempVersionRAII RAII(*Info.CurrentCall);
7378     // The initializer may not have been parsed yet, or might be erroneous.
7379     if (!E->getExpr())
7380       return Error(E);
7381     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7382     return StmtVisitorTy::Visit(E->getExpr());
7383   }
7384 
7385   bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7386     FullExpressionRAII Scope(Info);
7387     return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
7388   }
7389 
7390   // Temporaries are registered when created, so we don't care about
7391   // CXXBindTemporaryExpr.
7392   bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7393     return StmtVisitorTy::Visit(E->getSubExpr());
7394   }
7395 
7396   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7397     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7398     return static_cast<Derived*>(this)->VisitCastExpr(E);
7399   }
7400   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7401     if (!Info.Ctx.getLangOpts().CPlusPlus20)
7402       CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
7403     return static_cast<Derived*>(this)->VisitCastExpr(E);
7404   }
7405   bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7406     return static_cast<Derived*>(this)->VisitCastExpr(E);
7407   }
7408 
7409   bool VisitBinaryOperator(const BinaryOperator *E) {
7410     switch (E->getOpcode()) {
7411     default:
7412       return Error(E);
7413 
7414     case BO_Comma:
7415       VisitIgnoredValue(E->getLHS());
7416       return StmtVisitorTy::Visit(E->getRHS());
7417 
7418     case BO_PtrMemD:
7419     case BO_PtrMemI: {
7420       LValue Obj;
7421       if (!HandleMemberPointerAccess(Info, E, Obj))
7422         return false;
7423       APValue Result;
7424       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7425         return false;
7426       return DerivedSuccess(Result, E);
7427     }
7428     }
7429   }
7430 
7431   bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
7432     return StmtVisitorTy::Visit(E->getSemanticForm());
7433   }
7434 
7435   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7436     // Evaluate and cache the common expression. We treat it as a temporary,
7437     // even though it's not quite the same thing.
7438     LValue CommonLV;
7439     if (!Evaluate(Info.CurrentCall->createTemporary(
7440                       E->getOpaqueValue(),
7441                       getStorageType(Info.Ctx, E->getOpaqueValue()),
7442                       ScopeKind::FullExpression, CommonLV),
7443                   Info, E->getCommon()))
7444       return false;
7445 
7446     return HandleConditionalOperator(E);
7447   }
7448 
7449   bool VisitConditionalOperator(const ConditionalOperator *E) {
7450     bool IsBcpCall = false;
7451     // If the condition (ignoring parens) is a __builtin_constant_p call,
7452     // the result is a constant expression if it can be folded without
7453     // side-effects. This is an important GNU extension. See GCC PR38377
7454     // for discussion.
7455     if (const CallExpr *CallCE =
7456           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7457       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7458         IsBcpCall = true;
7459 
7460     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7461     // constant expression; we can't check whether it's potentially foldable.
7462     // FIXME: We should instead treat __builtin_constant_p as non-constant if
7463     // it would return 'false' in this mode.
7464     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
7465       return false;
7466 
7467     FoldConstant Fold(Info, IsBcpCall);
7468     if (!HandleConditionalOperator(E)) {
7469       Fold.keepDiagnostics();
7470       return false;
7471     }
7472 
7473     return true;
7474   }
7475 
7476   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7477     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
7478       return DerivedSuccess(*Value, E);
7479 
7480     const Expr *Source = E->getSourceExpr();
7481     if (!Source)
7482       return Error(E);
7483     if (Source == E) { // sanity checking.
7484       assert(0 && "OpaqueValueExpr recursively refers to itself");
7485       return Error(E);
7486     }
7487     return StmtVisitorTy::Visit(Source);
7488   }
7489 
7490   bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7491     for (const Expr *SemE : E->semantics()) {
7492       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7493         // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7494         // result expression: there could be two different LValues that would
7495         // refer to the same object in that case, and we can't model that.
7496         if (SemE == E->getResultExpr())
7497           return Error(E);
7498 
7499         // Unique OVEs get evaluated if and when we encounter them when
7500         // emitting the rest of the semantic form, rather than eagerly.
7501         if (OVE->isUnique())
7502           continue;
7503 
7504         LValue LV;
7505         if (!Evaluate(Info.CurrentCall->createTemporary(
7506                           OVE, getStorageType(Info.Ctx, OVE),
7507                           ScopeKind::FullExpression, LV),
7508                       Info, OVE->getSourceExpr()))
7509           return false;
7510       } else if (SemE == E->getResultExpr()) {
7511         if (!StmtVisitorTy::Visit(SemE))
7512           return false;
7513       } else {
7514         if (!EvaluateIgnoredValue(Info, SemE))
7515           return false;
7516       }
7517     }
7518     return true;
7519   }
7520 
7521   bool VisitCallExpr(const CallExpr *E) {
7522     APValue Result;
7523     if (!handleCallExpr(E, Result, nullptr))
7524       return false;
7525     return DerivedSuccess(Result, E);
7526   }
7527 
7528   bool handleCallExpr(const CallExpr *E, APValue &Result,
7529                      const LValue *ResultSlot) {
7530     CallScopeRAII CallScope(Info);
7531 
7532     const Expr *Callee = E->getCallee()->IgnoreParens();
7533     QualType CalleeType = Callee->getType();
7534 
7535     const FunctionDecl *FD = nullptr;
7536     LValue *This = nullptr, ThisVal;
7537     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
7538     bool HasQualifier = false;
7539 
7540     CallRef Call;
7541 
7542     // Extract function decl and 'this' pointer from the callee.
7543     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7544       const CXXMethodDecl *Member = nullptr;
7545       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7546         // Explicit bound member calls, such as x.f() or p->g();
7547         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7548           return false;
7549         Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7550         if (!Member)
7551           return Error(Callee);
7552         This = &ThisVal;
7553         HasQualifier = ME->hasQualifier();
7554       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
7555         // Indirect bound member calls ('.*' or '->*').
7556         const ValueDecl *D =
7557             HandleMemberPointerAccess(Info, BE, ThisVal, false);
7558         if (!D)
7559           return false;
7560         Member = dyn_cast<CXXMethodDecl>(D);
7561         if (!Member)
7562           return Error(Callee);
7563         This = &ThisVal;
7564       } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7565         if (!Info.getLangOpts().CPlusPlus20)
7566           Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7567         return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7568                HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7569       } else
7570         return Error(Callee);
7571       FD = Member;
7572     } else if (CalleeType->isFunctionPointerType()) {
7573       LValue CalleeLV;
7574       if (!EvaluatePointer(Callee, CalleeLV, Info))
7575         return false;
7576 
7577       if (!CalleeLV.getLValueOffset().isZero())
7578         return Error(Callee);
7579       FD = dyn_cast_or_null<FunctionDecl>(
7580           CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
7581       if (!FD)
7582         return Error(Callee);
7583       // Don't call function pointers which have been cast to some other type.
7584       // Per DR (no number yet), the caller and callee can differ in noexcept.
7585       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7586         CalleeType->getPointeeType(), FD->getType())) {
7587         return Error(E);
7588       }
7589 
7590       // For an (overloaded) assignment expression, evaluate the RHS before the
7591       // LHS.
7592       auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
7593       if (OCE && OCE->isAssignmentOp()) {
7594         assert(Args.size() == 2 && "wrong number of arguments in assignment");
7595         Call = Info.CurrentCall->createCall(FD);
7596         if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call,
7597                           Info, FD, /*RightToLeft=*/true))
7598           return false;
7599       }
7600 
7601       // Overloaded operator calls to member functions are represented as normal
7602       // calls with '*this' as the first argument.
7603       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7604       if (MD && !MD->isStatic()) {
7605         // FIXME: When selecting an implicit conversion for an overloaded
7606         // operator delete, we sometimes try to evaluate calls to conversion
7607         // operators without a 'this' parameter!
7608         if (Args.empty())
7609           return Error(E);
7610 
7611         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7612           return false;
7613         This = &ThisVal;
7614         Args = Args.slice(1);
7615       } else if (MD && MD->isLambdaStaticInvoker()) {
7616         // Map the static invoker for the lambda back to the call operator.
7617         // Conveniently, we don't have to slice out the 'this' argument (as is
7618         // being done for the non-static case), since a static member function
7619         // doesn't have an implicit argument passed in.
7620         const CXXRecordDecl *ClosureClass = MD->getParent();
7621         assert(
7622             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7623             "Number of captures must be zero for conversion to function-ptr");
7624 
7625         const CXXMethodDecl *LambdaCallOp =
7626             ClosureClass->getLambdaCallOperator();
7627 
7628         // Set 'FD', the function that will be called below, to the call
7629         // operator.  If the closure object represents a generic lambda, find
7630         // the corresponding specialization of the call operator.
7631 
7632         if (ClosureClass->isGenericLambda()) {
7633           assert(MD->isFunctionTemplateSpecialization() &&
7634                  "A generic lambda's static-invoker function must be a "
7635                  "template specialization");
7636           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7637           FunctionTemplateDecl *CallOpTemplate =
7638               LambdaCallOp->getDescribedFunctionTemplate();
7639           void *InsertPos = nullptr;
7640           FunctionDecl *CorrespondingCallOpSpecialization =
7641               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7642           assert(CorrespondingCallOpSpecialization &&
7643                  "We must always have a function call operator specialization "
7644                  "that corresponds to our static invoker specialization");
7645           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7646         } else
7647           FD = LambdaCallOp;
7648       } else if (FD->isReplaceableGlobalAllocationFunction()) {
7649         if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7650             FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7651           LValue Ptr;
7652           if (!HandleOperatorNewCall(Info, E, Ptr))
7653             return false;
7654           Ptr.moveInto(Result);
7655           return CallScope.destroy();
7656         } else {
7657           return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
7658         }
7659       }
7660     } else
7661       return Error(E);
7662 
7663     // Evaluate the arguments now if we've not already done so.
7664     if (!Call) {
7665       Call = Info.CurrentCall->createCall(FD);
7666       if (!EvaluateArgs(Args, Call, Info, FD))
7667         return false;
7668     }
7669 
7670     SmallVector<QualType, 4> CovariantAdjustmentPath;
7671     if (This) {
7672       auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7673       if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
7674         // Perform virtual dispatch, if necessary.
7675         FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
7676                                    CovariantAdjustmentPath);
7677         if (!FD)
7678           return false;
7679       } else {
7680         // Check that the 'this' pointer points to an object of the right type.
7681         // FIXME: If this is an assignment operator call, we may need to change
7682         // the active union member before we check this.
7683         if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
7684           return false;
7685       }
7686     }
7687 
7688     // Destructor calls are different enough that they have their own codepath.
7689     if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
7690       assert(This && "no 'this' pointer for destructor call");
7691       return HandleDestruction(Info, E, *This,
7692                                Info.Ctx.getRecordType(DD->getParent())) &&
7693              CallScope.destroy();
7694     }
7695 
7696     const FunctionDecl *Definition = nullptr;
7697     Stmt *Body = FD->getBody(Definition);
7698 
7699     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
7700         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call,
7701                             Body, Info, Result, ResultSlot))
7702       return false;
7703 
7704     if (!CovariantAdjustmentPath.empty() &&
7705         !HandleCovariantReturnAdjustment(Info, E, Result,
7706                                          CovariantAdjustmentPath))
7707       return false;
7708 
7709     return CallScope.destroy();
7710   }
7711 
7712   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7713     return StmtVisitorTy::Visit(E->getInitializer());
7714   }
7715   bool VisitInitListExpr(const InitListExpr *E) {
7716     if (E->getNumInits() == 0)
7717       return DerivedZeroInitialization(E);
7718     if (E->getNumInits() == 1)
7719       return StmtVisitorTy::Visit(E->getInit(0));
7720     return Error(E);
7721   }
7722   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
7723     return DerivedZeroInitialization(E);
7724   }
7725   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
7726     return DerivedZeroInitialization(E);
7727   }
7728   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
7729     return DerivedZeroInitialization(E);
7730   }
7731 
7732   /// A member expression where the object is a prvalue is itself a prvalue.
7733   bool VisitMemberExpr(const MemberExpr *E) {
7734     assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
7735            "missing temporary materialization conversion");
7736     assert(!E->isArrow() && "missing call to bound member function?");
7737 
7738     APValue Val;
7739     if (!Evaluate(Val, Info, E->getBase()))
7740       return false;
7741 
7742     QualType BaseTy = E->getBase()->getType();
7743 
7744     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
7745     if (!FD) return Error(E);
7746     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
7747     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7748            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7749 
7750     // Note: there is no lvalue base here. But this case should only ever
7751     // happen in C or in C++98, where we cannot be evaluating a constexpr
7752     // constructor, which is the only case the base matters.
7753     CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
7754     SubobjectDesignator Designator(BaseTy);
7755     Designator.addDeclUnchecked(FD);
7756 
7757     APValue Result;
7758     return extractSubobject(Info, E, Obj, Designator, Result) &&
7759            DerivedSuccess(Result, E);
7760   }
7761 
7762   bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
7763     APValue Val;
7764     if (!Evaluate(Val, Info, E->getBase()))
7765       return false;
7766 
7767     if (Val.isVector()) {
7768       SmallVector<uint32_t, 4> Indices;
7769       E->getEncodedElementAccess(Indices);
7770       if (Indices.size() == 1) {
7771         // Return scalar.
7772         return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
7773       } else {
7774         // Construct new APValue vector.
7775         SmallVector<APValue, 4> Elts;
7776         for (unsigned I = 0; I < Indices.size(); ++I) {
7777           Elts.push_back(Val.getVectorElt(Indices[I]));
7778         }
7779         APValue VecResult(Elts.data(), Indices.size());
7780         return DerivedSuccess(VecResult, E);
7781       }
7782     }
7783 
7784     return false;
7785   }
7786 
7787   bool VisitCastExpr(const CastExpr *E) {
7788     switch (E->getCastKind()) {
7789     default:
7790       break;
7791 
7792     case CK_AtomicToNonAtomic: {
7793       APValue AtomicVal;
7794       // This does not need to be done in place even for class/array types:
7795       // atomic-to-non-atomic conversion implies copying the object
7796       // representation.
7797       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
7798         return false;
7799       return DerivedSuccess(AtomicVal, E);
7800     }
7801 
7802     case CK_NoOp:
7803     case CK_UserDefinedConversion:
7804       return StmtVisitorTy::Visit(E->getSubExpr());
7805 
7806     case CK_LValueToRValue: {
7807       LValue LVal;
7808       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
7809         return false;
7810       APValue RVal;
7811       // Note, we use the subexpression's type in order to retain cv-qualifiers.
7812       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7813                                           LVal, RVal))
7814         return false;
7815       return DerivedSuccess(RVal, E);
7816     }
7817     case CK_LValueToRValueBitCast: {
7818       APValue DestValue, SourceValue;
7819       if (!Evaluate(SourceValue, Info, E->getSubExpr()))
7820         return false;
7821       if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
7822         return false;
7823       return DerivedSuccess(DestValue, E);
7824     }
7825 
7826     case CK_AddressSpaceConversion: {
7827       APValue Value;
7828       if (!Evaluate(Value, Info, E->getSubExpr()))
7829         return false;
7830       return DerivedSuccess(Value, E);
7831     }
7832     }
7833 
7834     return Error(E);
7835   }
7836 
7837   bool VisitUnaryPostInc(const UnaryOperator *UO) {
7838     return VisitUnaryPostIncDec(UO);
7839   }
7840   bool VisitUnaryPostDec(const UnaryOperator *UO) {
7841     return VisitUnaryPostIncDec(UO);
7842   }
7843   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
7844     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7845       return Error(UO);
7846 
7847     LValue LVal;
7848     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
7849       return false;
7850     APValue RVal;
7851     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
7852                       UO->isIncrementOp(), &RVal))
7853       return false;
7854     return DerivedSuccess(RVal, UO);
7855   }
7856 
7857   bool VisitStmtExpr(const StmtExpr *E) {
7858     // We will have checked the full-expressions inside the statement expression
7859     // when they were completed, and don't need to check them again now.
7860     llvm::SaveAndRestore<bool> NotCheckingForUB(
7861         Info.CheckingForUndefinedBehavior, false);
7862 
7863     const CompoundStmt *CS = E->getSubStmt();
7864     if (CS->body_empty())
7865       return true;
7866 
7867     BlockScopeRAII Scope(Info);
7868     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
7869                                            BE = CS->body_end();
7870          /**/; ++BI) {
7871       if (BI + 1 == BE) {
7872         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
7873         if (!FinalExpr) {
7874           Info.FFDiag((*BI)->getBeginLoc(),
7875                       diag::note_constexpr_stmt_expr_unsupported);
7876           return false;
7877         }
7878         return this->Visit(FinalExpr) && Scope.destroy();
7879       }
7880 
7881       APValue ReturnValue;
7882       StmtResult Result = { ReturnValue, nullptr };
7883       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
7884       if (ESR != ESR_Succeeded) {
7885         // FIXME: If the statement-expression terminated due to 'return',
7886         // 'break', or 'continue', it would be nice to propagate that to
7887         // the outer statement evaluation rather than bailing out.
7888         if (ESR != ESR_Failed)
7889           Info.FFDiag((*BI)->getBeginLoc(),
7890                       diag::note_constexpr_stmt_expr_unsupported);
7891         return false;
7892       }
7893     }
7894 
7895     llvm_unreachable("Return from function from the loop above.");
7896   }
7897 
7898   /// Visit a value which is evaluated, but whose value is ignored.
7899   void VisitIgnoredValue(const Expr *E) {
7900     EvaluateIgnoredValue(Info, E);
7901   }
7902 
7903   /// Potentially visit a MemberExpr's base expression.
7904   void VisitIgnoredBaseExpression(const Expr *E) {
7905     // While MSVC doesn't evaluate the base expression, it does diagnose the
7906     // presence of side-effecting behavior.
7907     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
7908       return;
7909     VisitIgnoredValue(E);
7910   }
7911 };
7912 
7913 } // namespace
7914 
7915 //===----------------------------------------------------------------------===//
7916 // Common base class for lvalue and temporary evaluation.
7917 //===----------------------------------------------------------------------===//
7918 namespace {
7919 template<class Derived>
7920 class LValueExprEvaluatorBase
7921   : public ExprEvaluatorBase<Derived> {
7922 protected:
7923   LValue &Result;
7924   bool InvalidBaseOK;
7925   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
7926   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
7927 
7928   bool Success(APValue::LValueBase B) {
7929     Result.set(B);
7930     return true;
7931   }
7932 
7933   bool evaluatePointer(const Expr *E, LValue &Result) {
7934     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
7935   }
7936 
7937 public:
7938   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
7939       : ExprEvaluatorBaseTy(Info), Result(Result),
7940         InvalidBaseOK(InvalidBaseOK) {}
7941 
7942   bool Success(const APValue &V, const Expr *E) {
7943     Result.setFrom(this->Info.Ctx, V);
7944     return true;
7945   }
7946 
7947   bool VisitMemberExpr(const MemberExpr *E) {
7948     // Handle non-static data members.
7949     QualType BaseTy;
7950     bool EvalOK;
7951     if (E->isArrow()) {
7952       EvalOK = evaluatePointer(E->getBase(), Result);
7953       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
7954     } else if (E->getBase()->isPRValue()) {
7955       assert(E->getBase()->getType()->isRecordType());
7956       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
7957       BaseTy = E->getBase()->getType();
7958     } else {
7959       EvalOK = this->Visit(E->getBase());
7960       BaseTy = E->getBase()->getType();
7961     }
7962     if (!EvalOK) {
7963       if (!InvalidBaseOK)
7964         return false;
7965       Result.setInvalid(E);
7966       return true;
7967     }
7968 
7969     const ValueDecl *MD = E->getMemberDecl();
7970     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
7971       assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7972              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7973       (void)BaseTy;
7974       if (!HandleLValueMember(this->Info, E, Result, FD))
7975         return false;
7976     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
7977       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
7978         return false;
7979     } else
7980       return this->Error(E);
7981 
7982     if (MD->getType()->isReferenceType()) {
7983       APValue RefValue;
7984       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
7985                                           RefValue))
7986         return false;
7987       return Success(RefValue, E);
7988     }
7989     return true;
7990   }
7991 
7992   bool VisitBinaryOperator(const BinaryOperator *E) {
7993     switch (E->getOpcode()) {
7994     default:
7995       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7996 
7997     case BO_PtrMemD:
7998     case BO_PtrMemI:
7999       return HandleMemberPointerAccess(this->Info, E, Result);
8000     }
8001   }
8002 
8003   bool VisitCastExpr(const CastExpr *E) {
8004     switch (E->getCastKind()) {
8005     default:
8006       return ExprEvaluatorBaseTy::VisitCastExpr(E);
8007 
8008     case CK_DerivedToBase:
8009     case CK_UncheckedDerivedToBase:
8010       if (!this->Visit(E->getSubExpr()))
8011         return false;
8012 
8013       // Now figure out the necessary offset to add to the base LV to get from
8014       // the derived class to the base class.
8015       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8016                                   Result);
8017     }
8018   }
8019 };
8020 }
8021 
8022 //===----------------------------------------------------------------------===//
8023 // LValue Evaluation
8024 //
8025 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8026 // function designators (in C), decl references to void objects (in C), and
8027 // temporaries (if building with -Wno-address-of-temporary).
8028 //
8029 // LValue evaluation produces values comprising a base expression of one of the
8030 // following types:
8031 // - Declarations
8032 //  * VarDecl
8033 //  * FunctionDecl
8034 // - Literals
8035 //  * CompoundLiteralExpr in C (and in global scope in C++)
8036 //  * StringLiteral
8037 //  * PredefinedExpr
8038 //  * ObjCStringLiteralExpr
8039 //  * ObjCEncodeExpr
8040 //  * AddrLabelExpr
8041 //  * BlockExpr
8042 //  * CallExpr for a MakeStringConstant builtin
8043 // - typeid(T) expressions, as TypeInfoLValues
8044 // - Locals and temporaries
8045 //  * MaterializeTemporaryExpr
8046 //  * Any Expr, with a CallIndex indicating the function in which the temporary
8047 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
8048 //    from the AST (FIXME).
8049 //  * A MaterializeTemporaryExpr that has static storage duration, with no
8050 //    CallIndex, for a lifetime-extended temporary.
8051 //  * The ConstantExpr that is currently being evaluated during evaluation of an
8052 //    immediate invocation.
8053 // plus an offset in bytes.
8054 //===----------------------------------------------------------------------===//
8055 namespace {
8056 class LValueExprEvaluator
8057   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8058 public:
8059   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8060     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8061 
8062   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8063   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8064 
8065   bool VisitDeclRefExpr(const DeclRefExpr *E);
8066   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8067   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8068   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8069   bool VisitMemberExpr(const MemberExpr *E);
8070   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
8071   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8072   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8073   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8074   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8075   bool VisitUnaryDeref(const UnaryOperator *E);
8076   bool VisitUnaryReal(const UnaryOperator *E);
8077   bool VisitUnaryImag(const UnaryOperator *E);
8078   bool VisitUnaryPreInc(const UnaryOperator *UO) {
8079     return VisitUnaryPreIncDec(UO);
8080   }
8081   bool VisitUnaryPreDec(const UnaryOperator *UO) {
8082     return VisitUnaryPreIncDec(UO);
8083   }
8084   bool VisitBinAssign(const BinaryOperator *BO);
8085   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8086 
8087   bool VisitCastExpr(const CastExpr *E) {
8088     switch (E->getCastKind()) {
8089     default:
8090       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8091 
8092     case CK_LValueBitCast:
8093       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8094       if (!Visit(E->getSubExpr()))
8095         return false;
8096       Result.Designator.setInvalid();
8097       return true;
8098 
8099     case CK_BaseToDerived:
8100       if (!Visit(E->getSubExpr()))
8101         return false;
8102       return HandleBaseToDerivedCast(Info, E, Result);
8103 
8104     case CK_Dynamic:
8105       if (!Visit(E->getSubExpr()))
8106         return false;
8107       return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8108     }
8109   }
8110 };
8111 } // end anonymous namespace
8112 
8113 /// Evaluate an expression as an lvalue. This can be legitimately called on
8114 /// expressions which are not glvalues, in three cases:
8115 ///  * function designators in C, and
8116 ///  * "extern void" objects
8117 ///  * @selector() expressions in Objective-C
8118 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
8119                            bool InvalidBaseOK) {
8120   assert(!E->isValueDependent());
8121   assert(E->isGLValue() || E->getType()->isFunctionType() ||
8122          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
8123   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8124 }
8125 
8126 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
8127   const NamedDecl *D = E->getDecl();
8128   if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl>(D))
8129     return Success(cast<ValueDecl>(D));
8130   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
8131     return VisitVarDecl(E, VD);
8132   if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
8133     return Visit(BD->getBinding());
8134   return Error(E);
8135 }
8136 
8137 
8138 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
8139 
8140   // If we are within a lambda's call operator, check whether the 'VD' referred
8141   // to within 'E' actually represents a lambda-capture that maps to a
8142   // data-member/field within the closure object, and if so, evaluate to the
8143   // field or what the field refers to.
8144   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
8145       isa<DeclRefExpr>(E) &&
8146       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
8147     // We don't always have a complete capture-map when checking or inferring if
8148     // the function call operator meets the requirements of a constexpr function
8149     // - but we don't need to evaluate the captures to determine constexprness
8150     // (dcl.constexpr C++17).
8151     if (Info.checkingPotentialConstantExpression())
8152       return false;
8153 
8154     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
8155       // Start with 'Result' referring to the complete closure object...
8156       Result = *Info.CurrentCall->This;
8157       // ... then update it to refer to the field of the closure object
8158       // that represents the capture.
8159       if (!HandleLValueMember(Info, E, Result, FD))
8160         return false;
8161       // And if the field is of reference type, update 'Result' to refer to what
8162       // the field refers to.
8163       if (FD->getType()->isReferenceType()) {
8164         APValue RVal;
8165         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
8166                                             RVal))
8167           return false;
8168         Result.setFrom(Info.Ctx, RVal);
8169       }
8170       return true;
8171     }
8172   }
8173 
8174   CallStackFrame *Frame = nullptr;
8175   unsigned Version = 0;
8176   if (VD->hasLocalStorage()) {
8177     // Only if a local variable was declared in the function currently being
8178     // evaluated, do we expect to be able to find its value in the current
8179     // frame. (Otherwise it was likely declared in an enclosing context and
8180     // could either have a valid evaluatable value (for e.g. a constexpr
8181     // variable) or be ill-formed (and trigger an appropriate evaluation
8182     // diagnostic)).
8183     CallStackFrame *CurrFrame = Info.CurrentCall;
8184     if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
8185       // Function parameters are stored in some caller's frame. (Usually the
8186       // immediate caller, but for an inherited constructor they may be more
8187       // distant.)
8188       if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
8189         if (CurrFrame->Arguments) {
8190           VD = CurrFrame->Arguments.getOrigParam(PVD);
8191           Frame =
8192               Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
8193           Version = CurrFrame->Arguments.Version;
8194         }
8195       } else {
8196         Frame = CurrFrame;
8197         Version = CurrFrame->getCurrentTemporaryVersion(VD);
8198       }
8199     }
8200   }
8201 
8202   if (!VD->getType()->isReferenceType()) {
8203     if (Frame) {
8204       Result.set({VD, Frame->Index, Version});
8205       return true;
8206     }
8207     return Success(VD);
8208   }
8209 
8210   if (!Info.getLangOpts().CPlusPlus11) {
8211     Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
8212         << VD << VD->getType();
8213     Info.Note(VD->getLocation(), diag::note_declared_at);
8214   }
8215 
8216   APValue *V;
8217   if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
8218     return false;
8219   if (!V->hasValue()) {
8220     // FIXME: Is it possible for V to be indeterminate here? If so, we should
8221     // adjust the diagnostic to say that.
8222     if (!Info.checkingPotentialConstantExpression())
8223       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
8224     return false;
8225   }
8226   return Success(*V, E);
8227 }
8228 
8229 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
8230     const MaterializeTemporaryExpr *E) {
8231   // Walk through the expression to find the materialized temporary itself.
8232   SmallVector<const Expr *, 2> CommaLHSs;
8233   SmallVector<SubobjectAdjustment, 2> Adjustments;
8234   const Expr *Inner =
8235       E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
8236 
8237   // If we passed any comma operators, evaluate their LHSs.
8238   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
8239     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
8240       return false;
8241 
8242   // A materialized temporary with static storage duration can appear within the
8243   // result of a constant expression evaluation, so we need to preserve its
8244   // value for use outside this evaluation.
8245   APValue *Value;
8246   if (E->getStorageDuration() == SD_Static) {
8247     // FIXME: What about SD_Thread?
8248     Value = E->getOrCreateValue(true);
8249     *Value = APValue();
8250     Result.set(E);
8251   } else {
8252     Value = &Info.CurrentCall->createTemporary(
8253         E, E->getType(),
8254         E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
8255                                                      : ScopeKind::Block,
8256         Result);
8257   }
8258 
8259   QualType Type = Inner->getType();
8260 
8261   // Materialize the temporary itself.
8262   if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
8263     *Value = APValue();
8264     return false;
8265   }
8266 
8267   // Adjust our lvalue to refer to the desired subobject.
8268   for (unsigned I = Adjustments.size(); I != 0; /**/) {
8269     --I;
8270     switch (Adjustments[I].Kind) {
8271     case SubobjectAdjustment::DerivedToBaseAdjustment:
8272       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
8273                                 Type, Result))
8274         return false;
8275       Type = Adjustments[I].DerivedToBase.BasePath->getType();
8276       break;
8277 
8278     case SubobjectAdjustment::FieldAdjustment:
8279       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
8280         return false;
8281       Type = Adjustments[I].Field->getType();
8282       break;
8283 
8284     case SubobjectAdjustment::MemberPointerAdjustment:
8285       if (!HandleMemberPointerAccess(this->Info, Type, Result,
8286                                      Adjustments[I].Ptr.RHS))
8287         return false;
8288       Type = Adjustments[I].Ptr.MPT->getPointeeType();
8289       break;
8290     }
8291   }
8292 
8293   return true;
8294 }
8295 
8296 bool
8297 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8298   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
8299          "lvalue compound literal in c++?");
8300   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
8301   // only see this when folding in C, so there's no standard to follow here.
8302   return Success(E);
8303 }
8304 
8305 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
8306   TypeInfoLValue TypeInfo;
8307 
8308   if (!E->isPotentiallyEvaluated()) {
8309     if (E->isTypeOperand())
8310       TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
8311     else
8312       TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
8313   } else {
8314     if (!Info.Ctx.getLangOpts().CPlusPlus20) {
8315       Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
8316         << E->getExprOperand()->getType()
8317         << E->getExprOperand()->getSourceRange();
8318     }
8319 
8320     if (!Visit(E->getExprOperand()))
8321       return false;
8322 
8323     Optional<DynamicType> DynType =
8324         ComputeDynamicType(Info, E, Result, AK_TypeId);
8325     if (!DynType)
8326       return false;
8327 
8328     TypeInfo =
8329         TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
8330   }
8331 
8332   return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
8333 }
8334 
8335 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
8336   return Success(E->getGuidDecl());
8337 }
8338 
8339 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
8340   // Handle static data members.
8341   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
8342     VisitIgnoredBaseExpression(E->getBase());
8343     return VisitVarDecl(E, VD);
8344   }
8345 
8346   // Handle static member functions.
8347   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
8348     if (MD->isStatic()) {
8349       VisitIgnoredBaseExpression(E->getBase());
8350       return Success(MD);
8351     }
8352   }
8353 
8354   // Handle non-static data members.
8355   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
8356 }
8357 
8358 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
8359   // FIXME: Deal with vectors as array subscript bases.
8360   if (E->getBase()->getType()->isVectorType())
8361     return Error(E);
8362 
8363   APSInt Index;
8364   bool Success = true;
8365 
8366   // C++17's rules require us to evaluate the LHS first, regardless of which
8367   // side is the base.
8368   for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
8369     if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
8370                                 : !EvaluateInteger(SubExpr, Index, Info)) {
8371       if (!Info.noteFailure())
8372         return false;
8373       Success = false;
8374     }
8375   }
8376 
8377   return Success &&
8378          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
8379 }
8380 
8381 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
8382   return evaluatePointer(E->getSubExpr(), Result);
8383 }
8384 
8385 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8386   if (!Visit(E->getSubExpr()))
8387     return false;
8388   // __real is a no-op on scalar lvalues.
8389   if (E->getSubExpr()->getType()->isAnyComplexType())
8390     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
8391   return true;
8392 }
8393 
8394 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8395   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
8396          "lvalue __imag__ on scalar?");
8397   if (!Visit(E->getSubExpr()))
8398     return false;
8399   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
8400   return true;
8401 }
8402 
8403 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
8404   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8405     return Error(UO);
8406 
8407   if (!this->Visit(UO->getSubExpr()))
8408     return false;
8409 
8410   return handleIncDec(
8411       this->Info, UO, Result, UO->getSubExpr()->getType(),
8412       UO->isIncrementOp(), nullptr);
8413 }
8414 
8415 bool LValueExprEvaluator::VisitCompoundAssignOperator(
8416     const CompoundAssignOperator *CAO) {
8417   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8418     return Error(CAO);
8419 
8420   bool Success = true;
8421 
8422   // C++17 onwards require that we evaluate the RHS first.
8423   APValue RHS;
8424   if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
8425     if (!Info.noteFailure())
8426       return false;
8427     Success = false;
8428   }
8429 
8430   // The overall lvalue result is the result of evaluating the LHS.
8431   if (!this->Visit(CAO->getLHS()) || !Success)
8432     return false;
8433 
8434   return handleCompoundAssignment(
8435       this->Info, CAO,
8436       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
8437       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
8438 }
8439 
8440 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
8441   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8442     return Error(E);
8443 
8444   bool Success = true;
8445 
8446   // C++17 onwards require that we evaluate the RHS first.
8447   APValue NewVal;
8448   if (!Evaluate(NewVal, this->Info, E->getRHS())) {
8449     if (!Info.noteFailure())
8450       return false;
8451     Success = false;
8452   }
8453 
8454   if (!this->Visit(E->getLHS()) || !Success)
8455     return false;
8456 
8457   if (Info.getLangOpts().CPlusPlus20 &&
8458       !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
8459     return false;
8460 
8461   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
8462                           NewVal);
8463 }
8464 
8465 //===----------------------------------------------------------------------===//
8466 // Pointer Evaluation
8467 //===----------------------------------------------------------------------===//
8468 
8469 /// Attempts to compute the number of bytes available at the pointer
8470 /// returned by a function with the alloc_size attribute. Returns true if we
8471 /// were successful. Places an unsigned number into `Result`.
8472 ///
8473 /// This expects the given CallExpr to be a call to a function with an
8474 /// alloc_size attribute.
8475 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8476                                             const CallExpr *Call,
8477                                             llvm::APInt &Result) {
8478   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
8479 
8480   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
8481   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
8482   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
8483   if (Call->getNumArgs() <= SizeArgNo)
8484     return false;
8485 
8486   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
8487     Expr::EvalResult ExprResult;
8488     if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
8489       return false;
8490     Into = ExprResult.Val.getInt();
8491     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
8492       return false;
8493     Into = Into.zextOrSelf(BitsInSizeT);
8494     return true;
8495   };
8496 
8497   APSInt SizeOfElem;
8498   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
8499     return false;
8500 
8501   if (!AllocSize->getNumElemsParam().isValid()) {
8502     Result = std::move(SizeOfElem);
8503     return true;
8504   }
8505 
8506   APSInt NumberOfElems;
8507   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
8508   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
8509     return false;
8510 
8511   bool Overflow;
8512   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
8513   if (Overflow)
8514     return false;
8515 
8516   Result = std::move(BytesAvailable);
8517   return true;
8518 }
8519 
8520 /// Convenience function. LVal's base must be a call to an alloc_size
8521 /// function.
8522 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8523                                             const LValue &LVal,
8524                                             llvm::APInt &Result) {
8525   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8526          "Can't get the size of a non alloc_size function");
8527   const auto *Base = LVal.getLValueBase().get<const Expr *>();
8528   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
8529   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
8530 }
8531 
8532 /// Attempts to evaluate the given LValueBase as the result of a call to
8533 /// a function with the alloc_size attribute. If it was possible to do so, this
8534 /// function will return true, make Result's Base point to said function call,
8535 /// and mark Result's Base as invalid.
8536 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
8537                                       LValue &Result) {
8538   if (Base.isNull())
8539     return false;
8540 
8541   // Because we do no form of static analysis, we only support const variables.
8542   //
8543   // Additionally, we can't support parameters, nor can we support static
8544   // variables (in the latter case, use-before-assign isn't UB; in the former,
8545   // we have no clue what they'll be assigned to).
8546   const auto *VD =
8547       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
8548   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
8549     return false;
8550 
8551   const Expr *Init = VD->getAnyInitializer();
8552   if (!Init)
8553     return false;
8554 
8555   const Expr *E = Init->IgnoreParens();
8556   if (!tryUnwrapAllocSizeCall(E))
8557     return false;
8558 
8559   // Store E instead of E unwrapped so that the type of the LValue's base is
8560   // what the user wanted.
8561   Result.setInvalid(E);
8562 
8563   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
8564   Result.addUnsizedArray(Info, E, Pointee);
8565   return true;
8566 }
8567 
8568 namespace {
8569 class PointerExprEvaluator
8570   : public ExprEvaluatorBase<PointerExprEvaluator> {
8571   LValue &Result;
8572   bool InvalidBaseOK;
8573 
8574   bool Success(const Expr *E) {
8575     Result.set(E);
8576     return true;
8577   }
8578 
8579   bool evaluateLValue(const Expr *E, LValue &Result) {
8580     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
8581   }
8582 
8583   bool evaluatePointer(const Expr *E, LValue &Result) {
8584     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
8585   }
8586 
8587   bool visitNonBuiltinCallExpr(const CallExpr *E);
8588 public:
8589 
8590   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
8591       : ExprEvaluatorBaseTy(info), Result(Result),
8592         InvalidBaseOK(InvalidBaseOK) {}
8593 
8594   bool Success(const APValue &V, const Expr *E) {
8595     Result.setFrom(Info.Ctx, V);
8596     return true;
8597   }
8598   bool ZeroInitialization(const Expr *E) {
8599     Result.setNull(Info.Ctx, E->getType());
8600     return true;
8601   }
8602 
8603   bool VisitBinaryOperator(const BinaryOperator *E);
8604   bool VisitCastExpr(const CastExpr* E);
8605   bool VisitUnaryAddrOf(const UnaryOperator *E);
8606   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
8607       { return Success(E); }
8608   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
8609     if (E->isExpressibleAsConstantInitializer())
8610       return Success(E);
8611     if (Info.noteFailure())
8612       EvaluateIgnoredValue(Info, E->getSubExpr());
8613     return Error(E);
8614   }
8615   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
8616       { return Success(E); }
8617   bool VisitCallExpr(const CallExpr *E);
8618   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
8619   bool VisitBlockExpr(const BlockExpr *E) {
8620     if (!E->getBlockDecl()->hasCaptures())
8621       return Success(E);
8622     return Error(E);
8623   }
8624   bool VisitCXXThisExpr(const CXXThisExpr *E) {
8625     // Can't look at 'this' when checking a potential constant expression.
8626     if (Info.checkingPotentialConstantExpression())
8627       return false;
8628     if (!Info.CurrentCall->This) {
8629       if (Info.getLangOpts().CPlusPlus11)
8630         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
8631       else
8632         Info.FFDiag(E);
8633       return false;
8634     }
8635     Result = *Info.CurrentCall->This;
8636     // If we are inside a lambda's call operator, the 'this' expression refers
8637     // to the enclosing '*this' object (either by value or reference) which is
8638     // either copied into the closure object's field that represents the '*this'
8639     // or refers to '*this'.
8640     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
8641       // Ensure we actually have captured 'this'. (an error will have
8642       // been previously reported if not).
8643       if (!Info.CurrentCall->LambdaThisCaptureField)
8644         return false;
8645 
8646       // Update 'Result' to refer to the data member/field of the closure object
8647       // that represents the '*this' capture.
8648       if (!HandleLValueMember(Info, E, Result,
8649                              Info.CurrentCall->LambdaThisCaptureField))
8650         return false;
8651       // If we captured '*this' by reference, replace the field with its referent.
8652       if (Info.CurrentCall->LambdaThisCaptureField->getType()
8653               ->isPointerType()) {
8654         APValue RVal;
8655         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
8656                                             RVal))
8657           return false;
8658 
8659         Result.setFrom(Info.Ctx, RVal);
8660       }
8661     }
8662     return true;
8663   }
8664 
8665   bool VisitCXXNewExpr(const CXXNewExpr *E);
8666 
8667   bool VisitSourceLocExpr(const SourceLocExpr *E) {
8668     assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
8669     APValue LValResult = E->EvaluateInContext(
8670         Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8671     Result.setFrom(Info.Ctx, LValResult);
8672     return true;
8673   }
8674 
8675   bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
8676     std::string ResultStr = E->ComputeName(Info.Ctx);
8677 
8678     Info.Ctx.SYCLUniqueStableNameEvaluatedValues[E] = ResultStr;
8679 
8680     QualType CharTy = Info.Ctx.CharTy.withConst();
8681     APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
8682                ResultStr.size() + 1);
8683     QualType ArrayTy = Info.Ctx.getConstantArrayType(CharTy, Size, nullptr,
8684                                                      ArrayType::Normal, 0);
8685 
8686     StringLiteral *SL =
8687         StringLiteral::Create(Info.Ctx, ResultStr, StringLiteral::Ascii,
8688                               /*Pascal*/ false, ArrayTy, E->getLocation());
8689 
8690     evaluateLValue(SL, Result);
8691     Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
8692     return true;
8693   }
8694 
8695   // FIXME: Missing: @protocol, @selector
8696 };
8697 } // end anonymous namespace
8698 
8699 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
8700                             bool InvalidBaseOK) {
8701   assert(!E->isValueDependent());
8702   assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
8703   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8704 }
8705 
8706 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8707   if (E->getOpcode() != BO_Add &&
8708       E->getOpcode() != BO_Sub)
8709     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8710 
8711   const Expr *PExp = E->getLHS();
8712   const Expr *IExp = E->getRHS();
8713   if (IExp->getType()->isPointerType())
8714     std::swap(PExp, IExp);
8715 
8716   bool EvalPtrOK = evaluatePointer(PExp, Result);
8717   if (!EvalPtrOK && !Info.noteFailure())
8718     return false;
8719 
8720   llvm::APSInt Offset;
8721   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
8722     return false;
8723 
8724   if (E->getOpcode() == BO_Sub)
8725     negateAsSigned(Offset);
8726 
8727   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
8728   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
8729 }
8730 
8731 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8732   return evaluateLValue(E->getSubExpr(), Result);
8733 }
8734 
8735 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8736   const Expr *SubExpr = E->getSubExpr();
8737 
8738   switch (E->getCastKind()) {
8739   default:
8740     break;
8741   case CK_BitCast:
8742   case CK_CPointerToObjCPointerCast:
8743   case CK_BlockPointerToObjCPointerCast:
8744   case CK_AnyPointerToBlockPointerCast:
8745   case CK_AddressSpaceConversion:
8746     if (!Visit(SubExpr))
8747       return false;
8748     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
8749     // permitted in constant expressions in C++11. Bitcasts from cv void* are
8750     // also static_casts, but we disallow them as a resolution to DR1312.
8751     if (!E->getType()->isVoidPointerType()) {
8752       if (!Result.InvalidBase && !Result.Designator.Invalid &&
8753           !Result.IsNullPtr &&
8754           Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
8755                                           E->getType()->getPointeeType()) &&
8756           Info.getStdAllocatorCaller("allocate")) {
8757         // Inside a call to std::allocator::allocate and friends, we permit
8758         // casting from void* back to cv1 T* for a pointer that points to a
8759         // cv2 T.
8760       } else {
8761         Result.Designator.setInvalid();
8762         if (SubExpr->getType()->isVoidPointerType())
8763           CCEDiag(E, diag::note_constexpr_invalid_cast)
8764             << 3 << SubExpr->getType();
8765         else
8766           CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8767       }
8768     }
8769     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
8770       ZeroInitialization(E);
8771     return true;
8772 
8773   case CK_DerivedToBase:
8774   case CK_UncheckedDerivedToBase:
8775     if (!evaluatePointer(E->getSubExpr(), Result))
8776       return false;
8777     if (!Result.Base && Result.Offset.isZero())
8778       return true;
8779 
8780     // Now figure out the necessary offset to add to the base LV to get from
8781     // the derived class to the base class.
8782     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
8783                                   castAs<PointerType>()->getPointeeType(),
8784                                 Result);
8785 
8786   case CK_BaseToDerived:
8787     if (!Visit(E->getSubExpr()))
8788       return false;
8789     if (!Result.Base && Result.Offset.isZero())
8790       return true;
8791     return HandleBaseToDerivedCast(Info, E, Result);
8792 
8793   case CK_Dynamic:
8794     if (!Visit(E->getSubExpr()))
8795       return false;
8796     return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8797 
8798   case CK_NullToPointer:
8799     VisitIgnoredValue(E->getSubExpr());
8800     return ZeroInitialization(E);
8801 
8802   case CK_IntegralToPointer: {
8803     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8804 
8805     APValue Value;
8806     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
8807       break;
8808 
8809     if (Value.isInt()) {
8810       unsigned Size = Info.Ctx.getTypeSize(E->getType());
8811       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
8812       Result.Base = (Expr*)nullptr;
8813       Result.InvalidBase = false;
8814       Result.Offset = CharUnits::fromQuantity(N);
8815       Result.Designator.setInvalid();
8816       Result.IsNullPtr = false;
8817       return true;
8818     } else {
8819       // Cast is of an lvalue, no need to change value.
8820       Result.setFrom(Info.Ctx, Value);
8821       return true;
8822     }
8823   }
8824 
8825   case CK_ArrayToPointerDecay: {
8826     if (SubExpr->isGLValue()) {
8827       if (!evaluateLValue(SubExpr, Result))
8828         return false;
8829     } else {
8830       APValue &Value = Info.CurrentCall->createTemporary(
8831           SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
8832       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
8833         return false;
8834     }
8835     // The result is a pointer to the first element of the array.
8836     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
8837     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
8838       Result.addArray(Info, E, CAT);
8839     else
8840       Result.addUnsizedArray(Info, E, AT->getElementType());
8841     return true;
8842   }
8843 
8844   case CK_FunctionToPointerDecay:
8845     return evaluateLValue(SubExpr, Result);
8846 
8847   case CK_LValueToRValue: {
8848     LValue LVal;
8849     if (!evaluateLValue(E->getSubExpr(), LVal))
8850       return false;
8851 
8852     APValue RVal;
8853     // Note, we use the subexpression's type in order to retain cv-qualifiers.
8854     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8855                                         LVal, RVal))
8856       return InvalidBaseOK &&
8857              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
8858     return Success(RVal, E);
8859   }
8860   }
8861 
8862   return ExprEvaluatorBaseTy::VisitCastExpr(E);
8863 }
8864 
8865 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
8866                                 UnaryExprOrTypeTrait ExprKind) {
8867   // C++ [expr.alignof]p3:
8868   //     When alignof is applied to a reference type, the result is the
8869   //     alignment of the referenced type.
8870   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
8871     T = Ref->getPointeeType();
8872 
8873   if (T.getQualifiers().hasUnaligned())
8874     return CharUnits::One();
8875 
8876   const bool AlignOfReturnsPreferred =
8877       Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
8878 
8879   // __alignof is defined to return the preferred alignment.
8880   // Before 8, clang returned the preferred alignment for alignof and _Alignof
8881   // as well.
8882   if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
8883     return Info.Ctx.toCharUnitsFromBits(
8884       Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
8885   // alignof and _Alignof are defined to return the ABI alignment.
8886   else if (ExprKind == UETT_AlignOf)
8887     return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
8888   else
8889     llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
8890 }
8891 
8892 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
8893                                 UnaryExprOrTypeTrait ExprKind) {
8894   E = E->IgnoreParens();
8895 
8896   // The kinds of expressions that we have special-case logic here for
8897   // should be kept up to date with the special checks for those
8898   // expressions in Sema.
8899 
8900   // alignof decl is always accepted, even if it doesn't make sense: we default
8901   // to 1 in those cases.
8902   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8903     return Info.Ctx.getDeclAlign(DRE->getDecl(),
8904                                  /*RefAsPointee*/true);
8905 
8906   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
8907     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
8908                                  /*RefAsPointee*/true);
8909 
8910   return GetAlignOfType(Info, E->getType(), ExprKind);
8911 }
8912 
8913 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
8914   if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
8915     return Info.Ctx.getDeclAlign(VD);
8916   if (const auto *E = Value.Base.dyn_cast<const Expr *>())
8917     return GetAlignOfExpr(Info, E, UETT_AlignOf);
8918   return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
8919 }
8920 
8921 /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
8922 /// __builtin_is_aligned and __builtin_assume_aligned.
8923 static bool getAlignmentArgument(const Expr *E, QualType ForType,
8924                                  EvalInfo &Info, APSInt &Alignment) {
8925   if (!EvaluateInteger(E, Alignment, Info))
8926     return false;
8927   if (Alignment < 0 || !Alignment.isPowerOf2()) {
8928     Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
8929     return false;
8930   }
8931   unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
8932   APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
8933   if (APSInt::compareValues(Alignment, MaxValue) > 0) {
8934     Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
8935         << MaxValue << ForType << Alignment;
8936     return false;
8937   }
8938   // Ensure both alignment and source value have the same bit width so that we
8939   // don't assert when computing the resulting value.
8940   APSInt ExtAlignment =
8941       APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
8942   assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
8943          "Alignment should not be changed by ext/trunc");
8944   Alignment = ExtAlignment;
8945   assert(Alignment.getBitWidth() == SrcWidth);
8946   return true;
8947 }
8948 
8949 // To be clear: this happily visits unsupported builtins. Better name welcomed.
8950 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
8951   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
8952     return true;
8953 
8954   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
8955     return false;
8956 
8957   Result.setInvalid(E);
8958   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
8959   Result.addUnsizedArray(Info, E, PointeeTy);
8960   return true;
8961 }
8962 
8963 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
8964   if (IsStringLiteralCall(E))
8965     return Success(E);
8966 
8967   if (unsigned BuiltinOp = E->getBuiltinCallee())
8968     return VisitBuiltinCallExpr(E, BuiltinOp);
8969 
8970   return visitNonBuiltinCallExpr(E);
8971 }
8972 
8973 // Determine if T is a character type for which we guarantee that
8974 // sizeof(T) == 1.
8975 static bool isOneByteCharacterType(QualType T) {
8976   return T->isCharType() || T->isChar8Type();
8977 }
8978 
8979 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8980                                                 unsigned BuiltinOp) {
8981   switch (BuiltinOp) {
8982   case Builtin::BI__builtin_addressof:
8983     return evaluateLValue(E->getArg(0), Result);
8984   case Builtin::BI__builtin_assume_aligned: {
8985     // We need to be very careful here because: if the pointer does not have the
8986     // asserted alignment, then the behavior is undefined, and undefined
8987     // behavior is non-constant.
8988     if (!evaluatePointer(E->getArg(0), Result))
8989       return false;
8990 
8991     LValue OffsetResult(Result);
8992     APSInt Alignment;
8993     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
8994                               Alignment))
8995       return false;
8996     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
8997 
8998     if (E->getNumArgs() > 2) {
8999       APSInt Offset;
9000       if (!EvaluateInteger(E->getArg(2), Offset, Info))
9001         return false;
9002 
9003       int64_t AdditionalOffset = -Offset.getZExtValue();
9004       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
9005     }
9006 
9007     // If there is a base object, then it must have the correct alignment.
9008     if (OffsetResult.Base) {
9009       CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
9010 
9011       if (BaseAlignment < Align) {
9012         Result.Designator.setInvalid();
9013         // FIXME: Add support to Diagnostic for long / long long.
9014         CCEDiag(E->getArg(0),
9015                 diag::note_constexpr_baa_insufficient_alignment) << 0
9016           << (unsigned)BaseAlignment.getQuantity()
9017           << (unsigned)Align.getQuantity();
9018         return false;
9019       }
9020     }
9021 
9022     // The offset must also have the correct alignment.
9023     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
9024       Result.Designator.setInvalid();
9025 
9026       (OffsetResult.Base
9027            ? CCEDiag(E->getArg(0),
9028                      diag::note_constexpr_baa_insufficient_alignment) << 1
9029            : CCEDiag(E->getArg(0),
9030                      diag::note_constexpr_baa_value_insufficient_alignment))
9031         << (int)OffsetResult.Offset.getQuantity()
9032         << (unsigned)Align.getQuantity();
9033       return false;
9034     }
9035 
9036     return true;
9037   }
9038   case Builtin::BI__builtin_align_up:
9039   case Builtin::BI__builtin_align_down: {
9040     if (!evaluatePointer(E->getArg(0), Result))
9041       return false;
9042     APSInt Alignment;
9043     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9044                               Alignment))
9045       return false;
9046     CharUnits BaseAlignment = getBaseAlignment(Info, Result);
9047     CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
9048     // For align_up/align_down, we can return the same value if the alignment
9049     // is known to be greater or equal to the requested value.
9050     if (PtrAlign.getQuantity() >= Alignment)
9051       return true;
9052 
9053     // The alignment could be greater than the minimum at run-time, so we cannot
9054     // infer much about the resulting pointer value. One case is possible:
9055     // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
9056     // can infer the correct index if the requested alignment is smaller than
9057     // the base alignment so we can perform the computation on the offset.
9058     if (BaseAlignment.getQuantity() >= Alignment) {
9059       assert(Alignment.getBitWidth() <= 64 &&
9060              "Cannot handle > 64-bit address-space");
9061       uint64_t Alignment64 = Alignment.getZExtValue();
9062       CharUnits NewOffset = CharUnits::fromQuantity(
9063           BuiltinOp == Builtin::BI__builtin_align_down
9064               ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
9065               : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
9066       Result.adjustOffset(NewOffset - Result.Offset);
9067       // TODO: diagnose out-of-bounds values/only allow for arrays?
9068       return true;
9069     }
9070     // Otherwise, we cannot constant-evaluate the result.
9071     Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
9072         << Alignment;
9073     return false;
9074   }
9075   case Builtin::BI__builtin_operator_new:
9076     return HandleOperatorNewCall(Info, E, Result);
9077   case Builtin::BI__builtin_launder:
9078     return evaluatePointer(E->getArg(0), Result);
9079   case Builtin::BIstrchr:
9080   case Builtin::BIwcschr:
9081   case Builtin::BImemchr:
9082   case Builtin::BIwmemchr:
9083     if (Info.getLangOpts().CPlusPlus11)
9084       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9085         << /*isConstexpr*/0 << /*isConstructor*/0
9086         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9087     else
9088       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9089     LLVM_FALLTHROUGH;
9090   case Builtin::BI__builtin_strchr:
9091   case Builtin::BI__builtin_wcschr:
9092   case Builtin::BI__builtin_memchr:
9093   case Builtin::BI__builtin_char_memchr:
9094   case Builtin::BI__builtin_wmemchr: {
9095     if (!Visit(E->getArg(0)))
9096       return false;
9097     APSInt Desired;
9098     if (!EvaluateInteger(E->getArg(1), Desired, Info))
9099       return false;
9100     uint64_t MaxLength = uint64_t(-1);
9101     if (BuiltinOp != Builtin::BIstrchr &&
9102         BuiltinOp != Builtin::BIwcschr &&
9103         BuiltinOp != Builtin::BI__builtin_strchr &&
9104         BuiltinOp != Builtin::BI__builtin_wcschr) {
9105       APSInt N;
9106       if (!EvaluateInteger(E->getArg(2), N, Info))
9107         return false;
9108       MaxLength = N.getExtValue();
9109     }
9110     // We cannot find the value if there are no candidates to match against.
9111     if (MaxLength == 0u)
9112       return ZeroInitialization(E);
9113     if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9114         Result.Designator.Invalid)
9115       return false;
9116     QualType CharTy = Result.Designator.getType(Info.Ctx);
9117     bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
9118                      BuiltinOp == Builtin::BI__builtin_memchr;
9119     assert(IsRawByte ||
9120            Info.Ctx.hasSameUnqualifiedType(
9121                CharTy, E->getArg(0)->getType()->getPointeeType()));
9122     // Pointers to const void may point to objects of incomplete type.
9123     if (IsRawByte && CharTy->isIncompleteType()) {
9124       Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
9125       return false;
9126     }
9127     // Give up on byte-oriented matching against multibyte elements.
9128     // FIXME: We can compare the bytes in the correct order.
9129     if (IsRawByte && !isOneByteCharacterType(CharTy)) {
9130       Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
9131           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
9132           << CharTy;
9133       return false;
9134     }
9135     // Figure out what value we're actually looking for (after converting to
9136     // the corresponding unsigned type if necessary).
9137     uint64_t DesiredVal;
9138     bool StopAtNull = false;
9139     switch (BuiltinOp) {
9140     case Builtin::BIstrchr:
9141     case Builtin::BI__builtin_strchr:
9142       // strchr compares directly to the passed integer, and therefore
9143       // always fails if given an int that is not a char.
9144       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
9145                                                   E->getArg(1)->getType(),
9146                                                   Desired),
9147                                Desired))
9148         return ZeroInitialization(E);
9149       StopAtNull = true;
9150       LLVM_FALLTHROUGH;
9151     case Builtin::BImemchr:
9152     case Builtin::BI__builtin_memchr:
9153     case Builtin::BI__builtin_char_memchr:
9154       // memchr compares by converting both sides to unsigned char. That's also
9155       // correct for strchr if we get this far (to cope with plain char being
9156       // unsigned in the strchr case).
9157       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
9158       break;
9159 
9160     case Builtin::BIwcschr:
9161     case Builtin::BI__builtin_wcschr:
9162       StopAtNull = true;
9163       LLVM_FALLTHROUGH;
9164     case Builtin::BIwmemchr:
9165     case Builtin::BI__builtin_wmemchr:
9166       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
9167       DesiredVal = Desired.getZExtValue();
9168       break;
9169     }
9170 
9171     for (; MaxLength; --MaxLength) {
9172       APValue Char;
9173       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
9174           !Char.isInt())
9175         return false;
9176       if (Char.getInt().getZExtValue() == DesiredVal)
9177         return true;
9178       if (StopAtNull && !Char.getInt())
9179         break;
9180       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
9181         return false;
9182     }
9183     // Not found: return nullptr.
9184     return ZeroInitialization(E);
9185   }
9186 
9187   case Builtin::BImemcpy:
9188   case Builtin::BImemmove:
9189   case Builtin::BIwmemcpy:
9190   case Builtin::BIwmemmove:
9191     if (Info.getLangOpts().CPlusPlus11)
9192       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9193         << /*isConstexpr*/0 << /*isConstructor*/0
9194         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9195     else
9196       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9197     LLVM_FALLTHROUGH;
9198   case Builtin::BI__builtin_memcpy:
9199   case Builtin::BI__builtin_memmove:
9200   case Builtin::BI__builtin_wmemcpy:
9201   case Builtin::BI__builtin_wmemmove: {
9202     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
9203                  BuiltinOp == Builtin::BIwmemmove ||
9204                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
9205                  BuiltinOp == Builtin::BI__builtin_wmemmove;
9206     bool Move = BuiltinOp == Builtin::BImemmove ||
9207                 BuiltinOp == Builtin::BIwmemmove ||
9208                 BuiltinOp == Builtin::BI__builtin_memmove ||
9209                 BuiltinOp == Builtin::BI__builtin_wmemmove;
9210 
9211     // The result of mem* is the first argument.
9212     if (!Visit(E->getArg(0)))
9213       return false;
9214     LValue Dest = Result;
9215 
9216     LValue Src;
9217     if (!EvaluatePointer(E->getArg(1), Src, Info))
9218       return false;
9219 
9220     APSInt N;
9221     if (!EvaluateInteger(E->getArg(2), N, Info))
9222       return false;
9223     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
9224 
9225     // If the size is zero, we treat this as always being a valid no-op.
9226     // (Even if one of the src and dest pointers is null.)
9227     if (!N)
9228       return true;
9229 
9230     // Otherwise, if either of the operands is null, we can't proceed. Don't
9231     // try to determine the type of the copied objects, because there aren't
9232     // any.
9233     if (!Src.Base || !Dest.Base) {
9234       APValue Val;
9235       (!Src.Base ? Src : Dest).moveInto(Val);
9236       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
9237           << Move << WChar << !!Src.Base
9238           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
9239       return false;
9240     }
9241     if (Src.Designator.Invalid || Dest.Designator.Invalid)
9242       return false;
9243 
9244     // We require that Src and Dest are both pointers to arrays of
9245     // trivially-copyable type. (For the wide version, the designator will be
9246     // invalid if the designated object is not a wchar_t.)
9247     QualType T = Dest.Designator.getType(Info.Ctx);
9248     QualType SrcT = Src.Designator.getType(Info.Ctx);
9249     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
9250       // FIXME: Consider using our bit_cast implementation to support this.
9251       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
9252       return false;
9253     }
9254     if (T->isIncompleteType()) {
9255       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
9256       return false;
9257     }
9258     if (!T.isTriviallyCopyableType(Info.Ctx)) {
9259       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
9260       return false;
9261     }
9262 
9263     // Figure out how many T's we're copying.
9264     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
9265     if (!WChar) {
9266       uint64_t Remainder;
9267       llvm::APInt OrigN = N;
9268       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
9269       if (Remainder) {
9270         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9271             << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
9272             << (unsigned)TSize;
9273         return false;
9274       }
9275     }
9276 
9277     // Check that the copying will remain within the arrays, just so that we
9278     // can give a more meaningful diagnostic. This implicitly also checks that
9279     // N fits into 64 bits.
9280     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
9281     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
9282     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
9283       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9284           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
9285           << toString(N, 10, /*Signed*/false);
9286       return false;
9287     }
9288     uint64_t NElems = N.getZExtValue();
9289     uint64_t NBytes = NElems * TSize;
9290 
9291     // Check for overlap.
9292     int Direction = 1;
9293     if (HasSameBase(Src, Dest)) {
9294       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
9295       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
9296       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
9297         // Dest is inside the source region.
9298         if (!Move) {
9299           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9300           return false;
9301         }
9302         // For memmove and friends, copy backwards.
9303         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
9304             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
9305           return false;
9306         Direction = -1;
9307       } else if (!Move && SrcOffset >= DestOffset &&
9308                  SrcOffset - DestOffset < NBytes) {
9309         // Src is inside the destination region for memcpy: invalid.
9310         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9311         return false;
9312       }
9313     }
9314 
9315     while (true) {
9316       APValue Val;
9317       // FIXME: Set WantObjectRepresentation to true if we're copying a
9318       // char-like type?
9319       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
9320           !handleAssignment(Info, E, Dest, T, Val))
9321         return false;
9322       // Do not iterate past the last element; if we're copying backwards, that
9323       // might take us off the start of the array.
9324       if (--NElems == 0)
9325         return true;
9326       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
9327           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
9328         return false;
9329     }
9330   }
9331 
9332   default:
9333     break;
9334   }
9335 
9336   return visitNonBuiltinCallExpr(E);
9337 }
9338 
9339 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9340                                      APValue &Result, const InitListExpr *ILE,
9341                                      QualType AllocType);
9342 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
9343                                           APValue &Result,
9344                                           const CXXConstructExpr *CCE,
9345                                           QualType AllocType);
9346 
9347 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
9348   if (!Info.getLangOpts().CPlusPlus20)
9349     Info.CCEDiag(E, diag::note_constexpr_new);
9350 
9351   // We cannot speculatively evaluate a delete expression.
9352   if (Info.SpeculativeEvaluationDepth)
9353     return false;
9354 
9355   FunctionDecl *OperatorNew = E->getOperatorNew();
9356 
9357   bool IsNothrow = false;
9358   bool IsPlacement = false;
9359   if (OperatorNew->isReservedGlobalPlacementOperator() &&
9360       Info.CurrentCall->isStdFunction() && !E->isArray()) {
9361     // FIXME Support array placement new.
9362     assert(E->getNumPlacementArgs() == 1);
9363     if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
9364       return false;
9365     if (Result.Designator.Invalid)
9366       return false;
9367     IsPlacement = true;
9368   } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
9369     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
9370         << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
9371     return false;
9372   } else if (E->getNumPlacementArgs()) {
9373     // The only new-placement list we support is of the form (std::nothrow).
9374     //
9375     // FIXME: There is no restriction on this, but it's not clear that any
9376     // other form makes any sense. We get here for cases such as:
9377     //
9378     //   new (std::align_val_t{N}) X(int)
9379     //
9380     // (which should presumably be valid only if N is a multiple of
9381     // alignof(int), and in any case can't be deallocated unless N is
9382     // alignof(X) and X has new-extended alignment).
9383     if (E->getNumPlacementArgs() != 1 ||
9384         !E->getPlacementArg(0)->getType()->isNothrowT())
9385       return Error(E, diag::note_constexpr_new_placement);
9386 
9387     LValue Nothrow;
9388     if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
9389       return false;
9390     IsNothrow = true;
9391   }
9392 
9393   const Expr *Init = E->getInitializer();
9394   const InitListExpr *ResizedArrayILE = nullptr;
9395   const CXXConstructExpr *ResizedArrayCCE = nullptr;
9396   bool ValueInit = false;
9397 
9398   QualType AllocType = E->getAllocatedType();
9399   if (Optional<const Expr*> ArraySize = E->getArraySize()) {
9400     const Expr *Stripped = *ArraySize;
9401     for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
9402          Stripped = ICE->getSubExpr())
9403       if (ICE->getCastKind() != CK_NoOp &&
9404           ICE->getCastKind() != CK_IntegralCast)
9405         break;
9406 
9407     llvm::APSInt ArrayBound;
9408     if (!EvaluateInteger(Stripped, ArrayBound, Info))
9409       return false;
9410 
9411     // C++ [expr.new]p9:
9412     //   The expression is erroneous if:
9413     //   -- [...] its value before converting to size_t [or] applying the
9414     //      second standard conversion sequence is less than zero
9415     if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
9416       if (IsNothrow)
9417         return ZeroInitialization(E);
9418 
9419       Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
9420           << ArrayBound << (*ArraySize)->getSourceRange();
9421       return false;
9422     }
9423 
9424     //   -- its value is such that the size of the allocated object would
9425     //      exceed the implementation-defined limit
9426     if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
9427                                                 ArrayBound) >
9428         ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
9429       if (IsNothrow)
9430         return ZeroInitialization(E);
9431 
9432       Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
9433         << ArrayBound << (*ArraySize)->getSourceRange();
9434       return false;
9435     }
9436 
9437     //   -- the new-initializer is a braced-init-list and the number of
9438     //      array elements for which initializers are provided [...]
9439     //      exceeds the number of elements to initialize
9440     if (!Init) {
9441       // No initialization is performed.
9442     } else if (isa<CXXScalarValueInitExpr>(Init) ||
9443                isa<ImplicitValueInitExpr>(Init)) {
9444       ValueInit = true;
9445     } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
9446       ResizedArrayCCE = CCE;
9447     } else {
9448       auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
9449       assert(CAT && "unexpected type for array initializer");
9450 
9451       unsigned Bits =
9452           std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
9453       llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits);
9454       llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits);
9455       if (InitBound.ugt(AllocBound)) {
9456         if (IsNothrow)
9457           return ZeroInitialization(E);
9458 
9459         Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
9460             << toString(AllocBound, 10, /*Signed=*/false)
9461             << toString(InitBound, 10, /*Signed=*/false)
9462             << (*ArraySize)->getSourceRange();
9463         return false;
9464       }
9465 
9466       // If the sizes differ, we must have an initializer list, and we need
9467       // special handling for this case when we initialize.
9468       if (InitBound != AllocBound)
9469         ResizedArrayILE = cast<InitListExpr>(Init);
9470     }
9471 
9472     AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
9473                                               ArrayType::Normal, 0);
9474   } else {
9475     assert(!AllocType->isArrayType() &&
9476            "array allocation with non-array new");
9477   }
9478 
9479   APValue *Val;
9480   if (IsPlacement) {
9481     AccessKinds AK = AK_Construct;
9482     struct FindObjectHandler {
9483       EvalInfo &Info;
9484       const Expr *E;
9485       QualType AllocType;
9486       const AccessKinds AccessKind;
9487       APValue *Value;
9488 
9489       typedef bool result_type;
9490       bool failed() { return false; }
9491       bool found(APValue &Subobj, QualType SubobjType) {
9492         // FIXME: Reject the cases where [basic.life]p8 would not permit the
9493         // old name of the object to be used to name the new object.
9494         if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
9495           Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
9496             SubobjType << AllocType;
9497           return false;
9498         }
9499         Value = &Subobj;
9500         return true;
9501       }
9502       bool found(APSInt &Value, QualType SubobjType) {
9503         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9504         return false;
9505       }
9506       bool found(APFloat &Value, QualType SubobjType) {
9507         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9508         return false;
9509       }
9510     } Handler = {Info, E, AllocType, AK, nullptr};
9511 
9512     CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
9513     if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
9514       return false;
9515 
9516     Val = Handler.Value;
9517 
9518     // [basic.life]p1:
9519     //   The lifetime of an object o of type T ends when [...] the storage
9520     //   which the object occupies is [...] reused by an object that is not
9521     //   nested within o (6.6.2).
9522     *Val = APValue();
9523   } else {
9524     // Perform the allocation and obtain a pointer to the resulting object.
9525     Val = Info.createHeapAlloc(E, AllocType, Result);
9526     if (!Val)
9527       return false;
9528   }
9529 
9530   if (ValueInit) {
9531     ImplicitValueInitExpr VIE(AllocType);
9532     if (!EvaluateInPlace(*Val, Info, Result, &VIE))
9533       return false;
9534   } else if (ResizedArrayILE) {
9535     if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
9536                                   AllocType))
9537       return false;
9538   } else if (ResizedArrayCCE) {
9539     if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
9540                                        AllocType))
9541       return false;
9542   } else if (Init) {
9543     if (!EvaluateInPlace(*Val, Info, Result, Init))
9544       return false;
9545   } else if (!getDefaultInitValue(AllocType, *Val)) {
9546     return false;
9547   }
9548 
9549   // Array new returns a pointer to the first element, not a pointer to the
9550   // array.
9551   if (auto *AT = AllocType->getAsArrayTypeUnsafe())
9552     Result.addArray(Info, E, cast<ConstantArrayType>(AT));
9553 
9554   return true;
9555 }
9556 //===----------------------------------------------------------------------===//
9557 // Member Pointer Evaluation
9558 //===----------------------------------------------------------------------===//
9559 
9560 namespace {
9561 class MemberPointerExprEvaluator
9562   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
9563   MemberPtr &Result;
9564 
9565   bool Success(const ValueDecl *D) {
9566     Result = MemberPtr(D);
9567     return true;
9568   }
9569 public:
9570 
9571   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
9572     : ExprEvaluatorBaseTy(Info), Result(Result) {}
9573 
9574   bool Success(const APValue &V, const Expr *E) {
9575     Result.setFrom(V);
9576     return true;
9577   }
9578   bool ZeroInitialization(const Expr *E) {
9579     return Success((const ValueDecl*)nullptr);
9580   }
9581 
9582   bool VisitCastExpr(const CastExpr *E);
9583   bool VisitUnaryAddrOf(const UnaryOperator *E);
9584 };
9585 } // end anonymous namespace
9586 
9587 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
9588                                   EvalInfo &Info) {
9589   assert(!E->isValueDependent());
9590   assert(E->isPRValue() && E->getType()->isMemberPointerType());
9591   return MemberPointerExprEvaluator(Info, Result).Visit(E);
9592 }
9593 
9594 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9595   switch (E->getCastKind()) {
9596   default:
9597     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9598 
9599   case CK_NullToMemberPointer:
9600     VisitIgnoredValue(E->getSubExpr());
9601     return ZeroInitialization(E);
9602 
9603   case CK_BaseToDerivedMemberPointer: {
9604     if (!Visit(E->getSubExpr()))
9605       return false;
9606     if (E->path_empty())
9607       return true;
9608     // Base-to-derived member pointer casts store the path in derived-to-base
9609     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
9610     // the wrong end of the derived->base arc, so stagger the path by one class.
9611     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
9612     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
9613          PathI != PathE; ++PathI) {
9614       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9615       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
9616       if (!Result.castToDerived(Derived))
9617         return Error(E);
9618     }
9619     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
9620     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
9621       return Error(E);
9622     return true;
9623   }
9624 
9625   case CK_DerivedToBaseMemberPointer:
9626     if (!Visit(E->getSubExpr()))
9627       return false;
9628     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9629          PathE = E->path_end(); PathI != PathE; ++PathI) {
9630       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9631       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9632       if (!Result.castToBase(Base))
9633         return Error(E);
9634     }
9635     return true;
9636   }
9637 }
9638 
9639 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9640   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
9641   // member can be formed.
9642   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
9643 }
9644 
9645 //===----------------------------------------------------------------------===//
9646 // Record Evaluation
9647 //===----------------------------------------------------------------------===//
9648 
9649 namespace {
9650   class RecordExprEvaluator
9651   : public ExprEvaluatorBase<RecordExprEvaluator> {
9652     const LValue &This;
9653     APValue &Result;
9654   public:
9655 
9656     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
9657       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
9658 
9659     bool Success(const APValue &V, const Expr *E) {
9660       Result = V;
9661       return true;
9662     }
9663     bool ZeroInitialization(const Expr *E) {
9664       return ZeroInitialization(E, E->getType());
9665     }
9666     bool ZeroInitialization(const Expr *E, QualType T);
9667 
9668     bool VisitCallExpr(const CallExpr *E) {
9669       return handleCallExpr(E, Result, &This);
9670     }
9671     bool VisitCastExpr(const CastExpr *E);
9672     bool VisitInitListExpr(const InitListExpr *E);
9673     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9674       return VisitCXXConstructExpr(E, E->getType());
9675     }
9676     bool VisitLambdaExpr(const LambdaExpr *E);
9677     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
9678     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
9679     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
9680     bool VisitBinCmp(const BinaryOperator *E);
9681   };
9682 }
9683 
9684 /// Perform zero-initialization on an object of non-union class type.
9685 /// C++11 [dcl.init]p5:
9686 ///  To zero-initialize an object or reference of type T means:
9687 ///    [...]
9688 ///    -- if T is a (possibly cv-qualified) non-union class type,
9689 ///       each non-static data member and each base-class subobject is
9690 ///       zero-initialized
9691 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
9692                                           const RecordDecl *RD,
9693                                           const LValue &This, APValue &Result) {
9694   assert(!RD->isUnion() && "Expected non-union class type");
9695   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
9696   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
9697                    std::distance(RD->field_begin(), RD->field_end()));
9698 
9699   if (RD->isInvalidDecl()) return false;
9700   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9701 
9702   if (CD) {
9703     unsigned Index = 0;
9704     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
9705            End = CD->bases_end(); I != End; ++I, ++Index) {
9706       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
9707       LValue Subobject = This;
9708       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
9709         return false;
9710       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
9711                                          Result.getStructBase(Index)))
9712         return false;
9713     }
9714   }
9715 
9716   for (const auto *I : RD->fields()) {
9717     // -- if T is a reference type, no initialization is performed.
9718     if (I->isUnnamedBitfield() || I->getType()->isReferenceType())
9719       continue;
9720 
9721     LValue Subobject = This;
9722     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
9723       return false;
9724 
9725     ImplicitValueInitExpr VIE(I->getType());
9726     if (!EvaluateInPlace(
9727           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
9728       return false;
9729   }
9730 
9731   return true;
9732 }
9733 
9734 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
9735   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
9736   if (RD->isInvalidDecl()) return false;
9737   if (RD->isUnion()) {
9738     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
9739     // object's first non-static named data member is zero-initialized
9740     RecordDecl::field_iterator I = RD->field_begin();
9741     while (I != RD->field_end() && (*I)->isUnnamedBitfield())
9742       ++I;
9743     if (I == RD->field_end()) {
9744       Result = APValue((const FieldDecl*)nullptr);
9745       return true;
9746     }
9747 
9748     LValue Subobject = This;
9749     if (!HandleLValueMember(Info, E, Subobject, *I))
9750       return false;
9751     Result = APValue(*I);
9752     ImplicitValueInitExpr VIE(I->getType());
9753     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
9754   }
9755 
9756   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
9757     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
9758     return false;
9759   }
9760 
9761   return HandleClassZeroInitialization(Info, E, RD, This, Result);
9762 }
9763 
9764 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
9765   switch (E->getCastKind()) {
9766   default:
9767     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9768 
9769   case CK_ConstructorConversion:
9770     return Visit(E->getSubExpr());
9771 
9772   case CK_DerivedToBase:
9773   case CK_UncheckedDerivedToBase: {
9774     APValue DerivedObject;
9775     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
9776       return false;
9777     if (!DerivedObject.isStruct())
9778       return Error(E->getSubExpr());
9779 
9780     // Derived-to-base rvalue conversion: just slice off the derived part.
9781     APValue *Value = &DerivedObject;
9782     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
9783     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9784          PathE = E->path_end(); PathI != PathE; ++PathI) {
9785       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
9786       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9787       Value = &Value->getStructBase(getBaseIndex(RD, Base));
9788       RD = Base;
9789     }
9790     Result = *Value;
9791     return true;
9792   }
9793   }
9794 }
9795 
9796 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9797   if (E->isTransparent())
9798     return Visit(E->getInit(0));
9799 
9800   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
9801   if (RD->isInvalidDecl()) return false;
9802   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9803   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
9804 
9805   EvalInfo::EvaluatingConstructorRAII EvalObj(
9806       Info,
9807       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
9808       CXXRD && CXXRD->getNumBases());
9809 
9810   if (RD->isUnion()) {
9811     const FieldDecl *Field = E->getInitializedFieldInUnion();
9812     Result = APValue(Field);
9813     if (!Field)
9814       return true;
9815 
9816     // If the initializer list for a union does not contain any elements, the
9817     // first element of the union is value-initialized.
9818     // FIXME: The element should be initialized from an initializer list.
9819     //        Is this difference ever observable for initializer lists which
9820     //        we don't build?
9821     ImplicitValueInitExpr VIE(Field->getType());
9822     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
9823 
9824     LValue Subobject = This;
9825     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
9826       return false;
9827 
9828     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9829     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9830                                   isa<CXXDefaultInitExpr>(InitExpr));
9831 
9832     if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
9833       if (Field->isBitField())
9834         return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
9835                                      Field);
9836       return true;
9837     }
9838 
9839     return false;
9840   }
9841 
9842   if (!Result.hasValue())
9843     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
9844                      std::distance(RD->field_begin(), RD->field_end()));
9845   unsigned ElementNo = 0;
9846   bool Success = true;
9847 
9848   // Initialize base classes.
9849   if (CXXRD && CXXRD->getNumBases()) {
9850     for (const auto &Base : CXXRD->bases()) {
9851       assert(ElementNo < E->getNumInits() && "missing init for base class");
9852       const Expr *Init = E->getInit(ElementNo);
9853 
9854       LValue Subobject = This;
9855       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
9856         return false;
9857 
9858       APValue &FieldVal = Result.getStructBase(ElementNo);
9859       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
9860         if (!Info.noteFailure())
9861           return false;
9862         Success = false;
9863       }
9864       ++ElementNo;
9865     }
9866 
9867     EvalObj.finishedConstructingBases();
9868   }
9869 
9870   // Initialize members.
9871   for (const auto *Field : RD->fields()) {
9872     // Anonymous bit-fields are not considered members of the class for
9873     // purposes of aggregate initialization.
9874     if (Field->isUnnamedBitfield())
9875       continue;
9876 
9877     LValue Subobject = This;
9878 
9879     bool HaveInit = ElementNo < E->getNumInits();
9880 
9881     // FIXME: Diagnostics here should point to the end of the initializer
9882     // list, not the start.
9883     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
9884                             Subobject, Field, &Layout))
9885       return false;
9886 
9887     // Perform an implicit value-initialization for members beyond the end of
9888     // the initializer list.
9889     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
9890     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
9891 
9892     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9893     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9894                                   isa<CXXDefaultInitExpr>(Init));
9895 
9896     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9897     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
9898         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
9899                                                        FieldVal, Field))) {
9900       if (!Info.noteFailure())
9901         return false;
9902       Success = false;
9903     }
9904   }
9905 
9906   EvalObj.finishedConstructingFields();
9907 
9908   return Success;
9909 }
9910 
9911 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
9912                                                 QualType T) {
9913   // Note that E's type is not necessarily the type of our class here; we might
9914   // be initializing an array element instead.
9915   const CXXConstructorDecl *FD = E->getConstructor();
9916   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
9917 
9918   bool ZeroInit = E->requiresZeroInitialization();
9919   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
9920     // If we've already performed zero-initialization, we're already done.
9921     if (Result.hasValue())
9922       return true;
9923 
9924     if (ZeroInit)
9925       return ZeroInitialization(E, T);
9926 
9927     return getDefaultInitValue(T, Result);
9928   }
9929 
9930   const FunctionDecl *Definition = nullptr;
9931   auto Body = FD->getBody(Definition);
9932 
9933   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9934     return false;
9935 
9936   // Avoid materializing a temporary for an elidable copy/move constructor.
9937   if (E->isElidable() && !ZeroInit) {
9938     // FIXME: This only handles the simplest case, where the source object
9939     //        is passed directly as the first argument to the constructor.
9940     //        This should also handle stepping though implicit casts and
9941     //        and conversion sequences which involve two steps, with a
9942     //        conversion operator followed by a converting constructor.
9943     const Expr *SrcObj = E->getArg(0);
9944     assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
9945     assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
9946     if (const MaterializeTemporaryExpr *ME =
9947             dyn_cast<MaterializeTemporaryExpr>(SrcObj))
9948       return Visit(ME->getSubExpr());
9949   }
9950 
9951   if (ZeroInit && !ZeroInitialization(E, T))
9952     return false;
9953 
9954   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
9955   return HandleConstructorCall(E, This, Args,
9956                                cast<CXXConstructorDecl>(Definition), Info,
9957                                Result);
9958 }
9959 
9960 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
9961     const CXXInheritedCtorInitExpr *E) {
9962   if (!Info.CurrentCall) {
9963     assert(Info.checkingPotentialConstantExpression());
9964     return false;
9965   }
9966 
9967   const CXXConstructorDecl *FD = E->getConstructor();
9968   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
9969     return false;
9970 
9971   const FunctionDecl *Definition = nullptr;
9972   auto Body = FD->getBody(Definition);
9973 
9974   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9975     return false;
9976 
9977   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
9978                                cast<CXXConstructorDecl>(Definition), Info,
9979                                Result);
9980 }
9981 
9982 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
9983     const CXXStdInitializerListExpr *E) {
9984   const ConstantArrayType *ArrayType =
9985       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
9986 
9987   LValue Array;
9988   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
9989     return false;
9990 
9991   // Get a pointer to the first element of the array.
9992   Array.addArray(Info, E, ArrayType);
9993 
9994   auto InvalidType = [&] {
9995     Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
9996       << E->getType();
9997     return false;
9998   };
9999 
10000   // FIXME: Perform the checks on the field types in SemaInit.
10001   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
10002   RecordDecl::field_iterator Field = Record->field_begin();
10003   if (Field == Record->field_end())
10004     return InvalidType();
10005 
10006   // Start pointer.
10007   if (!Field->getType()->isPointerType() ||
10008       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10009                             ArrayType->getElementType()))
10010     return InvalidType();
10011 
10012   // FIXME: What if the initializer_list type has base classes, etc?
10013   Result = APValue(APValue::UninitStruct(), 0, 2);
10014   Array.moveInto(Result.getStructField(0));
10015 
10016   if (++Field == Record->field_end())
10017     return InvalidType();
10018 
10019   if (Field->getType()->isPointerType() &&
10020       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10021                            ArrayType->getElementType())) {
10022     // End pointer.
10023     if (!HandleLValueArrayAdjustment(Info, E, Array,
10024                                      ArrayType->getElementType(),
10025                                      ArrayType->getSize().getZExtValue()))
10026       return false;
10027     Array.moveInto(Result.getStructField(1));
10028   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
10029     // Length.
10030     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
10031   else
10032     return InvalidType();
10033 
10034   if (++Field != Record->field_end())
10035     return InvalidType();
10036 
10037   return true;
10038 }
10039 
10040 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
10041   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
10042   if (ClosureClass->isInvalidDecl())
10043     return false;
10044 
10045   const size_t NumFields =
10046       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
10047 
10048   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
10049                                             E->capture_init_end()) &&
10050          "The number of lambda capture initializers should equal the number of "
10051          "fields within the closure type");
10052 
10053   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
10054   // Iterate through all the lambda's closure object's fields and initialize
10055   // them.
10056   auto *CaptureInitIt = E->capture_init_begin();
10057   const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
10058   bool Success = true;
10059   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
10060   for (const auto *Field : ClosureClass->fields()) {
10061     assert(CaptureInitIt != E->capture_init_end());
10062     // Get the initializer for this field
10063     Expr *const CurFieldInit = *CaptureInitIt++;
10064 
10065     // If there is no initializer, either this is a VLA or an error has
10066     // occurred.
10067     if (!CurFieldInit)
10068       return Error(E);
10069 
10070     LValue Subobject = This;
10071 
10072     if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
10073       return false;
10074 
10075     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10076     if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
10077       if (!Info.keepEvaluatingAfterFailure())
10078         return false;
10079       Success = false;
10080     }
10081     ++CaptureIt;
10082   }
10083   return Success;
10084 }
10085 
10086 static bool EvaluateRecord(const Expr *E, const LValue &This,
10087                            APValue &Result, EvalInfo &Info) {
10088   assert(!E->isValueDependent());
10089   assert(E->isPRValue() && E->getType()->isRecordType() &&
10090          "can't evaluate expression as a record rvalue");
10091   return RecordExprEvaluator(Info, This, Result).Visit(E);
10092 }
10093 
10094 //===----------------------------------------------------------------------===//
10095 // Temporary Evaluation
10096 //
10097 // Temporaries are represented in the AST as rvalues, but generally behave like
10098 // lvalues. The full-object of which the temporary is a subobject is implicitly
10099 // materialized so that a reference can bind to it.
10100 //===----------------------------------------------------------------------===//
10101 namespace {
10102 class TemporaryExprEvaluator
10103   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
10104 public:
10105   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
10106     LValueExprEvaluatorBaseTy(Info, Result, false) {}
10107 
10108   /// Visit an expression which constructs the value of this temporary.
10109   bool VisitConstructExpr(const Expr *E) {
10110     APValue &Value = Info.CurrentCall->createTemporary(
10111         E, E->getType(), ScopeKind::FullExpression, Result);
10112     return EvaluateInPlace(Value, Info, Result, E);
10113   }
10114 
10115   bool VisitCastExpr(const CastExpr *E) {
10116     switch (E->getCastKind()) {
10117     default:
10118       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
10119 
10120     case CK_ConstructorConversion:
10121       return VisitConstructExpr(E->getSubExpr());
10122     }
10123   }
10124   bool VisitInitListExpr(const InitListExpr *E) {
10125     return VisitConstructExpr(E);
10126   }
10127   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10128     return VisitConstructExpr(E);
10129   }
10130   bool VisitCallExpr(const CallExpr *E) {
10131     return VisitConstructExpr(E);
10132   }
10133   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
10134     return VisitConstructExpr(E);
10135   }
10136   bool VisitLambdaExpr(const LambdaExpr *E) {
10137     return VisitConstructExpr(E);
10138   }
10139 };
10140 } // end anonymous namespace
10141 
10142 /// Evaluate an expression of record type as a temporary.
10143 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
10144   assert(!E->isValueDependent());
10145   assert(E->isPRValue() && E->getType()->isRecordType());
10146   return TemporaryExprEvaluator(Info, Result).Visit(E);
10147 }
10148 
10149 //===----------------------------------------------------------------------===//
10150 // Vector Evaluation
10151 //===----------------------------------------------------------------------===//
10152 
10153 namespace {
10154   class VectorExprEvaluator
10155   : public ExprEvaluatorBase<VectorExprEvaluator> {
10156     APValue &Result;
10157   public:
10158 
10159     VectorExprEvaluator(EvalInfo &info, APValue &Result)
10160       : ExprEvaluatorBaseTy(info), Result(Result) {}
10161 
10162     bool Success(ArrayRef<APValue> V, const Expr *E) {
10163       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
10164       // FIXME: remove this APValue copy.
10165       Result = APValue(V.data(), V.size());
10166       return true;
10167     }
10168     bool Success(const APValue &V, const Expr *E) {
10169       assert(V.isVector());
10170       Result = V;
10171       return true;
10172     }
10173     bool ZeroInitialization(const Expr *E);
10174 
10175     bool VisitUnaryReal(const UnaryOperator *E)
10176       { return Visit(E->getSubExpr()); }
10177     bool VisitCastExpr(const CastExpr* E);
10178     bool VisitInitListExpr(const InitListExpr *E);
10179     bool VisitUnaryImag(const UnaryOperator *E);
10180     bool VisitBinaryOperator(const BinaryOperator *E);
10181     // FIXME: Missing: unary -, unary ~, conditional operator (for GNU
10182     //                 conditional select), shufflevector, ExtVectorElementExpr
10183   };
10184 } // end anonymous namespace
10185 
10186 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
10187   assert(E->isPRValue() && E->getType()->isVectorType() &&
10188          "not a vector prvalue");
10189   return VectorExprEvaluator(Info, Result).Visit(E);
10190 }
10191 
10192 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
10193   const VectorType *VTy = E->getType()->castAs<VectorType>();
10194   unsigned NElts = VTy->getNumElements();
10195 
10196   const Expr *SE = E->getSubExpr();
10197   QualType SETy = SE->getType();
10198 
10199   switch (E->getCastKind()) {
10200   case CK_VectorSplat: {
10201     APValue Val = APValue();
10202     if (SETy->isIntegerType()) {
10203       APSInt IntResult;
10204       if (!EvaluateInteger(SE, IntResult, Info))
10205         return false;
10206       Val = APValue(std::move(IntResult));
10207     } else if (SETy->isRealFloatingType()) {
10208       APFloat FloatResult(0.0);
10209       if (!EvaluateFloat(SE, FloatResult, Info))
10210         return false;
10211       Val = APValue(std::move(FloatResult));
10212     } else {
10213       return Error(E);
10214     }
10215 
10216     // Splat and create vector APValue.
10217     SmallVector<APValue, 4> Elts(NElts, Val);
10218     return Success(Elts, E);
10219   }
10220   case CK_BitCast: {
10221     // Evaluate the operand into an APInt we can extract from.
10222     llvm::APInt SValInt;
10223     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
10224       return false;
10225     // Extract the elements
10226     QualType EltTy = VTy->getElementType();
10227     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
10228     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
10229     SmallVector<APValue, 4> Elts;
10230     if (EltTy->isRealFloatingType()) {
10231       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
10232       unsigned FloatEltSize = EltSize;
10233       if (&Sem == &APFloat::x87DoubleExtended())
10234         FloatEltSize = 80;
10235       for (unsigned i = 0; i < NElts; i++) {
10236         llvm::APInt Elt;
10237         if (BigEndian)
10238           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
10239         else
10240           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
10241         Elts.push_back(APValue(APFloat(Sem, Elt)));
10242       }
10243     } else if (EltTy->isIntegerType()) {
10244       for (unsigned i = 0; i < NElts; i++) {
10245         llvm::APInt Elt;
10246         if (BigEndian)
10247           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
10248         else
10249           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
10250         Elts.push_back(APValue(APSInt(Elt, !EltTy->isSignedIntegerType())));
10251       }
10252     } else {
10253       return Error(E);
10254     }
10255     return Success(Elts, E);
10256   }
10257   default:
10258     return ExprEvaluatorBaseTy::VisitCastExpr(E);
10259   }
10260 }
10261 
10262 bool
10263 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10264   const VectorType *VT = E->getType()->castAs<VectorType>();
10265   unsigned NumInits = E->getNumInits();
10266   unsigned NumElements = VT->getNumElements();
10267 
10268   QualType EltTy = VT->getElementType();
10269   SmallVector<APValue, 4> Elements;
10270 
10271   // The number of initializers can be less than the number of
10272   // vector elements. For OpenCL, this can be due to nested vector
10273   // initialization. For GCC compatibility, missing trailing elements
10274   // should be initialized with zeroes.
10275   unsigned CountInits = 0, CountElts = 0;
10276   while (CountElts < NumElements) {
10277     // Handle nested vector initialization.
10278     if (CountInits < NumInits
10279         && E->getInit(CountInits)->getType()->isVectorType()) {
10280       APValue v;
10281       if (!EvaluateVector(E->getInit(CountInits), v, Info))
10282         return Error(E);
10283       unsigned vlen = v.getVectorLength();
10284       for (unsigned j = 0; j < vlen; j++)
10285         Elements.push_back(v.getVectorElt(j));
10286       CountElts += vlen;
10287     } else if (EltTy->isIntegerType()) {
10288       llvm::APSInt sInt(32);
10289       if (CountInits < NumInits) {
10290         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
10291           return false;
10292       } else // trailing integer zero.
10293         sInt = Info.Ctx.MakeIntValue(0, EltTy);
10294       Elements.push_back(APValue(sInt));
10295       CountElts++;
10296     } else {
10297       llvm::APFloat f(0.0);
10298       if (CountInits < NumInits) {
10299         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
10300           return false;
10301       } else // trailing float zero.
10302         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
10303       Elements.push_back(APValue(f));
10304       CountElts++;
10305     }
10306     CountInits++;
10307   }
10308   return Success(Elements, E);
10309 }
10310 
10311 bool
10312 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
10313   const auto *VT = E->getType()->castAs<VectorType>();
10314   QualType EltTy = VT->getElementType();
10315   APValue ZeroElement;
10316   if (EltTy->isIntegerType())
10317     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
10318   else
10319     ZeroElement =
10320         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
10321 
10322   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
10323   return Success(Elements, E);
10324 }
10325 
10326 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
10327   VisitIgnoredValue(E->getSubExpr());
10328   return ZeroInitialization(E);
10329 }
10330 
10331 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10332   BinaryOperatorKind Op = E->getOpcode();
10333   assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
10334          "Operation not supported on vector types");
10335 
10336   if (Op == BO_Comma)
10337     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10338 
10339   Expr *LHS = E->getLHS();
10340   Expr *RHS = E->getRHS();
10341 
10342   assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
10343          "Must both be vector types");
10344   // Checking JUST the types are the same would be fine, except shifts don't
10345   // need to have their types be the same (since you always shift by an int).
10346   assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
10347              E->getType()->castAs<VectorType>()->getNumElements() &&
10348          RHS->getType()->castAs<VectorType>()->getNumElements() ==
10349              E->getType()->castAs<VectorType>()->getNumElements() &&
10350          "All operands must be the same size.");
10351 
10352   APValue LHSValue;
10353   APValue RHSValue;
10354   bool LHSOK = Evaluate(LHSValue, Info, LHS);
10355   if (!LHSOK && !Info.noteFailure())
10356     return false;
10357   if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
10358     return false;
10359 
10360   if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
10361     return false;
10362 
10363   return Success(LHSValue, E);
10364 }
10365 
10366 //===----------------------------------------------------------------------===//
10367 // Array Evaluation
10368 //===----------------------------------------------------------------------===//
10369 
10370 namespace {
10371   class ArrayExprEvaluator
10372   : public ExprEvaluatorBase<ArrayExprEvaluator> {
10373     const LValue &This;
10374     APValue &Result;
10375   public:
10376 
10377     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
10378       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
10379 
10380     bool Success(const APValue &V, const Expr *E) {
10381       assert(V.isArray() && "expected array");
10382       Result = V;
10383       return true;
10384     }
10385 
10386     bool ZeroInitialization(const Expr *E) {
10387       const ConstantArrayType *CAT =
10388           Info.Ctx.getAsConstantArrayType(E->getType());
10389       if (!CAT) {
10390         if (E->getType()->isIncompleteArrayType()) {
10391           // We can be asked to zero-initialize a flexible array member; this
10392           // is represented as an ImplicitValueInitExpr of incomplete array
10393           // type. In this case, the array has zero elements.
10394           Result = APValue(APValue::UninitArray(), 0, 0);
10395           return true;
10396         }
10397         // FIXME: We could handle VLAs here.
10398         return Error(E);
10399       }
10400 
10401       Result = APValue(APValue::UninitArray(), 0,
10402                        CAT->getSize().getZExtValue());
10403       if (!Result.hasArrayFiller())
10404         return true;
10405 
10406       // Zero-initialize all elements.
10407       LValue Subobject = This;
10408       Subobject.addArray(Info, E, CAT);
10409       ImplicitValueInitExpr VIE(CAT->getElementType());
10410       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
10411     }
10412 
10413     bool VisitCallExpr(const CallExpr *E) {
10414       return handleCallExpr(E, Result, &This);
10415     }
10416     bool VisitInitListExpr(const InitListExpr *E,
10417                            QualType AllocType = QualType());
10418     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
10419     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
10420     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
10421                                const LValue &Subobject,
10422                                APValue *Value, QualType Type);
10423     bool VisitStringLiteral(const StringLiteral *E,
10424                             QualType AllocType = QualType()) {
10425       expandStringLiteral(Info, E, Result, AllocType);
10426       return true;
10427     }
10428   };
10429 } // end anonymous namespace
10430 
10431 static bool EvaluateArray(const Expr *E, const LValue &This,
10432                           APValue &Result, EvalInfo &Info) {
10433   assert(!E->isValueDependent());
10434   assert(E->isPRValue() && E->getType()->isArrayType() &&
10435          "not an array prvalue");
10436   return ArrayExprEvaluator(Info, This, Result).Visit(E);
10437 }
10438 
10439 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10440                                      APValue &Result, const InitListExpr *ILE,
10441                                      QualType AllocType) {
10442   assert(!ILE->isValueDependent());
10443   assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
10444          "not an array prvalue");
10445   return ArrayExprEvaluator(Info, This, Result)
10446       .VisitInitListExpr(ILE, AllocType);
10447 }
10448 
10449 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10450                                           APValue &Result,
10451                                           const CXXConstructExpr *CCE,
10452                                           QualType AllocType) {
10453   assert(!CCE->isValueDependent());
10454   assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
10455          "not an array prvalue");
10456   return ArrayExprEvaluator(Info, This, Result)
10457       .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
10458 }
10459 
10460 // Return true iff the given array filler may depend on the element index.
10461 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
10462   // For now, just allow non-class value-initialization and initialization
10463   // lists comprised of them.
10464   if (isa<ImplicitValueInitExpr>(FillerExpr))
10465     return false;
10466   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
10467     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
10468       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
10469         return true;
10470     }
10471     return false;
10472   }
10473   return true;
10474 }
10475 
10476 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
10477                                            QualType AllocType) {
10478   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
10479       AllocType.isNull() ? E->getType() : AllocType);
10480   if (!CAT)
10481     return Error(E);
10482 
10483   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
10484   // an appropriately-typed string literal enclosed in braces.
10485   if (E->isStringLiteralInit()) {
10486     auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens());
10487     // FIXME: Support ObjCEncodeExpr here once we support it in
10488     // ArrayExprEvaluator generally.
10489     if (!SL)
10490       return Error(E);
10491     return VisitStringLiteral(SL, AllocType);
10492   }
10493 
10494   bool Success = true;
10495 
10496   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
10497          "zero-initialized array shouldn't have any initialized elts");
10498   APValue Filler;
10499   if (Result.isArray() && Result.hasArrayFiller())
10500     Filler = Result.getArrayFiller();
10501 
10502   unsigned NumEltsToInit = E->getNumInits();
10503   unsigned NumElts = CAT->getSize().getZExtValue();
10504   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
10505 
10506   // If the initializer might depend on the array index, run it for each
10507   // array element.
10508   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
10509     NumEltsToInit = NumElts;
10510 
10511   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
10512                           << NumEltsToInit << ".\n");
10513 
10514   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
10515 
10516   // If the array was previously zero-initialized, preserve the
10517   // zero-initialized values.
10518   if (Filler.hasValue()) {
10519     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
10520       Result.getArrayInitializedElt(I) = Filler;
10521     if (Result.hasArrayFiller())
10522       Result.getArrayFiller() = Filler;
10523   }
10524 
10525   LValue Subobject = This;
10526   Subobject.addArray(Info, E, CAT);
10527   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
10528     const Expr *Init =
10529         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
10530     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10531                          Info, Subobject, Init) ||
10532         !HandleLValueArrayAdjustment(Info, Init, Subobject,
10533                                      CAT->getElementType(), 1)) {
10534       if (!Info.noteFailure())
10535         return false;
10536       Success = false;
10537     }
10538   }
10539 
10540   if (!Result.hasArrayFiller())
10541     return Success;
10542 
10543   // If we get here, we have a trivial filler, which we can just evaluate
10544   // once and splat over the rest of the array elements.
10545   assert(FillerExpr && "no array filler for incomplete init list");
10546   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
10547                          FillerExpr) && Success;
10548 }
10549 
10550 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
10551   LValue CommonLV;
10552   if (E->getCommonExpr() &&
10553       !Evaluate(Info.CurrentCall->createTemporary(
10554                     E->getCommonExpr(),
10555                     getStorageType(Info.Ctx, E->getCommonExpr()),
10556                     ScopeKind::FullExpression, CommonLV),
10557                 Info, E->getCommonExpr()->getSourceExpr()))
10558     return false;
10559 
10560   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
10561 
10562   uint64_t Elements = CAT->getSize().getZExtValue();
10563   Result = APValue(APValue::UninitArray(), Elements, Elements);
10564 
10565   LValue Subobject = This;
10566   Subobject.addArray(Info, E, CAT);
10567 
10568   bool Success = true;
10569   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
10570     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10571                          Info, Subobject, E->getSubExpr()) ||
10572         !HandleLValueArrayAdjustment(Info, E, Subobject,
10573                                      CAT->getElementType(), 1)) {
10574       if (!Info.noteFailure())
10575         return false;
10576       Success = false;
10577     }
10578   }
10579 
10580   return Success;
10581 }
10582 
10583 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
10584   return VisitCXXConstructExpr(E, This, &Result, E->getType());
10585 }
10586 
10587 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10588                                                const LValue &Subobject,
10589                                                APValue *Value,
10590                                                QualType Type) {
10591   bool HadZeroInit = Value->hasValue();
10592 
10593   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
10594     unsigned N = CAT->getSize().getZExtValue();
10595 
10596     // Preserve the array filler if we had prior zero-initialization.
10597     APValue Filler =
10598       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
10599                                              : APValue();
10600 
10601     *Value = APValue(APValue::UninitArray(), N, N);
10602 
10603     if (HadZeroInit)
10604       for (unsigned I = 0; I != N; ++I)
10605         Value->getArrayInitializedElt(I) = Filler;
10606 
10607     // Initialize the elements.
10608     LValue ArrayElt = Subobject;
10609     ArrayElt.addArray(Info, E, CAT);
10610     for (unsigned I = 0; I != N; ++I)
10611       if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
10612                                  CAT->getElementType()) ||
10613           !HandleLValueArrayAdjustment(Info, E, ArrayElt,
10614                                        CAT->getElementType(), 1))
10615         return false;
10616 
10617     return true;
10618   }
10619 
10620   if (!Type->isRecordType())
10621     return Error(E);
10622 
10623   return RecordExprEvaluator(Info, Subobject, *Value)
10624              .VisitCXXConstructExpr(E, Type);
10625 }
10626 
10627 //===----------------------------------------------------------------------===//
10628 // Integer Evaluation
10629 //
10630 // As a GNU extension, we support casting pointers to sufficiently-wide integer
10631 // types and back in constant folding. Integer values are thus represented
10632 // either as an integer-valued APValue, or as an lvalue-valued APValue.
10633 //===----------------------------------------------------------------------===//
10634 
10635 namespace {
10636 class IntExprEvaluator
10637         : public ExprEvaluatorBase<IntExprEvaluator> {
10638   APValue &Result;
10639 public:
10640   IntExprEvaluator(EvalInfo &info, APValue &result)
10641       : ExprEvaluatorBaseTy(info), Result(result) {}
10642 
10643   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
10644     assert(E->getType()->isIntegralOrEnumerationType() &&
10645            "Invalid evaluation result.");
10646     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
10647            "Invalid evaluation result.");
10648     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10649            "Invalid evaluation result.");
10650     Result = APValue(SI);
10651     return true;
10652   }
10653   bool Success(const llvm::APSInt &SI, const Expr *E) {
10654     return Success(SI, E, Result);
10655   }
10656 
10657   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
10658     assert(E->getType()->isIntegralOrEnumerationType() &&
10659            "Invalid evaluation result.");
10660     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10661            "Invalid evaluation result.");
10662     Result = APValue(APSInt(I));
10663     Result.getInt().setIsUnsigned(
10664                             E->getType()->isUnsignedIntegerOrEnumerationType());
10665     return true;
10666   }
10667   bool Success(const llvm::APInt &I, const Expr *E) {
10668     return Success(I, E, Result);
10669   }
10670 
10671   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
10672     assert(E->getType()->isIntegralOrEnumerationType() &&
10673            "Invalid evaluation result.");
10674     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
10675     return true;
10676   }
10677   bool Success(uint64_t Value, const Expr *E) {
10678     return Success(Value, E, Result);
10679   }
10680 
10681   bool Success(CharUnits Size, const Expr *E) {
10682     return Success(Size.getQuantity(), E);
10683   }
10684 
10685   bool Success(const APValue &V, const Expr *E) {
10686     if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
10687       Result = V;
10688       return true;
10689     }
10690     return Success(V.getInt(), E);
10691   }
10692 
10693   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
10694 
10695   //===--------------------------------------------------------------------===//
10696   //                            Visitor Methods
10697   //===--------------------------------------------------------------------===//
10698 
10699   bool VisitIntegerLiteral(const IntegerLiteral *E) {
10700     return Success(E->getValue(), E);
10701   }
10702   bool VisitCharacterLiteral(const CharacterLiteral *E) {
10703     return Success(E->getValue(), E);
10704   }
10705 
10706   bool CheckReferencedDecl(const Expr *E, const Decl *D);
10707   bool VisitDeclRefExpr(const DeclRefExpr *E) {
10708     if (CheckReferencedDecl(E, E->getDecl()))
10709       return true;
10710 
10711     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
10712   }
10713   bool VisitMemberExpr(const MemberExpr *E) {
10714     if (CheckReferencedDecl(E, E->getMemberDecl())) {
10715       VisitIgnoredBaseExpression(E->getBase());
10716       return true;
10717     }
10718 
10719     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
10720   }
10721 
10722   bool VisitCallExpr(const CallExpr *E);
10723   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
10724   bool VisitBinaryOperator(const BinaryOperator *E);
10725   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
10726   bool VisitUnaryOperator(const UnaryOperator *E);
10727 
10728   bool VisitCastExpr(const CastExpr* E);
10729   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
10730 
10731   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
10732     return Success(E->getValue(), E);
10733   }
10734 
10735   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
10736     return Success(E->getValue(), E);
10737   }
10738 
10739   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
10740     if (Info.ArrayInitIndex == uint64_t(-1)) {
10741       // We were asked to evaluate this subexpression independent of the
10742       // enclosing ArrayInitLoopExpr. We can't do that.
10743       Info.FFDiag(E);
10744       return false;
10745     }
10746     return Success(Info.ArrayInitIndex, E);
10747   }
10748 
10749   // Note, GNU defines __null as an integer, not a pointer.
10750   bool VisitGNUNullExpr(const GNUNullExpr *E) {
10751     return ZeroInitialization(E);
10752   }
10753 
10754   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
10755     return Success(E->getValue(), E);
10756   }
10757 
10758   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
10759     return Success(E->getValue(), E);
10760   }
10761 
10762   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
10763     return Success(E->getValue(), E);
10764   }
10765 
10766   bool VisitUnaryReal(const UnaryOperator *E);
10767   bool VisitUnaryImag(const UnaryOperator *E);
10768 
10769   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
10770   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
10771   bool VisitSourceLocExpr(const SourceLocExpr *E);
10772   bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
10773   bool VisitRequiresExpr(const RequiresExpr *E);
10774   // FIXME: Missing: array subscript of vector, member of vector
10775 };
10776 
10777 class FixedPointExprEvaluator
10778     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
10779   APValue &Result;
10780 
10781  public:
10782   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
10783       : ExprEvaluatorBaseTy(info), Result(result) {}
10784 
10785   bool Success(const llvm::APInt &I, const Expr *E) {
10786     return Success(
10787         APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10788   }
10789 
10790   bool Success(uint64_t Value, const Expr *E) {
10791     return Success(
10792         APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10793   }
10794 
10795   bool Success(const APValue &V, const Expr *E) {
10796     return Success(V.getFixedPoint(), E);
10797   }
10798 
10799   bool Success(const APFixedPoint &V, const Expr *E) {
10800     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
10801     assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10802            "Invalid evaluation result.");
10803     Result = APValue(V);
10804     return true;
10805   }
10806 
10807   //===--------------------------------------------------------------------===//
10808   //                            Visitor Methods
10809   //===--------------------------------------------------------------------===//
10810 
10811   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
10812     return Success(E->getValue(), E);
10813   }
10814 
10815   bool VisitCastExpr(const CastExpr *E);
10816   bool VisitUnaryOperator(const UnaryOperator *E);
10817   bool VisitBinaryOperator(const BinaryOperator *E);
10818 };
10819 } // end anonymous namespace
10820 
10821 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
10822 /// produce either the integer value or a pointer.
10823 ///
10824 /// GCC has a heinous extension which folds casts between pointer types and
10825 /// pointer-sized integral types. We support this by allowing the evaluation of
10826 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
10827 /// Some simple arithmetic on such values is supported (they are treated much
10828 /// like char*).
10829 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
10830                                     EvalInfo &Info) {
10831   assert(!E->isValueDependent());
10832   assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
10833   return IntExprEvaluator(Info, Result).Visit(E);
10834 }
10835 
10836 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
10837   assert(!E->isValueDependent());
10838   APValue Val;
10839   if (!EvaluateIntegerOrLValue(E, Val, Info))
10840     return false;
10841   if (!Val.isInt()) {
10842     // FIXME: It would be better to produce the diagnostic for casting
10843     //        a pointer to an integer.
10844     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10845     return false;
10846   }
10847   Result = Val.getInt();
10848   return true;
10849 }
10850 
10851 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
10852   APValue Evaluated = E->EvaluateInContext(
10853       Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
10854   return Success(Evaluated, E);
10855 }
10856 
10857 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
10858                                EvalInfo &Info) {
10859   assert(!E->isValueDependent());
10860   if (E->getType()->isFixedPointType()) {
10861     APValue Val;
10862     if (!FixedPointExprEvaluator(Info, Val).Visit(E))
10863       return false;
10864     if (!Val.isFixedPoint())
10865       return false;
10866 
10867     Result = Val.getFixedPoint();
10868     return true;
10869   }
10870   return false;
10871 }
10872 
10873 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
10874                                         EvalInfo &Info) {
10875   assert(!E->isValueDependent());
10876   if (E->getType()->isIntegerType()) {
10877     auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
10878     APSInt Val;
10879     if (!EvaluateInteger(E, Val, Info))
10880       return false;
10881     Result = APFixedPoint(Val, FXSema);
10882     return true;
10883   } else if (E->getType()->isFixedPointType()) {
10884     return EvaluateFixedPoint(E, Result, Info);
10885   }
10886   return false;
10887 }
10888 
10889 /// Check whether the given declaration can be directly converted to an integral
10890 /// rvalue. If not, no diagnostic is produced; there are other things we can
10891 /// try.
10892 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
10893   // Enums are integer constant exprs.
10894   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
10895     // Check for signedness/width mismatches between E type and ECD value.
10896     bool SameSign = (ECD->getInitVal().isSigned()
10897                      == E->getType()->isSignedIntegerOrEnumerationType());
10898     bool SameWidth = (ECD->getInitVal().getBitWidth()
10899                       == Info.Ctx.getIntWidth(E->getType()));
10900     if (SameSign && SameWidth)
10901       return Success(ECD->getInitVal(), E);
10902     else {
10903       // Get rid of mismatch (otherwise Success assertions will fail)
10904       // by computing a new value matching the type of E.
10905       llvm::APSInt Val = ECD->getInitVal();
10906       if (!SameSign)
10907         Val.setIsSigned(!ECD->getInitVal().isSigned());
10908       if (!SameWidth)
10909         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
10910       return Success(Val, E);
10911     }
10912   }
10913   return false;
10914 }
10915 
10916 /// Values returned by __builtin_classify_type, chosen to match the values
10917 /// produced by GCC's builtin.
10918 enum class GCCTypeClass {
10919   None = -1,
10920   Void = 0,
10921   Integer = 1,
10922   // GCC reserves 2 for character types, but instead classifies them as
10923   // integers.
10924   Enum = 3,
10925   Bool = 4,
10926   Pointer = 5,
10927   // GCC reserves 6 for references, but appears to never use it (because
10928   // expressions never have reference type, presumably).
10929   PointerToDataMember = 7,
10930   RealFloat = 8,
10931   Complex = 9,
10932   // GCC reserves 10 for functions, but does not use it since GCC version 6 due
10933   // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
10934   // GCC claims to reserve 11 for pointers to member functions, but *actually*
10935   // uses 12 for that purpose, same as for a class or struct. Maybe it
10936   // internally implements a pointer to member as a struct?  Who knows.
10937   PointerToMemberFunction = 12, // Not a bug, see above.
10938   ClassOrStruct = 12,
10939   Union = 13,
10940   // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
10941   // decay to pointer. (Prior to version 6 it was only used in C++ mode).
10942   // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
10943   // literals.
10944 };
10945 
10946 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
10947 /// as GCC.
10948 static GCCTypeClass
10949 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
10950   assert(!T->isDependentType() && "unexpected dependent type");
10951 
10952   QualType CanTy = T.getCanonicalType();
10953   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
10954 
10955   switch (CanTy->getTypeClass()) {
10956 #define TYPE(ID, BASE)
10957 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
10958 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
10959 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
10960 #include "clang/AST/TypeNodes.inc"
10961   case Type::Auto:
10962   case Type::DeducedTemplateSpecialization:
10963       llvm_unreachable("unexpected non-canonical or dependent type");
10964 
10965   case Type::Builtin:
10966     switch (BT->getKind()) {
10967 #define BUILTIN_TYPE(ID, SINGLETON_ID)
10968 #define SIGNED_TYPE(ID, SINGLETON_ID) \
10969     case BuiltinType::ID: return GCCTypeClass::Integer;
10970 #define FLOATING_TYPE(ID, SINGLETON_ID) \
10971     case BuiltinType::ID: return GCCTypeClass::RealFloat;
10972 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
10973     case BuiltinType::ID: break;
10974 #include "clang/AST/BuiltinTypes.def"
10975     case BuiltinType::Void:
10976       return GCCTypeClass::Void;
10977 
10978     case BuiltinType::Bool:
10979       return GCCTypeClass::Bool;
10980 
10981     case BuiltinType::Char_U:
10982     case BuiltinType::UChar:
10983     case BuiltinType::WChar_U:
10984     case BuiltinType::Char8:
10985     case BuiltinType::Char16:
10986     case BuiltinType::Char32:
10987     case BuiltinType::UShort:
10988     case BuiltinType::UInt:
10989     case BuiltinType::ULong:
10990     case BuiltinType::ULongLong:
10991     case BuiltinType::UInt128:
10992       return GCCTypeClass::Integer;
10993 
10994     case BuiltinType::UShortAccum:
10995     case BuiltinType::UAccum:
10996     case BuiltinType::ULongAccum:
10997     case BuiltinType::UShortFract:
10998     case BuiltinType::UFract:
10999     case BuiltinType::ULongFract:
11000     case BuiltinType::SatUShortAccum:
11001     case BuiltinType::SatUAccum:
11002     case BuiltinType::SatULongAccum:
11003     case BuiltinType::SatUShortFract:
11004     case BuiltinType::SatUFract:
11005     case BuiltinType::SatULongFract:
11006       return GCCTypeClass::None;
11007 
11008     case BuiltinType::NullPtr:
11009 
11010     case BuiltinType::ObjCId:
11011     case BuiltinType::ObjCClass:
11012     case BuiltinType::ObjCSel:
11013 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
11014     case BuiltinType::Id:
11015 #include "clang/Basic/OpenCLImageTypes.def"
11016 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
11017     case BuiltinType::Id:
11018 #include "clang/Basic/OpenCLExtensionTypes.def"
11019     case BuiltinType::OCLSampler:
11020     case BuiltinType::OCLEvent:
11021     case BuiltinType::OCLClkEvent:
11022     case BuiltinType::OCLQueue:
11023     case BuiltinType::OCLReserveID:
11024 #define SVE_TYPE(Name, Id, SingletonId) \
11025     case BuiltinType::Id:
11026 #include "clang/Basic/AArch64SVEACLETypes.def"
11027 #define PPC_VECTOR_TYPE(Name, Id, Size) \
11028     case BuiltinType::Id:
11029 #include "clang/Basic/PPCTypes.def"
11030 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
11031 #include "clang/Basic/RISCVVTypes.def"
11032       return GCCTypeClass::None;
11033 
11034     case BuiltinType::Dependent:
11035       llvm_unreachable("unexpected dependent type");
11036     };
11037     llvm_unreachable("unexpected placeholder type");
11038 
11039   case Type::Enum:
11040     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
11041 
11042   case Type::Pointer:
11043   case Type::ConstantArray:
11044   case Type::VariableArray:
11045   case Type::IncompleteArray:
11046   case Type::FunctionNoProto:
11047   case Type::FunctionProto:
11048     return GCCTypeClass::Pointer;
11049 
11050   case Type::MemberPointer:
11051     return CanTy->isMemberDataPointerType()
11052                ? GCCTypeClass::PointerToDataMember
11053                : GCCTypeClass::PointerToMemberFunction;
11054 
11055   case Type::Complex:
11056     return GCCTypeClass::Complex;
11057 
11058   case Type::Record:
11059     return CanTy->isUnionType() ? GCCTypeClass::Union
11060                                 : GCCTypeClass::ClassOrStruct;
11061 
11062   case Type::Atomic:
11063     // GCC classifies _Atomic T the same as T.
11064     return EvaluateBuiltinClassifyType(
11065         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
11066 
11067   case Type::BlockPointer:
11068   case Type::Vector:
11069   case Type::ExtVector:
11070   case Type::ConstantMatrix:
11071   case Type::ObjCObject:
11072   case Type::ObjCInterface:
11073   case Type::ObjCObjectPointer:
11074   case Type::Pipe:
11075   case Type::ExtInt:
11076     // GCC classifies vectors as None. We follow its lead and classify all
11077     // other types that don't fit into the regular classification the same way.
11078     return GCCTypeClass::None;
11079 
11080   case Type::LValueReference:
11081   case Type::RValueReference:
11082     llvm_unreachable("invalid type for expression");
11083   }
11084 
11085   llvm_unreachable("unexpected type class");
11086 }
11087 
11088 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11089 /// as GCC.
11090 static GCCTypeClass
11091 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
11092   // If no argument was supplied, default to None. This isn't
11093   // ideal, however it is what gcc does.
11094   if (E->getNumArgs() == 0)
11095     return GCCTypeClass::None;
11096 
11097   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
11098   // being an ICE, but still folds it to a constant using the type of the first
11099   // argument.
11100   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
11101 }
11102 
11103 /// EvaluateBuiltinConstantPForLValue - Determine the result of
11104 /// __builtin_constant_p when applied to the given pointer.
11105 ///
11106 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
11107 /// or it points to the first character of a string literal.
11108 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
11109   APValue::LValueBase Base = LV.getLValueBase();
11110   if (Base.isNull()) {
11111     // A null base is acceptable.
11112     return true;
11113   } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
11114     if (!isa<StringLiteral>(E))
11115       return false;
11116     return LV.getLValueOffset().isZero();
11117   } else if (Base.is<TypeInfoLValue>()) {
11118     // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
11119     // evaluate to true.
11120     return true;
11121   } else {
11122     // Any other base is not constant enough for GCC.
11123     return false;
11124   }
11125 }
11126 
11127 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
11128 /// GCC as we can manage.
11129 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
11130   // This evaluation is not permitted to have side-effects, so evaluate it in
11131   // a speculative evaluation context.
11132   SpeculativeEvaluationRAII SpeculativeEval(Info);
11133 
11134   // Constant-folding is always enabled for the operand of __builtin_constant_p
11135   // (even when the enclosing evaluation context otherwise requires a strict
11136   // language-specific constant expression).
11137   FoldConstant Fold(Info, true);
11138 
11139   QualType ArgType = Arg->getType();
11140 
11141   // __builtin_constant_p always has one operand. The rules which gcc follows
11142   // are not precisely documented, but are as follows:
11143   //
11144   //  - If the operand is of integral, floating, complex or enumeration type,
11145   //    and can be folded to a known value of that type, it returns 1.
11146   //  - If the operand can be folded to a pointer to the first character
11147   //    of a string literal (or such a pointer cast to an integral type)
11148   //    or to a null pointer or an integer cast to a pointer, it returns 1.
11149   //
11150   // Otherwise, it returns 0.
11151   //
11152   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
11153   // its support for this did not work prior to GCC 9 and is not yet well
11154   // understood.
11155   if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
11156       ArgType->isAnyComplexType() || ArgType->isPointerType() ||
11157       ArgType->isNullPtrType()) {
11158     APValue V;
11159     if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
11160       Fold.keepDiagnostics();
11161       return false;
11162     }
11163 
11164     // For a pointer (possibly cast to integer), there are special rules.
11165     if (V.getKind() == APValue::LValue)
11166       return EvaluateBuiltinConstantPForLValue(V);
11167 
11168     // Otherwise, any constant value is good enough.
11169     return V.hasValue();
11170   }
11171 
11172   // Anything else isn't considered to be sufficiently constant.
11173   return false;
11174 }
11175 
11176 /// Retrieves the "underlying object type" of the given expression,
11177 /// as used by __builtin_object_size.
11178 static QualType getObjectType(APValue::LValueBase B) {
11179   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
11180     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
11181       return VD->getType();
11182   } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
11183     if (isa<CompoundLiteralExpr>(E))
11184       return E->getType();
11185   } else if (B.is<TypeInfoLValue>()) {
11186     return B.getTypeInfoType();
11187   } else if (B.is<DynamicAllocLValue>()) {
11188     return B.getDynamicAllocType();
11189   }
11190 
11191   return QualType();
11192 }
11193 
11194 /// A more selective version of E->IgnoreParenCasts for
11195 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
11196 /// to change the type of E.
11197 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
11198 ///
11199 /// Always returns an RValue with a pointer representation.
11200 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
11201   assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
11202 
11203   auto *NoParens = E->IgnoreParens();
11204   auto *Cast = dyn_cast<CastExpr>(NoParens);
11205   if (Cast == nullptr)
11206     return NoParens;
11207 
11208   // We only conservatively allow a few kinds of casts, because this code is
11209   // inherently a simple solution that seeks to support the common case.
11210   auto CastKind = Cast->getCastKind();
11211   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
11212       CastKind != CK_AddressSpaceConversion)
11213     return NoParens;
11214 
11215   auto *SubExpr = Cast->getSubExpr();
11216   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
11217     return NoParens;
11218   return ignorePointerCastsAndParens(SubExpr);
11219 }
11220 
11221 /// Checks to see if the given LValue's Designator is at the end of the LValue's
11222 /// record layout. e.g.
11223 ///   struct { struct { int a, b; } fst, snd; } obj;
11224 ///   obj.fst   // no
11225 ///   obj.snd   // yes
11226 ///   obj.fst.a // no
11227 ///   obj.fst.b // no
11228 ///   obj.snd.a // no
11229 ///   obj.snd.b // yes
11230 ///
11231 /// Please note: this function is specialized for how __builtin_object_size
11232 /// views "objects".
11233 ///
11234 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
11235 /// correct result, it will always return true.
11236 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
11237   assert(!LVal.Designator.Invalid);
11238 
11239   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
11240     const RecordDecl *Parent = FD->getParent();
11241     Invalid = Parent->isInvalidDecl();
11242     if (Invalid || Parent->isUnion())
11243       return true;
11244     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
11245     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
11246   };
11247 
11248   auto &Base = LVal.getLValueBase();
11249   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
11250     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
11251       bool Invalid;
11252       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11253         return Invalid;
11254     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
11255       for (auto *FD : IFD->chain()) {
11256         bool Invalid;
11257         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
11258           return Invalid;
11259       }
11260     }
11261   }
11262 
11263   unsigned I = 0;
11264   QualType BaseType = getType(Base);
11265   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
11266     // If we don't know the array bound, conservatively assume we're looking at
11267     // the final array element.
11268     ++I;
11269     if (BaseType->isIncompleteArrayType())
11270       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
11271     else
11272       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
11273   }
11274 
11275   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
11276     const auto &Entry = LVal.Designator.Entries[I];
11277     if (BaseType->isArrayType()) {
11278       // Because __builtin_object_size treats arrays as objects, we can ignore
11279       // the index iff this is the last array in the Designator.
11280       if (I + 1 == E)
11281         return true;
11282       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
11283       uint64_t Index = Entry.getAsArrayIndex();
11284       if (Index + 1 != CAT->getSize())
11285         return false;
11286       BaseType = CAT->getElementType();
11287     } else if (BaseType->isAnyComplexType()) {
11288       const auto *CT = BaseType->castAs<ComplexType>();
11289       uint64_t Index = Entry.getAsArrayIndex();
11290       if (Index != 1)
11291         return false;
11292       BaseType = CT->getElementType();
11293     } else if (auto *FD = getAsField(Entry)) {
11294       bool Invalid;
11295       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11296         return Invalid;
11297       BaseType = FD->getType();
11298     } else {
11299       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
11300       return false;
11301     }
11302   }
11303   return true;
11304 }
11305 
11306 /// Tests to see if the LValue has a user-specified designator (that isn't
11307 /// necessarily valid). Note that this always returns 'true' if the LValue has
11308 /// an unsized array as its first designator entry, because there's currently no
11309 /// way to tell if the user typed *foo or foo[0].
11310 static bool refersToCompleteObject(const LValue &LVal) {
11311   if (LVal.Designator.Invalid)
11312     return false;
11313 
11314   if (!LVal.Designator.Entries.empty())
11315     return LVal.Designator.isMostDerivedAnUnsizedArray();
11316 
11317   if (!LVal.InvalidBase)
11318     return true;
11319 
11320   // If `E` is a MemberExpr, then the first part of the designator is hiding in
11321   // the LValueBase.
11322   const auto *E = LVal.Base.dyn_cast<const Expr *>();
11323   return !E || !isa<MemberExpr>(E);
11324 }
11325 
11326 /// Attempts to detect a user writing into a piece of memory that's impossible
11327 /// to figure out the size of by just using types.
11328 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
11329   const SubobjectDesignator &Designator = LVal.Designator;
11330   // Notes:
11331   // - Users can only write off of the end when we have an invalid base. Invalid
11332   //   bases imply we don't know where the memory came from.
11333   // - We used to be a bit more aggressive here; we'd only be conservative if
11334   //   the array at the end was flexible, or if it had 0 or 1 elements. This
11335   //   broke some common standard library extensions (PR30346), but was
11336   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
11337   //   with some sort of list. OTOH, it seems that GCC is always
11338   //   conservative with the last element in structs (if it's an array), so our
11339   //   current behavior is more compatible than an explicit list approach would
11340   //   be.
11341   return LVal.InvalidBase &&
11342          Designator.Entries.size() == Designator.MostDerivedPathLength &&
11343          Designator.MostDerivedIsArrayElement &&
11344          isDesignatorAtObjectEnd(Ctx, LVal);
11345 }
11346 
11347 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
11348 /// Fails if the conversion would cause loss of precision.
11349 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
11350                                             CharUnits &Result) {
11351   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
11352   if (Int.ugt(CharUnitsMax))
11353     return false;
11354   Result = CharUnits::fromQuantity(Int.getZExtValue());
11355   return true;
11356 }
11357 
11358 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
11359 /// determine how many bytes exist from the beginning of the object to either
11360 /// the end of the current subobject, or the end of the object itself, depending
11361 /// on what the LValue looks like + the value of Type.
11362 ///
11363 /// If this returns false, the value of Result is undefined.
11364 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
11365                                unsigned Type, const LValue &LVal,
11366                                CharUnits &EndOffset) {
11367   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
11368 
11369   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
11370     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
11371       return false;
11372     return HandleSizeof(Info, ExprLoc, Ty, Result);
11373   };
11374 
11375   // We want to evaluate the size of the entire object. This is a valid fallback
11376   // for when Type=1 and the designator is invalid, because we're asked for an
11377   // upper-bound.
11378   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
11379     // Type=3 wants a lower bound, so we can't fall back to this.
11380     if (Type == 3 && !DetermineForCompleteObject)
11381       return false;
11382 
11383     llvm::APInt APEndOffset;
11384     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11385         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11386       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11387 
11388     if (LVal.InvalidBase)
11389       return false;
11390 
11391     QualType BaseTy = getObjectType(LVal.getLValueBase());
11392     return CheckedHandleSizeof(BaseTy, EndOffset);
11393   }
11394 
11395   // We want to evaluate the size of a subobject.
11396   const SubobjectDesignator &Designator = LVal.Designator;
11397 
11398   // The following is a moderately common idiom in C:
11399   //
11400   // struct Foo { int a; char c[1]; };
11401   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
11402   // strcpy(&F->c[0], Bar);
11403   //
11404   // In order to not break too much legacy code, we need to support it.
11405   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
11406     // If we can resolve this to an alloc_size call, we can hand that back,
11407     // because we know for certain how many bytes there are to write to.
11408     llvm::APInt APEndOffset;
11409     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11410         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11411       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11412 
11413     // If we cannot determine the size of the initial allocation, then we can't
11414     // given an accurate upper-bound. However, we are still able to give
11415     // conservative lower-bounds for Type=3.
11416     if (Type == 1)
11417       return false;
11418   }
11419 
11420   CharUnits BytesPerElem;
11421   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
11422     return false;
11423 
11424   // According to the GCC documentation, we want the size of the subobject
11425   // denoted by the pointer. But that's not quite right -- what we actually
11426   // want is the size of the immediately-enclosing array, if there is one.
11427   int64_t ElemsRemaining;
11428   if (Designator.MostDerivedIsArrayElement &&
11429       Designator.Entries.size() == Designator.MostDerivedPathLength) {
11430     uint64_t ArraySize = Designator.getMostDerivedArraySize();
11431     uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
11432     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
11433   } else {
11434     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
11435   }
11436 
11437   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
11438   return true;
11439 }
11440 
11441 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
11442 /// returns true and stores the result in @p Size.
11443 ///
11444 /// If @p WasError is non-null, this will report whether the failure to evaluate
11445 /// is to be treated as an Error in IntExprEvaluator.
11446 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
11447                                          EvalInfo &Info, uint64_t &Size) {
11448   // Determine the denoted object.
11449   LValue LVal;
11450   {
11451     // The operand of __builtin_object_size is never evaluated for side-effects.
11452     // If there are any, but we can determine the pointed-to object anyway, then
11453     // ignore the side-effects.
11454     SpeculativeEvaluationRAII SpeculativeEval(Info);
11455     IgnoreSideEffectsRAII Fold(Info);
11456 
11457     if (E->isGLValue()) {
11458       // It's possible for us to be given GLValues if we're called via
11459       // Expr::tryEvaluateObjectSize.
11460       APValue RVal;
11461       if (!EvaluateAsRValue(Info, E, RVal))
11462         return false;
11463       LVal.setFrom(Info.Ctx, RVal);
11464     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
11465                                 /*InvalidBaseOK=*/true))
11466       return false;
11467   }
11468 
11469   // If we point to before the start of the object, there are no accessible
11470   // bytes.
11471   if (LVal.getLValueOffset().isNegative()) {
11472     Size = 0;
11473     return true;
11474   }
11475 
11476   CharUnits EndOffset;
11477   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
11478     return false;
11479 
11480   // If we've fallen outside of the end offset, just pretend there's nothing to
11481   // write to/read from.
11482   if (EndOffset <= LVal.getLValueOffset())
11483     Size = 0;
11484   else
11485     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
11486   return true;
11487 }
11488 
11489 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
11490   if (unsigned BuiltinOp = E->getBuiltinCallee())
11491     return VisitBuiltinCallExpr(E, BuiltinOp);
11492 
11493   return ExprEvaluatorBaseTy::VisitCallExpr(E);
11494 }
11495 
11496 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
11497                                      APValue &Val, APSInt &Alignment) {
11498   QualType SrcTy = E->getArg(0)->getType();
11499   if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
11500     return false;
11501   // Even though we are evaluating integer expressions we could get a pointer
11502   // argument for the __builtin_is_aligned() case.
11503   if (SrcTy->isPointerType()) {
11504     LValue Ptr;
11505     if (!EvaluatePointer(E->getArg(0), Ptr, Info))
11506       return false;
11507     Ptr.moveInto(Val);
11508   } else if (!SrcTy->isIntegralOrEnumerationType()) {
11509     Info.FFDiag(E->getArg(0));
11510     return false;
11511   } else {
11512     APSInt SrcInt;
11513     if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
11514       return false;
11515     assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
11516            "Bit widths must be the same");
11517     Val = APValue(SrcInt);
11518   }
11519   assert(Val.hasValue());
11520   return true;
11521 }
11522 
11523 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
11524                                             unsigned BuiltinOp) {
11525   switch (BuiltinOp) {
11526   default:
11527     return ExprEvaluatorBaseTy::VisitCallExpr(E);
11528 
11529   case Builtin::BI__builtin_dynamic_object_size:
11530   case Builtin::BI__builtin_object_size: {
11531     // The type was checked when we built the expression.
11532     unsigned Type =
11533         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11534     assert(Type <= 3 && "unexpected type");
11535 
11536     uint64_t Size;
11537     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
11538       return Success(Size, E);
11539 
11540     if (E->getArg(0)->HasSideEffects(Info.Ctx))
11541       return Success((Type & 2) ? 0 : -1, E);
11542 
11543     // Expression had no side effects, but we couldn't statically determine the
11544     // size of the referenced object.
11545     switch (Info.EvalMode) {
11546     case EvalInfo::EM_ConstantExpression:
11547     case EvalInfo::EM_ConstantFold:
11548     case EvalInfo::EM_IgnoreSideEffects:
11549       // Leave it to IR generation.
11550       return Error(E);
11551     case EvalInfo::EM_ConstantExpressionUnevaluated:
11552       // Reduce it to a constant now.
11553       return Success((Type & 2) ? 0 : -1, E);
11554     }
11555 
11556     llvm_unreachable("unexpected EvalMode");
11557   }
11558 
11559   case Builtin::BI__builtin_os_log_format_buffer_size: {
11560     analyze_os_log::OSLogBufferLayout Layout;
11561     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
11562     return Success(Layout.size().getQuantity(), E);
11563   }
11564 
11565   case Builtin::BI__builtin_is_aligned: {
11566     APValue Src;
11567     APSInt Alignment;
11568     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11569       return false;
11570     if (Src.isLValue()) {
11571       // If we evaluated a pointer, check the minimum known alignment.
11572       LValue Ptr;
11573       Ptr.setFrom(Info.Ctx, Src);
11574       CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
11575       CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
11576       // We can return true if the known alignment at the computed offset is
11577       // greater than the requested alignment.
11578       assert(PtrAlign.isPowerOfTwo());
11579       assert(Alignment.isPowerOf2());
11580       if (PtrAlign.getQuantity() >= Alignment)
11581         return Success(1, E);
11582       // If the alignment is not known to be sufficient, some cases could still
11583       // be aligned at run time. However, if the requested alignment is less or
11584       // equal to the base alignment and the offset is not aligned, we know that
11585       // the run-time value can never be aligned.
11586       if (BaseAlignment.getQuantity() >= Alignment &&
11587           PtrAlign.getQuantity() < Alignment)
11588         return Success(0, E);
11589       // Otherwise we can't infer whether the value is sufficiently aligned.
11590       // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
11591       //  in cases where we can't fully evaluate the pointer.
11592       Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
11593           << Alignment;
11594       return false;
11595     }
11596     assert(Src.isInt());
11597     return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
11598   }
11599   case Builtin::BI__builtin_align_up: {
11600     APValue Src;
11601     APSInt Alignment;
11602     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11603       return false;
11604     if (!Src.isInt())
11605       return Error(E);
11606     APSInt AlignedVal =
11607         APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
11608                Src.getInt().isUnsigned());
11609     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11610     return Success(AlignedVal, E);
11611   }
11612   case Builtin::BI__builtin_align_down: {
11613     APValue Src;
11614     APSInt Alignment;
11615     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11616       return false;
11617     if (!Src.isInt())
11618       return Error(E);
11619     APSInt AlignedVal =
11620         APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
11621     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11622     return Success(AlignedVal, E);
11623   }
11624 
11625   case Builtin::BI__builtin_bitreverse8:
11626   case Builtin::BI__builtin_bitreverse16:
11627   case Builtin::BI__builtin_bitreverse32:
11628   case Builtin::BI__builtin_bitreverse64: {
11629     APSInt Val;
11630     if (!EvaluateInteger(E->getArg(0), Val, Info))
11631       return false;
11632 
11633     return Success(Val.reverseBits(), E);
11634   }
11635 
11636   case Builtin::BI__builtin_bswap16:
11637   case Builtin::BI__builtin_bswap32:
11638   case Builtin::BI__builtin_bswap64: {
11639     APSInt Val;
11640     if (!EvaluateInteger(E->getArg(0), Val, Info))
11641       return false;
11642 
11643     return Success(Val.byteSwap(), E);
11644   }
11645 
11646   case Builtin::BI__builtin_classify_type:
11647     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
11648 
11649   case Builtin::BI__builtin_clrsb:
11650   case Builtin::BI__builtin_clrsbl:
11651   case Builtin::BI__builtin_clrsbll: {
11652     APSInt Val;
11653     if (!EvaluateInteger(E->getArg(0), Val, Info))
11654       return false;
11655 
11656     return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
11657   }
11658 
11659   case Builtin::BI__builtin_clz:
11660   case Builtin::BI__builtin_clzl:
11661   case Builtin::BI__builtin_clzll:
11662   case Builtin::BI__builtin_clzs: {
11663     APSInt Val;
11664     if (!EvaluateInteger(E->getArg(0), Val, Info))
11665       return false;
11666     if (!Val)
11667       return Error(E);
11668 
11669     return Success(Val.countLeadingZeros(), E);
11670   }
11671 
11672   case Builtin::BI__builtin_constant_p: {
11673     const Expr *Arg = E->getArg(0);
11674     if (EvaluateBuiltinConstantP(Info, Arg))
11675       return Success(true, E);
11676     if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
11677       // Outside a constant context, eagerly evaluate to false in the presence
11678       // of side-effects in order to avoid -Wunsequenced false-positives in
11679       // a branch on __builtin_constant_p(expr).
11680       return Success(false, E);
11681     }
11682     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11683     return false;
11684   }
11685 
11686   case Builtin::BI__builtin_is_constant_evaluated: {
11687     const auto *Callee = Info.CurrentCall->getCallee();
11688     if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
11689         (Info.CallStackDepth == 1 ||
11690          (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
11691           Callee->getIdentifier() &&
11692           Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
11693       // FIXME: Find a better way to avoid duplicated diagnostics.
11694       if (Info.EvalStatus.Diag)
11695         Info.report((Info.CallStackDepth == 1) ? E->getExprLoc()
11696                                                : Info.CurrentCall->CallLoc,
11697                     diag::warn_is_constant_evaluated_always_true_constexpr)
11698             << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
11699                                          : "std::is_constant_evaluated");
11700     }
11701 
11702     return Success(Info.InConstantContext, E);
11703   }
11704 
11705   case Builtin::BI__builtin_ctz:
11706   case Builtin::BI__builtin_ctzl:
11707   case Builtin::BI__builtin_ctzll:
11708   case Builtin::BI__builtin_ctzs: {
11709     APSInt Val;
11710     if (!EvaluateInteger(E->getArg(0), Val, Info))
11711       return false;
11712     if (!Val)
11713       return Error(E);
11714 
11715     return Success(Val.countTrailingZeros(), E);
11716   }
11717 
11718   case Builtin::BI__builtin_eh_return_data_regno: {
11719     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11720     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
11721     return Success(Operand, E);
11722   }
11723 
11724   case Builtin::BI__builtin_expect:
11725   case Builtin::BI__builtin_expect_with_probability:
11726     return Visit(E->getArg(0));
11727 
11728   case Builtin::BI__builtin_ffs:
11729   case Builtin::BI__builtin_ffsl:
11730   case Builtin::BI__builtin_ffsll: {
11731     APSInt Val;
11732     if (!EvaluateInteger(E->getArg(0), Val, Info))
11733       return false;
11734 
11735     unsigned N = Val.countTrailingZeros();
11736     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
11737   }
11738 
11739   case Builtin::BI__builtin_fpclassify: {
11740     APFloat Val(0.0);
11741     if (!EvaluateFloat(E->getArg(5), Val, Info))
11742       return false;
11743     unsigned Arg;
11744     switch (Val.getCategory()) {
11745     case APFloat::fcNaN: Arg = 0; break;
11746     case APFloat::fcInfinity: Arg = 1; break;
11747     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
11748     case APFloat::fcZero: Arg = 4; break;
11749     }
11750     return Visit(E->getArg(Arg));
11751   }
11752 
11753   case Builtin::BI__builtin_isinf_sign: {
11754     APFloat Val(0.0);
11755     return EvaluateFloat(E->getArg(0), Val, Info) &&
11756            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
11757   }
11758 
11759   case Builtin::BI__builtin_isinf: {
11760     APFloat Val(0.0);
11761     return EvaluateFloat(E->getArg(0), Val, Info) &&
11762            Success(Val.isInfinity() ? 1 : 0, E);
11763   }
11764 
11765   case Builtin::BI__builtin_isfinite: {
11766     APFloat Val(0.0);
11767     return EvaluateFloat(E->getArg(0), Val, Info) &&
11768            Success(Val.isFinite() ? 1 : 0, E);
11769   }
11770 
11771   case Builtin::BI__builtin_isnan: {
11772     APFloat Val(0.0);
11773     return EvaluateFloat(E->getArg(0), Val, Info) &&
11774            Success(Val.isNaN() ? 1 : 0, E);
11775   }
11776 
11777   case Builtin::BI__builtin_isnormal: {
11778     APFloat Val(0.0);
11779     return EvaluateFloat(E->getArg(0), Val, Info) &&
11780            Success(Val.isNormal() ? 1 : 0, E);
11781   }
11782 
11783   case Builtin::BI__builtin_parity:
11784   case Builtin::BI__builtin_parityl:
11785   case Builtin::BI__builtin_parityll: {
11786     APSInt Val;
11787     if (!EvaluateInteger(E->getArg(0), Val, Info))
11788       return false;
11789 
11790     return Success(Val.countPopulation() % 2, E);
11791   }
11792 
11793   case Builtin::BI__builtin_popcount:
11794   case Builtin::BI__builtin_popcountl:
11795   case Builtin::BI__builtin_popcountll: {
11796     APSInt Val;
11797     if (!EvaluateInteger(E->getArg(0), Val, Info))
11798       return false;
11799 
11800     return Success(Val.countPopulation(), E);
11801   }
11802 
11803   case Builtin::BI__builtin_rotateleft8:
11804   case Builtin::BI__builtin_rotateleft16:
11805   case Builtin::BI__builtin_rotateleft32:
11806   case Builtin::BI__builtin_rotateleft64:
11807   case Builtin::BI_rotl8: // Microsoft variants of rotate right
11808   case Builtin::BI_rotl16:
11809   case Builtin::BI_rotl:
11810   case Builtin::BI_lrotl:
11811   case Builtin::BI_rotl64: {
11812     APSInt Val, Amt;
11813     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
11814         !EvaluateInteger(E->getArg(1), Amt, Info))
11815       return false;
11816 
11817     return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
11818   }
11819 
11820   case Builtin::BI__builtin_rotateright8:
11821   case Builtin::BI__builtin_rotateright16:
11822   case Builtin::BI__builtin_rotateright32:
11823   case Builtin::BI__builtin_rotateright64:
11824   case Builtin::BI_rotr8: // Microsoft variants of rotate right
11825   case Builtin::BI_rotr16:
11826   case Builtin::BI_rotr:
11827   case Builtin::BI_lrotr:
11828   case Builtin::BI_rotr64: {
11829     APSInt Val, Amt;
11830     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
11831         !EvaluateInteger(E->getArg(1), Amt, Info))
11832       return false;
11833 
11834     return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
11835   }
11836 
11837   case Builtin::BIstrlen:
11838   case Builtin::BIwcslen:
11839     // A call to strlen is not a constant expression.
11840     if (Info.getLangOpts().CPlusPlus11)
11841       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11842         << /*isConstexpr*/0 << /*isConstructor*/0
11843         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11844     else
11845       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11846     LLVM_FALLTHROUGH;
11847   case Builtin::BI__builtin_strlen:
11848   case Builtin::BI__builtin_wcslen: {
11849     // As an extension, we support __builtin_strlen() as a constant expression,
11850     // and support folding strlen() to a constant.
11851     LValue String;
11852     if (!EvaluatePointer(E->getArg(0), String, Info))
11853       return false;
11854 
11855     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
11856 
11857     // Fast path: if it's a string literal, search the string value.
11858     if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
11859             String.getLValueBase().dyn_cast<const Expr *>())) {
11860       // The string literal may have embedded null characters. Find the first
11861       // one and truncate there.
11862       StringRef Str = S->getBytes();
11863       int64_t Off = String.Offset.getQuantity();
11864       if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
11865           S->getCharByteWidth() == 1 &&
11866           // FIXME: Add fast-path for wchar_t too.
11867           Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
11868         Str = Str.substr(Off);
11869 
11870         StringRef::size_type Pos = Str.find(0);
11871         if (Pos != StringRef::npos)
11872           Str = Str.substr(0, Pos);
11873 
11874         return Success(Str.size(), E);
11875       }
11876 
11877       // Fall through to slow path to issue appropriate diagnostic.
11878     }
11879 
11880     // Slow path: scan the bytes of the string looking for the terminating 0.
11881     for (uint64_t Strlen = 0; /**/; ++Strlen) {
11882       APValue Char;
11883       if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
11884           !Char.isInt())
11885         return false;
11886       if (!Char.getInt())
11887         return Success(Strlen, E);
11888       if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
11889         return false;
11890     }
11891   }
11892 
11893   case Builtin::BIstrcmp:
11894   case Builtin::BIwcscmp:
11895   case Builtin::BIstrncmp:
11896   case Builtin::BIwcsncmp:
11897   case Builtin::BImemcmp:
11898   case Builtin::BIbcmp:
11899   case Builtin::BIwmemcmp:
11900     // A call to strlen is not a constant expression.
11901     if (Info.getLangOpts().CPlusPlus11)
11902       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11903         << /*isConstexpr*/0 << /*isConstructor*/0
11904         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11905     else
11906       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11907     LLVM_FALLTHROUGH;
11908   case Builtin::BI__builtin_strcmp:
11909   case Builtin::BI__builtin_wcscmp:
11910   case Builtin::BI__builtin_strncmp:
11911   case Builtin::BI__builtin_wcsncmp:
11912   case Builtin::BI__builtin_memcmp:
11913   case Builtin::BI__builtin_bcmp:
11914   case Builtin::BI__builtin_wmemcmp: {
11915     LValue String1, String2;
11916     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
11917         !EvaluatePointer(E->getArg(1), String2, Info))
11918       return false;
11919 
11920     uint64_t MaxLength = uint64_t(-1);
11921     if (BuiltinOp != Builtin::BIstrcmp &&
11922         BuiltinOp != Builtin::BIwcscmp &&
11923         BuiltinOp != Builtin::BI__builtin_strcmp &&
11924         BuiltinOp != Builtin::BI__builtin_wcscmp) {
11925       APSInt N;
11926       if (!EvaluateInteger(E->getArg(2), N, Info))
11927         return false;
11928       MaxLength = N.getExtValue();
11929     }
11930 
11931     // Empty substrings compare equal by definition.
11932     if (MaxLength == 0u)
11933       return Success(0, E);
11934 
11935     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11936         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11937         String1.Designator.Invalid || String2.Designator.Invalid)
11938       return false;
11939 
11940     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
11941     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
11942 
11943     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
11944                      BuiltinOp == Builtin::BIbcmp ||
11945                      BuiltinOp == Builtin::BI__builtin_memcmp ||
11946                      BuiltinOp == Builtin::BI__builtin_bcmp;
11947 
11948     assert(IsRawByte ||
11949            (Info.Ctx.hasSameUnqualifiedType(
11950                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
11951             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
11952 
11953     // For memcmp, allow comparing any arrays of '[[un]signed] char' or
11954     // 'char8_t', but no other types.
11955     if (IsRawByte &&
11956         !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
11957       // FIXME: Consider using our bit_cast implementation to support this.
11958       Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
11959           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
11960           << CharTy1 << CharTy2;
11961       return false;
11962     }
11963 
11964     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
11965       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
11966              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
11967              Char1.isInt() && Char2.isInt();
11968     };
11969     const auto &AdvanceElems = [&] {
11970       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
11971              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
11972     };
11973 
11974     bool StopAtNull =
11975         (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
11976          BuiltinOp != Builtin::BIwmemcmp &&
11977          BuiltinOp != Builtin::BI__builtin_memcmp &&
11978          BuiltinOp != Builtin::BI__builtin_bcmp &&
11979          BuiltinOp != Builtin::BI__builtin_wmemcmp);
11980     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
11981                   BuiltinOp == Builtin::BIwcsncmp ||
11982                   BuiltinOp == Builtin::BIwmemcmp ||
11983                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
11984                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
11985                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
11986 
11987     for (; MaxLength; --MaxLength) {
11988       APValue Char1, Char2;
11989       if (!ReadCurElems(Char1, Char2))
11990         return false;
11991       if (Char1.getInt().ne(Char2.getInt())) {
11992         if (IsWide) // wmemcmp compares with wchar_t signedness.
11993           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
11994         // memcmp always compares unsigned chars.
11995         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
11996       }
11997       if (StopAtNull && !Char1.getInt())
11998         return Success(0, E);
11999       assert(!(StopAtNull && !Char2.getInt()));
12000       if (!AdvanceElems())
12001         return false;
12002     }
12003     // We hit the strncmp / memcmp limit.
12004     return Success(0, E);
12005   }
12006 
12007   case Builtin::BI__atomic_always_lock_free:
12008   case Builtin::BI__atomic_is_lock_free:
12009   case Builtin::BI__c11_atomic_is_lock_free: {
12010     APSInt SizeVal;
12011     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
12012       return false;
12013 
12014     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
12015     // of two less than or equal to the maximum inline atomic width, we know it
12016     // is lock-free.  If the size isn't a power of two, or greater than the
12017     // maximum alignment where we promote atomics, we know it is not lock-free
12018     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
12019     // the answer can only be determined at runtime; for example, 16-byte
12020     // atomics have lock-free implementations on some, but not all,
12021     // x86-64 processors.
12022 
12023     // Check power-of-two.
12024     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
12025     if (Size.isPowerOfTwo()) {
12026       // Check against inlining width.
12027       unsigned InlineWidthBits =
12028           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
12029       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
12030         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
12031             Size == CharUnits::One() ||
12032             E->getArg(1)->isNullPointerConstant(Info.Ctx,
12033                                                 Expr::NPC_NeverValueDependent))
12034           // OK, we will inline appropriately-aligned operations of this size,
12035           // and _Atomic(T) is appropriately-aligned.
12036           return Success(1, E);
12037 
12038         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
12039           castAs<PointerType>()->getPointeeType();
12040         if (!PointeeType->isIncompleteType() &&
12041             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
12042           // OK, we will inline operations on this object.
12043           return Success(1, E);
12044         }
12045       }
12046     }
12047 
12048     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
12049         Success(0, E) : Error(E);
12050   }
12051   case Builtin::BI__builtin_add_overflow:
12052   case Builtin::BI__builtin_sub_overflow:
12053   case Builtin::BI__builtin_mul_overflow:
12054   case Builtin::BI__builtin_sadd_overflow:
12055   case Builtin::BI__builtin_uadd_overflow:
12056   case Builtin::BI__builtin_uaddl_overflow:
12057   case Builtin::BI__builtin_uaddll_overflow:
12058   case Builtin::BI__builtin_usub_overflow:
12059   case Builtin::BI__builtin_usubl_overflow:
12060   case Builtin::BI__builtin_usubll_overflow:
12061   case Builtin::BI__builtin_umul_overflow:
12062   case Builtin::BI__builtin_umull_overflow:
12063   case Builtin::BI__builtin_umulll_overflow:
12064   case Builtin::BI__builtin_saddl_overflow:
12065   case Builtin::BI__builtin_saddll_overflow:
12066   case Builtin::BI__builtin_ssub_overflow:
12067   case Builtin::BI__builtin_ssubl_overflow:
12068   case Builtin::BI__builtin_ssubll_overflow:
12069   case Builtin::BI__builtin_smul_overflow:
12070   case Builtin::BI__builtin_smull_overflow:
12071   case Builtin::BI__builtin_smulll_overflow: {
12072     LValue ResultLValue;
12073     APSInt LHS, RHS;
12074 
12075     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
12076     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
12077         !EvaluateInteger(E->getArg(1), RHS, Info) ||
12078         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
12079       return false;
12080 
12081     APSInt Result;
12082     bool DidOverflow = false;
12083 
12084     // If the types don't have to match, enlarge all 3 to the largest of them.
12085     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12086         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12087         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12088       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
12089                       ResultType->isSignedIntegerOrEnumerationType();
12090       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
12091                       ResultType->isSignedIntegerOrEnumerationType();
12092       uint64_t LHSSize = LHS.getBitWidth();
12093       uint64_t RHSSize = RHS.getBitWidth();
12094       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
12095       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
12096 
12097       // Add an additional bit if the signedness isn't uniformly agreed to. We
12098       // could do this ONLY if there is a signed and an unsigned that both have
12099       // MaxBits, but the code to check that is pretty nasty.  The issue will be
12100       // caught in the shrink-to-result later anyway.
12101       if (IsSigned && !AllSigned)
12102         ++MaxBits;
12103 
12104       LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
12105       RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
12106       Result = APSInt(MaxBits, !IsSigned);
12107     }
12108 
12109     // Find largest int.
12110     switch (BuiltinOp) {
12111     default:
12112       llvm_unreachable("Invalid value for BuiltinOp");
12113     case Builtin::BI__builtin_add_overflow:
12114     case Builtin::BI__builtin_sadd_overflow:
12115     case Builtin::BI__builtin_saddl_overflow:
12116     case Builtin::BI__builtin_saddll_overflow:
12117     case Builtin::BI__builtin_uadd_overflow:
12118     case Builtin::BI__builtin_uaddl_overflow:
12119     case Builtin::BI__builtin_uaddll_overflow:
12120       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
12121                               : LHS.uadd_ov(RHS, DidOverflow);
12122       break;
12123     case Builtin::BI__builtin_sub_overflow:
12124     case Builtin::BI__builtin_ssub_overflow:
12125     case Builtin::BI__builtin_ssubl_overflow:
12126     case Builtin::BI__builtin_ssubll_overflow:
12127     case Builtin::BI__builtin_usub_overflow:
12128     case Builtin::BI__builtin_usubl_overflow:
12129     case Builtin::BI__builtin_usubll_overflow:
12130       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
12131                               : LHS.usub_ov(RHS, DidOverflow);
12132       break;
12133     case Builtin::BI__builtin_mul_overflow:
12134     case Builtin::BI__builtin_smul_overflow:
12135     case Builtin::BI__builtin_smull_overflow:
12136     case Builtin::BI__builtin_smulll_overflow:
12137     case Builtin::BI__builtin_umul_overflow:
12138     case Builtin::BI__builtin_umull_overflow:
12139     case Builtin::BI__builtin_umulll_overflow:
12140       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
12141                               : LHS.umul_ov(RHS, DidOverflow);
12142       break;
12143     }
12144 
12145     // In the case where multiple sizes are allowed, truncate and see if
12146     // the values are the same.
12147     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12148         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12149         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12150       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
12151       // since it will give us the behavior of a TruncOrSelf in the case where
12152       // its parameter <= its size.  We previously set Result to be at least the
12153       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
12154       // will work exactly like TruncOrSelf.
12155       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
12156       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
12157 
12158       if (!APSInt::isSameValue(Temp, Result))
12159         DidOverflow = true;
12160       Result = Temp;
12161     }
12162 
12163     APValue APV{Result};
12164     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
12165       return false;
12166     return Success(DidOverflow, E);
12167   }
12168   }
12169 }
12170 
12171 /// Determine whether this is a pointer past the end of the complete
12172 /// object referred to by the lvalue.
12173 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
12174                                             const LValue &LV) {
12175   // A null pointer can be viewed as being "past the end" but we don't
12176   // choose to look at it that way here.
12177   if (!LV.getLValueBase())
12178     return false;
12179 
12180   // If the designator is valid and refers to a subobject, we're not pointing
12181   // past the end.
12182   if (!LV.getLValueDesignator().Invalid &&
12183       !LV.getLValueDesignator().isOnePastTheEnd())
12184     return false;
12185 
12186   // A pointer to an incomplete type might be past-the-end if the type's size is
12187   // zero.  We cannot tell because the type is incomplete.
12188   QualType Ty = getType(LV.getLValueBase());
12189   if (Ty->isIncompleteType())
12190     return true;
12191 
12192   // We're a past-the-end pointer if we point to the byte after the object,
12193   // no matter what our type or path is.
12194   auto Size = Ctx.getTypeSizeInChars(Ty);
12195   return LV.getLValueOffset() == Size;
12196 }
12197 
12198 namespace {
12199 
12200 /// Data recursive integer evaluator of certain binary operators.
12201 ///
12202 /// We use a data recursive algorithm for binary operators so that we are able
12203 /// to handle extreme cases of chained binary operators without causing stack
12204 /// overflow.
12205 class DataRecursiveIntBinOpEvaluator {
12206   struct EvalResult {
12207     APValue Val;
12208     bool Failed;
12209 
12210     EvalResult() : Failed(false) { }
12211 
12212     void swap(EvalResult &RHS) {
12213       Val.swap(RHS.Val);
12214       Failed = RHS.Failed;
12215       RHS.Failed = false;
12216     }
12217   };
12218 
12219   struct Job {
12220     const Expr *E;
12221     EvalResult LHSResult; // meaningful only for binary operator expression.
12222     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
12223 
12224     Job() = default;
12225     Job(Job &&) = default;
12226 
12227     void startSpeculativeEval(EvalInfo &Info) {
12228       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
12229     }
12230 
12231   private:
12232     SpeculativeEvaluationRAII SpecEvalRAII;
12233   };
12234 
12235   SmallVector<Job, 16> Queue;
12236 
12237   IntExprEvaluator &IntEval;
12238   EvalInfo &Info;
12239   APValue &FinalResult;
12240 
12241 public:
12242   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
12243     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
12244 
12245   /// True if \param E is a binary operator that we are going to handle
12246   /// data recursively.
12247   /// We handle binary operators that are comma, logical, or that have operands
12248   /// with integral or enumeration type.
12249   static bool shouldEnqueue(const BinaryOperator *E) {
12250     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
12251            (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() &&
12252             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12253             E->getRHS()->getType()->isIntegralOrEnumerationType());
12254   }
12255 
12256   bool Traverse(const BinaryOperator *E) {
12257     enqueue(E);
12258     EvalResult PrevResult;
12259     while (!Queue.empty())
12260       process(PrevResult);
12261 
12262     if (PrevResult.Failed) return false;
12263 
12264     FinalResult.swap(PrevResult.Val);
12265     return true;
12266   }
12267 
12268 private:
12269   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
12270     return IntEval.Success(Value, E, Result);
12271   }
12272   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
12273     return IntEval.Success(Value, E, Result);
12274   }
12275   bool Error(const Expr *E) {
12276     return IntEval.Error(E);
12277   }
12278   bool Error(const Expr *E, diag::kind D) {
12279     return IntEval.Error(E, D);
12280   }
12281 
12282   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
12283     return Info.CCEDiag(E, D);
12284   }
12285 
12286   // Returns true if visiting the RHS is necessary, false otherwise.
12287   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12288                          bool &SuppressRHSDiags);
12289 
12290   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12291                   const BinaryOperator *E, APValue &Result);
12292 
12293   void EvaluateExpr(const Expr *E, EvalResult &Result) {
12294     Result.Failed = !Evaluate(Result.Val, Info, E);
12295     if (Result.Failed)
12296       Result.Val = APValue();
12297   }
12298 
12299   void process(EvalResult &Result);
12300 
12301   void enqueue(const Expr *E) {
12302     E = E->IgnoreParens();
12303     Queue.resize(Queue.size()+1);
12304     Queue.back().E = E;
12305     Queue.back().Kind = Job::AnyExprKind;
12306   }
12307 };
12308 
12309 }
12310 
12311 bool DataRecursiveIntBinOpEvaluator::
12312        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12313                          bool &SuppressRHSDiags) {
12314   if (E->getOpcode() == BO_Comma) {
12315     // Ignore LHS but note if we could not evaluate it.
12316     if (LHSResult.Failed)
12317       return Info.noteSideEffect();
12318     return true;
12319   }
12320 
12321   if (E->isLogicalOp()) {
12322     bool LHSAsBool;
12323     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
12324       // We were able to evaluate the LHS, see if we can get away with not
12325       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
12326       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
12327         Success(LHSAsBool, E, LHSResult.Val);
12328         return false; // Ignore RHS
12329       }
12330     } else {
12331       LHSResult.Failed = true;
12332 
12333       // Since we weren't able to evaluate the left hand side, it
12334       // might have had side effects.
12335       if (!Info.noteSideEffect())
12336         return false;
12337 
12338       // We can't evaluate the LHS; however, sometimes the result
12339       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12340       // Don't ignore RHS and suppress diagnostics from this arm.
12341       SuppressRHSDiags = true;
12342     }
12343 
12344     return true;
12345   }
12346 
12347   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12348          E->getRHS()->getType()->isIntegralOrEnumerationType());
12349 
12350   if (LHSResult.Failed && !Info.noteFailure())
12351     return false; // Ignore RHS;
12352 
12353   return true;
12354 }
12355 
12356 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
12357                                     bool IsSub) {
12358   // Compute the new offset in the appropriate width, wrapping at 64 bits.
12359   // FIXME: When compiling for a 32-bit target, we should use 32-bit
12360   // offsets.
12361   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
12362   CharUnits &Offset = LVal.getLValueOffset();
12363   uint64_t Offset64 = Offset.getQuantity();
12364   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
12365   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
12366                                          : Offset64 + Index64);
12367 }
12368 
12369 bool DataRecursiveIntBinOpEvaluator::
12370        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12371                   const BinaryOperator *E, APValue &Result) {
12372   if (E->getOpcode() == BO_Comma) {
12373     if (RHSResult.Failed)
12374       return false;
12375     Result = RHSResult.Val;
12376     return true;
12377   }
12378 
12379   if (E->isLogicalOp()) {
12380     bool lhsResult, rhsResult;
12381     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
12382     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
12383 
12384     if (LHSIsOK) {
12385       if (RHSIsOK) {
12386         if (E->getOpcode() == BO_LOr)
12387           return Success(lhsResult || rhsResult, E, Result);
12388         else
12389           return Success(lhsResult && rhsResult, E, Result);
12390       }
12391     } else {
12392       if (RHSIsOK) {
12393         // We can't evaluate the LHS; however, sometimes the result
12394         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12395         if (rhsResult == (E->getOpcode() == BO_LOr))
12396           return Success(rhsResult, E, Result);
12397       }
12398     }
12399 
12400     return false;
12401   }
12402 
12403   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12404          E->getRHS()->getType()->isIntegralOrEnumerationType());
12405 
12406   if (LHSResult.Failed || RHSResult.Failed)
12407     return false;
12408 
12409   const APValue &LHSVal = LHSResult.Val;
12410   const APValue &RHSVal = RHSResult.Val;
12411 
12412   // Handle cases like (unsigned long)&a + 4.
12413   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
12414     Result = LHSVal;
12415     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
12416     return true;
12417   }
12418 
12419   // Handle cases like 4 + (unsigned long)&a
12420   if (E->getOpcode() == BO_Add &&
12421       RHSVal.isLValue() && LHSVal.isInt()) {
12422     Result = RHSVal;
12423     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
12424     return true;
12425   }
12426 
12427   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
12428     // Handle (intptr_t)&&A - (intptr_t)&&B.
12429     if (!LHSVal.getLValueOffset().isZero() ||
12430         !RHSVal.getLValueOffset().isZero())
12431       return false;
12432     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
12433     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
12434     if (!LHSExpr || !RHSExpr)
12435       return false;
12436     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12437     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12438     if (!LHSAddrExpr || !RHSAddrExpr)
12439       return false;
12440     // Make sure both labels come from the same function.
12441     if (LHSAddrExpr->getLabel()->getDeclContext() !=
12442         RHSAddrExpr->getLabel()->getDeclContext())
12443       return false;
12444     Result = APValue(LHSAddrExpr, RHSAddrExpr);
12445     return true;
12446   }
12447 
12448   // All the remaining cases expect both operands to be an integer
12449   if (!LHSVal.isInt() || !RHSVal.isInt())
12450     return Error(E);
12451 
12452   // Set up the width and signedness manually, in case it can't be deduced
12453   // from the operation we're performing.
12454   // FIXME: Don't do this in the cases where we can deduce it.
12455   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
12456                E->getType()->isUnsignedIntegerOrEnumerationType());
12457   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
12458                          RHSVal.getInt(), Value))
12459     return false;
12460   return Success(Value, E, Result);
12461 }
12462 
12463 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
12464   Job &job = Queue.back();
12465 
12466   switch (job.Kind) {
12467     case Job::AnyExprKind: {
12468       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
12469         if (shouldEnqueue(Bop)) {
12470           job.Kind = Job::BinOpKind;
12471           enqueue(Bop->getLHS());
12472           return;
12473         }
12474       }
12475 
12476       EvaluateExpr(job.E, Result);
12477       Queue.pop_back();
12478       return;
12479     }
12480 
12481     case Job::BinOpKind: {
12482       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12483       bool SuppressRHSDiags = false;
12484       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
12485         Queue.pop_back();
12486         return;
12487       }
12488       if (SuppressRHSDiags)
12489         job.startSpeculativeEval(Info);
12490       job.LHSResult.swap(Result);
12491       job.Kind = Job::BinOpVisitedLHSKind;
12492       enqueue(Bop->getRHS());
12493       return;
12494     }
12495 
12496     case Job::BinOpVisitedLHSKind: {
12497       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12498       EvalResult RHS;
12499       RHS.swap(Result);
12500       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
12501       Queue.pop_back();
12502       return;
12503     }
12504   }
12505 
12506   llvm_unreachable("Invalid Job::Kind!");
12507 }
12508 
12509 namespace {
12510 enum class CmpResult {
12511   Unequal,
12512   Less,
12513   Equal,
12514   Greater,
12515   Unordered,
12516 };
12517 }
12518 
12519 template <class SuccessCB, class AfterCB>
12520 static bool
12521 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
12522                                  SuccessCB &&Success, AfterCB &&DoAfter) {
12523   assert(!E->isValueDependent());
12524   assert(E->isComparisonOp() && "expected comparison operator");
12525   assert((E->getOpcode() == BO_Cmp ||
12526           E->getType()->isIntegralOrEnumerationType()) &&
12527          "unsupported binary expression evaluation");
12528   auto Error = [&](const Expr *E) {
12529     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12530     return false;
12531   };
12532 
12533   bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
12534   bool IsEquality = E->isEqualityOp();
12535 
12536   QualType LHSTy = E->getLHS()->getType();
12537   QualType RHSTy = E->getRHS()->getType();
12538 
12539   if (LHSTy->isIntegralOrEnumerationType() &&
12540       RHSTy->isIntegralOrEnumerationType()) {
12541     APSInt LHS, RHS;
12542     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
12543     if (!LHSOK && !Info.noteFailure())
12544       return false;
12545     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
12546       return false;
12547     if (LHS < RHS)
12548       return Success(CmpResult::Less, E);
12549     if (LHS > RHS)
12550       return Success(CmpResult::Greater, E);
12551     return Success(CmpResult::Equal, E);
12552   }
12553 
12554   if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
12555     APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
12556     APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
12557 
12558     bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
12559     if (!LHSOK && !Info.noteFailure())
12560       return false;
12561     if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
12562       return false;
12563     if (LHSFX < RHSFX)
12564       return Success(CmpResult::Less, E);
12565     if (LHSFX > RHSFX)
12566       return Success(CmpResult::Greater, E);
12567     return Success(CmpResult::Equal, E);
12568   }
12569 
12570   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
12571     ComplexValue LHS, RHS;
12572     bool LHSOK;
12573     if (E->isAssignmentOp()) {
12574       LValue LV;
12575       EvaluateLValue(E->getLHS(), LV, Info);
12576       LHSOK = false;
12577     } else if (LHSTy->isRealFloatingType()) {
12578       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
12579       if (LHSOK) {
12580         LHS.makeComplexFloat();
12581         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
12582       }
12583     } else {
12584       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
12585     }
12586     if (!LHSOK && !Info.noteFailure())
12587       return false;
12588 
12589     if (E->getRHS()->getType()->isRealFloatingType()) {
12590       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
12591         return false;
12592       RHS.makeComplexFloat();
12593       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
12594     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
12595       return false;
12596 
12597     if (LHS.isComplexFloat()) {
12598       APFloat::cmpResult CR_r =
12599         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
12600       APFloat::cmpResult CR_i =
12601         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
12602       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
12603       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12604     } else {
12605       assert(IsEquality && "invalid complex comparison");
12606       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
12607                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
12608       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12609     }
12610   }
12611 
12612   if (LHSTy->isRealFloatingType() &&
12613       RHSTy->isRealFloatingType()) {
12614     APFloat RHS(0.0), LHS(0.0);
12615 
12616     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
12617     if (!LHSOK && !Info.noteFailure())
12618       return false;
12619 
12620     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
12621       return false;
12622 
12623     assert(E->isComparisonOp() && "Invalid binary operator!");
12624     llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
12625     if (!Info.InConstantContext &&
12626         APFloatCmpResult == APFloat::cmpUnordered &&
12627         E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
12628       // Note: Compares may raise invalid in some cases involving NaN or sNaN.
12629       Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
12630       return false;
12631     }
12632     auto GetCmpRes = [&]() {
12633       switch (APFloatCmpResult) {
12634       case APFloat::cmpEqual:
12635         return CmpResult::Equal;
12636       case APFloat::cmpLessThan:
12637         return CmpResult::Less;
12638       case APFloat::cmpGreaterThan:
12639         return CmpResult::Greater;
12640       case APFloat::cmpUnordered:
12641         return CmpResult::Unordered;
12642       }
12643       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
12644     };
12645     return Success(GetCmpRes(), E);
12646   }
12647 
12648   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
12649     LValue LHSValue, RHSValue;
12650 
12651     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12652     if (!LHSOK && !Info.noteFailure())
12653       return false;
12654 
12655     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12656       return false;
12657 
12658     // Reject differing bases from the normal codepath; we special-case
12659     // comparisons to null.
12660     if (!HasSameBase(LHSValue, RHSValue)) {
12661       // Inequalities and subtractions between unrelated pointers have
12662       // unspecified or undefined behavior.
12663       if (!IsEquality) {
12664         Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified);
12665         return false;
12666       }
12667       // A constant address may compare equal to the address of a symbol.
12668       // The one exception is that address of an object cannot compare equal
12669       // to a null pointer constant.
12670       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
12671           (!RHSValue.Base && !RHSValue.Offset.isZero()))
12672         return Error(E);
12673       // It's implementation-defined whether distinct literals will have
12674       // distinct addresses. In clang, the result of such a comparison is
12675       // unspecified, so it is not a constant expression. However, we do know
12676       // that the address of a literal will be non-null.
12677       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
12678           LHSValue.Base && RHSValue.Base)
12679         return Error(E);
12680       // We can't tell whether weak symbols will end up pointing to the same
12681       // object.
12682       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
12683         return Error(E);
12684       // We can't compare the address of the start of one object with the
12685       // past-the-end address of another object, per C++ DR1652.
12686       if ((LHSValue.Base && LHSValue.Offset.isZero() &&
12687            isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
12688           (RHSValue.Base && RHSValue.Offset.isZero() &&
12689            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
12690         return Error(E);
12691       // We can't tell whether an object is at the same address as another
12692       // zero sized object.
12693       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
12694           (LHSValue.Base && isZeroSized(RHSValue)))
12695         return Error(E);
12696       return Success(CmpResult::Unequal, E);
12697     }
12698 
12699     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12700     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12701 
12702     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12703     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12704 
12705     // C++11 [expr.rel]p3:
12706     //   Pointers to void (after pointer conversions) can be compared, with a
12707     //   result defined as follows: If both pointers represent the same
12708     //   address or are both the null pointer value, the result is true if the
12709     //   operator is <= or >= and false otherwise; otherwise the result is
12710     //   unspecified.
12711     // We interpret this as applying to pointers to *cv* void.
12712     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
12713       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
12714 
12715     // C++11 [expr.rel]p2:
12716     // - If two pointers point to non-static data members of the same object,
12717     //   or to subobjects or array elements fo such members, recursively, the
12718     //   pointer to the later declared member compares greater provided the
12719     //   two members have the same access control and provided their class is
12720     //   not a union.
12721     //   [...]
12722     // - Otherwise pointer comparisons are unspecified.
12723     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
12724       bool WasArrayIndex;
12725       unsigned Mismatch = FindDesignatorMismatch(
12726           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
12727       // At the point where the designators diverge, the comparison has a
12728       // specified value if:
12729       //  - we are comparing array indices
12730       //  - we are comparing fields of a union, or fields with the same access
12731       // Otherwise, the result is unspecified and thus the comparison is not a
12732       // constant expression.
12733       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
12734           Mismatch < RHSDesignator.Entries.size()) {
12735         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
12736         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
12737         if (!LF && !RF)
12738           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
12739         else if (!LF)
12740           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12741               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
12742               << RF->getParent() << RF;
12743         else if (!RF)
12744           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12745               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
12746               << LF->getParent() << LF;
12747         else if (!LF->getParent()->isUnion() &&
12748                  LF->getAccess() != RF->getAccess())
12749           Info.CCEDiag(E,
12750                        diag::note_constexpr_pointer_comparison_differing_access)
12751               << LF << LF->getAccess() << RF << RF->getAccess()
12752               << LF->getParent();
12753       }
12754     }
12755 
12756     // The comparison here must be unsigned, and performed with the same
12757     // width as the pointer.
12758     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
12759     uint64_t CompareLHS = LHSOffset.getQuantity();
12760     uint64_t CompareRHS = RHSOffset.getQuantity();
12761     assert(PtrSize <= 64 && "Unexpected pointer width");
12762     uint64_t Mask = ~0ULL >> (64 - PtrSize);
12763     CompareLHS &= Mask;
12764     CompareRHS &= Mask;
12765 
12766     // If there is a base and this is a relational operator, we can only
12767     // compare pointers within the object in question; otherwise, the result
12768     // depends on where the object is located in memory.
12769     if (!LHSValue.Base.isNull() && IsRelational) {
12770       QualType BaseTy = getType(LHSValue.Base);
12771       if (BaseTy->isIncompleteType())
12772         return Error(E);
12773       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
12774       uint64_t OffsetLimit = Size.getQuantity();
12775       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
12776         return Error(E);
12777     }
12778 
12779     if (CompareLHS < CompareRHS)
12780       return Success(CmpResult::Less, E);
12781     if (CompareLHS > CompareRHS)
12782       return Success(CmpResult::Greater, E);
12783     return Success(CmpResult::Equal, E);
12784   }
12785 
12786   if (LHSTy->isMemberPointerType()) {
12787     assert(IsEquality && "unexpected member pointer operation");
12788     assert(RHSTy->isMemberPointerType() && "invalid comparison");
12789 
12790     MemberPtr LHSValue, RHSValue;
12791 
12792     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
12793     if (!LHSOK && !Info.noteFailure())
12794       return false;
12795 
12796     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12797       return false;
12798 
12799     // C++11 [expr.eq]p2:
12800     //   If both operands are null, they compare equal. Otherwise if only one is
12801     //   null, they compare unequal.
12802     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
12803       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
12804       return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12805     }
12806 
12807     //   Otherwise if either is a pointer to a virtual member function, the
12808     //   result is unspecified.
12809     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
12810       if (MD->isVirtual())
12811         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12812     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
12813       if (MD->isVirtual())
12814         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12815 
12816     //   Otherwise they compare equal if and only if they would refer to the
12817     //   same member of the same most derived object or the same subobject if
12818     //   they were dereferenced with a hypothetical object of the associated
12819     //   class type.
12820     bool Equal = LHSValue == RHSValue;
12821     return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12822   }
12823 
12824   if (LHSTy->isNullPtrType()) {
12825     assert(E->isComparisonOp() && "unexpected nullptr operation");
12826     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
12827     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
12828     // are compared, the result is true of the operator is <=, >= or ==, and
12829     // false otherwise.
12830     return Success(CmpResult::Equal, E);
12831   }
12832 
12833   return DoAfter();
12834 }
12835 
12836 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
12837   if (!CheckLiteralType(Info, E))
12838     return false;
12839 
12840   auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12841     ComparisonCategoryResult CCR;
12842     switch (CR) {
12843     case CmpResult::Unequal:
12844       llvm_unreachable("should never produce Unequal for three-way comparison");
12845     case CmpResult::Less:
12846       CCR = ComparisonCategoryResult::Less;
12847       break;
12848     case CmpResult::Equal:
12849       CCR = ComparisonCategoryResult::Equal;
12850       break;
12851     case CmpResult::Greater:
12852       CCR = ComparisonCategoryResult::Greater;
12853       break;
12854     case CmpResult::Unordered:
12855       CCR = ComparisonCategoryResult::Unordered;
12856       break;
12857     }
12858     // Evaluation succeeded. Lookup the information for the comparison category
12859     // type and fetch the VarDecl for the result.
12860     const ComparisonCategoryInfo &CmpInfo =
12861         Info.Ctx.CompCategories.getInfoForType(E->getType());
12862     const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
12863     // Check and evaluate the result as a constant expression.
12864     LValue LV;
12865     LV.set(VD);
12866     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
12867       return false;
12868     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
12869                                    ConstantExprKind::Normal);
12870   };
12871   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12872     return ExprEvaluatorBaseTy::VisitBinCmp(E);
12873   });
12874 }
12875 
12876 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12877   // We don't support assignment in C. C++ assignments don't get here because
12878   // assignment is an lvalue in C++.
12879   if (E->isAssignmentOp()) {
12880     Error(E);
12881     if (!Info.noteFailure())
12882       return false;
12883   }
12884 
12885   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
12886     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
12887 
12888   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
12889           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
12890          "DataRecursiveIntBinOpEvaluator should have handled integral types");
12891 
12892   if (E->isComparisonOp()) {
12893     // Evaluate builtin binary comparisons by evaluating them as three-way
12894     // comparisons and then translating the result.
12895     auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12896       assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
12897              "should only produce Unequal for equality comparisons");
12898       bool IsEqual   = CR == CmpResult::Equal,
12899            IsLess    = CR == CmpResult::Less,
12900            IsGreater = CR == CmpResult::Greater;
12901       auto Op = E->getOpcode();
12902       switch (Op) {
12903       default:
12904         llvm_unreachable("unsupported binary operator");
12905       case BO_EQ:
12906       case BO_NE:
12907         return Success(IsEqual == (Op == BO_EQ), E);
12908       case BO_LT:
12909         return Success(IsLess, E);
12910       case BO_GT:
12911         return Success(IsGreater, E);
12912       case BO_LE:
12913         return Success(IsEqual || IsLess, E);
12914       case BO_GE:
12915         return Success(IsEqual || IsGreater, E);
12916       }
12917     };
12918     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12919       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12920     });
12921   }
12922 
12923   QualType LHSTy = E->getLHS()->getType();
12924   QualType RHSTy = E->getRHS()->getType();
12925 
12926   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
12927       E->getOpcode() == BO_Sub) {
12928     LValue LHSValue, RHSValue;
12929 
12930     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12931     if (!LHSOK && !Info.noteFailure())
12932       return false;
12933 
12934     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12935       return false;
12936 
12937     // Reject differing bases from the normal codepath; we special-case
12938     // comparisons to null.
12939     if (!HasSameBase(LHSValue, RHSValue)) {
12940       // Handle &&A - &&B.
12941       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
12942         return Error(E);
12943       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
12944       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
12945       if (!LHSExpr || !RHSExpr)
12946         return Error(E);
12947       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12948       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12949       if (!LHSAddrExpr || !RHSAddrExpr)
12950         return Error(E);
12951       // Make sure both labels come from the same function.
12952       if (LHSAddrExpr->getLabel()->getDeclContext() !=
12953           RHSAddrExpr->getLabel()->getDeclContext())
12954         return Error(E);
12955       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
12956     }
12957     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12958     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12959 
12960     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12961     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12962 
12963     // C++11 [expr.add]p6:
12964     //   Unless both pointers point to elements of the same array object, or
12965     //   one past the last element of the array object, the behavior is
12966     //   undefined.
12967     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
12968         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
12969                                 RHSDesignator))
12970       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
12971 
12972     QualType Type = E->getLHS()->getType();
12973     QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
12974 
12975     CharUnits ElementSize;
12976     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
12977       return false;
12978 
12979     // As an extension, a type may have zero size (empty struct or union in
12980     // C, array of zero length). Pointer subtraction in such cases has
12981     // undefined behavior, so is not constant.
12982     if (ElementSize.isZero()) {
12983       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
12984           << ElementType;
12985       return false;
12986     }
12987 
12988     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
12989     // and produce incorrect results when it overflows. Such behavior
12990     // appears to be non-conforming, but is common, so perhaps we should
12991     // assume the standard intended for such cases to be undefined behavior
12992     // and check for them.
12993 
12994     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
12995     // overflow in the final conversion to ptrdiff_t.
12996     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
12997     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
12998     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
12999                     false);
13000     APSInt TrueResult = (LHS - RHS) / ElemSize;
13001     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
13002 
13003     if (Result.extend(65) != TrueResult &&
13004         !HandleOverflow(Info, E, TrueResult, E->getType()))
13005       return false;
13006     return Success(Result, E);
13007   }
13008 
13009   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13010 }
13011 
13012 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
13013 /// a result as the expression's type.
13014 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
13015                                     const UnaryExprOrTypeTraitExpr *E) {
13016   switch(E->getKind()) {
13017   case UETT_PreferredAlignOf:
13018   case UETT_AlignOf: {
13019     if (E->isArgumentType())
13020       return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
13021                      E);
13022     else
13023       return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
13024                      E);
13025   }
13026 
13027   case UETT_VecStep: {
13028     QualType Ty = E->getTypeOfArgument();
13029 
13030     if (Ty->isVectorType()) {
13031       unsigned n = Ty->castAs<VectorType>()->getNumElements();
13032 
13033       // The vec_step built-in functions that take a 3-component
13034       // vector return 4. (OpenCL 1.1 spec 6.11.12)
13035       if (n == 3)
13036         n = 4;
13037 
13038       return Success(n, E);
13039     } else
13040       return Success(1, E);
13041   }
13042 
13043   case UETT_SizeOf: {
13044     QualType SrcTy = E->getTypeOfArgument();
13045     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
13046     //   the result is the size of the referenced type."
13047     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
13048       SrcTy = Ref->getPointeeType();
13049 
13050     CharUnits Sizeof;
13051     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
13052       return false;
13053     return Success(Sizeof, E);
13054   }
13055   case UETT_OpenMPRequiredSimdAlign:
13056     assert(E->isArgumentType());
13057     return Success(
13058         Info.Ctx.toCharUnitsFromBits(
13059                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
13060             .getQuantity(),
13061         E);
13062   }
13063 
13064   llvm_unreachable("unknown expr/type trait");
13065 }
13066 
13067 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
13068   CharUnits Result;
13069   unsigned n = OOE->getNumComponents();
13070   if (n == 0)
13071     return Error(OOE);
13072   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
13073   for (unsigned i = 0; i != n; ++i) {
13074     OffsetOfNode ON = OOE->getComponent(i);
13075     switch (ON.getKind()) {
13076     case OffsetOfNode::Array: {
13077       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
13078       APSInt IdxResult;
13079       if (!EvaluateInteger(Idx, IdxResult, Info))
13080         return false;
13081       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
13082       if (!AT)
13083         return Error(OOE);
13084       CurrentType = AT->getElementType();
13085       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
13086       Result += IdxResult.getSExtValue() * ElementSize;
13087       break;
13088     }
13089 
13090     case OffsetOfNode::Field: {
13091       FieldDecl *MemberDecl = ON.getField();
13092       const RecordType *RT = CurrentType->getAs<RecordType>();
13093       if (!RT)
13094         return Error(OOE);
13095       RecordDecl *RD = RT->getDecl();
13096       if (RD->isInvalidDecl()) return false;
13097       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13098       unsigned i = MemberDecl->getFieldIndex();
13099       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
13100       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
13101       CurrentType = MemberDecl->getType().getNonReferenceType();
13102       break;
13103     }
13104 
13105     case OffsetOfNode::Identifier:
13106       llvm_unreachable("dependent __builtin_offsetof");
13107 
13108     case OffsetOfNode::Base: {
13109       CXXBaseSpecifier *BaseSpec = ON.getBase();
13110       if (BaseSpec->isVirtual())
13111         return Error(OOE);
13112 
13113       // Find the layout of the class whose base we are looking into.
13114       const RecordType *RT = CurrentType->getAs<RecordType>();
13115       if (!RT)
13116         return Error(OOE);
13117       RecordDecl *RD = RT->getDecl();
13118       if (RD->isInvalidDecl()) return false;
13119       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13120 
13121       // Find the base class itself.
13122       CurrentType = BaseSpec->getType();
13123       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
13124       if (!BaseRT)
13125         return Error(OOE);
13126 
13127       // Add the offset to the base.
13128       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
13129       break;
13130     }
13131     }
13132   }
13133   return Success(Result, OOE);
13134 }
13135 
13136 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13137   switch (E->getOpcode()) {
13138   default:
13139     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
13140     // See C99 6.6p3.
13141     return Error(E);
13142   case UO_Extension:
13143     // FIXME: Should extension allow i-c-e extension expressions in its scope?
13144     // If so, we could clear the diagnostic ID.
13145     return Visit(E->getSubExpr());
13146   case UO_Plus:
13147     // The result is just the value.
13148     return Visit(E->getSubExpr());
13149   case UO_Minus: {
13150     if (!Visit(E->getSubExpr()))
13151       return false;
13152     if (!Result.isInt()) return Error(E);
13153     const APSInt &Value = Result.getInt();
13154     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
13155         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
13156                         E->getType()))
13157       return false;
13158     return Success(-Value, E);
13159   }
13160   case UO_Not: {
13161     if (!Visit(E->getSubExpr()))
13162       return false;
13163     if (!Result.isInt()) return Error(E);
13164     return Success(~Result.getInt(), E);
13165   }
13166   case UO_LNot: {
13167     bool bres;
13168     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13169       return false;
13170     return Success(!bres, E);
13171   }
13172   }
13173 }
13174 
13175 /// HandleCast - This is used to evaluate implicit or explicit casts where the
13176 /// result type is integer.
13177 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
13178   const Expr *SubExpr = E->getSubExpr();
13179   QualType DestType = E->getType();
13180   QualType SrcType = SubExpr->getType();
13181 
13182   switch (E->getCastKind()) {
13183   case CK_BaseToDerived:
13184   case CK_DerivedToBase:
13185   case CK_UncheckedDerivedToBase:
13186   case CK_Dynamic:
13187   case CK_ToUnion:
13188   case CK_ArrayToPointerDecay:
13189   case CK_FunctionToPointerDecay:
13190   case CK_NullToPointer:
13191   case CK_NullToMemberPointer:
13192   case CK_BaseToDerivedMemberPointer:
13193   case CK_DerivedToBaseMemberPointer:
13194   case CK_ReinterpretMemberPointer:
13195   case CK_ConstructorConversion:
13196   case CK_IntegralToPointer:
13197   case CK_ToVoid:
13198   case CK_VectorSplat:
13199   case CK_IntegralToFloating:
13200   case CK_FloatingCast:
13201   case CK_CPointerToObjCPointerCast:
13202   case CK_BlockPointerToObjCPointerCast:
13203   case CK_AnyPointerToBlockPointerCast:
13204   case CK_ObjCObjectLValueCast:
13205   case CK_FloatingRealToComplex:
13206   case CK_FloatingComplexToReal:
13207   case CK_FloatingComplexCast:
13208   case CK_FloatingComplexToIntegralComplex:
13209   case CK_IntegralRealToComplex:
13210   case CK_IntegralComplexCast:
13211   case CK_IntegralComplexToFloatingComplex:
13212   case CK_BuiltinFnToFnPtr:
13213   case CK_ZeroToOCLOpaqueType:
13214   case CK_NonAtomicToAtomic:
13215   case CK_AddressSpaceConversion:
13216   case CK_IntToOCLSampler:
13217   case CK_FloatingToFixedPoint:
13218   case CK_FixedPointToFloating:
13219   case CK_FixedPointCast:
13220   case CK_IntegralToFixedPoint:
13221   case CK_MatrixCast:
13222     llvm_unreachable("invalid cast kind for integral value");
13223 
13224   case CK_BitCast:
13225   case CK_Dependent:
13226   case CK_LValueBitCast:
13227   case CK_ARCProduceObject:
13228   case CK_ARCConsumeObject:
13229   case CK_ARCReclaimReturnedObject:
13230   case CK_ARCExtendBlockObject:
13231   case CK_CopyAndAutoreleaseBlockObject:
13232     return Error(E);
13233 
13234   case CK_UserDefinedConversion:
13235   case CK_LValueToRValue:
13236   case CK_AtomicToNonAtomic:
13237   case CK_NoOp:
13238   case CK_LValueToRValueBitCast:
13239     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13240 
13241   case CK_MemberPointerToBoolean:
13242   case CK_PointerToBoolean:
13243   case CK_IntegralToBoolean:
13244   case CK_FloatingToBoolean:
13245   case CK_BooleanToSignedIntegral:
13246   case CK_FloatingComplexToBoolean:
13247   case CK_IntegralComplexToBoolean: {
13248     bool BoolResult;
13249     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
13250       return false;
13251     uint64_t IntResult = BoolResult;
13252     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
13253       IntResult = (uint64_t)-1;
13254     return Success(IntResult, E);
13255   }
13256 
13257   case CK_FixedPointToIntegral: {
13258     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
13259     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13260       return false;
13261     bool Overflowed;
13262     llvm::APSInt Result = Src.convertToInt(
13263         Info.Ctx.getIntWidth(DestType),
13264         DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
13265     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
13266       return false;
13267     return Success(Result, E);
13268   }
13269 
13270   case CK_FixedPointToBoolean: {
13271     // Unsigned padding does not affect this.
13272     APValue Val;
13273     if (!Evaluate(Val, Info, SubExpr))
13274       return false;
13275     return Success(Val.getFixedPoint().getBoolValue(), E);
13276   }
13277 
13278   case CK_IntegralCast: {
13279     if (!Visit(SubExpr))
13280       return false;
13281 
13282     if (!Result.isInt()) {
13283       // Allow casts of address-of-label differences if they are no-ops
13284       // or narrowing.  (The narrowing case isn't actually guaranteed to
13285       // be constant-evaluatable except in some narrow cases which are hard
13286       // to detect here.  We let it through on the assumption the user knows
13287       // what they are doing.)
13288       if (Result.isAddrLabelDiff())
13289         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
13290       // Only allow casts of lvalues if they are lossless.
13291       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
13292     }
13293 
13294     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
13295                                       Result.getInt()), E);
13296   }
13297 
13298   case CK_PointerToIntegral: {
13299     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
13300 
13301     LValue LV;
13302     if (!EvaluatePointer(SubExpr, LV, Info))
13303       return false;
13304 
13305     if (LV.getLValueBase()) {
13306       // Only allow based lvalue casts if they are lossless.
13307       // FIXME: Allow a larger integer size than the pointer size, and allow
13308       // narrowing back down to pointer width in subsequent integral casts.
13309       // FIXME: Check integer type's active bits, not its type size.
13310       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
13311         return Error(E);
13312 
13313       LV.Designator.setInvalid();
13314       LV.moveInto(Result);
13315       return true;
13316     }
13317 
13318     APSInt AsInt;
13319     APValue V;
13320     LV.moveInto(V);
13321     if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
13322       llvm_unreachable("Can't cast this!");
13323 
13324     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
13325   }
13326 
13327   case CK_IntegralComplexToReal: {
13328     ComplexValue C;
13329     if (!EvaluateComplex(SubExpr, C, Info))
13330       return false;
13331     return Success(C.getComplexIntReal(), E);
13332   }
13333 
13334   case CK_FloatingToIntegral: {
13335     APFloat F(0.0);
13336     if (!EvaluateFloat(SubExpr, F, Info))
13337       return false;
13338 
13339     APSInt Value;
13340     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
13341       return false;
13342     return Success(Value, E);
13343   }
13344   }
13345 
13346   llvm_unreachable("unknown cast resulting in integral value");
13347 }
13348 
13349 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13350   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13351     ComplexValue LV;
13352     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13353       return false;
13354     if (!LV.isComplexInt())
13355       return Error(E);
13356     return Success(LV.getComplexIntReal(), E);
13357   }
13358 
13359   return Visit(E->getSubExpr());
13360 }
13361 
13362 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13363   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
13364     ComplexValue LV;
13365     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13366       return false;
13367     if (!LV.isComplexInt())
13368       return Error(E);
13369     return Success(LV.getComplexIntImag(), E);
13370   }
13371 
13372   VisitIgnoredValue(E->getSubExpr());
13373   return Success(0, E);
13374 }
13375 
13376 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
13377   return Success(E->getPackLength(), E);
13378 }
13379 
13380 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
13381   return Success(E->getValue(), E);
13382 }
13383 
13384 bool IntExprEvaluator::VisitConceptSpecializationExpr(
13385        const ConceptSpecializationExpr *E) {
13386   return Success(E->isSatisfied(), E);
13387 }
13388 
13389 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
13390   return Success(E->isSatisfied(), E);
13391 }
13392 
13393 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13394   switch (E->getOpcode()) {
13395     default:
13396       // Invalid unary operators
13397       return Error(E);
13398     case UO_Plus:
13399       // The result is just the value.
13400       return Visit(E->getSubExpr());
13401     case UO_Minus: {
13402       if (!Visit(E->getSubExpr())) return false;
13403       if (!Result.isFixedPoint())
13404         return Error(E);
13405       bool Overflowed;
13406       APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
13407       if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
13408         return false;
13409       return Success(Negated, E);
13410     }
13411     case UO_LNot: {
13412       bool bres;
13413       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13414         return false;
13415       return Success(!bres, E);
13416     }
13417   }
13418 }
13419 
13420 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
13421   const Expr *SubExpr = E->getSubExpr();
13422   QualType DestType = E->getType();
13423   assert(DestType->isFixedPointType() &&
13424          "Expected destination type to be a fixed point type");
13425   auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
13426 
13427   switch (E->getCastKind()) {
13428   case CK_FixedPointCast: {
13429     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13430     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13431       return false;
13432     bool Overflowed;
13433     APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
13434     if (Overflowed) {
13435       if (Info.checkingForUndefinedBehavior())
13436         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13437                                          diag::warn_fixedpoint_constant_overflow)
13438           << Result.toString() << E->getType();
13439       if (!HandleOverflow(Info, E, Result, E->getType()))
13440         return false;
13441     }
13442     return Success(Result, E);
13443   }
13444   case CK_IntegralToFixedPoint: {
13445     APSInt Src;
13446     if (!EvaluateInteger(SubExpr, Src, Info))
13447       return false;
13448 
13449     bool Overflowed;
13450     APFixedPoint IntResult = APFixedPoint::getFromIntValue(
13451         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13452 
13453     if (Overflowed) {
13454       if (Info.checkingForUndefinedBehavior())
13455         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13456                                          diag::warn_fixedpoint_constant_overflow)
13457           << IntResult.toString() << E->getType();
13458       if (!HandleOverflow(Info, E, IntResult, E->getType()))
13459         return false;
13460     }
13461 
13462     return Success(IntResult, E);
13463   }
13464   case CK_FloatingToFixedPoint: {
13465     APFloat Src(0.0);
13466     if (!EvaluateFloat(SubExpr, Src, Info))
13467       return false;
13468 
13469     bool Overflowed;
13470     APFixedPoint Result = APFixedPoint::getFromFloatValue(
13471         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13472 
13473     if (Overflowed) {
13474       if (Info.checkingForUndefinedBehavior())
13475         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13476                                          diag::warn_fixedpoint_constant_overflow)
13477           << Result.toString() << E->getType();
13478       if (!HandleOverflow(Info, E, Result, E->getType()))
13479         return false;
13480     }
13481 
13482     return Success(Result, E);
13483   }
13484   case CK_NoOp:
13485   case CK_LValueToRValue:
13486     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13487   default:
13488     return Error(E);
13489   }
13490 }
13491 
13492 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13493   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13494     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13495 
13496   const Expr *LHS = E->getLHS();
13497   const Expr *RHS = E->getRHS();
13498   FixedPointSemantics ResultFXSema =
13499       Info.Ctx.getFixedPointSemantics(E->getType());
13500 
13501   APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
13502   if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
13503     return false;
13504   APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
13505   if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
13506     return false;
13507 
13508   bool OpOverflow = false, ConversionOverflow = false;
13509   APFixedPoint Result(LHSFX.getSemantics());
13510   switch (E->getOpcode()) {
13511   case BO_Add: {
13512     Result = LHSFX.add(RHSFX, &OpOverflow)
13513                   .convert(ResultFXSema, &ConversionOverflow);
13514     break;
13515   }
13516   case BO_Sub: {
13517     Result = LHSFX.sub(RHSFX, &OpOverflow)
13518                   .convert(ResultFXSema, &ConversionOverflow);
13519     break;
13520   }
13521   case BO_Mul: {
13522     Result = LHSFX.mul(RHSFX, &OpOverflow)
13523                   .convert(ResultFXSema, &ConversionOverflow);
13524     break;
13525   }
13526   case BO_Div: {
13527     if (RHSFX.getValue() == 0) {
13528       Info.FFDiag(E, diag::note_expr_divide_by_zero);
13529       return false;
13530     }
13531     Result = LHSFX.div(RHSFX, &OpOverflow)
13532                   .convert(ResultFXSema, &ConversionOverflow);
13533     break;
13534   }
13535   case BO_Shl:
13536   case BO_Shr: {
13537     FixedPointSemantics LHSSema = LHSFX.getSemantics();
13538     llvm::APSInt RHSVal = RHSFX.getValue();
13539 
13540     unsigned ShiftBW =
13541         LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
13542     unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
13543     // Embedded-C 4.1.6.2.2:
13544     //   The right operand must be nonnegative and less than the total number
13545     //   of (nonpadding) bits of the fixed-point operand ...
13546     if (RHSVal.isNegative())
13547       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
13548     else if (Amt != RHSVal)
13549       Info.CCEDiag(E, diag::note_constexpr_large_shift)
13550           << RHSVal << E->getType() << ShiftBW;
13551 
13552     if (E->getOpcode() == BO_Shl)
13553       Result = LHSFX.shl(Amt, &OpOverflow);
13554     else
13555       Result = LHSFX.shr(Amt, &OpOverflow);
13556     break;
13557   }
13558   default:
13559     return false;
13560   }
13561   if (OpOverflow || ConversionOverflow) {
13562     if (Info.checkingForUndefinedBehavior())
13563       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13564                                        diag::warn_fixedpoint_constant_overflow)
13565         << Result.toString() << E->getType();
13566     if (!HandleOverflow(Info, E, Result, E->getType()))
13567       return false;
13568   }
13569   return Success(Result, E);
13570 }
13571 
13572 //===----------------------------------------------------------------------===//
13573 // Float Evaluation
13574 //===----------------------------------------------------------------------===//
13575 
13576 namespace {
13577 class FloatExprEvaluator
13578   : public ExprEvaluatorBase<FloatExprEvaluator> {
13579   APFloat &Result;
13580 public:
13581   FloatExprEvaluator(EvalInfo &info, APFloat &result)
13582     : ExprEvaluatorBaseTy(info), Result(result) {}
13583 
13584   bool Success(const APValue &V, const Expr *e) {
13585     Result = V.getFloat();
13586     return true;
13587   }
13588 
13589   bool ZeroInitialization(const Expr *E) {
13590     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
13591     return true;
13592   }
13593 
13594   bool VisitCallExpr(const CallExpr *E);
13595 
13596   bool VisitUnaryOperator(const UnaryOperator *E);
13597   bool VisitBinaryOperator(const BinaryOperator *E);
13598   bool VisitFloatingLiteral(const FloatingLiteral *E);
13599   bool VisitCastExpr(const CastExpr *E);
13600 
13601   bool VisitUnaryReal(const UnaryOperator *E);
13602   bool VisitUnaryImag(const UnaryOperator *E);
13603 
13604   // FIXME: Missing: array subscript of vector, member of vector
13605 };
13606 } // end anonymous namespace
13607 
13608 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
13609   assert(!E->isValueDependent());
13610   assert(E->isPRValue() && E->getType()->isRealFloatingType());
13611   return FloatExprEvaluator(Info, Result).Visit(E);
13612 }
13613 
13614 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
13615                                   QualType ResultTy,
13616                                   const Expr *Arg,
13617                                   bool SNaN,
13618                                   llvm::APFloat &Result) {
13619   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
13620   if (!S) return false;
13621 
13622   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
13623 
13624   llvm::APInt fill;
13625 
13626   // Treat empty strings as if they were zero.
13627   if (S->getString().empty())
13628     fill = llvm::APInt(32, 0);
13629   else if (S->getString().getAsInteger(0, fill))
13630     return false;
13631 
13632   if (Context.getTargetInfo().isNan2008()) {
13633     if (SNaN)
13634       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13635     else
13636       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13637   } else {
13638     // Prior to IEEE 754-2008, architectures were allowed to choose whether
13639     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
13640     // a different encoding to what became a standard in 2008, and for pre-
13641     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
13642     // sNaN. This is now known as "legacy NaN" encoding.
13643     if (SNaN)
13644       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13645     else
13646       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13647   }
13648 
13649   return true;
13650 }
13651 
13652 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
13653   switch (E->getBuiltinCallee()) {
13654   default:
13655     return ExprEvaluatorBaseTy::VisitCallExpr(E);
13656 
13657   case Builtin::BI__builtin_huge_val:
13658   case Builtin::BI__builtin_huge_valf:
13659   case Builtin::BI__builtin_huge_vall:
13660   case Builtin::BI__builtin_huge_valf128:
13661   case Builtin::BI__builtin_inf:
13662   case Builtin::BI__builtin_inff:
13663   case Builtin::BI__builtin_infl:
13664   case Builtin::BI__builtin_inff128: {
13665     const llvm::fltSemantics &Sem =
13666       Info.Ctx.getFloatTypeSemantics(E->getType());
13667     Result = llvm::APFloat::getInf(Sem);
13668     return true;
13669   }
13670 
13671   case Builtin::BI__builtin_nans:
13672   case Builtin::BI__builtin_nansf:
13673   case Builtin::BI__builtin_nansl:
13674   case Builtin::BI__builtin_nansf128:
13675     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13676                                true, Result))
13677       return Error(E);
13678     return true;
13679 
13680   case Builtin::BI__builtin_nan:
13681   case Builtin::BI__builtin_nanf:
13682   case Builtin::BI__builtin_nanl:
13683   case Builtin::BI__builtin_nanf128:
13684     // If this is __builtin_nan() turn this into a nan, otherwise we
13685     // can't constant fold it.
13686     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13687                                false, Result))
13688       return Error(E);
13689     return true;
13690 
13691   case Builtin::BI__builtin_fabs:
13692   case Builtin::BI__builtin_fabsf:
13693   case Builtin::BI__builtin_fabsl:
13694   case Builtin::BI__builtin_fabsf128:
13695     // The C standard says "fabs raises no floating-point exceptions,
13696     // even if x is a signaling NaN. The returned value is independent of
13697     // the current rounding direction mode."  Therefore constant folding can
13698     // proceed without regard to the floating point settings.
13699     // Reference, WG14 N2478 F.10.4.3
13700     if (!EvaluateFloat(E->getArg(0), Result, Info))
13701       return false;
13702 
13703     if (Result.isNegative())
13704       Result.changeSign();
13705     return true;
13706 
13707   case Builtin::BI__arithmetic_fence:
13708     return EvaluateFloat(E->getArg(0), Result, Info);
13709 
13710   // FIXME: Builtin::BI__builtin_powi
13711   // FIXME: Builtin::BI__builtin_powif
13712   // FIXME: Builtin::BI__builtin_powil
13713 
13714   case Builtin::BI__builtin_copysign:
13715   case Builtin::BI__builtin_copysignf:
13716   case Builtin::BI__builtin_copysignl:
13717   case Builtin::BI__builtin_copysignf128: {
13718     APFloat RHS(0.);
13719     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
13720         !EvaluateFloat(E->getArg(1), RHS, Info))
13721       return false;
13722     Result.copySign(RHS);
13723     return true;
13724   }
13725   }
13726 }
13727 
13728 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13729   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13730     ComplexValue CV;
13731     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13732       return false;
13733     Result = CV.FloatReal;
13734     return true;
13735   }
13736 
13737   return Visit(E->getSubExpr());
13738 }
13739 
13740 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13741   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13742     ComplexValue CV;
13743     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13744       return false;
13745     Result = CV.FloatImag;
13746     return true;
13747   }
13748 
13749   VisitIgnoredValue(E->getSubExpr());
13750   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
13751   Result = llvm::APFloat::getZero(Sem);
13752   return true;
13753 }
13754 
13755 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13756   switch (E->getOpcode()) {
13757   default: return Error(E);
13758   case UO_Plus:
13759     return EvaluateFloat(E->getSubExpr(), Result, Info);
13760   case UO_Minus:
13761     // In C standard, WG14 N2478 F.3 p4
13762     // "the unary - raises no floating point exceptions,
13763     // even if the operand is signalling."
13764     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
13765       return false;
13766     Result.changeSign();
13767     return true;
13768   }
13769 }
13770 
13771 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13772   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13773     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13774 
13775   APFloat RHS(0.0);
13776   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
13777   if (!LHSOK && !Info.noteFailure())
13778     return false;
13779   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
13780          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
13781 }
13782 
13783 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
13784   Result = E->getValue();
13785   return true;
13786 }
13787 
13788 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
13789   const Expr* SubExpr = E->getSubExpr();
13790 
13791   switch (E->getCastKind()) {
13792   default:
13793     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13794 
13795   case CK_IntegralToFloating: {
13796     APSInt IntResult;
13797     const FPOptions FPO = E->getFPFeaturesInEffect(
13798                                   Info.Ctx.getLangOpts());
13799     return EvaluateInteger(SubExpr, IntResult, Info) &&
13800            HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
13801                                 IntResult, E->getType(), Result);
13802   }
13803 
13804   case CK_FixedPointToFloating: {
13805     APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13806     if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
13807       return false;
13808     Result =
13809         FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
13810     return true;
13811   }
13812 
13813   case CK_FloatingCast: {
13814     if (!Visit(SubExpr))
13815       return false;
13816     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
13817                                   Result);
13818   }
13819 
13820   case CK_FloatingComplexToReal: {
13821     ComplexValue V;
13822     if (!EvaluateComplex(SubExpr, V, Info))
13823       return false;
13824     Result = V.getComplexFloatReal();
13825     return true;
13826   }
13827   }
13828 }
13829 
13830 //===----------------------------------------------------------------------===//
13831 // Complex Evaluation (for float and integer)
13832 //===----------------------------------------------------------------------===//
13833 
13834 namespace {
13835 class ComplexExprEvaluator
13836   : public ExprEvaluatorBase<ComplexExprEvaluator> {
13837   ComplexValue &Result;
13838 
13839 public:
13840   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
13841     : ExprEvaluatorBaseTy(info), Result(Result) {}
13842 
13843   bool Success(const APValue &V, const Expr *e) {
13844     Result.setFrom(V);
13845     return true;
13846   }
13847 
13848   bool ZeroInitialization(const Expr *E);
13849 
13850   //===--------------------------------------------------------------------===//
13851   //                            Visitor Methods
13852   //===--------------------------------------------------------------------===//
13853 
13854   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
13855   bool VisitCastExpr(const CastExpr *E);
13856   bool VisitBinaryOperator(const BinaryOperator *E);
13857   bool VisitUnaryOperator(const UnaryOperator *E);
13858   bool VisitInitListExpr(const InitListExpr *E);
13859   bool VisitCallExpr(const CallExpr *E);
13860 };
13861 } // end anonymous namespace
13862 
13863 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
13864                             EvalInfo &Info) {
13865   assert(!E->isValueDependent());
13866   assert(E->isPRValue() && E->getType()->isAnyComplexType());
13867   return ComplexExprEvaluator(Info, Result).Visit(E);
13868 }
13869 
13870 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
13871   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
13872   if (ElemTy->isRealFloatingType()) {
13873     Result.makeComplexFloat();
13874     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
13875     Result.FloatReal = Zero;
13876     Result.FloatImag = Zero;
13877   } else {
13878     Result.makeComplexInt();
13879     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
13880     Result.IntReal = Zero;
13881     Result.IntImag = Zero;
13882   }
13883   return true;
13884 }
13885 
13886 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
13887   const Expr* SubExpr = E->getSubExpr();
13888 
13889   if (SubExpr->getType()->isRealFloatingType()) {
13890     Result.makeComplexFloat();
13891     APFloat &Imag = Result.FloatImag;
13892     if (!EvaluateFloat(SubExpr, Imag, Info))
13893       return false;
13894 
13895     Result.FloatReal = APFloat(Imag.getSemantics());
13896     return true;
13897   } else {
13898     assert(SubExpr->getType()->isIntegerType() &&
13899            "Unexpected imaginary literal.");
13900 
13901     Result.makeComplexInt();
13902     APSInt &Imag = Result.IntImag;
13903     if (!EvaluateInteger(SubExpr, Imag, Info))
13904       return false;
13905 
13906     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
13907     return true;
13908   }
13909 }
13910 
13911 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
13912 
13913   switch (E->getCastKind()) {
13914   case CK_BitCast:
13915   case CK_BaseToDerived:
13916   case CK_DerivedToBase:
13917   case CK_UncheckedDerivedToBase:
13918   case CK_Dynamic:
13919   case CK_ToUnion:
13920   case CK_ArrayToPointerDecay:
13921   case CK_FunctionToPointerDecay:
13922   case CK_NullToPointer:
13923   case CK_NullToMemberPointer:
13924   case CK_BaseToDerivedMemberPointer:
13925   case CK_DerivedToBaseMemberPointer:
13926   case CK_MemberPointerToBoolean:
13927   case CK_ReinterpretMemberPointer:
13928   case CK_ConstructorConversion:
13929   case CK_IntegralToPointer:
13930   case CK_PointerToIntegral:
13931   case CK_PointerToBoolean:
13932   case CK_ToVoid:
13933   case CK_VectorSplat:
13934   case CK_IntegralCast:
13935   case CK_BooleanToSignedIntegral:
13936   case CK_IntegralToBoolean:
13937   case CK_IntegralToFloating:
13938   case CK_FloatingToIntegral:
13939   case CK_FloatingToBoolean:
13940   case CK_FloatingCast:
13941   case CK_CPointerToObjCPointerCast:
13942   case CK_BlockPointerToObjCPointerCast:
13943   case CK_AnyPointerToBlockPointerCast:
13944   case CK_ObjCObjectLValueCast:
13945   case CK_FloatingComplexToReal:
13946   case CK_FloatingComplexToBoolean:
13947   case CK_IntegralComplexToReal:
13948   case CK_IntegralComplexToBoolean:
13949   case CK_ARCProduceObject:
13950   case CK_ARCConsumeObject:
13951   case CK_ARCReclaimReturnedObject:
13952   case CK_ARCExtendBlockObject:
13953   case CK_CopyAndAutoreleaseBlockObject:
13954   case CK_BuiltinFnToFnPtr:
13955   case CK_ZeroToOCLOpaqueType:
13956   case CK_NonAtomicToAtomic:
13957   case CK_AddressSpaceConversion:
13958   case CK_IntToOCLSampler:
13959   case CK_FloatingToFixedPoint:
13960   case CK_FixedPointToFloating:
13961   case CK_FixedPointCast:
13962   case CK_FixedPointToBoolean:
13963   case CK_FixedPointToIntegral:
13964   case CK_IntegralToFixedPoint:
13965   case CK_MatrixCast:
13966     llvm_unreachable("invalid cast kind for complex value");
13967 
13968   case CK_LValueToRValue:
13969   case CK_AtomicToNonAtomic:
13970   case CK_NoOp:
13971   case CK_LValueToRValueBitCast:
13972     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13973 
13974   case CK_Dependent:
13975   case CK_LValueBitCast:
13976   case CK_UserDefinedConversion:
13977     return Error(E);
13978 
13979   case CK_FloatingRealToComplex: {
13980     APFloat &Real = Result.FloatReal;
13981     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
13982       return false;
13983 
13984     Result.makeComplexFloat();
13985     Result.FloatImag = APFloat(Real.getSemantics());
13986     return true;
13987   }
13988 
13989   case CK_FloatingComplexCast: {
13990     if (!Visit(E->getSubExpr()))
13991       return false;
13992 
13993     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13994     QualType From
13995       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13996 
13997     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
13998            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
13999   }
14000 
14001   case CK_FloatingComplexToIntegralComplex: {
14002     if (!Visit(E->getSubExpr()))
14003       return false;
14004 
14005     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14006     QualType From
14007       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14008     Result.makeComplexInt();
14009     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
14010                                 To, Result.IntReal) &&
14011            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
14012                                 To, Result.IntImag);
14013   }
14014 
14015   case CK_IntegralRealToComplex: {
14016     APSInt &Real = Result.IntReal;
14017     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
14018       return false;
14019 
14020     Result.makeComplexInt();
14021     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
14022     return true;
14023   }
14024 
14025   case CK_IntegralComplexCast: {
14026     if (!Visit(E->getSubExpr()))
14027       return false;
14028 
14029     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14030     QualType From
14031       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14032 
14033     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
14034     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
14035     return true;
14036   }
14037 
14038   case CK_IntegralComplexToFloatingComplex: {
14039     if (!Visit(E->getSubExpr()))
14040       return false;
14041 
14042     const FPOptions FPO = E->getFPFeaturesInEffect(
14043                                   Info.Ctx.getLangOpts());
14044     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14045     QualType From
14046       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14047     Result.makeComplexFloat();
14048     return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
14049                                 To, Result.FloatReal) &&
14050            HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
14051                                 To, Result.FloatImag);
14052   }
14053   }
14054 
14055   llvm_unreachable("unknown cast resulting in complex value");
14056 }
14057 
14058 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14059   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14060     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14061 
14062   // Track whether the LHS or RHS is real at the type system level. When this is
14063   // the case we can simplify our evaluation strategy.
14064   bool LHSReal = false, RHSReal = false;
14065 
14066   bool LHSOK;
14067   if (E->getLHS()->getType()->isRealFloatingType()) {
14068     LHSReal = true;
14069     APFloat &Real = Result.FloatReal;
14070     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
14071     if (LHSOK) {
14072       Result.makeComplexFloat();
14073       Result.FloatImag = APFloat(Real.getSemantics());
14074     }
14075   } else {
14076     LHSOK = Visit(E->getLHS());
14077   }
14078   if (!LHSOK && !Info.noteFailure())
14079     return false;
14080 
14081   ComplexValue RHS;
14082   if (E->getRHS()->getType()->isRealFloatingType()) {
14083     RHSReal = true;
14084     APFloat &Real = RHS.FloatReal;
14085     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
14086       return false;
14087     RHS.makeComplexFloat();
14088     RHS.FloatImag = APFloat(Real.getSemantics());
14089   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
14090     return false;
14091 
14092   assert(!(LHSReal && RHSReal) &&
14093          "Cannot have both operands of a complex operation be real.");
14094   switch (E->getOpcode()) {
14095   default: return Error(E);
14096   case BO_Add:
14097     if (Result.isComplexFloat()) {
14098       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
14099                                        APFloat::rmNearestTiesToEven);
14100       if (LHSReal)
14101         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14102       else if (!RHSReal)
14103         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
14104                                          APFloat::rmNearestTiesToEven);
14105     } else {
14106       Result.getComplexIntReal() += RHS.getComplexIntReal();
14107       Result.getComplexIntImag() += RHS.getComplexIntImag();
14108     }
14109     break;
14110   case BO_Sub:
14111     if (Result.isComplexFloat()) {
14112       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
14113                                             APFloat::rmNearestTiesToEven);
14114       if (LHSReal) {
14115         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14116         Result.getComplexFloatImag().changeSign();
14117       } else if (!RHSReal) {
14118         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
14119                                               APFloat::rmNearestTiesToEven);
14120       }
14121     } else {
14122       Result.getComplexIntReal() -= RHS.getComplexIntReal();
14123       Result.getComplexIntImag() -= RHS.getComplexIntImag();
14124     }
14125     break;
14126   case BO_Mul:
14127     if (Result.isComplexFloat()) {
14128       // This is an implementation of complex multiplication according to the
14129       // constraints laid out in C11 Annex G. The implementation uses the
14130       // following naming scheme:
14131       //   (a + ib) * (c + id)
14132       ComplexValue LHS = Result;
14133       APFloat &A = LHS.getComplexFloatReal();
14134       APFloat &B = LHS.getComplexFloatImag();
14135       APFloat &C = RHS.getComplexFloatReal();
14136       APFloat &D = RHS.getComplexFloatImag();
14137       APFloat &ResR = Result.getComplexFloatReal();
14138       APFloat &ResI = Result.getComplexFloatImag();
14139       if (LHSReal) {
14140         assert(!RHSReal && "Cannot have two real operands for a complex op!");
14141         ResR = A * C;
14142         ResI = A * D;
14143       } else if (RHSReal) {
14144         ResR = C * A;
14145         ResI = C * B;
14146       } else {
14147         // In the fully general case, we need to handle NaNs and infinities
14148         // robustly.
14149         APFloat AC = A * C;
14150         APFloat BD = B * D;
14151         APFloat AD = A * D;
14152         APFloat BC = B * C;
14153         ResR = AC - BD;
14154         ResI = AD + BC;
14155         if (ResR.isNaN() && ResI.isNaN()) {
14156           bool Recalc = false;
14157           if (A.isInfinity() || B.isInfinity()) {
14158             A = APFloat::copySign(
14159                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14160             B = APFloat::copySign(
14161                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14162             if (C.isNaN())
14163               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14164             if (D.isNaN())
14165               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14166             Recalc = true;
14167           }
14168           if (C.isInfinity() || D.isInfinity()) {
14169             C = APFloat::copySign(
14170                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14171             D = APFloat::copySign(
14172                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14173             if (A.isNaN())
14174               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14175             if (B.isNaN())
14176               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14177             Recalc = true;
14178           }
14179           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
14180                           AD.isInfinity() || BC.isInfinity())) {
14181             if (A.isNaN())
14182               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14183             if (B.isNaN())
14184               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14185             if (C.isNaN())
14186               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14187             if (D.isNaN())
14188               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14189             Recalc = true;
14190           }
14191           if (Recalc) {
14192             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
14193             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
14194           }
14195         }
14196       }
14197     } else {
14198       ComplexValue LHS = Result;
14199       Result.getComplexIntReal() =
14200         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
14201          LHS.getComplexIntImag() * RHS.getComplexIntImag());
14202       Result.getComplexIntImag() =
14203         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
14204          LHS.getComplexIntImag() * RHS.getComplexIntReal());
14205     }
14206     break;
14207   case BO_Div:
14208     if (Result.isComplexFloat()) {
14209       // This is an implementation of complex division according to the
14210       // constraints laid out in C11 Annex G. The implementation uses the
14211       // following naming scheme:
14212       //   (a + ib) / (c + id)
14213       ComplexValue LHS = Result;
14214       APFloat &A = LHS.getComplexFloatReal();
14215       APFloat &B = LHS.getComplexFloatImag();
14216       APFloat &C = RHS.getComplexFloatReal();
14217       APFloat &D = RHS.getComplexFloatImag();
14218       APFloat &ResR = Result.getComplexFloatReal();
14219       APFloat &ResI = Result.getComplexFloatImag();
14220       if (RHSReal) {
14221         ResR = A / C;
14222         ResI = B / C;
14223       } else {
14224         if (LHSReal) {
14225           // No real optimizations we can do here, stub out with zero.
14226           B = APFloat::getZero(A.getSemantics());
14227         }
14228         int DenomLogB = 0;
14229         APFloat MaxCD = maxnum(abs(C), abs(D));
14230         if (MaxCD.isFinite()) {
14231           DenomLogB = ilogb(MaxCD);
14232           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
14233           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
14234         }
14235         APFloat Denom = C * C + D * D;
14236         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
14237                       APFloat::rmNearestTiesToEven);
14238         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
14239                       APFloat::rmNearestTiesToEven);
14240         if (ResR.isNaN() && ResI.isNaN()) {
14241           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
14242             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
14243             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
14244           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
14245                      D.isFinite()) {
14246             A = APFloat::copySign(
14247                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14248             B = APFloat::copySign(
14249                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14250             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
14251             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
14252           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
14253             C = APFloat::copySign(
14254                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14255             D = APFloat::copySign(
14256                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14257             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
14258             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
14259           }
14260         }
14261       }
14262     } else {
14263       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
14264         return Error(E, diag::note_expr_divide_by_zero);
14265 
14266       ComplexValue LHS = Result;
14267       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
14268         RHS.getComplexIntImag() * RHS.getComplexIntImag();
14269       Result.getComplexIntReal() =
14270         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
14271          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
14272       Result.getComplexIntImag() =
14273         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
14274          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
14275     }
14276     break;
14277   }
14278 
14279   return true;
14280 }
14281 
14282 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14283   // Get the operand value into 'Result'.
14284   if (!Visit(E->getSubExpr()))
14285     return false;
14286 
14287   switch (E->getOpcode()) {
14288   default:
14289     return Error(E);
14290   case UO_Extension:
14291     return true;
14292   case UO_Plus:
14293     // The result is always just the subexpr.
14294     return true;
14295   case UO_Minus:
14296     if (Result.isComplexFloat()) {
14297       Result.getComplexFloatReal().changeSign();
14298       Result.getComplexFloatImag().changeSign();
14299     }
14300     else {
14301       Result.getComplexIntReal() = -Result.getComplexIntReal();
14302       Result.getComplexIntImag() = -Result.getComplexIntImag();
14303     }
14304     return true;
14305   case UO_Not:
14306     if (Result.isComplexFloat())
14307       Result.getComplexFloatImag().changeSign();
14308     else
14309       Result.getComplexIntImag() = -Result.getComplexIntImag();
14310     return true;
14311   }
14312 }
14313 
14314 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
14315   if (E->getNumInits() == 2) {
14316     if (E->getType()->isComplexType()) {
14317       Result.makeComplexFloat();
14318       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
14319         return false;
14320       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
14321         return false;
14322     } else {
14323       Result.makeComplexInt();
14324       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
14325         return false;
14326       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
14327         return false;
14328     }
14329     return true;
14330   }
14331   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
14332 }
14333 
14334 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
14335   switch (E->getBuiltinCallee()) {
14336   case Builtin::BI__builtin_complex:
14337     Result.makeComplexFloat();
14338     if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
14339       return false;
14340     if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
14341       return false;
14342     return true;
14343 
14344   default:
14345     break;
14346   }
14347 
14348   return ExprEvaluatorBaseTy::VisitCallExpr(E);
14349 }
14350 
14351 //===----------------------------------------------------------------------===//
14352 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
14353 // implicit conversion.
14354 //===----------------------------------------------------------------------===//
14355 
14356 namespace {
14357 class AtomicExprEvaluator :
14358     public ExprEvaluatorBase<AtomicExprEvaluator> {
14359   const LValue *This;
14360   APValue &Result;
14361 public:
14362   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
14363       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
14364 
14365   bool Success(const APValue &V, const Expr *E) {
14366     Result = V;
14367     return true;
14368   }
14369 
14370   bool ZeroInitialization(const Expr *E) {
14371     ImplicitValueInitExpr VIE(
14372         E->getType()->castAs<AtomicType>()->getValueType());
14373     // For atomic-qualified class (and array) types in C++, initialize the
14374     // _Atomic-wrapped subobject directly, in-place.
14375     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
14376                 : Evaluate(Result, Info, &VIE);
14377   }
14378 
14379   bool VisitCastExpr(const CastExpr *E) {
14380     switch (E->getCastKind()) {
14381     default:
14382       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14383     case CK_NonAtomicToAtomic:
14384       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
14385                   : Evaluate(Result, Info, E->getSubExpr());
14386     }
14387   }
14388 };
14389 } // end anonymous namespace
14390 
14391 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
14392                            EvalInfo &Info) {
14393   assert(!E->isValueDependent());
14394   assert(E->isPRValue() && E->getType()->isAtomicType());
14395   return AtomicExprEvaluator(Info, This, Result).Visit(E);
14396 }
14397 
14398 //===----------------------------------------------------------------------===//
14399 // Void expression evaluation, primarily for a cast to void on the LHS of a
14400 // comma operator
14401 //===----------------------------------------------------------------------===//
14402 
14403 namespace {
14404 class VoidExprEvaluator
14405   : public ExprEvaluatorBase<VoidExprEvaluator> {
14406 public:
14407   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
14408 
14409   bool Success(const APValue &V, const Expr *e) { return true; }
14410 
14411   bool ZeroInitialization(const Expr *E) { return true; }
14412 
14413   bool VisitCastExpr(const CastExpr *E) {
14414     switch (E->getCastKind()) {
14415     default:
14416       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14417     case CK_ToVoid:
14418       VisitIgnoredValue(E->getSubExpr());
14419       return true;
14420     }
14421   }
14422 
14423   bool VisitCallExpr(const CallExpr *E) {
14424     switch (E->getBuiltinCallee()) {
14425     case Builtin::BI__assume:
14426     case Builtin::BI__builtin_assume:
14427       // The argument is not evaluated!
14428       return true;
14429 
14430     case Builtin::BI__builtin_operator_delete:
14431       return HandleOperatorDeleteCall(Info, E);
14432 
14433     default:
14434       break;
14435     }
14436 
14437     return ExprEvaluatorBaseTy::VisitCallExpr(E);
14438   }
14439 
14440   bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
14441 };
14442 } // end anonymous namespace
14443 
14444 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
14445   // We cannot speculatively evaluate a delete expression.
14446   if (Info.SpeculativeEvaluationDepth)
14447     return false;
14448 
14449   FunctionDecl *OperatorDelete = E->getOperatorDelete();
14450   if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
14451     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14452         << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
14453     return false;
14454   }
14455 
14456   const Expr *Arg = E->getArgument();
14457 
14458   LValue Pointer;
14459   if (!EvaluatePointer(Arg, Pointer, Info))
14460     return false;
14461   if (Pointer.Designator.Invalid)
14462     return false;
14463 
14464   // Deleting a null pointer has no effect.
14465   if (Pointer.isNullPointer()) {
14466     // This is the only case where we need to produce an extension warning:
14467     // the only other way we can succeed is if we find a dynamic allocation,
14468     // and we will have warned when we allocated it in that case.
14469     if (!Info.getLangOpts().CPlusPlus20)
14470       Info.CCEDiag(E, diag::note_constexpr_new);
14471     return true;
14472   }
14473 
14474   Optional<DynAlloc *> Alloc = CheckDeleteKind(
14475       Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
14476   if (!Alloc)
14477     return false;
14478   QualType AllocType = Pointer.Base.getDynamicAllocType();
14479 
14480   // For the non-array case, the designator must be empty if the static type
14481   // does not have a virtual destructor.
14482   if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
14483       !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
14484     Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
14485         << Arg->getType()->getPointeeType() << AllocType;
14486     return false;
14487   }
14488 
14489   // For a class type with a virtual destructor, the selected operator delete
14490   // is the one looked up when building the destructor.
14491   if (!E->isArrayForm() && !E->isGlobalDelete()) {
14492     const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
14493     if (VirtualDelete &&
14494         !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
14495       Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14496           << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
14497       return false;
14498     }
14499   }
14500 
14501   if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
14502                          (*Alloc)->Value, AllocType))
14503     return false;
14504 
14505   if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
14506     // The element was already erased. This means the destructor call also
14507     // deleted the object.
14508     // FIXME: This probably results in undefined behavior before we get this
14509     // far, and should be diagnosed elsewhere first.
14510     Info.FFDiag(E, diag::note_constexpr_double_delete);
14511     return false;
14512   }
14513 
14514   return true;
14515 }
14516 
14517 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
14518   assert(!E->isValueDependent());
14519   assert(E->isPRValue() && E->getType()->isVoidType());
14520   return VoidExprEvaluator(Info).Visit(E);
14521 }
14522 
14523 //===----------------------------------------------------------------------===//
14524 // Top level Expr::EvaluateAsRValue method.
14525 //===----------------------------------------------------------------------===//
14526 
14527 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
14528   assert(!E->isValueDependent());
14529   // In C, function designators are not lvalues, but we evaluate them as if they
14530   // are.
14531   QualType T = E->getType();
14532   if (E->isGLValue() || T->isFunctionType()) {
14533     LValue LV;
14534     if (!EvaluateLValue(E, LV, Info))
14535       return false;
14536     LV.moveInto(Result);
14537   } else if (T->isVectorType()) {
14538     if (!EvaluateVector(E, Result, Info))
14539       return false;
14540   } else if (T->isIntegralOrEnumerationType()) {
14541     if (!IntExprEvaluator(Info, Result).Visit(E))
14542       return false;
14543   } else if (T->hasPointerRepresentation()) {
14544     LValue LV;
14545     if (!EvaluatePointer(E, LV, Info))
14546       return false;
14547     LV.moveInto(Result);
14548   } else if (T->isRealFloatingType()) {
14549     llvm::APFloat F(0.0);
14550     if (!EvaluateFloat(E, F, Info))
14551       return false;
14552     Result = APValue(F);
14553   } else if (T->isAnyComplexType()) {
14554     ComplexValue C;
14555     if (!EvaluateComplex(E, C, Info))
14556       return false;
14557     C.moveInto(Result);
14558   } else if (T->isFixedPointType()) {
14559     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
14560   } else if (T->isMemberPointerType()) {
14561     MemberPtr P;
14562     if (!EvaluateMemberPointer(E, P, Info))
14563       return false;
14564     P.moveInto(Result);
14565     return true;
14566   } else if (T->isArrayType()) {
14567     LValue LV;
14568     APValue &Value =
14569         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14570     if (!EvaluateArray(E, LV, Value, Info))
14571       return false;
14572     Result = Value;
14573   } else if (T->isRecordType()) {
14574     LValue LV;
14575     APValue &Value =
14576         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14577     if (!EvaluateRecord(E, LV, Value, Info))
14578       return false;
14579     Result = Value;
14580   } else if (T->isVoidType()) {
14581     if (!Info.getLangOpts().CPlusPlus11)
14582       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
14583         << E->getType();
14584     if (!EvaluateVoid(E, Info))
14585       return false;
14586   } else if (T->isAtomicType()) {
14587     QualType Unqual = T.getAtomicUnqualifiedType();
14588     if (Unqual->isArrayType() || Unqual->isRecordType()) {
14589       LValue LV;
14590       APValue &Value = Info.CurrentCall->createTemporary(
14591           E, Unqual, ScopeKind::FullExpression, LV);
14592       if (!EvaluateAtomic(E, &LV, Value, Info))
14593         return false;
14594     } else {
14595       if (!EvaluateAtomic(E, nullptr, Result, Info))
14596         return false;
14597     }
14598   } else if (Info.getLangOpts().CPlusPlus11) {
14599     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
14600     return false;
14601   } else {
14602     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
14603     return false;
14604   }
14605 
14606   return true;
14607 }
14608 
14609 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
14610 /// cases, the in-place evaluation is essential, since later initializers for
14611 /// an object can indirectly refer to subobjects which were initialized earlier.
14612 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
14613                             const Expr *E, bool AllowNonLiteralTypes) {
14614   assert(!E->isValueDependent());
14615 
14616   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
14617     return false;
14618 
14619   if (E->isPRValue()) {
14620     // Evaluate arrays and record types in-place, so that later initializers can
14621     // refer to earlier-initialized members of the object.
14622     QualType T = E->getType();
14623     if (T->isArrayType())
14624       return EvaluateArray(E, This, Result, Info);
14625     else if (T->isRecordType())
14626       return EvaluateRecord(E, This, Result, Info);
14627     else if (T->isAtomicType()) {
14628       QualType Unqual = T.getAtomicUnqualifiedType();
14629       if (Unqual->isArrayType() || Unqual->isRecordType())
14630         return EvaluateAtomic(E, &This, Result, Info);
14631     }
14632   }
14633 
14634   // For any other type, in-place evaluation is unimportant.
14635   return Evaluate(Result, Info, E);
14636 }
14637 
14638 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
14639 /// lvalue-to-rvalue cast if it is an lvalue.
14640 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
14641   assert(!E->isValueDependent());
14642   if (Info.EnableNewConstInterp) {
14643     if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
14644       return false;
14645   } else {
14646     if (E->getType().isNull())
14647       return false;
14648 
14649     if (!CheckLiteralType(Info, E))
14650       return false;
14651 
14652     if (!::Evaluate(Result, Info, E))
14653       return false;
14654 
14655     if (E->isGLValue()) {
14656       LValue LV;
14657       LV.setFrom(Info.Ctx, Result);
14658       if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
14659         return false;
14660     }
14661   }
14662 
14663   // Check this core constant expression is a constant expression.
14664   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
14665                                  ConstantExprKind::Normal) &&
14666          CheckMemoryLeaks(Info);
14667 }
14668 
14669 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
14670                                  const ASTContext &Ctx, bool &IsConst) {
14671   // Fast-path evaluations of integer literals, since we sometimes see files
14672   // containing vast quantities of these.
14673   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
14674     Result.Val = APValue(APSInt(L->getValue(),
14675                                 L->getType()->isUnsignedIntegerType()));
14676     IsConst = true;
14677     return true;
14678   }
14679 
14680   // This case should be rare, but we need to check it before we check on
14681   // the type below.
14682   if (Exp->getType().isNull()) {
14683     IsConst = false;
14684     return true;
14685   }
14686 
14687   // FIXME: Evaluating values of large array and record types can cause
14688   // performance problems. Only do so in C++11 for now.
14689   if (Exp->isPRValue() &&
14690       (Exp->getType()->isArrayType() || Exp->getType()->isRecordType()) &&
14691       !Ctx.getLangOpts().CPlusPlus11) {
14692     IsConst = false;
14693     return true;
14694   }
14695   return false;
14696 }
14697 
14698 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
14699                                       Expr::SideEffectsKind SEK) {
14700   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
14701          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
14702 }
14703 
14704 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
14705                              const ASTContext &Ctx, EvalInfo &Info) {
14706   assert(!E->isValueDependent());
14707   bool IsConst;
14708   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
14709     return IsConst;
14710 
14711   return EvaluateAsRValue(Info, E, Result.Val);
14712 }
14713 
14714 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
14715                           const ASTContext &Ctx,
14716                           Expr::SideEffectsKind AllowSideEffects,
14717                           EvalInfo &Info) {
14718   assert(!E->isValueDependent());
14719   if (!E->getType()->isIntegralOrEnumerationType())
14720     return false;
14721 
14722   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
14723       !ExprResult.Val.isInt() ||
14724       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14725     return false;
14726 
14727   return true;
14728 }
14729 
14730 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
14731                                  const ASTContext &Ctx,
14732                                  Expr::SideEffectsKind AllowSideEffects,
14733                                  EvalInfo &Info) {
14734   assert(!E->isValueDependent());
14735   if (!E->getType()->isFixedPointType())
14736     return false;
14737 
14738   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
14739     return false;
14740 
14741   if (!ExprResult.Val.isFixedPoint() ||
14742       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14743     return false;
14744 
14745   return true;
14746 }
14747 
14748 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
14749 /// any crazy technique (that has nothing to do with language standards) that
14750 /// we want to.  If this function returns true, it returns the folded constant
14751 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
14752 /// will be applied to the result.
14753 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
14754                             bool InConstantContext) const {
14755   assert(!isValueDependent() &&
14756          "Expression evaluator can't be called on a dependent expression.");
14757   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14758   Info.InConstantContext = InConstantContext;
14759   return ::EvaluateAsRValue(this, Result, Ctx, Info);
14760 }
14761 
14762 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
14763                                       bool InConstantContext) const {
14764   assert(!isValueDependent() &&
14765          "Expression evaluator can't be called on a dependent expression.");
14766   EvalResult Scratch;
14767   return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
14768          HandleConversionToBool(Scratch.Val, Result);
14769 }
14770 
14771 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
14772                          SideEffectsKind AllowSideEffects,
14773                          bool InConstantContext) const {
14774   assert(!isValueDependent() &&
14775          "Expression evaluator can't be called on a dependent expression.");
14776   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14777   Info.InConstantContext = InConstantContext;
14778   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
14779 }
14780 
14781 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
14782                                 SideEffectsKind AllowSideEffects,
14783                                 bool InConstantContext) const {
14784   assert(!isValueDependent() &&
14785          "Expression evaluator can't be called on a dependent expression.");
14786   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14787   Info.InConstantContext = InConstantContext;
14788   return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
14789 }
14790 
14791 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
14792                            SideEffectsKind AllowSideEffects,
14793                            bool InConstantContext) const {
14794   assert(!isValueDependent() &&
14795          "Expression evaluator can't be called on a dependent expression.");
14796 
14797   if (!getType()->isRealFloatingType())
14798     return false;
14799 
14800   EvalResult ExprResult;
14801   if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
14802       !ExprResult.Val.isFloat() ||
14803       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14804     return false;
14805 
14806   Result = ExprResult.Val.getFloat();
14807   return true;
14808 }
14809 
14810 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
14811                             bool InConstantContext) const {
14812   assert(!isValueDependent() &&
14813          "Expression evaluator can't be called on a dependent expression.");
14814 
14815   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
14816   Info.InConstantContext = InConstantContext;
14817   LValue LV;
14818   CheckedTemporaries CheckedTemps;
14819   if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
14820       Result.HasSideEffects ||
14821       !CheckLValueConstantExpression(Info, getExprLoc(),
14822                                      Ctx.getLValueReferenceType(getType()), LV,
14823                                      ConstantExprKind::Normal, CheckedTemps))
14824     return false;
14825 
14826   LV.moveInto(Result.Val);
14827   return true;
14828 }
14829 
14830 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base,
14831                                 APValue DestroyedValue, QualType Type,
14832                                 SourceLocation Loc, Expr::EvalStatus &EStatus,
14833                                 bool IsConstantDestruction) {
14834   EvalInfo Info(Ctx, EStatus,
14835                 IsConstantDestruction ? EvalInfo::EM_ConstantExpression
14836                                       : EvalInfo::EM_ConstantFold);
14837   Info.setEvaluatingDecl(Base, DestroyedValue,
14838                          EvalInfo::EvaluatingDeclKind::Dtor);
14839   Info.InConstantContext = IsConstantDestruction;
14840 
14841   LValue LVal;
14842   LVal.set(Base);
14843 
14844   if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
14845       EStatus.HasSideEffects)
14846     return false;
14847 
14848   if (!Info.discardCleanups())
14849     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14850 
14851   return true;
14852 }
14853 
14854 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx,
14855                                   ConstantExprKind Kind) const {
14856   assert(!isValueDependent() &&
14857          "Expression evaluator can't be called on a dependent expression.");
14858 
14859   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
14860   EvalInfo Info(Ctx, Result, EM);
14861   Info.InConstantContext = true;
14862 
14863   // The type of the object we're initializing is 'const T' for a class NTTP.
14864   QualType T = getType();
14865   if (Kind == ConstantExprKind::ClassTemplateArgument)
14866     T.addConst();
14867 
14868   // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
14869   // represent the result of the evaluation. CheckConstantExpression ensures
14870   // this doesn't escape.
14871   MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
14872   APValue::LValueBase Base(&BaseMTE);
14873 
14874   Info.setEvaluatingDecl(Base, Result.Val);
14875   LValue LVal;
14876   LVal.set(Base);
14877 
14878   if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || Result.HasSideEffects)
14879     return false;
14880 
14881   if (!Info.discardCleanups())
14882     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14883 
14884   if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
14885                                Result.Val, Kind))
14886     return false;
14887   if (!CheckMemoryLeaks(Info))
14888     return false;
14889 
14890   // If this is a class template argument, it's required to have constant
14891   // destruction too.
14892   if (Kind == ConstantExprKind::ClassTemplateArgument &&
14893       (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result,
14894                             true) ||
14895        Result.HasSideEffects)) {
14896     // FIXME: Prefix a note to indicate that the problem is lack of constant
14897     // destruction.
14898     return false;
14899   }
14900 
14901   return true;
14902 }
14903 
14904 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
14905                                  const VarDecl *VD,
14906                             SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
14907   assert(!isValueDependent() &&
14908          "Expression evaluator can't be called on a dependent expression.");
14909 
14910   // FIXME: Evaluating initializers for large array and record types can cause
14911   // performance problems. Only do so in C++11 for now.
14912   if (isPRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
14913       !Ctx.getLangOpts().CPlusPlus11)
14914     return false;
14915 
14916   Expr::EvalStatus EStatus;
14917   EStatus.Diag = &Notes;
14918 
14919   EvalInfo Info(Ctx, EStatus, VD->isConstexpr()
14920                                       ? EvalInfo::EM_ConstantExpression
14921                                       : EvalInfo::EM_ConstantFold);
14922   Info.setEvaluatingDecl(VD, Value);
14923   Info.InConstantContext = true;
14924 
14925   SourceLocation DeclLoc = VD->getLocation();
14926   QualType DeclTy = VD->getType();
14927 
14928   if (Info.EnableNewConstInterp) {
14929     auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
14930     if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
14931       return false;
14932   } else {
14933     LValue LVal;
14934     LVal.set(VD);
14935 
14936     if (!EvaluateInPlace(Value, Info, LVal, this,
14937                          /*AllowNonLiteralTypes=*/true) ||
14938         EStatus.HasSideEffects)
14939       return false;
14940 
14941     // At this point, any lifetime-extended temporaries are completely
14942     // initialized.
14943     Info.performLifetimeExtension();
14944 
14945     if (!Info.discardCleanups())
14946       llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14947   }
14948   return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
14949                                  ConstantExprKind::Normal) &&
14950          CheckMemoryLeaks(Info);
14951 }
14952 
14953 bool VarDecl::evaluateDestruction(
14954     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
14955   Expr::EvalStatus EStatus;
14956   EStatus.Diag = &Notes;
14957 
14958   // Only treat the destruction as constant destruction if we formally have
14959   // constant initialization (or are usable in a constant expression).
14960   bool IsConstantDestruction = hasConstantInitialization();
14961 
14962   // Make a copy of the value for the destructor to mutate, if we know it.
14963   // Otherwise, treat the value as default-initialized; if the destructor works
14964   // anyway, then the destruction is constant (and must be essentially empty).
14965   APValue DestroyedValue;
14966   if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
14967     DestroyedValue = *getEvaluatedValue();
14968   else if (!getDefaultInitValue(getType(), DestroyedValue))
14969     return false;
14970 
14971   if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
14972                            getType(), getLocation(), EStatus,
14973                            IsConstantDestruction) ||
14974       EStatus.HasSideEffects)
14975     return false;
14976 
14977   ensureEvaluatedStmt()->HasConstantDestruction = true;
14978   return true;
14979 }
14980 
14981 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
14982 /// constant folded, but discard the result.
14983 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
14984   assert(!isValueDependent() &&
14985          "Expression evaluator can't be called on a dependent expression.");
14986 
14987   EvalResult Result;
14988   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
14989          !hasUnacceptableSideEffect(Result, SEK);
14990 }
14991 
14992 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
14993                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
14994   assert(!isValueDependent() &&
14995          "Expression evaluator can't be called on a dependent expression.");
14996 
14997   EvalResult EVResult;
14998   EVResult.Diag = Diag;
14999   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15000   Info.InConstantContext = true;
15001 
15002   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
15003   (void)Result;
15004   assert(Result && "Could not evaluate expression");
15005   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
15006 
15007   return EVResult.Val.getInt();
15008 }
15009 
15010 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
15011     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
15012   assert(!isValueDependent() &&
15013          "Expression evaluator can't be called on a dependent expression.");
15014 
15015   EvalResult EVResult;
15016   EVResult.Diag = Diag;
15017   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15018   Info.InConstantContext = true;
15019   Info.CheckingForUndefinedBehavior = true;
15020 
15021   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
15022   (void)Result;
15023   assert(Result && "Could not evaluate expression");
15024   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
15025 
15026   return EVResult.Val.getInt();
15027 }
15028 
15029 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
15030   assert(!isValueDependent() &&
15031          "Expression evaluator can't be called on a dependent expression.");
15032 
15033   bool IsConst;
15034   EvalResult EVResult;
15035   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
15036     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15037     Info.CheckingForUndefinedBehavior = true;
15038     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
15039   }
15040 }
15041 
15042 bool Expr::EvalResult::isGlobalLValue() const {
15043   assert(Val.isLValue());
15044   return IsGlobalLValue(Val.getLValueBase());
15045 }
15046 
15047 /// isIntegerConstantExpr - this recursive routine will test if an expression is
15048 /// an integer constant expression.
15049 
15050 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
15051 /// comma, etc
15052 
15053 // CheckICE - This function does the fundamental ICE checking: the returned
15054 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
15055 // and a (possibly null) SourceLocation indicating the location of the problem.
15056 //
15057 // Note that to reduce code duplication, this helper does no evaluation
15058 // itself; the caller checks whether the expression is evaluatable, and
15059 // in the rare cases where CheckICE actually cares about the evaluated
15060 // value, it calls into Evaluate.
15061 
15062 namespace {
15063 
15064 enum ICEKind {
15065   /// This expression is an ICE.
15066   IK_ICE,
15067   /// This expression is not an ICE, but if it isn't evaluated, it's
15068   /// a legal subexpression for an ICE. This return value is used to handle
15069   /// the comma operator in C99 mode, and non-constant subexpressions.
15070   IK_ICEIfUnevaluated,
15071   /// This expression is not an ICE, and is not a legal subexpression for one.
15072   IK_NotICE
15073 };
15074 
15075 struct ICEDiag {
15076   ICEKind Kind;
15077   SourceLocation Loc;
15078 
15079   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
15080 };
15081 
15082 }
15083 
15084 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
15085 
15086 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
15087 
15088 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
15089   Expr::EvalResult EVResult;
15090   Expr::EvalStatus Status;
15091   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15092 
15093   Info.InConstantContext = true;
15094   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
15095       !EVResult.Val.isInt())
15096     return ICEDiag(IK_NotICE, E->getBeginLoc());
15097 
15098   return NoDiag();
15099 }
15100 
15101 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
15102   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
15103   if (!E->getType()->isIntegralOrEnumerationType())
15104     return ICEDiag(IK_NotICE, E->getBeginLoc());
15105 
15106   switch (E->getStmtClass()) {
15107 #define ABSTRACT_STMT(Node)
15108 #define STMT(Node, Base) case Expr::Node##Class:
15109 #define EXPR(Node, Base)
15110 #include "clang/AST/StmtNodes.inc"
15111   case Expr::PredefinedExprClass:
15112   case Expr::FloatingLiteralClass:
15113   case Expr::ImaginaryLiteralClass:
15114   case Expr::StringLiteralClass:
15115   case Expr::ArraySubscriptExprClass:
15116   case Expr::MatrixSubscriptExprClass:
15117   case Expr::OMPArraySectionExprClass:
15118   case Expr::OMPArrayShapingExprClass:
15119   case Expr::OMPIteratorExprClass:
15120   case Expr::MemberExprClass:
15121   case Expr::CompoundAssignOperatorClass:
15122   case Expr::CompoundLiteralExprClass:
15123   case Expr::ExtVectorElementExprClass:
15124   case Expr::DesignatedInitExprClass:
15125   case Expr::ArrayInitLoopExprClass:
15126   case Expr::ArrayInitIndexExprClass:
15127   case Expr::NoInitExprClass:
15128   case Expr::DesignatedInitUpdateExprClass:
15129   case Expr::ImplicitValueInitExprClass:
15130   case Expr::ParenListExprClass:
15131   case Expr::VAArgExprClass:
15132   case Expr::AddrLabelExprClass:
15133   case Expr::StmtExprClass:
15134   case Expr::CXXMemberCallExprClass:
15135   case Expr::CUDAKernelCallExprClass:
15136   case Expr::CXXAddrspaceCastExprClass:
15137   case Expr::CXXDynamicCastExprClass:
15138   case Expr::CXXTypeidExprClass:
15139   case Expr::CXXUuidofExprClass:
15140   case Expr::MSPropertyRefExprClass:
15141   case Expr::MSPropertySubscriptExprClass:
15142   case Expr::CXXNullPtrLiteralExprClass:
15143   case Expr::UserDefinedLiteralClass:
15144   case Expr::CXXThisExprClass:
15145   case Expr::CXXThrowExprClass:
15146   case Expr::CXXNewExprClass:
15147   case Expr::CXXDeleteExprClass:
15148   case Expr::CXXPseudoDestructorExprClass:
15149   case Expr::UnresolvedLookupExprClass:
15150   case Expr::TypoExprClass:
15151   case Expr::RecoveryExprClass:
15152   case Expr::DependentScopeDeclRefExprClass:
15153   case Expr::CXXConstructExprClass:
15154   case Expr::CXXInheritedCtorInitExprClass:
15155   case Expr::CXXStdInitializerListExprClass:
15156   case Expr::CXXBindTemporaryExprClass:
15157   case Expr::ExprWithCleanupsClass:
15158   case Expr::CXXTemporaryObjectExprClass:
15159   case Expr::CXXUnresolvedConstructExprClass:
15160   case Expr::CXXDependentScopeMemberExprClass:
15161   case Expr::UnresolvedMemberExprClass:
15162   case Expr::ObjCStringLiteralClass:
15163   case Expr::ObjCBoxedExprClass:
15164   case Expr::ObjCArrayLiteralClass:
15165   case Expr::ObjCDictionaryLiteralClass:
15166   case Expr::ObjCEncodeExprClass:
15167   case Expr::ObjCMessageExprClass:
15168   case Expr::ObjCSelectorExprClass:
15169   case Expr::ObjCProtocolExprClass:
15170   case Expr::ObjCIvarRefExprClass:
15171   case Expr::ObjCPropertyRefExprClass:
15172   case Expr::ObjCSubscriptRefExprClass:
15173   case Expr::ObjCIsaExprClass:
15174   case Expr::ObjCAvailabilityCheckExprClass:
15175   case Expr::ShuffleVectorExprClass:
15176   case Expr::ConvertVectorExprClass:
15177   case Expr::BlockExprClass:
15178   case Expr::NoStmtClass:
15179   case Expr::OpaqueValueExprClass:
15180   case Expr::PackExpansionExprClass:
15181   case Expr::SubstNonTypeTemplateParmPackExprClass:
15182   case Expr::FunctionParmPackExprClass:
15183   case Expr::AsTypeExprClass:
15184   case Expr::ObjCIndirectCopyRestoreExprClass:
15185   case Expr::MaterializeTemporaryExprClass:
15186   case Expr::PseudoObjectExprClass:
15187   case Expr::AtomicExprClass:
15188   case Expr::LambdaExprClass:
15189   case Expr::CXXFoldExprClass:
15190   case Expr::CoawaitExprClass:
15191   case Expr::DependentCoawaitExprClass:
15192   case Expr::CoyieldExprClass:
15193   case Expr::SYCLUniqueStableNameExprClass:
15194     return ICEDiag(IK_NotICE, E->getBeginLoc());
15195 
15196   case Expr::InitListExprClass: {
15197     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
15198     // form "T x = { a };" is equivalent to "T x = a;".
15199     // Unless we're initializing a reference, T is a scalar as it is known to be
15200     // of integral or enumeration type.
15201     if (E->isPRValue())
15202       if (cast<InitListExpr>(E)->getNumInits() == 1)
15203         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
15204     return ICEDiag(IK_NotICE, E->getBeginLoc());
15205   }
15206 
15207   case Expr::SizeOfPackExprClass:
15208   case Expr::GNUNullExprClass:
15209   case Expr::SourceLocExprClass:
15210     return NoDiag();
15211 
15212   case Expr::SubstNonTypeTemplateParmExprClass:
15213     return
15214       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
15215 
15216   case Expr::ConstantExprClass:
15217     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
15218 
15219   case Expr::ParenExprClass:
15220     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
15221   case Expr::GenericSelectionExprClass:
15222     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
15223   case Expr::IntegerLiteralClass:
15224   case Expr::FixedPointLiteralClass:
15225   case Expr::CharacterLiteralClass:
15226   case Expr::ObjCBoolLiteralExprClass:
15227   case Expr::CXXBoolLiteralExprClass:
15228   case Expr::CXXScalarValueInitExprClass:
15229   case Expr::TypeTraitExprClass:
15230   case Expr::ConceptSpecializationExprClass:
15231   case Expr::RequiresExprClass:
15232   case Expr::ArrayTypeTraitExprClass:
15233   case Expr::ExpressionTraitExprClass:
15234   case Expr::CXXNoexceptExprClass:
15235     return NoDiag();
15236   case Expr::CallExprClass:
15237   case Expr::CXXOperatorCallExprClass: {
15238     // C99 6.6/3 allows function calls within unevaluated subexpressions of
15239     // constant expressions, but they can never be ICEs because an ICE cannot
15240     // contain an operand of (pointer to) function type.
15241     const CallExpr *CE = cast<CallExpr>(E);
15242     if (CE->getBuiltinCallee())
15243       return CheckEvalInICE(E, Ctx);
15244     return ICEDiag(IK_NotICE, E->getBeginLoc());
15245   }
15246   case Expr::CXXRewrittenBinaryOperatorClass:
15247     return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
15248                     Ctx);
15249   case Expr::DeclRefExprClass: {
15250     const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
15251     if (isa<EnumConstantDecl>(D))
15252       return NoDiag();
15253 
15254     // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
15255     // integer variables in constant expressions:
15256     //
15257     // C++ 7.1.5.1p2
15258     //   A variable of non-volatile const-qualified integral or enumeration
15259     //   type initialized by an ICE can be used in ICEs.
15260     //
15261     // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
15262     // that mode, use of reference variables should not be allowed.
15263     const VarDecl *VD = dyn_cast<VarDecl>(D);
15264     if (VD && VD->isUsableInConstantExpressions(Ctx) &&
15265         !VD->getType()->isReferenceType())
15266       return NoDiag();
15267 
15268     return ICEDiag(IK_NotICE, E->getBeginLoc());
15269   }
15270   case Expr::UnaryOperatorClass: {
15271     const UnaryOperator *Exp = cast<UnaryOperator>(E);
15272     switch (Exp->getOpcode()) {
15273     case UO_PostInc:
15274     case UO_PostDec:
15275     case UO_PreInc:
15276     case UO_PreDec:
15277     case UO_AddrOf:
15278     case UO_Deref:
15279     case UO_Coawait:
15280       // C99 6.6/3 allows increment and decrement within unevaluated
15281       // subexpressions of constant expressions, but they can never be ICEs
15282       // because an ICE cannot contain an lvalue operand.
15283       return ICEDiag(IK_NotICE, E->getBeginLoc());
15284     case UO_Extension:
15285     case UO_LNot:
15286     case UO_Plus:
15287     case UO_Minus:
15288     case UO_Not:
15289     case UO_Real:
15290     case UO_Imag:
15291       return CheckICE(Exp->getSubExpr(), Ctx);
15292     }
15293     llvm_unreachable("invalid unary operator class");
15294   }
15295   case Expr::OffsetOfExprClass: {
15296     // Note that per C99, offsetof must be an ICE. And AFAIK, using
15297     // EvaluateAsRValue matches the proposed gcc behavior for cases like
15298     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
15299     // compliance: we should warn earlier for offsetof expressions with
15300     // array subscripts that aren't ICEs, and if the array subscripts
15301     // are ICEs, the value of the offsetof must be an integer constant.
15302     return CheckEvalInICE(E, Ctx);
15303   }
15304   case Expr::UnaryExprOrTypeTraitExprClass: {
15305     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
15306     if ((Exp->getKind() ==  UETT_SizeOf) &&
15307         Exp->getTypeOfArgument()->isVariableArrayType())
15308       return ICEDiag(IK_NotICE, E->getBeginLoc());
15309     return NoDiag();
15310   }
15311   case Expr::BinaryOperatorClass: {
15312     const BinaryOperator *Exp = cast<BinaryOperator>(E);
15313     switch (Exp->getOpcode()) {
15314     case BO_PtrMemD:
15315     case BO_PtrMemI:
15316     case BO_Assign:
15317     case BO_MulAssign:
15318     case BO_DivAssign:
15319     case BO_RemAssign:
15320     case BO_AddAssign:
15321     case BO_SubAssign:
15322     case BO_ShlAssign:
15323     case BO_ShrAssign:
15324     case BO_AndAssign:
15325     case BO_XorAssign:
15326     case BO_OrAssign:
15327       // C99 6.6/3 allows assignments within unevaluated subexpressions of
15328       // constant expressions, but they can never be ICEs because an ICE cannot
15329       // contain an lvalue operand.
15330       return ICEDiag(IK_NotICE, E->getBeginLoc());
15331 
15332     case BO_Mul:
15333     case BO_Div:
15334     case BO_Rem:
15335     case BO_Add:
15336     case BO_Sub:
15337     case BO_Shl:
15338     case BO_Shr:
15339     case BO_LT:
15340     case BO_GT:
15341     case BO_LE:
15342     case BO_GE:
15343     case BO_EQ:
15344     case BO_NE:
15345     case BO_And:
15346     case BO_Xor:
15347     case BO_Or:
15348     case BO_Comma:
15349     case BO_Cmp: {
15350       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15351       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15352       if (Exp->getOpcode() == BO_Div ||
15353           Exp->getOpcode() == BO_Rem) {
15354         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
15355         // we don't evaluate one.
15356         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
15357           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
15358           if (REval == 0)
15359             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15360           if (REval.isSigned() && REval.isAllOnesValue()) {
15361             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
15362             if (LEval.isMinSignedValue())
15363               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15364           }
15365         }
15366       }
15367       if (Exp->getOpcode() == BO_Comma) {
15368         if (Ctx.getLangOpts().C99) {
15369           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
15370           // if it isn't evaluated.
15371           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
15372             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15373         } else {
15374           // In both C89 and C++, commas in ICEs are illegal.
15375           return ICEDiag(IK_NotICE, E->getBeginLoc());
15376         }
15377       }
15378       return Worst(LHSResult, RHSResult);
15379     }
15380     case BO_LAnd:
15381     case BO_LOr: {
15382       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15383       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15384       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
15385         // Rare case where the RHS has a comma "side-effect"; we need
15386         // to actually check the condition to see whether the side
15387         // with the comma is evaluated.
15388         if ((Exp->getOpcode() == BO_LAnd) !=
15389             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
15390           return RHSResult;
15391         return NoDiag();
15392       }
15393 
15394       return Worst(LHSResult, RHSResult);
15395     }
15396     }
15397     llvm_unreachable("invalid binary operator kind");
15398   }
15399   case Expr::ImplicitCastExprClass:
15400   case Expr::CStyleCastExprClass:
15401   case Expr::CXXFunctionalCastExprClass:
15402   case Expr::CXXStaticCastExprClass:
15403   case Expr::CXXReinterpretCastExprClass:
15404   case Expr::CXXConstCastExprClass:
15405   case Expr::ObjCBridgedCastExprClass: {
15406     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
15407     if (isa<ExplicitCastExpr>(E)) {
15408       if (const FloatingLiteral *FL
15409             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
15410         unsigned DestWidth = Ctx.getIntWidth(E->getType());
15411         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
15412         APSInt IgnoredVal(DestWidth, !DestSigned);
15413         bool Ignored;
15414         // If the value does not fit in the destination type, the behavior is
15415         // undefined, so we are not required to treat it as a constant
15416         // expression.
15417         if (FL->getValue().convertToInteger(IgnoredVal,
15418                                             llvm::APFloat::rmTowardZero,
15419                                             &Ignored) & APFloat::opInvalidOp)
15420           return ICEDiag(IK_NotICE, E->getBeginLoc());
15421         return NoDiag();
15422       }
15423     }
15424     switch (cast<CastExpr>(E)->getCastKind()) {
15425     case CK_LValueToRValue:
15426     case CK_AtomicToNonAtomic:
15427     case CK_NonAtomicToAtomic:
15428     case CK_NoOp:
15429     case CK_IntegralToBoolean:
15430     case CK_IntegralCast:
15431       return CheckICE(SubExpr, Ctx);
15432     default:
15433       return ICEDiag(IK_NotICE, E->getBeginLoc());
15434     }
15435   }
15436   case Expr::BinaryConditionalOperatorClass: {
15437     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
15438     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
15439     if (CommonResult.Kind == IK_NotICE) return CommonResult;
15440     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15441     if (FalseResult.Kind == IK_NotICE) return FalseResult;
15442     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
15443     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
15444         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
15445     return FalseResult;
15446   }
15447   case Expr::ConditionalOperatorClass: {
15448     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
15449     // If the condition (ignoring parens) is a __builtin_constant_p call,
15450     // then only the true side is actually considered in an integer constant
15451     // expression, and it is fully evaluated.  This is an important GNU
15452     // extension.  See GCC PR38377 for discussion.
15453     if (const CallExpr *CallCE
15454         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
15455       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
15456         return CheckEvalInICE(E, Ctx);
15457     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
15458     if (CondResult.Kind == IK_NotICE)
15459       return CondResult;
15460 
15461     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
15462     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15463 
15464     if (TrueResult.Kind == IK_NotICE)
15465       return TrueResult;
15466     if (FalseResult.Kind == IK_NotICE)
15467       return FalseResult;
15468     if (CondResult.Kind == IK_ICEIfUnevaluated)
15469       return CondResult;
15470     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
15471       return NoDiag();
15472     // Rare case where the diagnostics depend on which side is evaluated
15473     // Note that if we get here, CondResult is 0, and at least one of
15474     // TrueResult and FalseResult is non-zero.
15475     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
15476       return FalseResult;
15477     return TrueResult;
15478   }
15479   case Expr::CXXDefaultArgExprClass:
15480     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
15481   case Expr::CXXDefaultInitExprClass:
15482     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
15483   case Expr::ChooseExprClass: {
15484     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
15485   }
15486   case Expr::BuiltinBitCastExprClass: {
15487     if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
15488       return ICEDiag(IK_NotICE, E->getBeginLoc());
15489     return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
15490   }
15491   }
15492 
15493   llvm_unreachable("Invalid StmtClass!");
15494 }
15495 
15496 /// Evaluate an expression as a C++11 integral constant expression.
15497 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
15498                                                     const Expr *E,
15499                                                     llvm::APSInt *Value,
15500                                                     SourceLocation *Loc) {
15501   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15502     if (Loc) *Loc = E->getExprLoc();
15503     return false;
15504   }
15505 
15506   APValue Result;
15507   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
15508     return false;
15509 
15510   if (!Result.isInt()) {
15511     if (Loc) *Loc = E->getExprLoc();
15512     return false;
15513   }
15514 
15515   if (Value) *Value = Result.getInt();
15516   return true;
15517 }
15518 
15519 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
15520                                  SourceLocation *Loc) const {
15521   assert(!isValueDependent() &&
15522          "Expression evaluator can't be called on a dependent expression.");
15523 
15524   if (Ctx.getLangOpts().CPlusPlus11)
15525     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
15526 
15527   ICEDiag D = CheckICE(this, Ctx);
15528   if (D.Kind != IK_ICE) {
15529     if (Loc) *Loc = D.Loc;
15530     return false;
15531   }
15532   return true;
15533 }
15534 
15535 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx,
15536                                                     SourceLocation *Loc,
15537                                                     bool isEvaluated) const {
15538   assert(!isValueDependent() &&
15539          "Expression evaluator can't be called on a dependent expression.");
15540 
15541   APSInt Value;
15542 
15543   if (Ctx.getLangOpts().CPlusPlus11) {
15544     if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc))
15545       return Value;
15546     return None;
15547   }
15548 
15549   if (!isIntegerConstantExpr(Ctx, Loc))
15550     return None;
15551 
15552   // The only possible side-effects here are due to UB discovered in the
15553   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
15554   // required to treat the expression as an ICE, so we produce the folded
15555   // value.
15556   EvalResult ExprResult;
15557   Expr::EvalStatus Status;
15558   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
15559   Info.InConstantContext = true;
15560 
15561   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
15562     llvm_unreachable("ICE cannot be evaluated!");
15563 
15564   return ExprResult.Val.getInt();
15565 }
15566 
15567 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
15568   assert(!isValueDependent() &&
15569          "Expression evaluator can't be called on a dependent expression.");
15570 
15571   return CheckICE(this, Ctx).Kind == IK_ICE;
15572 }
15573 
15574 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
15575                                SourceLocation *Loc) const {
15576   assert(!isValueDependent() &&
15577          "Expression evaluator can't be called on a dependent expression.");
15578 
15579   // We support this checking in C++98 mode in order to diagnose compatibility
15580   // issues.
15581   assert(Ctx.getLangOpts().CPlusPlus);
15582 
15583   // Build evaluation settings.
15584   Expr::EvalStatus Status;
15585   SmallVector<PartialDiagnosticAt, 8> Diags;
15586   Status.Diag = &Diags;
15587   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15588 
15589   APValue Scratch;
15590   bool IsConstExpr =
15591       ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
15592       // FIXME: We don't produce a diagnostic for this, but the callers that
15593       // call us on arbitrary full-expressions should generally not care.
15594       Info.discardCleanups() && !Status.HasSideEffects;
15595 
15596   if (!Diags.empty()) {
15597     IsConstExpr = false;
15598     if (Loc) *Loc = Diags[0].first;
15599   } else if (!IsConstExpr) {
15600     // FIXME: This shouldn't happen.
15601     if (Loc) *Loc = getExprLoc();
15602   }
15603 
15604   return IsConstExpr;
15605 }
15606 
15607 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
15608                                     const FunctionDecl *Callee,
15609                                     ArrayRef<const Expr*> Args,
15610                                     const Expr *This) const {
15611   assert(!isValueDependent() &&
15612          "Expression evaluator can't be called on a dependent expression.");
15613 
15614   Expr::EvalStatus Status;
15615   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
15616   Info.InConstantContext = true;
15617 
15618   LValue ThisVal;
15619   const LValue *ThisPtr = nullptr;
15620   if (This) {
15621 #ifndef NDEBUG
15622     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
15623     assert(MD && "Don't provide `this` for non-methods.");
15624     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
15625 #endif
15626     if (!This->isValueDependent() &&
15627         EvaluateObjectArgument(Info, This, ThisVal) &&
15628         !Info.EvalStatus.HasSideEffects)
15629       ThisPtr = &ThisVal;
15630 
15631     // Ignore any side-effects from a failed evaluation. This is safe because
15632     // they can't interfere with any other argument evaluation.
15633     Info.EvalStatus.HasSideEffects = false;
15634   }
15635 
15636   CallRef Call = Info.CurrentCall->createCall(Callee);
15637   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
15638        I != E; ++I) {
15639     unsigned Idx = I - Args.begin();
15640     if (Idx >= Callee->getNumParams())
15641       break;
15642     const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
15643     if ((*I)->isValueDependent() ||
15644         !EvaluateCallArg(PVD, *I, Call, Info) ||
15645         Info.EvalStatus.HasSideEffects) {
15646       // If evaluation fails, throw away the argument entirely.
15647       if (APValue *Slot = Info.getParamSlot(Call, PVD))
15648         *Slot = APValue();
15649     }
15650 
15651     // Ignore any side-effects from a failed evaluation. This is safe because
15652     // they can't interfere with any other argument evaluation.
15653     Info.EvalStatus.HasSideEffects = false;
15654   }
15655 
15656   // Parameter cleanups happen in the caller and are not part of this
15657   // evaluation.
15658   Info.discardCleanups();
15659   Info.EvalStatus.HasSideEffects = false;
15660 
15661   // Build fake call to Callee.
15662   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call);
15663   // FIXME: Missing ExprWithCleanups in enable_if conditions?
15664   FullExpressionRAII Scope(Info);
15665   return Evaluate(Value, Info, this) && Scope.destroy() &&
15666          !Info.EvalStatus.HasSideEffects;
15667 }
15668 
15669 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
15670                                    SmallVectorImpl<
15671                                      PartialDiagnosticAt> &Diags) {
15672   // FIXME: It would be useful to check constexpr function templates, but at the
15673   // moment the constant expression evaluator cannot cope with the non-rigorous
15674   // ASTs which we build for dependent expressions.
15675   if (FD->isDependentContext())
15676     return true;
15677 
15678   Expr::EvalStatus Status;
15679   Status.Diag = &Diags;
15680 
15681   EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
15682   Info.InConstantContext = true;
15683   Info.CheckingPotentialConstantExpression = true;
15684 
15685   // The constexpr VM attempts to compile all methods to bytecode here.
15686   if (Info.EnableNewConstInterp) {
15687     Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
15688     return Diags.empty();
15689   }
15690 
15691   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
15692   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
15693 
15694   // Fabricate an arbitrary expression on the stack and pretend that it
15695   // is a temporary being used as the 'this' pointer.
15696   LValue This;
15697   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
15698   This.set({&VIE, Info.CurrentCall->Index});
15699 
15700   ArrayRef<const Expr*> Args;
15701 
15702   APValue Scratch;
15703   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
15704     // Evaluate the call as a constant initializer, to allow the construction
15705     // of objects of non-literal types.
15706     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
15707     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
15708   } else {
15709     SourceLocation Loc = FD->getLocation();
15710     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
15711                        Args, CallRef(), FD->getBody(), Info, Scratch, nullptr);
15712   }
15713 
15714   return Diags.empty();
15715 }
15716 
15717 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
15718                                               const FunctionDecl *FD,
15719                                               SmallVectorImpl<
15720                                                 PartialDiagnosticAt> &Diags) {
15721   assert(!E->isValueDependent() &&
15722          "Expression evaluator can't be called on a dependent expression.");
15723 
15724   Expr::EvalStatus Status;
15725   Status.Diag = &Diags;
15726 
15727   EvalInfo Info(FD->getASTContext(), Status,
15728                 EvalInfo::EM_ConstantExpressionUnevaluated);
15729   Info.InConstantContext = true;
15730   Info.CheckingPotentialConstantExpression = true;
15731 
15732   // Fabricate a call stack frame to give the arguments a plausible cover story.
15733   CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef());
15734 
15735   APValue ResultScratch;
15736   Evaluate(ResultScratch, Info, E);
15737   return Diags.empty();
15738 }
15739 
15740 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
15741                                  unsigned Type) const {
15742   if (!getType()->isPointerType())
15743     return false;
15744 
15745   Expr::EvalStatus Status;
15746   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
15747   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
15748 }
15749