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       llvm::erase_if(CleanupStack, [](Cleanup &C) {
1088         return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1089       });
1090     }
1091 
1092     /// Throw away any remaining cleanups at the end of evaluation. If any
1093     /// cleanups would have had a side-effect, note that as an unmodeled
1094     /// side-effect and return false. Otherwise, return true.
1095     bool discardCleanups() {
1096       for (Cleanup &C : CleanupStack) {
1097         if (C.hasSideEffect() && !noteSideEffect()) {
1098           CleanupStack.clear();
1099           return false;
1100         }
1101       }
1102       CleanupStack.clear();
1103       return true;
1104     }
1105 
1106   private:
1107     interp::Frame *getCurrentFrame() override { return CurrentCall; }
1108     const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1109 
1110     bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1111     void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1112 
1113     void setFoldFailureDiagnostic(bool Flag) override {
1114       HasFoldFailureDiagnostic = Flag;
1115     }
1116 
1117     Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1118 
1119     ASTContext &getCtx() const override { return Ctx; }
1120 
1121     // If we have a prior diagnostic, it will be noting that the expression
1122     // isn't a constant expression. This diagnostic is more important,
1123     // unless we require this evaluation to produce a constant expression.
1124     //
1125     // FIXME: We might want to show both diagnostics to the user in
1126     // EM_ConstantFold mode.
1127     bool hasPriorDiagnostic() override {
1128       if (!EvalStatus.Diag->empty()) {
1129         switch (EvalMode) {
1130         case EM_ConstantFold:
1131         case EM_IgnoreSideEffects:
1132           if (!HasFoldFailureDiagnostic)
1133             break;
1134           // We've already failed to fold something. Keep that diagnostic.
1135           LLVM_FALLTHROUGH;
1136         case EM_ConstantExpression:
1137         case EM_ConstantExpressionUnevaluated:
1138           setActiveDiagnostic(false);
1139           return true;
1140         }
1141       }
1142       return false;
1143     }
1144 
1145     unsigned getCallStackDepth() override { return CallStackDepth; }
1146 
1147   public:
1148     /// Should we continue evaluation after encountering a side-effect that we
1149     /// couldn't model?
1150     bool keepEvaluatingAfterSideEffect() {
1151       switch (EvalMode) {
1152       case EM_IgnoreSideEffects:
1153         return true;
1154 
1155       case EM_ConstantExpression:
1156       case EM_ConstantExpressionUnevaluated:
1157       case EM_ConstantFold:
1158         // By default, assume any side effect might be valid in some other
1159         // evaluation of this expression from a different context.
1160         return checkingPotentialConstantExpression() ||
1161                checkingForUndefinedBehavior();
1162       }
1163       llvm_unreachable("Missed EvalMode case");
1164     }
1165 
1166     /// Note that we have had a side-effect, and determine whether we should
1167     /// keep evaluating.
1168     bool noteSideEffect() {
1169       EvalStatus.HasSideEffects = true;
1170       return keepEvaluatingAfterSideEffect();
1171     }
1172 
1173     /// Should we continue evaluation after encountering undefined behavior?
1174     bool keepEvaluatingAfterUndefinedBehavior() {
1175       switch (EvalMode) {
1176       case EM_IgnoreSideEffects:
1177       case EM_ConstantFold:
1178         return true;
1179 
1180       case EM_ConstantExpression:
1181       case EM_ConstantExpressionUnevaluated:
1182         return checkingForUndefinedBehavior();
1183       }
1184       llvm_unreachable("Missed EvalMode case");
1185     }
1186 
1187     /// Note that we hit something that was technically undefined behavior, but
1188     /// that we can evaluate past it (such as signed overflow or floating-point
1189     /// division by zero.)
1190     bool noteUndefinedBehavior() override {
1191       EvalStatus.HasUndefinedBehavior = true;
1192       return keepEvaluatingAfterUndefinedBehavior();
1193     }
1194 
1195     /// Should we continue evaluation as much as possible after encountering a
1196     /// construct which can't be reduced to a value?
1197     bool keepEvaluatingAfterFailure() const override {
1198       if (!StepsLeft)
1199         return false;
1200 
1201       switch (EvalMode) {
1202       case EM_ConstantExpression:
1203       case EM_ConstantExpressionUnevaluated:
1204       case EM_ConstantFold:
1205       case EM_IgnoreSideEffects:
1206         return checkingPotentialConstantExpression() ||
1207                checkingForUndefinedBehavior();
1208       }
1209       llvm_unreachable("Missed EvalMode case");
1210     }
1211 
1212     /// Notes that we failed to evaluate an expression that other expressions
1213     /// directly depend on, and determine if we should keep evaluating. This
1214     /// should only be called if we actually intend to keep evaluating.
1215     ///
1216     /// Call noteSideEffect() instead if we may be able to ignore the value that
1217     /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1218     ///
1219     /// (Foo(), 1)      // use noteSideEffect
1220     /// (Foo() || true) // use noteSideEffect
1221     /// Foo() + 1       // use noteFailure
1222     LLVM_NODISCARD bool noteFailure() {
1223       // Failure when evaluating some expression often means there is some
1224       // subexpression whose evaluation was skipped. Therefore, (because we
1225       // don't track whether we skipped an expression when unwinding after an
1226       // evaluation failure) every evaluation failure that bubbles up from a
1227       // subexpression implies that a side-effect has potentially happened. We
1228       // skip setting the HasSideEffects flag to true until we decide to
1229       // continue evaluating after that point, which happens here.
1230       bool KeepGoing = keepEvaluatingAfterFailure();
1231       EvalStatus.HasSideEffects |= KeepGoing;
1232       return KeepGoing;
1233     }
1234 
1235     class ArrayInitLoopIndex {
1236       EvalInfo &Info;
1237       uint64_t OuterIndex;
1238 
1239     public:
1240       ArrayInitLoopIndex(EvalInfo &Info)
1241           : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1242         Info.ArrayInitIndex = 0;
1243       }
1244       ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1245 
1246       operator uint64_t&() { return Info.ArrayInitIndex; }
1247     };
1248   };
1249 
1250   /// Object used to treat all foldable expressions as constant expressions.
1251   struct FoldConstant {
1252     EvalInfo &Info;
1253     bool Enabled;
1254     bool HadNoPriorDiags;
1255     EvalInfo::EvaluationMode OldMode;
1256 
1257     explicit FoldConstant(EvalInfo &Info, bool Enabled)
1258       : Info(Info),
1259         Enabled(Enabled),
1260         HadNoPriorDiags(Info.EvalStatus.Diag &&
1261                         Info.EvalStatus.Diag->empty() &&
1262                         !Info.EvalStatus.HasSideEffects),
1263         OldMode(Info.EvalMode) {
1264       if (Enabled)
1265         Info.EvalMode = EvalInfo::EM_ConstantFold;
1266     }
1267     void keepDiagnostics() { Enabled = false; }
1268     ~FoldConstant() {
1269       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1270           !Info.EvalStatus.HasSideEffects)
1271         Info.EvalStatus.Diag->clear();
1272       Info.EvalMode = OldMode;
1273     }
1274   };
1275 
1276   /// RAII object used to set the current evaluation mode to ignore
1277   /// side-effects.
1278   struct IgnoreSideEffectsRAII {
1279     EvalInfo &Info;
1280     EvalInfo::EvaluationMode OldMode;
1281     explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1282         : Info(Info), OldMode(Info.EvalMode) {
1283       Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1284     }
1285 
1286     ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1287   };
1288 
1289   /// RAII object used to optionally suppress diagnostics and side-effects from
1290   /// a speculative evaluation.
1291   class SpeculativeEvaluationRAII {
1292     EvalInfo *Info = nullptr;
1293     Expr::EvalStatus OldStatus;
1294     unsigned OldSpeculativeEvaluationDepth;
1295 
1296     void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1297       Info = Other.Info;
1298       OldStatus = Other.OldStatus;
1299       OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1300       Other.Info = nullptr;
1301     }
1302 
1303     void maybeRestoreState() {
1304       if (!Info)
1305         return;
1306 
1307       Info->EvalStatus = OldStatus;
1308       Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1309     }
1310 
1311   public:
1312     SpeculativeEvaluationRAII() = default;
1313 
1314     SpeculativeEvaluationRAII(
1315         EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1316         : Info(&Info), OldStatus(Info.EvalStatus),
1317           OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1318       Info.EvalStatus.Diag = NewDiag;
1319       Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1320     }
1321 
1322     SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1323     SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1324       moveFromAndCancel(std::move(Other));
1325     }
1326 
1327     SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1328       maybeRestoreState();
1329       moveFromAndCancel(std::move(Other));
1330       return *this;
1331     }
1332 
1333     ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1334   };
1335 
1336   /// RAII object wrapping a full-expression or block scope, and handling
1337   /// the ending of the lifetime of temporaries created within it.
1338   template<ScopeKind Kind>
1339   class ScopeRAII {
1340     EvalInfo &Info;
1341     unsigned OldStackSize;
1342   public:
1343     ScopeRAII(EvalInfo &Info)
1344         : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1345       // Push a new temporary version. This is needed to distinguish between
1346       // temporaries created in different iterations of a loop.
1347       Info.CurrentCall->pushTempVersion();
1348     }
1349     bool destroy(bool RunDestructors = true) {
1350       bool OK = cleanup(Info, RunDestructors, OldStackSize);
1351       OldStackSize = -1U;
1352       return OK;
1353     }
1354     ~ScopeRAII() {
1355       if (OldStackSize != -1U)
1356         destroy(false);
1357       // Body moved to a static method to encourage the compiler to inline away
1358       // instances of this class.
1359       Info.CurrentCall->popTempVersion();
1360     }
1361   private:
1362     static bool cleanup(EvalInfo &Info, bool RunDestructors,
1363                         unsigned OldStackSize) {
1364       assert(OldStackSize <= Info.CleanupStack.size() &&
1365              "running cleanups out of order?");
1366 
1367       // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1368       // for a full-expression scope.
1369       bool Success = true;
1370       for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1371         if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1372           if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1373             Success = false;
1374             break;
1375           }
1376         }
1377       }
1378 
1379       // Compact any retained cleanups.
1380       auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1381       if (Kind != ScopeKind::Block)
1382         NewEnd =
1383             std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1384               return C.isDestroyedAtEndOf(Kind);
1385             });
1386       Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1387       return Success;
1388     }
1389   };
1390   typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1391   typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1392   typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1393 }
1394 
1395 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1396                                          CheckSubobjectKind CSK) {
1397   if (Invalid)
1398     return false;
1399   if (isOnePastTheEnd()) {
1400     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1401       << CSK;
1402     setInvalid();
1403     return false;
1404   }
1405   // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1406   // must actually be at least one array element; even a VLA cannot have a
1407   // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1408   return true;
1409 }
1410 
1411 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1412                                                                 const Expr *E) {
1413   Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1414   // Do not set the designator as invalid: we can represent this situation,
1415   // and correct handling of __builtin_object_size requires us to do so.
1416 }
1417 
1418 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1419                                                     const Expr *E,
1420                                                     const APSInt &N) {
1421   // If we're complaining, we must be able to statically determine the size of
1422   // the most derived array.
1423   if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1424     Info.CCEDiag(E, diag::note_constexpr_array_index)
1425       << N << /*array*/ 0
1426       << static_cast<unsigned>(getMostDerivedArraySize());
1427   else
1428     Info.CCEDiag(E, diag::note_constexpr_array_index)
1429       << N << /*non-array*/ 1;
1430   setInvalid();
1431 }
1432 
1433 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1434                                const FunctionDecl *Callee, const LValue *This,
1435                                CallRef Call)
1436     : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1437       Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1438   Info.CurrentCall = this;
1439   ++Info.CallStackDepth;
1440 }
1441 
1442 CallStackFrame::~CallStackFrame() {
1443   assert(Info.CurrentCall == this && "calls retired out of order");
1444   --Info.CallStackDepth;
1445   Info.CurrentCall = Caller;
1446 }
1447 
1448 static bool isRead(AccessKinds AK) {
1449   return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1450 }
1451 
1452 static bool isModification(AccessKinds AK) {
1453   switch (AK) {
1454   case AK_Read:
1455   case AK_ReadObjectRepresentation:
1456   case AK_MemberCall:
1457   case AK_DynamicCast:
1458   case AK_TypeId:
1459     return false;
1460   case AK_Assign:
1461   case AK_Increment:
1462   case AK_Decrement:
1463   case AK_Construct:
1464   case AK_Destroy:
1465     return true;
1466   }
1467   llvm_unreachable("unknown access kind");
1468 }
1469 
1470 static bool isAnyAccess(AccessKinds AK) {
1471   return isRead(AK) || isModification(AK);
1472 }
1473 
1474 /// Is this an access per the C++ definition?
1475 static bool isFormalAccess(AccessKinds AK) {
1476   return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
1477 }
1478 
1479 /// Is this kind of axcess valid on an indeterminate object value?
1480 static bool isValidIndeterminateAccess(AccessKinds AK) {
1481   switch (AK) {
1482   case AK_Read:
1483   case AK_Increment:
1484   case AK_Decrement:
1485     // These need the object's value.
1486     return false;
1487 
1488   case AK_ReadObjectRepresentation:
1489   case AK_Assign:
1490   case AK_Construct:
1491   case AK_Destroy:
1492     // Construction and destruction don't need the value.
1493     return true;
1494 
1495   case AK_MemberCall:
1496   case AK_DynamicCast:
1497   case AK_TypeId:
1498     // These aren't really meaningful on scalars.
1499     return true;
1500   }
1501   llvm_unreachable("unknown access kind");
1502 }
1503 
1504 namespace {
1505   struct ComplexValue {
1506   private:
1507     bool IsInt;
1508 
1509   public:
1510     APSInt IntReal, IntImag;
1511     APFloat FloatReal, FloatImag;
1512 
1513     ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1514 
1515     void makeComplexFloat() { IsInt = false; }
1516     bool isComplexFloat() const { return !IsInt; }
1517     APFloat &getComplexFloatReal() { return FloatReal; }
1518     APFloat &getComplexFloatImag() { return FloatImag; }
1519 
1520     void makeComplexInt() { IsInt = true; }
1521     bool isComplexInt() const { return IsInt; }
1522     APSInt &getComplexIntReal() { return IntReal; }
1523     APSInt &getComplexIntImag() { return IntImag; }
1524 
1525     void moveInto(APValue &v) const {
1526       if (isComplexFloat())
1527         v = APValue(FloatReal, FloatImag);
1528       else
1529         v = APValue(IntReal, IntImag);
1530     }
1531     void setFrom(const APValue &v) {
1532       assert(v.isComplexFloat() || v.isComplexInt());
1533       if (v.isComplexFloat()) {
1534         makeComplexFloat();
1535         FloatReal = v.getComplexFloatReal();
1536         FloatImag = v.getComplexFloatImag();
1537       } else {
1538         makeComplexInt();
1539         IntReal = v.getComplexIntReal();
1540         IntImag = v.getComplexIntImag();
1541       }
1542     }
1543   };
1544 
1545   struct LValue {
1546     APValue::LValueBase Base;
1547     CharUnits Offset;
1548     SubobjectDesignator Designator;
1549     bool IsNullPtr : 1;
1550     bool InvalidBase : 1;
1551 
1552     const APValue::LValueBase getLValueBase() const { return Base; }
1553     CharUnits &getLValueOffset() { return Offset; }
1554     const CharUnits &getLValueOffset() const { return Offset; }
1555     SubobjectDesignator &getLValueDesignator() { return Designator; }
1556     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1557     bool isNullPointer() const { return IsNullPtr;}
1558 
1559     unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1560     unsigned getLValueVersion() const { return Base.getVersion(); }
1561 
1562     void moveInto(APValue &V) const {
1563       if (Designator.Invalid)
1564         V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1565       else {
1566         assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1567         V = APValue(Base, Offset, Designator.Entries,
1568                     Designator.IsOnePastTheEnd, IsNullPtr);
1569       }
1570     }
1571     void setFrom(ASTContext &Ctx, const APValue &V) {
1572       assert(V.isLValue() && "Setting LValue from a non-LValue?");
1573       Base = V.getLValueBase();
1574       Offset = V.getLValueOffset();
1575       InvalidBase = false;
1576       Designator = SubobjectDesignator(Ctx, V);
1577       IsNullPtr = V.isNullPointer();
1578     }
1579 
1580     void set(APValue::LValueBase B, bool BInvalid = false) {
1581 #ifndef NDEBUG
1582       // We only allow a few types of invalid bases. Enforce that here.
1583       if (BInvalid) {
1584         const auto *E = B.get<const Expr *>();
1585         assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1586                "Unexpected type of invalid base");
1587       }
1588 #endif
1589 
1590       Base = B;
1591       Offset = CharUnits::fromQuantity(0);
1592       InvalidBase = BInvalid;
1593       Designator = SubobjectDesignator(getType(B));
1594       IsNullPtr = false;
1595     }
1596 
1597     void setNull(ASTContext &Ctx, QualType PointerTy) {
1598       Base = (const ValueDecl *)nullptr;
1599       Offset =
1600           CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
1601       InvalidBase = false;
1602       Designator = SubobjectDesignator(PointerTy->getPointeeType());
1603       IsNullPtr = true;
1604     }
1605 
1606     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1607       set(B, true);
1608     }
1609 
1610     std::string toString(ASTContext &Ctx, QualType T) const {
1611       APValue Printable;
1612       moveInto(Printable);
1613       return Printable.getAsString(Ctx, T);
1614     }
1615 
1616   private:
1617     // Check that this LValue is not based on a null pointer. If it is, produce
1618     // a diagnostic and mark the designator as invalid.
1619     template <typename GenDiagType>
1620     bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1621       if (Designator.Invalid)
1622         return false;
1623       if (IsNullPtr) {
1624         GenDiag();
1625         Designator.setInvalid();
1626         return false;
1627       }
1628       return true;
1629     }
1630 
1631   public:
1632     bool checkNullPointer(EvalInfo &Info, const Expr *E,
1633                           CheckSubobjectKind CSK) {
1634       return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1635         Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1636       });
1637     }
1638 
1639     bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1640                                        AccessKinds AK) {
1641       return checkNullPointerDiagnosingWith([&Info, E, AK] {
1642         Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1643       });
1644     }
1645 
1646     // Check this LValue refers to an object. If not, set the designator to be
1647     // invalid and emit a diagnostic.
1648     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1649       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1650              Designator.checkSubobject(Info, E, CSK);
1651     }
1652 
1653     void addDecl(EvalInfo &Info, const Expr *E,
1654                  const Decl *D, bool Virtual = false) {
1655       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1656         Designator.addDeclUnchecked(D, Virtual);
1657     }
1658     void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1659       if (!Designator.Entries.empty()) {
1660         Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1661         Designator.setInvalid();
1662         return;
1663       }
1664       if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1665         assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1666         Designator.FirstEntryIsAnUnsizedArray = true;
1667         Designator.addUnsizedArrayUnchecked(ElemTy);
1668       }
1669     }
1670     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1671       if (checkSubobject(Info, E, CSK_ArrayToPointer))
1672         Designator.addArrayUnchecked(CAT);
1673     }
1674     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1675       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1676         Designator.addComplexUnchecked(EltTy, Imag);
1677     }
1678     void clearIsNullPointer() {
1679       IsNullPtr = false;
1680     }
1681     void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1682                               const APSInt &Index, CharUnits ElementSize) {
1683       // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1684       // but we're not required to diagnose it and it's valid in C++.)
1685       if (!Index)
1686         return;
1687 
1688       // Compute the new offset in the appropriate width, wrapping at 64 bits.
1689       // FIXME: When compiling for a 32-bit target, we should use 32-bit
1690       // offsets.
1691       uint64_t Offset64 = Offset.getQuantity();
1692       uint64_t ElemSize64 = ElementSize.getQuantity();
1693       uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1694       Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1695 
1696       if (checkNullPointer(Info, E, CSK_ArrayIndex))
1697         Designator.adjustIndex(Info, E, Index);
1698       clearIsNullPointer();
1699     }
1700     void adjustOffset(CharUnits N) {
1701       Offset += N;
1702       if (N.getQuantity())
1703         clearIsNullPointer();
1704     }
1705   };
1706 
1707   struct MemberPtr {
1708     MemberPtr() {}
1709     explicit MemberPtr(const ValueDecl *Decl)
1710         : DeclAndIsDerivedMember(Decl, false) {}
1711 
1712     /// The member or (direct or indirect) field referred to by this member
1713     /// pointer, or 0 if this is a null member pointer.
1714     const ValueDecl *getDecl() const {
1715       return DeclAndIsDerivedMember.getPointer();
1716     }
1717     /// Is this actually a member of some type derived from the relevant class?
1718     bool isDerivedMember() const {
1719       return DeclAndIsDerivedMember.getInt();
1720     }
1721     /// Get the class which the declaration actually lives in.
1722     const CXXRecordDecl *getContainingRecord() const {
1723       return cast<CXXRecordDecl>(
1724           DeclAndIsDerivedMember.getPointer()->getDeclContext());
1725     }
1726 
1727     void moveInto(APValue &V) const {
1728       V = APValue(getDecl(), isDerivedMember(), Path);
1729     }
1730     void setFrom(const APValue &V) {
1731       assert(V.isMemberPointer());
1732       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1733       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1734       Path.clear();
1735       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1736       Path.insert(Path.end(), P.begin(), P.end());
1737     }
1738 
1739     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1740     /// whether the member is a member of some class derived from the class type
1741     /// of the member pointer.
1742     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1743     /// Path - The path of base/derived classes from the member declaration's
1744     /// class (exclusive) to the class type of the member pointer (inclusive).
1745     SmallVector<const CXXRecordDecl*, 4> Path;
1746 
1747     /// Perform a cast towards the class of the Decl (either up or down the
1748     /// hierarchy).
1749     bool castBack(const CXXRecordDecl *Class) {
1750       assert(!Path.empty());
1751       const CXXRecordDecl *Expected;
1752       if (Path.size() >= 2)
1753         Expected = Path[Path.size() - 2];
1754       else
1755         Expected = getContainingRecord();
1756       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1757         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1758         // if B does not contain the original member and is not a base or
1759         // derived class of the class containing the original member, the result
1760         // of the cast is undefined.
1761         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1762         // (D::*). We consider that to be a language defect.
1763         return false;
1764       }
1765       Path.pop_back();
1766       return true;
1767     }
1768     /// Perform a base-to-derived member pointer cast.
1769     bool castToDerived(const CXXRecordDecl *Derived) {
1770       if (!getDecl())
1771         return true;
1772       if (!isDerivedMember()) {
1773         Path.push_back(Derived);
1774         return true;
1775       }
1776       if (!castBack(Derived))
1777         return false;
1778       if (Path.empty())
1779         DeclAndIsDerivedMember.setInt(false);
1780       return true;
1781     }
1782     /// Perform a derived-to-base member pointer cast.
1783     bool castToBase(const CXXRecordDecl *Base) {
1784       if (!getDecl())
1785         return true;
1786       if (Path.empty())
1787         DeclAndIsDerivedMember.setInt(true);
1788       if (isDerivedMember()) {
1789         Path.push_back(Base);
1790         return true;
1791       }
1792       return castBack(Base);
1793     }
1794   };
1795 
1796   /// Compare two member pointers, which are assumed to be of the same type.
1797   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1798     if (!LHS.getDecl() || !RHS.getDecl())
1799       return !LHS.getDecl() && !RHS.getDecl();
1800     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1801       return false;
1802     return LHS.Path == RHS.Path;
1803   }
1804 }
1805 
1806 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1807 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1808                             const LValue &This, const Expr *E,
1809                             bool AllowNonLiteralTypes = false);
1810 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1811                            bool InvalidBaseOK = false);
1812 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1813                             bool InvalidBaseOK = false);
1814 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1815                                   EvalInfo &Info);
1816 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1817 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1818 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1819                                     EvalInfo &Info);
1820 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1821 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1822 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1823                            EvalInfo &Info);
1824 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1825 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
1826                                   EvalInfo &Info);
1827 
1828 /// Evaluate an integer or fixed point expression into an APResult.
1829 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1830                                         EvalInfo &Info);
1831 
1832 /// Evaluate only a fixed point expression into an APResult.
1833 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1834                                EvalInfo &Info);
1835 
1836 //===----------------------------------------------------------------------===//
1837 // Misc utilities
1838 //===----------------------------------------------------------------------===//
1839 
1840 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1841 /// preserving its value (by extending by up to one bit as needed).
1842 static void negateAsSigned(APSInt &Int) {
1843   if (Int.isUnsigned() || Int.isMinSignedValue()) {
1844     Int = Int.extend(Int.getBitWidth() + 1);
1845     Int.setIsSigned(true);
1846   }
1847   Int = -Int;
1848 }
1849 
1850 template<typename KeyT>
1851 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1852                                          ScopeKind Scope, LValue &LV) {
1853   unsigned Version = getTempVersion();
1854   APValue::LValueBase Base(Key, Index, Version);
1855   LV.set(Base);
1856   return createLocal(Base, Key, T, Scope);
1857 }
1858 
1859 /// Allocate storage for a parameter of a function call made in this frame.
1860 APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1861                                      LValue &LV) {
1862   assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1863   APValue::LValueBase Base(PVD, Index, Args.Version);
1864   LV.set(Base);
1865   // We always destroy parameters at the end of the call, even if we'd allow
1866   // them to live to the end of the full-expression at runtime, in order to
1867   // give portable results and match other compilers.
1868   return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1869 }
1870 
1871 APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1872                                      QualType T, ScopeKind Scope) {
1873   assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1874   unsigned Version = Base.getVersion();
1875   APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1876   assert(Result.isAbsent() && "local created multiple times");
1877 
1878   // If we're creating a local immediately in the operand of a speculative
1879   // evaluation, don't register a cleanup to be run outside the speculative
1880   // evaluation context, since we won't actually be able to initialize this
1881   // object.
1882   if (Index <= Info.SpeculativeEvaluationDepth) {
1883     if (T.isDestructedType())
1884       Info.noteSideEffect();
1885   } else {
1886     Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1887   }
1888   return Result;
1889 }
1890 
1891 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1892   if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1893     FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1894     return nullptr;
1895   }
1896 
1897   DynamicAllocLValue DA(NumHeapAllocs++);
1898   LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1899   auto Result = HeapAllocs.emplace(std::piecewise_construct,
1900                                    std::forward_as_tuple(DA), std::tuple<>());
1901   assert(Result.second && "reused a heap alloc index?");
1902   Result.first->second.AllocExpr = E;
1903   return &Result.first->second.Value;
1904 }
1905 
1906 /// Produce a string describing the given constexpr call.
1907 void CallStackFrame::describe(raw_ostream &Out) {
1908   unsigned ArgIndex = 0;
1909   bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1910                       !isa<CXXConstructorDecl>(Callee) &&
1911                       cast<CXXMethodDecl>(Callee)->isInstance();
1912 
1913   if (!IsMemberCall)
1914     Out << *Callee << '(';
1915 
1916   if (This && IsMemberCall) {
1917     APValue Val;
1918     This->moveInto(Val);
1919     Val.printPretty(Out, Info.Ctx,
1920                     This->Designator.MostDerivedType);
1921     // FIXME: Add parens around Val if needed.
1922     Out << "->" << *Callee << '(';
1923     IsMemberCall = false;
1924   }
1925 
1926   for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1927        E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
1928     if (ArgIndex > (unsigned)IsMemberCall)
1929       Out << ", ";
1930 
1931     const ParmVarDecl *Param = *I;
1932     APValue *V = Info.getParamSlot(Arguments, Param);
1933     if (V)
1934       V->printPretty(Out, Info.Ctx, Param->getType());
1935     else
1936       Out << "<...>";
1937 
1938     if (ArgIndex == 0 && IsMemberCall)
1939       Out << "->" << *Callee << '(';
1940   }
1941 
1942   Out << ')';
1943 }
1944 
1945 /// Evaluate an expression to see if it had side-effects, and discard its
1946 /// result.
1947 /// \return \c true if the caller should keep evaluating.
1948 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1949   assert(!E->isValueDependent());
1950   APValue Scratch;
1951   if (!Evaluate(Scratch, Info, E))
1952     // We don't need the value, but we might have skipped a side effect here.
1953     return Info.noteSideEffect();
1954   return true;
1955 }
1956 
1957 /// Should this call expression be treated as a constant?
1958 static bool IsConstantCall(const CallExpr *E) {
1959   unsigned Builtin = E->getBuiltinCallee();
1960   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1961           Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
1962           Builtin == Builtin::BI__builtin_function_start);
1963 }
1964 
1965 static bool IsGlobalLValue(APValue::LValueBase B) {
1966   // C++11 [expr.const]p3 An address constant expression is a prvalue core
1967   // constant expression of pointer type that evaluates to...
1968 
1969   // ... a null pointer value, or a prvalue core constant expression of type
1970   // std::nullptr_t.
1971   if (!B) return true;
1972 
1973   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1974     // ... the address of an object with static storage duration,
1975     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1976       return VD->hasGlobalStorage();
1977     if (isa<TemplateParamObjectDecl>(D))
1978       return true;
1979     // ... the address of a function,
1980     // ... the address of a GUID [MS extension],
1981     return isa<FunctionDecl>(D) || isa<MSGuidDecl>(D);
1982   }
1983 
1984   if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
1985     return true;
1986 
1987   const Expr *E = B.get<const Expr*>();
1988   switch (E->getStmtClass()) {
1989   default:
1990     return false;
1991   case Expr::CompoundLiteralExprClass: {
1992     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1993     return CLE->isFileScope() && CLE->isLValue();
1994   }
1995   case Expr::MaterializeTemporaryExprClass:
1996     // A materialized temporary might have been lifetime-extended to static
1997     // storage duration.
1998     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1999   // A string literal has static storage duration.
2000   case Expr::StringLiteralClass:
2001   case Expr::PredefinedExprClass:
2002   case Expr::ObjCStringLiteralClass:
2003   case Expr::ObjCEncodeExprClass:
2004     return true;
2005   case Expr::ObjCBoxedExprClass:
2006     return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2007   case Expr::CallExprClass:
2008     return IsConstantCall(cast<CallExpr>(E));
2009   // For GCC compatibility, &&label has static storage duration.
2010   case Expr::AddrLabelExprClass:
2011     return true;
2012   // A Block literal expression may be used as the initialization value for
2013   // Block variables at global or local static scope.
2014   case Expr::BlockExprClass:
2015     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2016   case Expr::ImplicitValueInitExprClass:
2017     // FIXME:
2018     // We can never form an lvalue with an implicit value initialization as its
2019     // base through expression evaluation, so these only appear in one case: the
2020     // implicit variable declaration we invent when checking whether a constexpr
2021     // constructor can produce a constant expression. We must assume that such
2022     // an expression might be a global lvalue.
2023     return true;
2024   }
2025 }
2026 
2027 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2028   return LVal.Base.dyn_cast<const ValueDecl*>();
2029 }
2030 
2031 static bool IsLiteralLValue(const LValue &Value) {
2032   if (Value.getLValueCallIndex())
2033     return false;
2034   const Expr *E = Value.Base.dyn_cast<const Expr*>();
2035   return E && !isa<MaterializeTemporaryExpr>(E);
2036 }
2037 
2038 static bool IsWeakLValue(const LValue &Value) {
2039   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2040   return Decl && Decl->isWeak();
2041 }
2042 
2043 static bool isZeroSized(const LValue &Value) {
2044   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2045   if (Decl && isa<VarDecl>(Decl)) {
2046     QualType Ty = Decl->getType();
2047     if (Ty->isArrayType())
2048       return Ty->isIncompleteType() ||
2049              Decl->getASTContext().getTypeSize(Ty) == 0;
2050   }
2051   return false;
2052 }
2053 
2054 static bool HasSameBase(const LValue &A, const LValue &B) {
2055   if (!A.getLValueBase())
2056     return !B.getLValueBase();
2057   if (!B.getLValueBase())
2058     return false;
2059 
2060   if (A.getLValueBase().getOpaqueValue() !=
2061       B.getLValueBase().getOpaqueValue())
2062     return false;
2063 
2064   return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2065          A.getLValueVersion() == B.getLValueVersion();
2066 }
2067 
2068 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2069   assert(Base && "no location for a null lvalue");
2070   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2071 
2072   // For a parameter, find the corresponding call stack frame (if it still
2073   // exists), and point at the parameter of the function definition we actually
2074   // invoked.
2075   if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2076     unsigned Idx = PVD->getFunctionScopeIndex();
2077     for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2078       if (F->Arguments.CallIndex == Base.getCallIndex() &&
2079           F->Arguments.Version == Base.getVersion() && F->Callee &&
2080           Idx < F->Callee->getNumParams()) {
2081         VD = F->Callee->getParamDecl(Idx);
2082         break;
2083       }
2084     }
2085   }
2086 
2087   if (VD)
2088     Info.Note(VD->getLocation(), diag::note_declared_at);
2089   else if (const Expr *E = Base.dyn_cast<const Expr*>())
2090     Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2091   else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2092     // FIXME: Produce a note for dangling pointers too.
2093     if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA))
2094       Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2095                 diag::note_constexpr_dynamic_alloc_here);
2096   }
2097   // We have no information to show for a typeid(T) object.
2098 }
2099 
2100 enum class CheckEvaluationResultKind {
2101   ConstantExpression,
2102   FullyInitialized,
2103 };
2104 
2105 /// Materialized temporaries that we've already checked to determine if they're
2106 /// initializsed by a constant expression.
2107 using CheckedTemporaries =
2108     llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
2109 
2110 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2111                                   EvalInfo &Info, SourceLocation DiagLoc,
2112                                   QualType Type, const APValue &Value,
2113                                   ConstantExprKind Kind,
2114                                   SourceLocation SubobjectLoc,
2115                                   CheckedTemporaries &CheckedTemps);
2116 
2117 /// Check that this reference or pointer core constant expression is a valid
2118 /// value for an address or reference constant expression. Return true if we
2119 /// can fold this expression, whether or not it's a constant expression.
2120 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2121                                           QualType Type, const LValue &LVal,
2122                                           ConstantExprKind Kind,
2123                                           CheckedTemporaries &CheckedTemps) {
2124   bool IsReferenceType = Type->isReferenceType();
2125 
2126   APValue::LValueBase Base = LVal.getLValueBase();
2127   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2128 
2129   const Expr *BaseE = Base.dyn_cast<const Expr *>();
2130   const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2131 
2132   // Additional restrictions apply in a template argument. We only enforce the
2133   // C++20 restrictions here; additional syntactic and semantic restrictions
2134   // are applied elsewhere.
2135   if (isTemplateArgument(Kind)) {
2136     int InvalidBaseKind = -1;
2137     StringRef Ident;
2138     if (Base.is<TypeInfoLValue>())
2139       InvalidBaseKind = 0;
2140     else if (isa_and_nonnull<StringLiteral>(BaseE))
2141       InvalidBaseKind = 1;
2142     else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2143              isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2144       InvalidBaseKind = 2;
2145     else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2146       InvalidBaseKind = 3;
2147       Ident = PE->getIdentKindName();
2148     }
2149 
2150     if (InvalidBaseKind != -1) {
2151       Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2152           << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2153           << Ident;
2154       return false;
2155     }
2156   }
2157 
2158   if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD)) {
2159     if (FD->isConsteval()) {
2160       Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2161           << !Type->isAnyPointerType();
2162       Info.Note(FD->getLocation(), diag::note_declared_at);
2163       return false;
2164     }
2165   }
2166 
2167   // Check that the object is a global. Note that the fake 'this' object we
2168   // manufacture when checking potential constant expressions is conservatively
2169   // assumed to be global here.
2170   if (!IsGlobalLValue(Base)) {
2171     if (Info.getLangOpts().CPlusPlus11) {
2172       const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2173       Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2174         << IsReferenceType << !Designator.Entries.empty()
2175         << !!VD << VD;
2176 
2177       auto *VarD = dyn_cast_or_null<VarDecl>(VD);
2178       if (VarD && VarD->isConstexpr()) {
2179         // Non-static local constexpr variables have unintuitive semantics:
2180         //   constexpr int a = 1;
2181         //   constexpr const int *p = &a;
2182         // ... is invalid because the address of 'a' is not constant. Suggest
2183         // adding a 'static' in this case.
2184         Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2185             << VarD
2186             << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2187       } else {
2188         NoteLValueLocation(Info, Base);
2189       }
2190     } else {
2191       Info.FFDiag(Loc);
2192     }
2193     // Don't allow references to temporaries to escape.
2194     return false;
2195   }
2196   assert((Info.checkingPotentialConstantExpression() ||
2197           LVal.getLValueCallIndex() == 0) &&
2198          "have call index for global lvalue");
2199 
2200   if (Base.is<DynamicAllocLValue>()) {
2201     Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2202         << IsReferenceType << !Designator.Entries.empty();
2203     NoteLValueLocation(Info, Base);
2204     return false;
2205   }
2206 
2207   if (BaseVD) {
2208     if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2209       // Check if this is a thread-local variable.
2210       if (Var->getTLSKind())
2211         // FIXME: Diagnostic!
2212         return false;
2213 
2214       // A dllimport variable never acts like a constant, unless we're
2215       // evaluating a value for use only in name mangling.
2216       if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2217         // FIXME: Diagnostic!
2218         return false;
2219     }
2220     if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2221       // __declspec(dllimport) must be handled very carefully:
2222       // We must never initialize an expression with the thunk in C++.
2223       // Doing otherwise would allow the same id-expression to yield
2224       // different addresses for the same function in different translation
2225       // units.  However, this means that we must dynamically initialize the
2226       // expression with the contents of the import address table at runtime.
2227       //
2228       // The C language has no notion of ODR; furthermore, it has no notion of
2229       // dynamic initialization.  This means that we are permitted to
2230       // perform initialization with the address of the thunk.
2231       if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2232           FD->hasAttr<DLLImportAttr>())
2233         // FIXME: Diagnostic!
2234         return false;
2235     }
2236   } else if (const auto *MTE =
2237                  dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2238     if (CheckedTemps.insert(MTE).second) {
2239       QualType TempType = getType(Base);
2240       if (TempType.isDestructedType()) {
2241         Info.FFDiag(MTE->getExprLoc(),
2242                     diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2243             << TempType;
2244         return false;
2245       }
2246 
2247       APValue *V = MTE->getOrCreateValue(false);
2248       assert(V && "evasluation result refers to uninitialised temporary");
2249       if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2250                                  Info, MTE->getExprLoc(), TempType, *V,
2251                                  Kind, SourceLocation(), CheckedTemps))
2252         return false;
2253     }
2254   }
2255 
2256   // Allow address constant expressions to be past-the-end pointers. This is
2257   // an extension: the standard requires them to point to an object.
2258   if (!IsReferenceType)
2259     return true;
2260 
2261   // A reference constant expression must refer to an object.
2262   if (!Base) {
2263     // FIXME: diagnostic
2264     Info.CCEDiag(Loc);
2265     return true;
2266   }
2267 
2268   // Does this refer one past the end of some object?
2269   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2270     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2271       << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2272     NoteLValueLocation(Info, Base);
2273   }
2274 
2275   return true;
2276 }
2277 
2278 /// Member pointers are constant expressions unless they point to a
2279 /// non-virtual dllimport member function.
2280 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2281                                                  SourceLocation Loc,
2282                                                  QualType Type,
2283                                                  const APValue &Value,
2284                                                  ConstantExprKind Kind) {
2285   const ValueDecl *Member = Value.getMemberPointerDecl();
2286   const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2287   if (!FD)
2288     return true;
2289   if (FD->isConsteval()) {
2290     Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2291     Info.Note(FD->getLocation(), diag::note_declared_at);
2292     return false;
2293   }
2294   return isForManglingOnly(Kind) || FD->isVirtual() ||
2295          !FD->hasAttr<DLLImportAttr>();
2296 }
2297 
2298 /// Check that this core constant expression is of literal type, and if not,
2299 /// produce an appropriate diagnostic.
2300 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2301                              const LValue *This = nullptr) {
2302   if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2303     return true;
2304 
2305   // C++1y: A constant initializer for an object o [...] may also invoke
2306   // constexpr constructors for o and its subobjects even if those objects
2307   // are of non-literal class types.
2308   //
2309   // C++11 missed this detail for aggregates, so classes like this:
2310   //   struct foo_t { union { int i; volatile int j; } u; };
2311   // are not (obviously) initializable like so:
2312   //   __attribute__((__require_constant_initialization__))
2313   //   static const foo_t x = {{0}};
2314   // because "i" is a subobject with non-literal initialization (due to the
2315   // volatile member of the union). See:
2316   //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2317   // Therefore, we use the C++1y behavior.
2318   if (This && Info.EvaluatingDecl == This->getLValueBase())
2319     return true;
2320 
2321   // Prvalue constant expressions must be of literal types.
2322   if (Info.getLangOpts().CPlusPlus11)
2323     Info.FFDiag(E, diag::note_constexpr_nonliteral)
2324       << E->getType();
2325   else
2326     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2327   return false;
2328 }
2329 
2330 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2331                                   EvalInfo &Info, SourceLocation DiagLoc,
2332                                   QualType Type, const APValue &Value,
2333                                   ConstantExprKind Kind,
2334                                   SourceLocation SubobjectLoc,
2335                                   CheckedTemporaries &CheckedTemps) {
2336   if (!Value.hasValue()) {
2337     Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2338       << true << Type;
2339     if (SubobjectLoc.isValid())
2340       Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2341     return false;
2342   }
2343 
2344   // We allow _Atomic(T) to be initialized from anything that T can be
2345   // initialized from.
2346   if (const AtomicType *AT = Type->getAs<AtomicType>())
2347     Type = AT->getValueType();
2348 
2349   // Core issue 1454: For a literal constant expression of array or class type,
2350   // each subobject of its value shall have been initialized by a constant
2351   // expression.
2352   if (Value.isArray()) {
2353     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2354     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2355       if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2356                                  Value.getArrayInitializedElt(I), Kind,
2357                                  SubobjectLoc, CheckedTemps))
2358         return false;
2359     }
2360     if (!Value.hasArrayFiller())
2361       return true;
2362     return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2363                                  Value.getArrayFiller(), Kind, SubobjectLoc,
2364                                  CheckedTemps);
2365   }
2366   if (Value.isUnion() && Value.getUnionField()) {
2367     return CheckEvaluationResult(
2368         CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2369         Value.getUnionValue(), Kind, Value.getUnionField()->getLocation(),
2370         CheckedTemps);
2371   }
2372   if (Value.isStruct()) {
2373     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2374     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2375       unsigned BaseIndex = 0;
2376       for (const CXXBaseSpecifier &BS : CD->bases()) {
2377         if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2378                                    Value.getStructBase(BaseIndex), Kind,
2379                                    BS.getBeginLoc(), CheckedTemps))
2380           return false;
2381         ++BaseIndex;
2382       }
2383     }
2384     for (const auto *I : RD->fields()) {
2385       if (I->isUnnamedBitfield())
2386         continue;
2387 
2388       if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2389                                  Value.getStructField(I->getFieldIndex()),
2390                                  Kind, I->getLocation(), CheckedTemps))
2391         return false;
2392     }
2393   }
2394 
2395   if (Value.isLValue() &&
2396       CERK == CheckEvaluationResultKind::ConstantExpression) {
2397     LValue LVal;
2398     LVal.setFrom(Info.Ctx, Value);
2399     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2400                                          CheckedTemps);
2401   }
2402 
2403   if (Value.isMemberPointer() &&
2404       CERK == CheckEvaluationResultKind::ConstantExpression)
2405     return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2406 
2407   // Everything else is fine.
2408   return true;
2409 }
2410 
2411 /// Check that this core constant expression value is a valid value for a
2412 /// constant expression. If not, report an appropriate diagnostic. Does not
2413 /// check that the expression is of literal type.
2414 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2415                                     QualType Type, const APValue &Value,
2416                                     ConstantExprKind Kind) {
2417   // Nothing to check for a constant expression of type 'cv void'.
2418   if (Type->isVoidType())
2419     return true;
2420 
2421   CheckedTemporaries CheckedTemps;
2422   return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2423                                Info, DiagLoc, Type, Value, Kind,
2424                                SourceLocation(), CheckedTemps);
2425 }
2426 
2427 /// Check that this evaluated value is fully-initialized and can be loaded by
2428 /// an lvalue-to-rvalue conversion.
2429 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2430                                   QualType Type, const APValue &Value) {
2431   CheckedTemporaries CheckedTemps;
2432   return CheckEvaluationResult(
2433       CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2434       ConstantExprKind::Normal, SourceLocation(), CheckedTemps);
2435 }
2436 
2437 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2438 /// "the allocated storage is deallocated within the evaluation".
2439 static bool CheckMemoryLeaks(EvalInfo &Info) {
2440   if (!Info.HeapAllocs.empty()) {
2441     // We can still fold to a constant despite a compile-time memory leak,
2442     // so long as the heap allocation isn't referenced in the result (we check
2443     // that in CheckConstantExpression).
2444     Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2445                  diag::note_constexpr_memory_leak)
2446         << unsigned(Info.HeapAllocs.size() - 1);
2447   }
2448   return true;
2449 }
2450 
2451 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2452   // A null base expression indicates a null pointer.  These are always
2453   // evaluatable, and they are false unless the offset is zero.
2454   if (!Value.getLValueBase()) {
2455     Result = !Value.getLValueOffset().isZero();
2456     return true;
2457   }
2458 
2459   // We have a non-null base.  These are generally known to be true, but if it's
2460   // a weak declaration it can be null at runtime.
2461   Result = true;
2462   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2463   return !Decl || !Decl->isWeak();
2464 }
2465 
2466 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2467   switch (Val.getKind()) {
2468   case APValue::None:
2469   case APValue::Indeterminate:
2470     return false;
2471   case APValue::Int:
2472     Result = Val.getInt().getBoolValue();
2473     return true;
2474   case APValue::FixedPoint:
2475     Result = Val.getFixedPoint().getBoolValue();
2476     return true;
2477   case APValue::Float:
2478     Result = !Val.getFloat().isZero();
2479     return true;
2480   case APValue::ComplexInt:
2481     Result = Val.getComplexIntReal().getBoolValue() ||
2482              Val.getComplexIntImag().getBoolValue();
2483     return true;
2484   case APValue::ComplexFloat:
2485     Result = !Val.getComplexFloatReal().isZero() ||
2486              !Val.getComplexFloatImag().isZero();
2487     return true;
2488   case APValue::LValue:
2489     return EvalPointerValueAsBool(Val, Result);
2490   case APValue::MemberPointer:
2491     Result = Val.getMemberPointerDecl();
2492     return true;
2493   case APValue::Vector:
2494   case APValue::Array:
2495   case APValue::Struct:
2496   case APValue::Union:
2497   case APValue::AddrLabelDiff:
2498     return false;
2499   }
2500 
2501   llvm_unreachable("unknown APValue kind");
2502 }
2503 
2504 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2505                                        EvalInfo &Info) {
2506   assert(!E->isValueDependent());
2507   assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2508   APValue Val;
2509   if (!Evaluate(Val, Info, E))
2510     return false;
2511   return HandleConversionToBool(Val, Result);
2512 }
2513 
2514 template<typename T>
2515 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2516                            const T &SrcValue, QualType DestType) {
2517   Info.CCEDiag(E, diag::note_constexpr_overflow)
2518     << SrcValue << DestType;
2519   return Info.noteUndefinedBehavior();
2520 }
2521 
2522 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2523                                  QualType SrcType, const APFloat &Value,
2524                                  QualType DestType, APSInt &Result) {
2525   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2526   // Determine whether we are converting to unsigned or signed.
2527   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2528 
2529   Result = APSInt(DestWidth, !DestSigned);
2530   bool ignored;
2531   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2532       & APFloat::opInvalidOp)
2533     return HandleOverflow(Info, E, Value, DestType);
2534   return true;
2535 }
2536 
2537 /// Get rounding mode used for evaluation of the specified expression.
2538 /// \param[out] DynamicRM Is set to true is the requested rounding mode is
2539 ///                       dynamic.
2540 /// If rounding mode is unknown at compile time, still try to evaluate the
2541 /// expression. If the result is exact, it does not depend on rounding mode.
2542 /// So return "tonearest" mode instead of "dynamic".
2543 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E,
2544                                                 bool &DynamicRM) {
2545   llvm::RoundingMode RM =
2546       E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2547   DynamicRM = (RM == llvm::RoundingMode::Dynamic);
2548   if (DynamicRM)
2549     RM = llvm::RoundingMode::NearestTiesToEven;
2550   return RM;
2551 }
2552 
2553 /// Check if the given evaluation result is allowed for constant evaluation.
2554 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2555                                      APFloat::opStatus St) {
2556   // In a constant context, assume that any dynamic rounding mode or FP
2557   // exception state matches the default floating-point environment.
2558   if (Info.InConstantContext)
2559     return true;
2560 
2561   FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2562   if ((St & APFloat::opInexact) &&
2563       FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2564     // Inexact result means that it depends on rounding mode. If the requested
2565     // mode is dynamic, the evaluation cannot be made in compile time.
2566     Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2567     return false;
2568   }
2569 
2570   if ((St != APFloat::opOK) &&
2571       (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2572        FPO.getFPExceptionMode() != LangOptions::FPE_Ignore ||
2573        FPO.getAllowFEnvAccess())) {
2574     Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2575     return false;
2576   }
2577 
2578   if ((St & APFloat::opStatus::opInvalidOp) &&
2579       FPO.getFPExceptionMode() != LangOptions::FPE_Ignore) {
2580     // There is no usefully definable result.
2581     Info.FFDiag(E);
2582     return false;
2583   }
2584 
2585   // FIXME: if:
2586   // - evaluation triggered other FP exception, and
2587   // - exception mode is not "ignore", and
2588   // - the expression being evaluated is not a part of global variable
2589   //   initializer,
2590   // the evaluation probably need to be rejected.
2591   return true;
2592 }
2593 
2594 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2595                                    QualType SrcType, QualType DestType,
2596                                    APFloat &Result) {
2597   assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E));
2598   bool DynamicRM;
2599   llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM);
2600   APFloat::opStatus St;
2601   APFloat Value = Result;
2602   bool ignored;
2603   St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2604   return checkFloatingPointResult(Info, E, St);
2605 }
2606 
2607 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2608                                  QualType DestType, QualType SrcType,
2609                                  const APSInt &Value) {
2610   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2611   // Figure out if this is a truncate, extend or noop cast.
2612   // If the input is signed, do a sign extend, noop, or truncate.
2613   APSInt Result = Value.extOrTrunc(DestWidth);
2614   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2615   if (DestType->isBooleanType())
2616     Result = Value.getBoolValue();
2617   return Result;
2618 }
2619 
2620 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2621                                  const FPOptions FPO,
2622                                  QualType SrcType, const APSInt &Value,
2623                                  QualType DestType, APFloat &Result) {
2624   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2625   APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(),
2626        APFloat::rmNearestTiesToEven);
2627   if (!Info.InConstantContext && St != llvm::APFloatBase::opOK &&
2628       FPO.isFPConstrained()) {
2629     Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2630     return false;
2631   }
2632   return true;
2633 }
2634 
2635 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2636                                   APValue &Value, const FieldDecl *FD) {
2637   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2638 
2639   if (!Value.isInt()) {
2640     // Trying to store a pointer-cast-to-integer into a bitfield.
2641     // FIXME: In this case, we should provide the diagnostic for casting
2642     // a pointer to an integer.
2643     assert(Value.isLValue() && "integral value neither int nor lvalue?");
2644     Info.FFDiag(E);
2645     return false;
2646   }
2647 
2648   APSInt &Int = Value.getInt();
2649   unsigned OldBitWidth = Int.getBitWidth();
2650   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2651   if (NewBitWidth < OldBitWidth)
2652     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2653   return true;
2654 }
2655 
2656 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2657                                   llvm::APInt &Res) {
2658   APValue SVal;
2659   if (!Evaluate(SVal, Info, E))
2660     return false;
2661   if (SVal.isInt()) {
2662     Res = SVal.getInt();
2663     return true;
2664   }
2665   if (SVal.isFloat()) {
2666     Res = SVal.getFloat().bitcastToAPInt();
2667     return true;
2668   }
2669   if (SVal.isVector()) {
2670     QualType VecTy = E->getType();
2671     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2672     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2673     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2674     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2675     Res = llvm::APInt::getZero(VecSize);
2676     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2677       APValue &Elt = SVal.getVectorElt(i);
2678       llvm::APInt EltAsInt;
2679       if (Elt.isInt()) {
2680         EltAsInt = Elt.getInt();
2681       } else if (Elt.isFloat()) {
2682         EltAsInt = Elt.getFloat().bitcastToAPInt();
2683       } else {
2684         // Don't try to handle vectors of anything other than int or float
2685         // (not sure if it's possible to hit this case).
2686         Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2687         return false;
2688       }
2689       unsigned BaseEltSize = EltAsInt.getBitWidth();
2690       if (BigEndian)
2691         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2692       else
2693         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2694     }
2695     return true;
2696   }
2697   // Give up if the input isn't an int, float, or vector.  For example, we
2698   // reject "(v4i16)(intptr_t)&a".
2699   Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2700   return false;
2701 }
2702 
2703 /// Perform the given integer operation, which is known to need at most BitWidth
2704 /// bits, and check for overflow in the original type (if that type was not an
2705 /// unsigned type).
2706 template<typename Operation>
2707 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2708                                  const APSInt &LHS, const APSInt &RHS,
2709                                  unsigned BitWidth, Operation Op,
2710                                  APSInt &Result) {
2711   if (LHS.isUnsigned()) {
2712     Result = Op(LHS, RHS);
2713     return true;
2714   }
2715 
2716   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2717   Result = Value.trunc(LHS.getBitWidth());
2718   if (Result.extend(BitWidth) != Value) {
2719     if (Info.checkingForUndefinedBehavior())
2720       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2721                                        diag::warn_integer_constant_overflow)
2722           << toString(Result, 10) << E->getType();
2723     return HandleOverflow(Info, E, Value, E->getType());
2724   }
2725   return true;
2726 }
2727 
2728 /// Perform the given binary integer operation.
2729 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2730                               BinaryOperatorKind Opcode, APSInt RHS,
2731                               APSInt &Result) {
2732   switch (Opcode) {
2733   default:
2734     Info.FFDiag(E);
2735     return false;
2736   case BO_Mul:
2737     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2738                                 std::multiplies<APSInt>(), Result);
2739   case BO_Add:
2740     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2741                                 std::plus<APSInt>(), Result);
2742   case BO_Sub:
2743     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2744                                 std::minus<APSInt>(), Result);
2745   case BO_And: Result = LHS & RHS; return true;
2746   case BO_Xor: Result = LHS ^ RHS; return true;
2747   case BO_Or:  Result = LHS | RHS; return true;
2748   case BO_Div:
2749   case BO_Rem:
2750     if (RHS == 0) {
2751       Info.FFDiag(E, diag::note_expr_divide_by_zero);
2752       return false;
2753     }
2754     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2755     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2756     // this operation and gives the two's complement result.
2757     if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2758         LHS.isMinSignedValue())
2759       return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2760                             E->getType());
2761     return true;
2762   case BO_Shl: {
2763     if (Info.getLangOpts().OpenCL)
2764       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2765       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2766                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2767                     RHS.isUnsigned());
2768     else if (RHS.isSigned() && RHS.isNegative()) {
2769       // During constant-folding, a negative shift is an opposite shift. Such
2770       // a shift is not a constant expression.
2771       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2772       RHS = -RHS;
2773       goto shift_right;
2774     }
2775   shift_left:
2776     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2777     // the shifted type.
2778     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2779     if (SA != RHS) {
2780       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2781         << RHS << E->getType() << LHS.getBitWidth();
2782     } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2783       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2784       // operand, and must not overflow the corresponding unsigned type.
2785       // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2786       // E1 x 2^E2 module 2^N.
2787       if (LHS.isNegative())
2788         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2789       else if (LHS.countLeadingZeros() < SA)
2790         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2791     }
2792     Result = LHS << SA;
2793     return true;
2794   }
2795   case BO_Shr: {
2796     if (Info.getLangOpts().OpenCL)
2797       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2798       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2799                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2800                     RHS.isUnsigned());
2801     else if (RHS.isSigned() && RHS.isNegative()) {
2802       // During constant-folding, a negative shift is an opposite shift. Such a
2803       // shift is not a constant expression.
2804       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2805       RHS = -RHS;
2806       goto shift_left;
2807     }
2808   shift_right:
2809     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2810     // shifted type.
2811     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2812     if (SA != RHS)
2813       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2814         << RHS << E->getType() << LHS.getBitWidth();
2815     Result = LHS >> SA;
2816     return true;
2817   }
2818 
2819   case BO_LT: Result = LHS < RHS; return true;
2820   case BO_GT: Result = LHS > RHS; return true;
2821   case BO_LE: Result = LHS <= RHS; return true;
2822   case BO_GE: Result = LHS >= RHS; return true;
2823   case BO_EQ: Result = LHS == RHS; return true;
2824   case BO_NE: Result = LHS != RHS; return true;
2825   case BO_Cmp:
2826     llvm_unreachable("BO_Cmp should be handled elsewhere");
2827   }
2828 }
2829 
2830 /// Perform the given binary floating-point operation, in-place, on LHS.
2831 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2832                                   APFloat &LHS, BinaryOperatorKind Opcode,
2833                                   const APFloat &RHS) {
2834   bool DynamicRM;
2835   llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM);
2836   APFloat::opStatus St;
2837   switch (Opcode) {
2838   default:
2839     Info.FFDiag(E);
2840     return false;
2841   case BO_Mul:
2842     St = LHS.multiply(RHS, RM);
2843     break;
2844   case BO_Add:
2845     St = LHS.add(RHS, RM);
2846     break;
2847   case BO_Sub:
2848     St = LHS.subtract(RHS, RM);
2849     break;
2850   case BO_Div:
2851     // [expr.mul]p4:
2852     //   If the second operand of / or % is zero the behavior is undefined.
2853     if (RHS.isZero())
2854       Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2855     St = LHS.divide(RHS, RM);
2856     break;
2857   }
2858 
2859   // [expr.pre]p4:
2860   //   If during the evaluation of an expression, the result is not
2861   //   mathematically defined [...], the behavior is undefined.
2862   // FIXME: C++ rules require us to not conform to IEEE 754 here.
2863   if (LHS.isNaN()) {
2864     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2865     return Info.noteUndefinedBehavior();
2866   }
2867 
2868   return checkFloatingPointResult(Info, E, St);
2869 }
2870 
2871 static bool handleLogicalOpForVector(const APInt &LHSValue,
2872                                      BinaryOperatorKind Opcode,
2873                                      const APInt &RHSValue, APInt &Result) {
2874   bool LHS = (LHSValue != 0);
2875   bool RHS = (RHSValue != 0);
2876 
2877   if (Opcode == BO_LAnd)
2878     Result = LHS && RHS;
2879   else
2880     Result = LHS || RHS;
2881   return true;
2882 }
2883 static bool handleLogicalOpForVector(const APFloat &LHSValue,
2884                                      BinaryOperatorKind Opcode,
2885                                      const APFloat &RHSValue, APInt &Result) {
2886   bool LHS = !LHSValue.isZero();
2887   bool RHS = !RHSValue.isZero();
2888 
2889   if (Opcode == BO_LAnd)
2890     Result = LHS && RHS;
2891   else
2892     Result = LHS || RHS;
2893   return true;
2894 }
2895 
2896 static bool handleLogicalOpForVector(const APValue &LHSValue,
2897                                      BinaryOperatorKind Opcode,
2898                                      const APValue &RHSValue, APInt &Result) {
2899   // The result is always an int type, however operands match the first.
2900   if (LHSValue.getKind() == APValue::Int)
2901     return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2902                                     RHSValue.getInt(), Result);
2903   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2904   return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2905                                   RHSValue.getFloat(), Result);
2906 }
2907 
2908 template <typename APTy>
2909 static bool
2910 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
2911                                const APTy &RHSValue, APInt &Result) {
2912   switch (Opcode) {
2913   default:
2914     llvm_unreachable("unsupported binary operator");
2915   case BO_EQ:
2916     Result = (LHSValue == RHSValue);
2917     break;
2918   case BO_NE:
2919     Result = (LHSValue != RHSValue);
2920     break;
2921   case BO_LT:
2922     Result = (LHSValue < RHSValue);
2923     break;
2924   case BO_GT:
2925     Result = (LHSValue > RHSValue);
2926     break;
2927   case BO_LE:
2928     Result = (LHSValue <= RHSValue);
2929     break;
2930   case BO_GE:
2931     Result = (LHSValue >= RHSValue);
2932     break;
2933   }
2934 
2935   // The boolean operations on these vector types use an instruction that
2936   // results in a mask of '-1' for the 'truth' value.  Ensure that we negate 1
2937   // to -1 to make sure that we produce the correct value.
2938   Result.negate();
2939 
2940   return true;
2941 }
2942 
2943 static bool handleCompareOpForVector(const APValue &LHSValue,
2944                                      BinaryOperatorKind Opcode,
2945                                      const APValue &RHSValue, APInt &Result) {
2946   // The result is always an int type, however operands match the first.
2947   if (LHSValue.getKind() == APValue::Int)
2948     return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
2949                                           RHSValue.getInt(), Result);
2950   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2951   return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
2952                                         RHSValue.getFloat(), Result);
2953 }
2954 
2955 // Perform binary operations for vector types, in place on the LHS.
2956 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
2957                                     BinaryOperatorKind Opcode,
2958                                     APValue &LHSValue,
2959                                     const APValue &RHSValue) {
2960   assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
2961          "Operation not supported on vector types");
2962 
2963   const auto *VT = E->getType()->castAs<VectorType>();
2964   unsigned NumElements = VT->getNumElements();
2965   QualType EltTy = VT->getElementType();
2966 
2967   // In the cases (typically C as I've observed) where we aren't evaluating
2968   // constexpr but are checking for cases where the LHS isn't yet evaluatable,
2969   // just give up.
2970   if (!LHSValue.isVector()) {
2971     assert(LHSValue.isLValue() &&
2972            "A vector result that isn't a vector OR uncalculated LValue");
2973     Info.FFDiag(E);
2974     return false;
2975   }
2976 
2977   assert(LHSValue.getVectorLength() == NumElements &&
2978          RHSValue.getVectorLength() == NumElements && "Different vector sizes");
2979 
2980   SmallVector<APValue, 4> ResultElements;
2981 
2982   for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
2983     APValue LHSElt = LHSValue.getVectorElt(EltNum);
2984     APValue RHSElt = RHSValue.getVectorElt(EltNum);
2985 
2986     if (EltTy->isIntegerType()) {
2987       APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
2988                        EltTy->isUnsignedIntegerType()};
2989       bool Success = true;
2990 
2991       if (BinaryOperator::isLogicalOp(Opcode))
2992         Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
2993       else if (BinaryOperator::isComparisonOp(Opcode))
2994         Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
2995       else
2996         Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
2997                                     RHSElt.getInt(), EltResult);
2998 
2999       if (!Success) {
3000         Info.FFDiag(E);
3001         return false;
3002       }
3003       ResultElements.emplace_back(EltResult);
3004 
3005     } else if (EltTy->isFloatingType()) {
3006       assert(LHSElt.getKind() == APValue::Float &&
3007              RHSElt.getKind() == APValue::Float &&
3008              "Mismatched LHS/RHS/Result Type");
3009       APFloat LHSFloat = LHSElt.getFloat();
3010 
3011       if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3012                                  RHSElt.getFloat())) {
3013         Info.FFDiag(E);
3014         return false;
3015       }
3016 
3017       ResultElements.emplace_back(LHSFloat);
3018     }
3019   }
3020 
3021   LHSValue = APValue(ResultElements.data(), ResultElements.size());
3022   return true;
3023 }
3024 
3025 /// Cast an lvalue referring to a base subobject to a derived class, by
3026 /// truncating the lvalue's path to the given length.
3027 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3028                                const RecordDecl *TruncatedType,
3029                                unsigned TruncatedElements) {
3030   SubobjectDesignator &D = Result.Designator;
3031 
3032   // Check we actually point to a derived class object.
3033   if (TruncatedElements == D.Entries.size())
3034     return true;
3035   assert(TruncatedElements >= D.MostDerivedPathLength &&
3036          "not casting to a derived class");
3037   if (!Result.checkSubobject(Info, E, CSK_Derived))
3038     return false;
3039 
3040   // Truncate the path to the subobject, and remove any derived-to-base offsets.
3041   const RecordDecl *RD = TruncatedType;
3042   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3043     if (RD->isInvalidDecl()) return false;
3044     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3045     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3046     if (isVirtualBaseClass(D.Entries[I]))
3047       Result.Offset -= Layout.getVBaseClassOffset(Base);
3048     else
3049       Result.Offset -= Layout.getBaseClassOffset(Base);
3050     RD = Base;
3051   }
3052   D.Entries.resize(TruncatedElements);
3053   return true;
3054 }
3055 
3056 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3057                                    const CXXRecordDecl *Derived,
3058                                    const CXXRecordDecl *Base,
3059                                    const ASTRecordLayout *RL = nullptr) {
3060   if (!RL) {
3061     if (Derived->isInvalidDecl()) return false;
3062     RL = &Info.Ctx.getASTRecordLayout(Derived);
3063   }
3064 
3065   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3066   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3067   return true;
3068 }
3069 
3070 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3071                              const CXXRecordDecl *DerivedDecl,
3072                              const CXXBaseSpecifier *Base) {
3073   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3074 
3075   if (!Base->isVirtual())
3076     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3077 
3078   SubobjectDesignator &D = Obj.Designator;
3079   if (D.Invalid)
3080     return false;
3081 
3082   // Extract most-derived object and corresponding type.
3083   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3084   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3085     return false;
3086 
3087   // Find the virtual base class.
3088   if (DerivedDecl->isInvalidDecl()) return false;
3089   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3090   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3091   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3092   return true;
3093 }
3094 
3095 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3096                                  QualType Type, LValue &Result) {
3097   for (CastExpr::path_const_iterator PathI = E->path_begin(),
3098                                      PathE = E->path_end();
3099        PathI != PathE; ++PathI) {
3100     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3101                           *PathI))
3102       return false;
3103     Type = (*PathI)->getType();
3104   }
3105   return true;
3106 }
3107 
3108 /// Cast an lvalue referring to a derived class to a known base subobject.
3109 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3110                             const CXXRecordDecl *DerivedRD,
3111                             const CXXRecordDecl *BaseRD) {
3112   CXXBasePaths Paths(/*FindAmbiguities=*/false,
3113                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
3114   if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3115     llvm_unreachable("Class must be derived from the passed in base class!");
3116 
3117   for (CXXBasePathElement &Elem : Paths.front())
3118     if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3119       return false;
3120   return true;
3121 }
3122 
3123 /// Update LVal to refer to the given field, which must be a member of the type
3124 /// currently described by LVal.
3125 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3126                                const FieldDecl *FD,
3127                                const ASTRecordLayout *RL = nullptr) {
3128   if (!RL) {
3129     if (FD->getParent()->isInvalidDecl()) return false;
3130     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3131   }
3132 
3133   unsigned I = FD->getFieldIndex();
3134   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3135   LVal.addDecl(Info, E, FD);
3136   return true;
3137 }
3138 
3139 /// Update LVal to refer to the given indirect field.
3140 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3141                                        LValue &LVal,
3142                                        const IndirectFieldDecl *IFD) {
3143   for (const auto *C : IFD->chain())
3144     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3145       return false;
3146   return true;
3147 }
3148 
3149 /// Get the size of the given type in char units.
3150 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
3151                          QualType Type, CharUnits &Size) {
3152   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3153   // extension.
3154   if (Type->isVoidType() || Type->isFunctionType()) {
3155     Size = CharUnits::One();
3156     return true;
3157   }
3158 
3159   if (Type->isDependentType()) {
3160     Info.FFDiag(Loc);
3161     return false;
3162   }
3163 
3164   if (!Type->isConstantSizeType()) {
3165     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3166     // FIXME: Better diagnostic.
3167     Info.FFDiag(Loc);
3168     return false;
3169   }
3170 
3171   Size = Info.Ctx.getTypeSizeInChars(Type);
3172   return true;
3173 }
3174 
3175 /// Update a pointer value to model pointer arithmetic.
3176 /// \param Info - Information about the ongoing evaluation.
3177 /// \param E - The expression being evaluated, for diagnostic purposes.
3178 /// \param LVal - The pointer value to be updated.
3179 /// \param EltTy - The pointee type represented by LVal.
3180 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3181 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3182                                         LValue &LVal, QualType EltTy,
3183                                         APSInt Adjustment) {
3184   CharUnits SizeOfPointee;
3185   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3186     return false;
3187 
3188   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3189   return true;
3190 }
3191 
3192 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3193                                         LValue &LVal, QualType EltTy,
3194                                         int64_t Adjustment) {
3195   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3196                                      APSInt::get(Adjustment));
3197 }
3198 
3199 /// Update an lvalue to refer to a component of a complex number.
3200 /// \param Info - Information about the ongoing evaluation.
3201 /// \param LVal - The lvalue to be updated.
3202 /// \param EltTy - The complex number's component type.
3203 /// \param Imag - False for the real component, true for the imaginary.
3204 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3205                                        LValue &LVal, QualType EltTy,
3206                                        bool Imag) {
3207   if (Imag) {
3208     CharUnits SizeOfComponent;
3209     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3210       return false;
3211     LVal.Offset += SizeOfComponent;
3212   }
3213   LVal.addComplex(Info, E, EltTy, Imag);
3214   return true;
3215 }
3216 
3217 /// Try to evaluate the initializer for a variable declaration.
3218 ///
3219 /// \param Info   Information about the ongoing evaluation.
3220 /// \param E      An expression to be used when printing diagnostics.
3221 /// \param VD     The variable whose initializer should be obtained.
3222 /// \param Version The version of the variable within the frame.
3223 /// \param Frame  The frame in which the variable was created. Must be null
3224 ///               if this variable is not local to the evaluation.
3225 /// \param Result Filled in with a pointer to the value of the variable.
3226 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3227                                 const VarDecl *VD, CallStackFrame *Frame,
3228                                 unsigned Version, APValue *&Result) {
3229   APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3230 
3231   // If this is a local variable, dig out its value.
3232   if (Frame) {
3233     Result = Frame->getTemporary(VD, Version);
3234     if (Result)
3235       return true;
3236 
3237     if (!isa<ParmVarDecl>(VD)) {
3238       // Assume variables referenced within a lambda's call operator that were
3239       // not declared within the call operator are captures and during checking
3240       // of a potential constant expression, assume they are unknown constant
3241       // expressions.
3242       assert(isLambdaCallOperator(Frame->Callee) &&
3243              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3244              "missing value for local variable");
3245       if (Info.checkingPotentialConstantExpression())
3246         return false;
3247       // FIXME: This diagnostic is bogus; we do support captures. Is this code
3248       // still reachable at all?
3249       Info.FFDiag(E->getBeginLoc(),
3250                   diag::note_unimplemented_constexpr_lambda_feature_ast)
3251           << "captures not currently allowed";
3252       return false;
3253     }
3254   }
3255 
3256   // If we're currently evaluating the initializer of this declaration, use that
3257   // in-flight value.
3258   if (Info.EvaluatingDecl == Base) {
3259     Result = Info.EvaluatingDeclValue;
3260     return true;
3261   }
3262 
3263   if (isa<ParmVarDecl>(VD)) {
3264     // Assume parameters of a potential constant expression are usable in
3265     // constant expressions.
3266     if (!Info.checkingPotentialConstantExpression() ||
3267         !Info.CurrentCall->Callee ||
3268         !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3269       if (Info.getLangOpts().CPlusPlus11) {
3270         Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3271             << VD;
3272         NoteLValueLocation(Info, Base);
3273       } else {
3274         Info.FFDiag(E);
3275       }
3276     }
3277     return false;
3278   }
3279 
3280   // Dig out the initializer, and use the declaration which it's attached to.
3281   // FIXME: We should eventually check whether the variable has a reachable
3282   // initializing declaration.
3283   const Expr *Init = VD->getAnyInitializer(VD);
3284   if (!Init) {
3285     // Don't diagnose during potential constant expression checking; an
3286     // initializer might be added later.
3287     if (!Info.checkingPotentialConstantExpression()) {
3288       Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3289         << VD;
3290       NoteLValueLocation(Info, Base);
3291     }
3292     return false;
3293   }
3294 
3295   if (Init->isValueDependent()) {
3296     // The DeclRefExpr is not value-dependent, but the variable it refers to
3297     // has a value-dependent initializer. This should only happen in
3298     // constant-folding cases, where the variable is not actually of a suitable
3299     // type for use in a constant expression (otherwise the DeclRefExpr would
3300     // have been value-dependent too), so diagnose that.
3301     assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3302     if (!Info.checkingPotentialConstantExpression()) {
3303       Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3304                          ? diag::note_constexpr_ltor_non_constexpr
3305                          : diag::note_constexpr_ltor_non_integral, 1)
3306           << VD << VD->getType();
3307       NoteLValueLocation(Info, Base);
3308     }
3309     return false;
3310   }
3311 
3312   // Check that we can fold the initializer. In C++, we will have already done
3313   // this in the cases where it matters for conformance.
3314   if (!VD->evaluateValue()) {
3315     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3316     NoteLValueLocation(Info, Base);
3317     return false;
3318   }
3319 
3320   // Check that the variable is actually usable in constant expressions. For a
3321   // const integral variable or a reference, we might have a non-constant
3322   // initializer that we can nonetheless evaluate the initializer for. Such
3323   // variables are not usable in constant expressions. In C++98, the
3324   // initializer also syntactically needs to be an ICE.
3325   //
3326   // FIXME: We don't diagnose cases that aren't potentially usable in constant
3327   // expressions here; doing so would regress diagnostics for things like
3328   // reading from a volatile constexpr variable.
3329   if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3330        VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||
3331       ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3332        !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3333     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3334     NoteLValueLocation(Info, Base);
3335   }
3336 
3337   // Never use the initializer of a weak variable, not even for constant
3338   // folding. We can't be sure that this is the definition that will be used.
3339   if (VD->isWeak()) {
3340     Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3341     NoteLValueLocation(Info, Base);
3342     return false;
3343   }
3344 
3345   Result = VD->getEvaluatedValue();
3346   return true;
3347 }
3348 
3349 /// Get the base index of the given base class within an APValue representing
3350 /// the given derived class.
3351 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3352                              const CXXRecordDecl *Base) {
3353   Base = Base->getCanonicalDecl();
3354   unsigned Index = 0;
3355   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3356          E = Derived->bases_end(); I != E; ++I, ++Index) {
3357     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3358       return Index;
3359   }
3360 
3361   llvm_unreachable("base class missing from derived class's bases list");
3362 }
3363 
3364 /// Extract the value of a character from a string literal.
3365 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3366                                             uint64_t Index) {
3367   assert(!isa<SourceLocExpr>(Lit) &&
3368          "SourceLocExpr should have already been converted to a StringLiteral");
3369 
3370   // FIXME: Support MakeStringConstant
3371   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3372     std::string Str;
3373     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3374     assert(Index <= Str.size() && "Index too large");
3375     return APSInt::getUnsigned(Str.c_str()[Index]);
3376   }
3377 
3378   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3379     Lit = PE->getFunctionName();
3380   const StringLiteral *S = cast<StringLiteral>(Lit);
3381   const ConstantArrayType *CAT =
3382       Info.Ctx.getAsConstantArrayType(S->getType());
3383   assert(CAT && "string literal isn't an array");
3384   QualType CharType = CAT->getElementType();
3385   assert(CharType->isIntegerType() && "unexpected character type");
3386 
3387   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3388                CharType->isUnsignedIntegerType());
3389   if (Index < S->getLength())
3390     Value = S->getCodeUnit(Index);
3391   return Value;
3392 }
3393 
3394 // Expand a string literal into an array of characters.
3395 //
3396 // FIXME: This is inefficient; we should probably introduce something similar
3397 // to the LLVM ConstantDataArray to make this cheaper.
3398 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3399                                 APValue &Result,
3400                                 QualType AllocType = QualType()) {
3401   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3402       AllocType.isNull() ? S->getType() : AllocType);
3403   assert(CAT && "string literal isn't an array");
3404   QualType CharType = CAT->getElementType();
3405   assert(CharType->isIntegerType() && "unexpected character type");
3406 
3407   unsigned Elts = CAT->getSize().getZExtValue();
3408   Result = APValue(APValue::UninitArray(),
3409                    std::min(S->getLength(), Elts), Elts);
3410   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3411                CharType->isUnsignedIntegerType());
3412   if (Result.hasArrayFiller())
3413     Result.getArrayFiller() = APValue(Value);
3414   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3415     Value = S->getCodeUnit(I);
3416     Result.getArrayInitializedElt(I) = APValue(Value);
3417   }
3418 }
3419 
3420 // Expand an array so that it has more than Index filled elements.
3421 static void expandArray(APValue &Array, unsigned Index) {
3422   unsigned Size = Array.getArraySize();
3423   assert(Index < Size);
3424 
3425   // Always at least double the number of elements for which we store a value.
3426   unsigned OldElts = Array.getArrayInitializedElts();
3427   unsigned NewElts = std::max(Index+1, OldElts * 2);
3428   NewElts = std::min(Size, std::max(NewElts, 8u));
3429 
3430   // Copy the data across.
3431   APValue NewValue(APValue::UninitArray(), NewElts, Size);
3432   for (unsigned I = 0; I != OldElts; ++I)
3433     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3434   for (unsigned I = OldElts; I != NewElts; ++I)
3435     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3436   if (NewValue.hasArrayFiller())
3437     NewValue.getArrayFiller() = Array.getArrayFiller();
3438   Array.swap(NewValue);
3439 }
3440 
3441 /// Determine whether a type would actually be read by an lvalue-to-rvalue
3442 /// conversion. If it's of class type, we may assume that the copy operation
3443 /// is trivial. Note that this is never true for a union type with fields
3444 /// (because the copy always "reads" the active member) and always true for
3445 /// a non-class type.
3446 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3447 static bool isReadByLvalueToRvalueConversion(QualType T) {
3448   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3449   return !RD || isReadByLvalueToRvalueConversion(RD);
3450 }
3451 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3452   // FIXME: A trivial copy of a union copies the object representation, even if
3453   // the union is empty.
3454   if (RD->isUnion())
3455     return !RD->field_empty();
3456   if (RD->isEmpty())
3457     return false;
3458 
3459   for (auto *Field : RD->fields())
3460     if (!Field->isUnnamedBitfield() &&
3461         isReadByLvalueToRvalueConversion(Field->getType()))
3462       return true;
3463 
3464   for (auto &BaseSpec : RD->bases())
3465     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3466       return true;
3467 
3468   return false;
3469 }
3470 
3471 /// Diagnose an attempt to read from any unreadable field within the specified
3472 /// type, which might be a class type.
3473 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3474                                   QualType T) {
3475   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3476   if (!RD)
3477     return false;
3478 
3479   if (!RD->hasMutableFields())
3480     return false;
3481 
3482   for (auto *Field : RD->fields()) {
3483     // If we're actually going to read this field in some way, then it can't
3484     // be mutable. If we're in a union, then assigning to a mutable field
3485     // (even an empty one) can change the active member, so that's not OK.
3486     // FIXME: Add core issue number for the union case.
3487     if (Field->isMutable() &&
3488         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3489       Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3490       Info.Note(Field->getLocation(), diag::note_declared_at);
3491       return true;
3492     }
3493 
3494     if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3495       return true;
3496   }
3497 
3498   for (auto &BaseSpec : RD->bases())
3499     if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3500       return true;
3501 
3502   // All mutable fields were empty, and thus not actually read.
3503   return false;
3504 }
3505 
3506 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3507                                         APValue::LValueBase Base,
3508                                         bool MutableSubobject = false) {
3509   // A temporary or transient heap allocation we created.
3510   if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3511     return true;
3512 
3513   switch (Info.IsEvaluatingDecl) {
3514   case EvalInfo::EvaluatingDeclKind::None:
3515     return false;
3516 
3517   case EvalInfo::EvaluatingDeclKind::Ctor:
3518     // The variable whose initializer we're evaluating.
3519     if (Info.EvaluatingDecl == Base)
3520       return true;
3521 
3522     // A temporary lifetime-extended by the variable whose initializer we're
3523     // evaluating.
3524     if (auto *BaseE = Base.dyn_cast<const Expr *>())
3525       if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3526         return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3527     return false;
3528 
3529   case EvalInfo::EvaluatingDeclKind::Dtor:
3530     // C++2a [expr.const]p6:
3531     //   [during constant destruction] the lifetime of a and its non-mutable
3532     //   subobjects (but not its mutable subobjects) [are] considered to start
3533     //   within e.
3534     if (MutableSubobject || Base != Info.EvaluatingDecl)
3535       return false;
3536     // FIXME: We can meaningfully extend this to cover non-const objects, but
3537     // we will need special handling: we should be able to access only
3538     // subobjects of such objects that are themselves declared const.
3539     QualType T = getType(Base);
3540     return T.isConstQualified() || T->isReferenceType();
3541   }
3542 
3543   llvm_unreachable("unknown evaluating decl kind");
3544 }
3545 
3546 namespace {
3547 /// A handle to a complete object (an object that is not a subobject of
3548 /// another object).
3549 struct CompleteObject {
3550   /// The identity of the object.
3551   APValue::LValueBase Base;
3552   /// The value of the complete object.
3553   APValue *Value;
3554   /// The type of the complete object.
3555   QualType Type;
3556 
3557   CompleteObject() : Value(nullptr) {}
3558   CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3559       : Base(Base), Value(Value), Type(Type) {}
3560 
3561   bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3562     // If this isn't a "real" access (eg, if it's just accessing the type
3563     // info), allow it. We assume the type doesn't change dynamically for
3564     // subobjects of constexpr objects (even though we'd hit UB here if it
3565     // did). FIXME: Is this right?
3566     if (!isAnyAccess(AK))
3567       return true;
3568 
3569     // In C++14 onwards, it is permitted to read a mutable member whose
3570     // lifetime began within the evaluation.
3571     // FIXME: Should we also allow this in C++11?
3572     if (!Info.getLangOpts().CPlusPlus14)
3573       return false;
3574     return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3575   }
3576 
3577   explicit operator bool() const { return !Type.isNull(); }
3578 };
3579 } // end anonymous namespace
3580 
3581 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3582                                  bool IsMutable = false) {
3583   // C++ [basic.type.qualifier]p1:
3584   // - A const object is an object of type const T or a non-mutable subobject
3585   //   of a const object.
3586   if (ObjType.isConstQualified() && !IsMutable)
3587     SubobjType.addConst();
3588   // - A volatile object is an object of type const T or a subobject of a
3589   //   volatile object.
3590   if (ObjType.isVolatileQualified())
3591     SubobjType.addVolatile();
3592   return SubobjType;
3593 }
3594 
3595 /// Find the designated sub-object of an rvalue.
3596 template<typename SubobjectHandler>
3597 typename SubobjectHandler::result_type
3598 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3599               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3600   if (Sub.Invalid)
3601     // A diagnostic will have already been produced.
3602     return handler.failed();
3603   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3604     if (Info.getLangOpts().CPlusPlus11)
3605       Info.FFDiag(E, Sub.isOnePastTheEnd()
3606                          ? diag::note_constexpr_access_past_end
3607                          : diag::note_constexpr_access_unsized_array)
3608           << handler.AccessKind;
3609     else
3610       Info.FFDiag(E);
3611     return handler.failed();
3612   }
3613 
3614   APValue *O = Obj.Value;
3615   QualType ObjType = Obj.Type;
3616   const FieldDecl *LastField = nullptr;
3617   const FieldDecl *VolatileField = nullptr;
3618 
3619   // Walk the designator's path to find the subobject.
3620   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3621     // Reading an indeterminate value is undefined, but assigning over one is OK.
3622     if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3623         (O->isIndeterminate() &&
3624          !isValidIndeterminateAccess(handler.AccessKind))) {
3625       if (!Info.checkingPotentialConstantExpression())
3626         Info.FFDiag(E, diag::note_constexpr_access_uninit)
3627             << handler.AccessKind << O->isIndeterminate();
3628       return handler.failed();
3629     }
3630 
3631     // C++ [class.ctor]p5, C++ [class.dtor]p5:
3632     //    const and volatile semantics are not applied on an object under
3633     //    {con,de}struction.
3634     if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3635         ObjType->isRecordType() &&
3636         Info.isEvaluatingCtorDtor(
3637             Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3638                                          Sub.Entries.begin() + I)) !=
3639                           ConstructionPhase::None) {
3640       ObjType = Info.Ctx.getCanonicalType(ObjType);
3641       ObjType.removeLocalConst();
3642       ObjType.removeLocalVolatile();
3643     }
3644 
3645     // If this is our last pass, check that the final object type is OK.
3646     if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3647       // Accesses to volatile objects are prohibited.
3648       if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3649         if (Info.getLangOpts().CPlusPlus) {
3650           int DiagKind;
3651           SourceLocation Loc;
3652           const NamedDecl *Decl = nullptr;
3653           if (VolatileField) {
3654             DiagKind = 2;
3655             Loc = VolatileField->getLocation();
3656             Decl = VolatileField;
3657           } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3658             DiagKind = 1;
3659             Loc = VD->getLocation();
3660             Decl = VD;
3661           } else {
3662             DiagKind = 0;
3663             if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3664               Loc = E->getExprLoc();
3665           }
3666           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3667               << handler.AccessKind << DiagKind << Decl;
3668           Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3669         } else {
3670           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3671         }
3672         return handler.failed();
3673       }
3674 
3675       // If we are reading an object of class type, there may still be more
3676       // things we need to check: if there are any mutable subobjects, we
3677       // cannot perform this read. (This only happens when performing a trivial
3678       // copy or assignment.)
3679       if (ObjType->isRecordType() &&
3680           !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3681           diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3682         return handler.failed();
3683     }
3684 
3685     if (I == N) {
3686       if (!handler.found(*O, ObjType))
3687         return false;
3688 
3689       // If we modified a bit-field, truncate it to the right width.
3690       if (isModification(handler.AccessKind) &&
3691           LastField && LastField->isBitField() &&
3692           !truncateBitfieldValue(Info, E, *O, LastField))
3693         return false;
3694 
3695       return true;
3696     }
3697 
3698     LastField = nullptr;
3699     if (ObjType->isArrayType()) {
3700       // Next subobject is an array element.
3701       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3702       assert(CAT && "vla in literal type?");
3703       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3704       if (CAT->getSize().ule(Index)) {
3705         // Note, it should not be possible to form a pointer with a valid
3706         // designator which points more than one past the end of the array.
3707         if (Info.getLangOpts().CPlusPlus11)
3708           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3709             << handler.AccessKind;
3710         else
3711           Info.FFDiag(E);
3712         return handler.failed();
3713       }
3714 
3715       ObjType = CAT->getElementType();
3716 
3717       if (O->getArrayInitializedElts() > Index)
3718         O = &O->getArrayInitializedElt(Index);
3719       else if (!isRead(handler.AccessKind)) {
3720         expandArray(*O, Index);
3721         O = &O->getArrayInitializedElt(Index);
3722       } else
3723         O = &O->getArrayFiller();
3724     } else if (ObjType->isAnyComplexType()) {
3725       // Next subobject is a complex number.
3726       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3727       if (Index > 1) {
3728         if (Info.getLangOpts().CPlusPlus11)
3729           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3730             << handler.AccessKind;
3731         else
3732           Info.FFDiag(E);
3733         return handler.failed();
3734       }
3735 
3736       ObjType = getSubobjectType(
3737           ObjType, ObjType->castAs<ComplexType>()->getElementType());
3738 
3739       assert(I == N - 1 && "extracting subobject of scalar?");
3740       if (O->isComplexInt()) {
3741         return handler.found(Index ? O->getComplexIntImag()
3742                                    : O->getComplexIntReal(), ObjType);
3743       } else {
3744         assert(O->isComplexFloat());
3745         return handler.found(Index ? O->getComplexFloatImag()
3746                                    : O->getComplexFloatReal(), ObjType);
3747       }
3748     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3749       if (Field->isMutable() &&
3750           !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3751         Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3752           << handler.AccessKind << Field;
3753         Info.Note(Field->getLocation(), diag::note_declared_at);
3754         return handler.failed();
3755       }
3756 
3757       // Next subobject is a class, struct or union field.
3758       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3759       if (RD->isUnion()) {
3760         const FieldDecl *UnionField = O->getUnionField();
3761         if (!UnionField ||
3762             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3763           if (I == N - 1 && handler.AccessKind == AK_Construct) {
3764             // Placement new onto an inactive union member makes it active.
3765             O->setUnion(Field, APValue());
3766           } else {
3767             // FIXME: If O->getUnionValue() is absent, report that there's no
3768             // active union member rather than reporting the prior active union
3769             // member. We'll need to fix nullptr_t to not use APValue() as its
3770             // representation first.
3771             Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3772                 << handler.AccessKind << Field << !UnionField << UnionField;
3773             return handler.failed();
3774           }
3775         }
3776         O = &O->getUnionValue();
3777       } else
3778         O = &O->getStructField(Field->getFieldIndex());
3779 
3780       ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3781       LastField = Field;
3782       if (Field->getType().isVolatileQualified())
3783         VolatileField = Field;
3784     } else {
3785       // Next subobject is a base class.
3786       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3787       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3788       O = &O->getStructBase(getBaseIndex(Derived, Base));
3789 
3790       ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3791     }
3792   }
3793 }
3794 
3795 namespace {
3796 struct ExtractSubobjectHandler {
3797   EvalInfo &Info;
3798   const Expr *E;
3799   APValue &Result;
3800   const AccessKinds AccessKind;
3801 
3802   typedef bool result_type;
3803   bool failed() { return false; }
3804   bool found(APValue &Subobj, QualType SubobjType) {
3805     Result = Subobj;
3806     if (AccessKind == AK_ReadObjectRepresentation)
3807       return true;
3808     return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3809   }
3810   bool found(APSInt &Value, QualType SubobjType) {
3811     Result = APValue(Value);
3812     return true;
3813   }
3814   bool found(APFloat &Value, QualType SubobjType) {
3815     Result = APValue(Value);
3816     return true;
3817   }
3818 };
3819 } // end anonymous namespace
3820 
3821 /// Extract the designated sub-object of an rvalue.
3822 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3823                              const CompleteObject &Obj,
3824                              const SubobjectDesignator &Sub, APValue &Result,
3825                              AccessKinds AK = AK_Read) {
3826   assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3827   ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3828   return findSubobject(Info, E, Obj, Sub, Handler);
3829 }
3830 
3831 namespace {
3832 struct ModifySubobjectHandler {
3833   EvalInfo &Info;
3834   APValue &NewVal;
3835   const Expr *E;
3836 
3837   typedef bool result_type;
3838   static const AccessKinds AccessKind = AK_Assign;
3839 
3840   bool checkConst(QualType QT) {
3841     // Assigning to a const object has undefined behavior.
3842     if (QT.isConstQualified()) {
3843       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3844       return false;
3845     }
3846     return true;
3847   }
3848 
3849   bool failed() { return false; }
3850   bool found(APValue &Subobj, QualType SubobjType) {
3851     if (!checkConst(SubobjType))
3852       return false;
3853     // We've been given ownership of NewVal, so just swap it in.
3854     Subobj.swap(NewVal);
3855     return true;
3856   }
3857   bool found(APSInt &Value, QualType SubobjType) {
3858     if (!checkConst(SubobjType))
3859       return false;
3860     if (!NewVal.isInt()) {
3861       // Maybe trying to write a cast pointer value into a complex?
3862       Info.FFDiag(E);
3863       return false;
3864     }
3865     Value = NewVal.getInt();
3866     return true;
3867   }
3868   bool found(APFloat &Value, QualType SubobjType) {
3869     if (!checkConst(SubobjType))
3870       return false;
3871     Value = NewVal.getFloat();
3872     return true;
3873   }
3874 };
3875 } // end anonymous namespace
3876 
3877 const AccessKinds ModifySubobjectHandler::AccessKind;
3878 
3879 /// Update the designated sub-object of an rvalue to the given value.
3880 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3881                             const CompleteObject &Obj,
3882                             const SubobjectDesignator &Sub,
3883                             APValue &NewVal) {
3884   ModifySubobjectHandler Handler = { Info, NewVal, E };
3885   return findSubobject(Info, E, Obj, Sub, Handler);
3886 }
3887 
3888 /// Find the position where two subobject designators diverge, or equivalently
3889 /// the length of the common initial subsequence.
3890 static unsigned FindDesignatorMismatch(QualType ObjType,
3891                                        const SubobjectDesignator &A,
3892                                        const SubobjectDesignator &B,
3893                                        bool &WasArrayIndex) {
3894   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3895   for (/**/; I != N; ++I) {
3896     if (!ObjType.isNull() &&
3897         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3898       // Next subobject is an array element.
3899       if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3900         WasArrayIndex = true;
3901         return I;
3902       }
3903       if (ObjType->isAnyComplexType())
3904         ObjType = ObjType->castAs<ComplexType>()->getElementType();
3905       else
3906         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3907     } else {
3908       if (A.Entries[I].getAsBaseOrMember() !=
3909           B.Entries[I].getAsBaseOrMember()) {
3910         WasArrayIndex = false;
3911         return I;
3912       }
3913       if (const FieldDecl *FD = getAsField(A.Entries[I]))
3914         // Next subobject is a field.
3915         ObjType = FD->getType();
3916       else
3917         // Next subobject is a base class.
3918         ObjType = QualType();
3919     }
3920   }
3921   WasArrayIndex = false;
3922   return I;
3923 }
3924 
3925 /// Determine whether the given subobject designators refer to elements of the
3926 /// same array object.
3927 static bool AreElementsOfSameArray(QualType ObjType,
3928                                    const SubobjectDesignator &A,
3929                                    const SubobjectDesignator &B) {
3930   if (A.Entries.size() != B.Entries.size())
3931     return false;
3932 
3933   bool IsArray = A.MostDerivedIsArrayElement;
3934   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3935     // A is a subobject of the array element.
3936     return false;
3937 
3938   // If A (and B) designates an array element, the last entry will be the array
3939   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3940   // of length 1' case, and the entire path must match.
3941   bool WasArrayIndex;
3942   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3943   return CommonLength >= A.Entries.size() - IsArray;
3944 }
3945 
3946 /// Find the complete object to which an LValue refers.
3947 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3948                                          AccessKinds AK, const LValue &LVal,
3949                                          QualType LValType) {
3950   if (LVal.InvalidBase) {
3951     Info.FFDiag(E);
3952     return CompleteObject();
3953   }
3954 
3955   if (!LVal.Base) {
3956     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3957     return CompleteObject();
3958   }
3959 
3960   CallStackFrame *Frame = nullptr;
3961   unsigned Depth = 0;
3962   if (LVal.getLValueCallIndex()) {
3963     std::tie(Frame, Depth) =
3964         Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3965     if (!Frame) {
3966       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3967         << AK << LVal.Base.is<const ValueDecl*>();
3968       NoteLValueLocation(Info, LVal.Base);
3969       return CompleteObject();
3970     }
3971   }
3972 
3973   bool IsAccess = isAnyAccess(AK);
3974 
3975   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3976   // is not a constant expression (even if the object is non-volatile). We also
3977   // apply this rule to C++98, in order to conform to the expected 'volatile'
3978   // semantics.
3979   if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
3980     if (Info.getLangOpts().CPlusPlus)
3981       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3982         << AK << LValType;
3983     else
3984       Info.FFDiag(E);
3985     return CompleteObject();
3986   }
3987 
3988   // Compute value storage location and type of base object.
3989   APValue *BaseVal = nullptr;
3990   QualType BaseType = getType(LVal.Base);
3991 
3992   if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
3993       lifetimeStartedInEvaluation(Info, LVal.Base)) {
3994     // This is the object whose initializer we're evaluating, so its lifetime
3995     // started in the current evaluation.
3996     BaseVal = Info.EvaluatingDeclValue;
3997   } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
3998     // Allow reading from a GUID declaration.
3999     if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4000       if (isModification(AK)) {
4001         // All the remaining cases do not permit modification of the object.
4002         Info.FFDiag(E, diag::note_constexpr_modify_global);
4003         return CompleteObject();
4004       }
4005       APValue &V = GD->getAsAPValue();
4006       if (V.isAbsent()) {
4007         Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4008             << GD->getType();
4009         return CompleteObject();
4010       }
4011       return CompleteObject(LVal.Base, &V, GD->getType());
4012     }
4013 
4014     // Allow reading from template parameter objects.
4015     if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4016       if (isModification(AK)) {
4017         Info.FFDiag(E, diag::note_constexpr_modify_global);
4018         return CompleteObject();
4019       }
4020       return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4021                             TPO->getType());
4022     }
4023 
4024     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4025     // In C++11, constexpr, non-volatile variables initialized with constant
4026     // expressions are constant expressions too. Inside constexpr functions,
4027     // parameters are constant expressions even if they're non-const.
4028     // In C++1y, objects local to a constant expression (those with a Frame) are
4029     // both readable and writable inside constant expressions.
4030     // In C, such things can also be folded, although they are not ICEs.
4031     const VarDecl *VD = dyn_cast<VarDecl>(D);
4032     if (VD) {
4033       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4034         VD = VDef;
4035     }
4036     if (!VD || VD->isInvalidDecl()) {
4037       Info.FFDiag(E);
4038       return CompleteObject();
4039     }
4040 
4041     bool IsConstant = BaseType.isConstant(Info.Ctx);
4042 
4043     // Unless we're looking at a local variable or argument in a constexpr call,
4044     // the variable we're reading must be const.
4045     if (!Frame) {
4046       if (IsAccess && isa<ParmVarDecl>(VD)) {
4047         // Access of a parameter that's not associated with a frame isn't going
4048         // to work out, but we can leave it to evaluateVarDeclInit to provide a
4049         // suitable diagnostic.
4050       } else if (Info.getLangOpts().CPlusPlus14 &&
4051                  lifetimeStartedInEvaluation(Info, LVal.Base)) {
4052         // OK, we can read and modify an object if we're in the process of
4053         // evaluating its initializer, because its lifetime began in this
4054         // evaluation.
4055       } else if (isModification(AK)) {
4056         // All the remaining cases do not permit modification of the object.
4057         Info.FFDiag(E, diag::note_constexpr_modify_global);
4058         return CompleteObject();
4059       } else if (VD->isConstexpr()) {
4060         // OK, we can read this variable.
4061       } else if (BaseType->isIntegralOrEnumerationType()) {
4062         if (!IsConstant) {
4063           if (!IsAccess)
4064             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4065           if (Info.getLangOpts().CPlusPlus) {
4066             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4067             Info.Note(VD->getLocation(), diag::note_declared_at);
4068           } else {
4069             Info.FFDiag(E);
4070           }
4071           return CompleteObject();
4072         }
4073       } else if (!IsAccess) {
4074         return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4075       } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
4076                  BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4077         // This variable might end up being constexpr. Don't diagnose it yet.
4078       } else if (IsConstant) {
4079         // Keep evaluating to see what we can do. In particular, we support
4080         // folding of const floating-point types, in order to make static const
4081         // data members of such types (supported as an extension) more useful.
4082         if (Info.getLangOpts().CPlusPlus) {
4083           Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4084                               ? diag::note_constexpr_ltor_non_constexpr
4085                               : diag::note_constexpr_ltor_non_integral, 1)
4086               << VD << BaseType;
4087           Info.Note(VD->getLocation(), diag::note_declared_at);
4088         } else {
4089           Info.CCEDiag(E);
4090         }
4091       } else {
4092         // Never allow reading a non-const value.
4093         if (Info.getLangOpts().CPlusPlus) {
4094           Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4095                              ? diag::note_constexpr_ltor_non_constexpr
4096                              : diag::note_constexpr_ltor_non_integral, 1)
4097               << VD << BaseType;
4098           Info.Note(VD->getLocation(), diag::note_declared_at);
4099         } else {
4100           Info.FFDiag(E);
4101         }
4102         return CompleteObject();
4103       }
4104     }
4105 
4106     if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
4107       return CompleteObject();
4108   } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4109     Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
4110     if (!Alloc) {
4111       Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4112       return CompleteObject();
4113     }
4114     return CompleteObject(LVal.Base, &(*Alloc)->Value,
4115                           LVal.Base.getDynamicAllocType());
4116   } else {
4117     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4118 
4119     if (!Frame) {
4120       if (const MaterializeTemporaryExpr *MTE =
4121               dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4122         assert(MTE->getStorageDuration() == SD_Static &&
4123                "should have a frame for a non-global materialized temporary");
4124 
4125         // C++20 [expr.const]p4: [DR2126]
4126         //   An object or reference is usable in constant expressions if it is
4127         //   - a temporary object of non-volatile const-qualified literal type
4128         //     whose lifetime is extended to that of a variable that is usable
4129         //     in constant expressions
4130         //
4131         // C++20 [expr.const]p5:
4132         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4133         //   - a non-volatile glvalue that refers to an object that is usable
4134         //     in constant expressions, or
4135         //   - a non-volatile glvalue of literal type that refers to a
4136         //     non-volatile object whose lifetime began within the evaluation
4137         //     of E;
4138         //
4139         // C++11 misses the 'began within the evaluation of e' check and
4140         // instead allows all temporaries, including things like:
4141         //   int &&r = 1;
4142         //   int x = ++r;
4143         //   constexpr int k = r;
4144         // Therefore we use the C++14-onwards rules in C++11 too.
4145         //
4146         // Note that temporaries whose lifetimes began while evaluating a
4147         // variable's constructor are not usable while evaluating the
4148         // corresponding destructor, not even if they're of const-qualified
4149         // types.
4150         if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4151             !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4152           if (!IsAccess)
4153             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4154           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4155           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4156           return CompleteObject();
4157         }
4158 
4159         BaseVal = MTE->getOrCreateValue(false);
4160         assert(BaseVal && "got reference to unevaluated temporary");
4161       } else {
4162         if (!IsAccess)
4163           return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4164         APValue Val;
4165         LVal.moveInto(Val);
4166         Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4167             << AK
4168             << Val.getAsString(Info.Ctx,
4169                                Info.Ctx.getLValueReferenceType(LValType));
4170         NoteLValueLocation(Info, LVal.Base);
4171         return CompleteObject();
4172       }
4173     } else {
4174       BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4175       assert(BaseVal && "missing value for temporary");
4176     }
4177   }
4178 
4179   // In C++14, we can't safely access any mutable state when we might be
4180   // evaluating after an unmodeled side effect. Parameters are modeled as state
4181   // in the caller, but aren't visible once the call returns, so they can be
4182   // modified in a speculatively-evaluated call.
4183   //
4184   // FIXME: Not all local state is mutable. Allow local constant subobjects
4185   // to be read here (but take care with 'mutable' fields).
4186   unsigned VisibleDepth = Depth;
4187   if (llvm::isa_and_nonnull<ParmVarDecl>(
4188           LVal.Base.dyn_cast<const ValueDecl *>()))
4189     ++VisibleDepth;
4190   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4191        Info.EvalStatus.HasSideEffects) ||
4192       (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4193     return CompleteObject();
4194 
4195   return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4196 }
4197 
4198 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4199 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4200 /// glvalue referred to by an entity of reference type.
4201 ///
4202 /// \param Info - Information about the ongoing evaluation.
4203 /// \param Conv - The expression for which we are performing the conversion.
4204 ///               Used for diagnostics.
4205 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4206 ///               case of a non-class type).
4207 /// \param LVal - The glvalue on which we are attempting to perform this action.
4208 /// \param RVal - The produced value will be placed here.
4209 /// \param WantObjectRepresentation - If true, we're looking for the object
4210 ///               representation rather than the value, and in particular,
4211 ///               there is no requirement that the result be fully initialized.
4212 static bool
4213 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
4214                                const LValue &LVal, APValue &RVal,
4215                                bool WantObjectRepresentation = false) {
4216   if (LVal.Designator.Invalid)
4217     return false;
4218 
4219   // Check for special cases where there is no existing APValue to look at.
4220   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4221 
4222   AccessKinds AK =
4223       WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4224 
4225   if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4226     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4227       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4228       // initializer until now for such expressions. Such an expression can't be
4229       // an ICE in C, so this only matters for fold.
4230       if (Type.isVolatileQualified()) {
4231         Info.FFDiag(Conv);
4232         return false;
4233       }
4234       APValue Lit;
4235       if (!Evaluate(Lit, Info, CLE->getInitializer()))
4236         return false;
4237       CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4238       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4239     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4240       // Special-case character extraction so we don't have to construct an
4241       // APValue for the whole string.
4242       assert(LVal.Designator.Entries.size() <= 1 &&
4243              "Can only read characters from string literals");
4244       if (LVal.Designator.Entries.empty()) {
4245         // Fail for now for LValue to RValue conversion of an array.
4246         // (This shouldn't show up in C/C++, but it could be triggered by a
4247         // weird EvaluateAsRValue call from a tool.)
4248         Info.FFDiag(Conv);
4249         return false;
4250       }
4251       if (LVal.Designator.isOnePastTheEnd()) {
4252         if (Info.getLangOpts().CPlusPlus11)
4253           Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4254         else
4255           Info.FFDiag(Conv);
4256         return false;
4257       }
4258       uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4259       RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4260       return true;
4261     }
4262   }
4263 
4264   CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4265   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4266 }
4267 
4268 /// Perform an assignment of Val to LVal. Takes ownership of Val.
4269 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4270                              QualType LValType, APValue &Val) {
4271   if (LVal.Designator.Invalid)
4272     return false;
4273 
4274   if (!Info.getLangOpts().CPlusPlus14) {
4275     Info.FFDiag(E);
4276     return false;
4277   }
4278 
4279   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4280   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4281 }
4282 
4283 namespace {
4284 struct CompoundAssignSubobjectHandler {
4285   EvalInfo &Info;
4286   const CompoundAssignOperator *E;
4287   QualType PromotedLHSType;
4288   BinaryOperatorKind Opcode;
4289   const APValue &RHS;
4290 
4291   static const AccessKinds AccessKind = AK_Assign;
4292 
4293   typedef bool result_type;
4294 
4295   bool checkConst(QualType QT) {
4296     // Assigning to a const object has undefined behavior.
4297     if (QT.isConstQualified()) {
4298       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4299       return false;
4300     }
4301     return true;
4302   }
4303 
4304   bool failed() { return false; }
4305   bool found(APValue &Subobj, QualType SubobjType) {
4306     switch (Subobj.getKind()) {
4307     case APValue::Int:
4308       return found(Subobj.getInt(), SubobjType);
4309     case APValue::Float:
4310       return found(Subobj.getFloat(), SubobjType);
4311     case APValue::ComplexInt:
4312     case APValue::ComplexFloat:
4313       // FIXME: Implement complex compound assignment.
4314       Info.FFDiag(E);
4315       return false;
4316     case APValue::LValue:
4317       return foundPointer(Subobj, SubobjType);
4318     case APValue::Vector:
4319       return foundVector(Subobj, SubobjType);
4320     default:
4321       // FIXME: can this happen?
4322       Info.FFDiag(E);
4323       return false;
4324     }
4325   }
4326 
4327   bool foundVector(APValue &Value, QualType SubobjType) {
4328     if (!checkConst(SubobjType))
4329       return false;
4330 
4331     if (!SubobjType->isVectorType()) {
4332       Info.FFDiag(E);
4333       return false;
4334     }
4335     return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4336   }
4337 
4338   bool found(APSInt &Value, QualType SubobjType) {
4339     if (!checkConst(SubobjType))
4340       return false;
4341 
4342     if (!SubobjType->isIntegerType()) {
4343       // We don't support compound assignment on integer-cast-to-pointer
4344       // values.
4345       Info.FFDiag(E);
4346       return false;
4347     }
4348 
4349     if (RHS.isInt()) {
4350       APSInt LHS =
4351           HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4352       if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4353         return false;
4354       Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4355       return true;
4356     } else if (RHS.isFloat()) {
4357       const FPOptions FPO = E->getFPFeaturesInEffect(
4358                                     Info.Ctx.getLangOpts());
4359       APFloat FValue(0.0);
4360       return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4361                                   PromotedLHSType, FValue) &&
4362              handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4363              HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4364                                   Value);
4365     }
4366 
4367     Info.FFDiag(E);
4368     return false;
4369   }
4370   bool found(APFloat &Value, QualType SubobjType) {
4371     return checkConst(SubobjType) &&
4372            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4373                                   Value) &&
4374            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4375            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4376   }
4377   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4378     if (!checkConst(SubobjType))
4379       return false;
4380 
4381     QualType PointeeType;
4382     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4383       PointeeType = PT->getPointeeType();
4384 
4385     if (PointeeType.isNull() || !RHS.isInt() ||
4386         (Opcode != BO_Add && Opcode != BO_Sub)) {
4387       Info.FFDiag(E);
4388       return false;
4389     }
4390 
4391     APSInt Offset = RHS.getInt();
4392     if (Opcode == BO_Sub)
4393       negateAsSigned(Offset);
4394 
4395     LValue LVal;
4396     LVal.setFrom(Info.Ctx, Subobj);
4397     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4398       return false;
4399     LVal.moveInto(Subobj);
4400     return true;
4401   }
4402 };
4403 } // end anonymous namespace
4404 
4405 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4406 
4407 /// Perform a compound assignment of LVal <op>= RVal.
4408 static bool handleCompoundAssignment(EvalInfo &Info,
4409                                      const CompoundAssignOperator *E,
4410                                      const LValue &LVal, QualType LValType,
4411                                      QualType PromotedLValType,
4412                                      BinaryOperatorKind Opcode,
4413                                      const APValue &RVal) {
4414   if (LVal.Designator.Invalid)
4415     return false;
4416 
4417   if (!Info.getLangOpts().CPlusPlus14) {
4418     Info.FFDiag(E);
4419     return false;
4420   }
4421 
4422   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4423   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4424                                              RVal };
4425   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4426 }
4427 
4428 namespace {
4429 struct IncDecSubobjectHandler {
4430   EvalInfo &Info;
4431   const UnaryOperator *E;
4432   AccessKinds AccessKind;
4433   APValue *Old;
4434 
4435   typedef bool result_type;
4436 
4437   bool checkConst(QualType QT) {
4438     // Assigning to a const object has undefined behavior.
4439     if (QT.isConstQualified()) {
4440       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4441       return false;
4442     }
4443     return true;
4444   }
4445 
4446   bool failed() { return false; }
4447   bool found(APValue &Subobj, QualType SubobjType) {
4448     // Stash the old value. Also clear Old, so we don't clobber it later
4449     // if we're post-incrementing a complex.
4450     if (Old) {
4451       *Old = Subobj;
4452       Old = nullptr;
4453     }
4454 
4455     switch (Subobj.getKind()) {
4456     case APValue::Int:
4457       return found(Subobj.getInt(), SubobjType);
4458     case APValue::Float:
4459       return found(Subobj.getFloat(), SubobjType);
4460     case APValue::ComplexInt:
4461       return found(Subobj.getComplexIntReal(),
4462                    SubobjType->castAs<ComplexType>()->getElementType()
4463                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4464     case APValue::ComplexFloat:
4465       return found(Subobj.getComplexFloatReal(),
4466                    SubobjType->castAs<ComplexType>()->getElementType()
4467                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4468     case APValue::LValue:
4469       return foundPointer(Subobj, SubobjType);
4470     default:
4471       // FIXME: can this happen?
4472       Info.FFDiag(E);
4473       return false;
4474     }
4475   }
4476   bool found(APSInt &Value, QualType SubobjType) {
4477     if (!checkConst(SubobjType))
4478       return false;
4479 
4480     if (!SubobjType->isIntegerType()) {
4481       // We don't support increment / decrement on integer-cast-to-pointer
4482       // values.
4483       Info.FFDiag(E);
4484       return false;
4485     }
4486 
4487     if (Old) *Old = APValue(Value);
4488 
4489     // bool arithmetic promotes to int, and the conversion back to bool
4490     // doesn't reduce mod 2^n, so special-case it.
4491     if (SubobjType->isBooleanType()) {
4492       if (AccessKind == AK_Increment)
4493         Value = 1;
4494       else
4495         Value = !Value;
4496       return true;
4497     }
4498 
4499     bool WasNegative = Value.isNegative();
4500     if (AccessKind == AK_Increment) {
4501       ++Value;
4502 
4503       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4504         APSInt ActualValue(Value, /*IsUnsigned*/true);
4505         return HandleOverflow(Info, E, ActualValue, SubobjType);
4506       }
4507     } else {
4508       --Value;
4509 
4510       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4511         unsigned BitWidth = Value.getBitWidth();
4512         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4513         ActualValue.setBit(BitWidth);
4514         return HandleOverflow(Info, E, ActualValue, SubobjType);
4515       }
4516     }
4517     return true;
4518   }
4519   bool found(APFloat &Value, QualType SubobjType) {
4520     if (!checkConst(SubobjType))
4521       return false;
4522 
4523     if (Old) *Old = APValue(Value);
4524 
4525     APFloat One(Value.getSemantics(), 1);
4526     if (AccessKind == AK_Increment)
4527       Value.add(One, APFloat::rmNearestTiesToEven);
4528     else
4529       Value.subtract(One, APFloat::rmNearestTiesToEven);
4530     return true;
4531   }
4532   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4533     if (!checkConst(SubobjType))
4534       return false;
4535 
4536     QualType PointeeType;
4537     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4538       PointeeType = PT->getPointeeType();
4539     else {
4540       Info.FFDiag(E);
4541       return false;
4542     }
4543 
4544     LValue LVal;
4545     LVal.setFrom(Info.Ctx, Subobj);
4546     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4547                                      AccessKind == AK_Increment ? 1 : -1))
4548       return false;
4549     LVal.moveInto(Subobj);
4550     return true;
4551   }
4552 };
4553 } // end anonymous namespace
4554 
4555 /// Perform an increment or decrement on LVal.
4556 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4557                          QualType LValType, bool IsIncrement, APValue *Old) {
4558   if (LVal.Designator.Invalid)
4559     return false;
4560 
4561   if (!Info.getLangOpts().CPlusPlus14) {
4562     Info.FFDiag(E);
4563     return false;
4564   }
4565 
4566   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4567   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4568   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4569   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4570 }
4571 
4572 /// Build an lvalue for the object argument of a member function call.
4573 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4574                                    LValue &This) {
4575   if (Object->getType()->isPointerType() && Object->isPRValue())
4576     return EvaluatePointer(Object, This, Info);
4577 
4578   if (Object->isGLValue())
4579     return EvaluateLValue(Object, This, Info);
4580 
4581   if (Object->getType()->isLiteralType(Info.Ctx))
4582     return EvaluateTemporary(Object, This, Info);
4583 
4584   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4585   return false;
4586 }
4587 
4588 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
4589 /// lvalue referring to the result.
4590 ///
4591 /// \param Info - Information about the ongoing evaluation.
4592 /// \param LV - An lvalue referring to the base of the member pointer.
4593 /// \param RHS - The member pointer expression.
4594 /// \param IncludeMember - Specifies whether the member itself is included in
4595 ///        the resulting LValue subobject designator. This is not possible when
4596 ///        creating a bound member function.
4597 /// \return The field or method declaration to which the member pointer refers,
4598 ///         or 0 if evaluation fails.
4599 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4600                                                   QualType LVType,
4601                                                   LValue &LV,
4602                                                   const Expr *RHS,
4603                                                   bool IncludeMember = true) {
4604   MemberPtr MemPtr;
4605   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4606     return nullptr;
4607 
4608   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4609   // member value, the behavior is undefined.
4610   if (!MemPtr.getDecl()) {
4611     // FIXME: Specific diagnostic.
4612     Info.FFDiag(RHS);
4613     return nullptr;
4614   }
4615 
4616   if (MemPtr.isDerivedMember()) {
4617     // This is a member of some derived class. Truncate LV appropriately.
4618     // The end of the derived-to-base path for the base object must match the
4619     // derived-to-base path for the member pointer.
4620     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4621         LV.Designator.Entries.size()) {
4622       Info.FFDiag(RHS);
4623       return nullptr;
4624     }
4625     unsigned PathLengthToMember =
4626         LV.Designator.Entries.size() - MemPtr.Path.size();
4627     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4628       const CXXRecordDecl *LVDecl = getAsBaseClass(
4629           LV.Designator.Entries[PathLengthToMember + I]);
4630       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4631       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4632         Info.FFDiag(RHS);
4633         return nullptr;
4634       }
4635     }
4636 
4637     // Truncate the lvalue to the appropriate derived class.
4638     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4639                             PathLengthToMember))
4640       return nullptr;
4641   } else if (!MemPtr.Path.empty()) {
4642     // Extend the LValue path with the member pointer's path.
4643     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4644                                   MemPtr.Path.size() + IncludeMember);
4645 
4646     // Walk down to the appropriate base class.
4647     if (const PointerType *PT = LVType->getAs<PointerType>())
4648       LVType = PT->getPointeeType();
4649     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4650     assert(RD && "member pointer access on non-class-type expression");
4651     // The first class in the path is that of the lvalue.
4652     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4653       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4654       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4655         return nullptr;
4656       RD = Base;
4657     }
4658     // Finally cast to the class containing the member.
4659     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4660                                 MemPtr.getContainingRecord()))
4661       return nullptr;
4662   }
4663 
4664   // Add the member. Note that we cannot build bound member functions here.
4665   if (IncludeMember) {
4666     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4667       if (!HandleLValueMember(Info, RHS, LV, FD))
4668         return nullptr;
4669     } else if (const IndirectFieldDecl *IFD =
4670                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4671       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4672         return nullptr;
4673     } else {
4674       llvm_unreachable("can't construct reference to bound member function");
4675     }
4676   }
4677 
4678   return MemPtr.getDecl();
4679 }
4680 
4681 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4682                                                   const BinaryOperator *BO,
4683                                                   LValue &LV,
4684                                                   bool IncludeMember = true) {
4685   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4686 
4687   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4688     if (Info.noteFailure()) {
4689       MemberPtr MemPtr;
4690       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4691     }
4692     return nullptr;
4693   }
4694 
4695   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4696                                    BO->getRHS(), IncludeMember);
4697 }
4698 
4699 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4700 /// the provided lvalue, which currently refers to the base object.
4701 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4702                                     LValue &Result) {
4703   SubobjectDesignator &D = Result.Designator;
4704   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4705     return false;
4706 
4707   QualType TargetQT = E->getType();
4708   if (const PointerType *PT = TargetQT->getAs<PointerType>())
4709     TargetQT = PT->getPointeeType();
4710 
4711   // Check this cast lands within the final derived-to-base subobject path.
4712   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4713     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4714       << D.MostDerivedType << TargetQT;
4715     return false;
4716   }
4717 
4718   // Check the type of the final cast. We don't need to check the path,
4719   // since a cast can only be formed if the path is unique.
4720   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4721   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4722   const CXXRecordDecl *FinalType;
4723   if (NewEntriesSize == D.MostDerivedPathLength)
4724     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4725   else
4726     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4727   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4728     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4729       << D.MostDerivedType << TargetQT;
4730     return false;
4731   }
4732 
4733   // Truncate the lvalue to the appropriate derived class.
4734   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4735 }
4736 
4737 /// Get the value to use for a default-initialized object of type T.
4738 /// Return false if it encounters something invalid.
4739 static bool getDefaultInitValue(QualType T, APValue &Result) {
4740   bool Success = true;
4741   if (auto *RD = T->getAsCXXRecordDecl()) {
4742     if (RD->isInvalidDecl()) {
4743       Result = APValue();
4744       return false;
4745     }
4746     if (RD->isUnion()) {
4747       Result = APValue((const FieldDecl *)nullptr);
4748       return true;
4749     }
4750     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4751                      std::distance(RD->field_begin(), RD->field_end()));
4752 
4753     unsigned Index = 0;
4754     for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4755                                                   End = RD->bases_end();
4756          I != End; ++I, ++Index)
4757       Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index));
4758 
4759     for (const auto *I : RD->fields()) {
4760       if (I->isUnnamedBitfield())
4761         continue;
4762       Success &= getDefaultInitValue(I->getType(),
4763                                      Result.getStructField(I->getFieldIndex()));
4764     }
4765     return Success;
4766   }
4767 
4768   if (auto *AT =
4769           dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4770     Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4771     if (Result.hasArrayFiller())
4772       Success &=
4773           getDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
4774 
4775     return Success;
4776   }
4777 
4778   Result = APValue::IndeterminateValue();
4779   return true;
4780 }
4781 
4782 namespace {
4783 enum EvalStmtResult {
4784   /// Evaluation failed.
4785   ESR_Failed,
4786   /// Hit a 'return' statement.
4787   ESR_Returned,
4788   /// Evaluation succeeded.
4789   ESR_Succeeded,
4790   /// Hit a 'continue' statement.
4791   ESR_Continue,
4792   /// Hit a 'break' statement.
4793   ESR_Break,
4794   /// Still scanning for 'case' or 'default' statement.
4795   ESR_CaseNotFound
4796 };
4797 }
4798 
4799 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4800   // We don't need to evaluate the initializer for a static local.
4801   if (!VD->hasLocalStorage())
4802     return true;
4803 
4804   LValue Result;
4805   APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
4806                                                    ScopeKind::Block, Result);
4807 
4808   const Expr *InitE = VD->getInit();
4809   if (!InitE) {
4810     if (VD->getType()->isDependentType())
4811       return Info.noteSideEffect();
4812     return getDefaultInitValue(VD->getType(), Val);
4813   }
4814   if (InitE->isValueDependent())
4815     return false;
4816 
4817   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4818     // Wipe out any partially-computed value, to allow tracking that this
4819     // evaluation failed.
4820     Val = APValue();
4821     return false;
4822   }
4823 
4824   return true;
4825 }
4826 
4827 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4828   bool OK = true;
4829 
4830   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4831     OK &= EvaluateVarDecl(Info, VD);
4832 
4833   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4834     for (auto *BD : DD->bindings())
4835       if (auto *VD = BD->getHoldingVar())
4836         OK &= EvaluateDecl(Info, VD);
4837 
4838   return OK;
4839 }
4840 
4841 static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
4842   assert(E->isValueDependent());
4843   if (Info.noteSideEffect())
4844     return true;
4845   assert(E->containsErrors() && "valid value-dependent expression should never "
4846                                 "reach invalid code path.");
4847   return false;
4848 }
4849 
4850 /// Evaluate a condition (either a variable declaration or an expression).
4851 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4852                          const Expr *Cond, bool &Result) {
4853   if (Cond->isValueDependent())
4854     return false;
4855   FullExpressionRAII Scope(Info);
4856   if (CondDecl && !EvaluateDecl(Info, CondDecl))
4857     return false;
4858   if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4859     return false;
4860   return Scope.destroy();
4861 }
4862 
4863 namespace {
4864 /// A location where the result (returned value) of evaluating a
4865 /// statement should be stored.
4866 struct StmtResult {
4867   /// The APValue that should be filled in with the returned value.
4868   APValue &Value;
4869   /// The location containing the result, if any (used to support RVO).
4870   const LValue *Slot;
4871 };
4872 
4873 struct TempVersionRAII {
4874   CallStackFrame &Frame;
4875 
4876   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4877     Frame.pushTempVersion();
4878   }
4879 
4880   ~TempVersionRAII() {
4881     Frame.popTempVersion();
4882   }
4883 };
4884 
4885 }
4886 
4887 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4888                                    const Stmt *S,
4889                                    const SwitchCase *SC = nullptr);
4890 
4891 /// Evaluate the body of a loop, and translate the result as appropriate.
4892 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4893                                        const Stmt *Body,
4894                                        const SwitchCase *Case = nullptr) {
4895   BlockScopeRAII Scope(Info);
4896 
4897   EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4898   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4899     ESR = ESR_Failed;
4900 
4901   switch (ESR) {
4902   case ESR_Break:
4903     return ESR_Succeeded;
4904   case ESR_Succeeded:
4905   case ESR_Continue:
4906     return ESR_Continue;
4907   case ESR_Failed:
4908   case ESR_Returned:
4909   case ESR_CaseNotFound:
4910     return ESR;
4911   }
4912   llvm_unreachable("Invalid EvalStmtResult!");
4913 }
4914 
4915 /// Evaluate a switch statement.
4916 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4917                                      const SwitchStmt *SS) {
4918   BlockScopeRAII Scope(Info);
4919 
4920   // Evaluate the switch condition.
4921   APSInt Value;
4922   {
4923     if (const Stmt *Init = SS->getInit()) {
4924       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4925       if (ESR != ESR_Succeeded) {
4926         if (ESR != ESR_Failed && !Scope.destroy())
4927           ESR = ESR_Failed;
4928         return ESR;
4929       }
4930     }
4931 
4932     FullExpressionRAII CondScope(Info);
4933     if (SS->getConditionVariable() &&
4934         !EvaluateDecl(Info, SS->getConditionVariable()))
4935       return ESR_Failed;
4936     if (!EvaluateInteger(SS->getCond(), Value, Info))
4937       return ESR_Failed;
4938     if (!CondScope.destroy())
4939       return ESR_Failed;
4940   }
4941 
4942   // Find the switch case corresponding to the value of the condition.
4943   // FIXME: Cache this lookup.
4944   const SwitchCase *Found = nullptr;
4945   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4946        SC = SC->getNextSwitchCase()) {
4947     if (isa<DefaultStmt>(SC)) {
4948       Found = SC;
4949       continue;
4950     }
4951 
4952     const CaseStmt *CS = cast<CaseStmt>(SC);
4953     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4954     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4955                               : LHS;
4956     if (LHS <= Value && Value <= RHS) {
4957       Found = SC;
4958       break;
4959     }
4960   }
4961 
4962   if (!Found)
4963     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4964 
4965   // Search the switch body for the switch case and evaluate it from there.
4966   EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
4967   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4968     return ESR_Failed;
4969 
4970   switch (ESR) {
4971   case ESR_Break:
4972     return ESR_Succeeded;
4973   case ESR_Succeeded:
4974   case ESR_Continue:
4975   case ESR_Failed:
4976   case ESR_Returned:
4977     return ESR;
4978   case ESR_CaseNotFound:
4979     // This can only happen if the switch case is nested within a statement
4980     // expression. We have no intention of supporting that.
4981     Info.FFDiag(Found->getBeginLoc(),
4982                 diag::note_constexpr_stmt_expr_unsupported);
4983     return ESR_Failed;
4984   }
4985   llvm_unreachable("Invalid EvalStmtResult!");
4986 }
4987 
4988 // Evaluate a statement.
4989 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4990                                    const Stmt *S, const SwitchCase *Case) {
4991   if (!Info.nextStep(S))
4992     return ESR_Failed;
4993 
4994   // If we're hunting down a 'case' or 'default' label, recurse through
4995   // substatements until we hit the label.
4996   if (Case) {
4997     switch (S->getStmtClass()) {
4998     case Stmt::CompoundStmtClass:
4999       // FIXME: Precompute which substatement of a compound statement we
5000       // would jump to, and go straight there rather than performing a
5001       // linear scan each time.
5002     case Stmt::LabelStmtClass:
5003     case Stmt::AttributedStmtClass:
5004     case Stmt::DoStmtClass:
5005       break;
5006 
5007     case Stmt::CaseStmtClass:
5008     case Stmt::DefaultStmtClass:
5009       if (Case == S)
5010         Case = nullptr;
5011       break;
5012 
5013     case Stmt::IfStmtClass: {
5014       // FIXME: Precompute which side of an 'if' we would jump to, and go
5015       // straight there rather than scanning both sides.
5016       const IfStmt *IS = cast<IfStmt>(S);
5017 
5018       // Wrap the evaluation in a block scope, in case it's a DeclStmt
5019       // preceded by our switch label.
5020       BlockScopeRAII Scope(Info);
5021 
5022       // Step into the init statement in case it brings an (uninitialized)
5023       // variable into scope.
5024       if (const Stmt *Init = IS->getInit()) {
5025         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5026         if (ESR != ESR_CaseNotFound) {
5027           assert(ESR != ESR_Succeeded);
5028           return ESR;
5029         }
5030       }
5031 
5032       // Condition variable must be initialized if it exists.
5033       // FIXME: We can skip evaluating the body if there's a condition
5034       // variable, as there can't be any case labels within it.
5035       // (The same is true for 'for' statements.)
5036 
5037       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5038       if (ESR == ESR_Failed)
5039         return ESR;
5040       if (ESR != ESR_CaseNotFound)
5041         return Scope.destroy() ? ESR : ESR_Failed;
5042       if (!IS->getElse())
5043         return ESR_CaseNotFound;
5044 
5045       ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5046       if (ESR == ESR_Failed)
5047         return ESR;
5048       if (ESR != ESR_CaseNotFound)
5049         return Scope.destroy() ? ESR : ESR_Failed;
5050       return ESR_CaseNotFound;
5051     }
5052 
5053     case Stmt::WhileStmtClass: {
5054       EvalStmtResult ESR =
5055           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5056       if (ESR != ESR_Continue)
5057         return ESR;
5058       break;
5059     }
5060 
5061     case Stmt::ForStmtClass: {
5062       const ForStmt *FS = cast<ForStmt>(S);
5063       BlockScopeRAII Scope(Info);
5064 
5065       // Step into the init statement in case it brings an (uninitialized)
5066       // variable into scope.
5067       if (const Stmt *Init = FS->getInit()) {
5068         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5069         if (ESR != ESR_CaseNotFound) {
5070           assert(ESR != ESR_Succeeded);
5071           return ESR;
5072         }
5073       }
5074 
5075       EvalStmtResult ESR =
5076           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5077       if (ESR != ESR_Continue)
5078         return ESR;
5079       if (const auto *Inc = FS->getInc()) {
5080         if (Inc->isValueDependent()) {
5081           if (!EvaluateDependentExpr(Inc, Info))
5082             return ESR_Failed;
5083         } else {
5084           FullExpressionRAII IncScope(Info);
5085           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5086             return ESR_Failed;
5087         }
5088       }
5089       break;
5090     }
5091 
5092     case Stmt::DeclStmtClass: {
5093       // Start the lifetime of any uninitialized variables we encounter. They
5094       // might be used by the selected branch of the switch.
5095       const DeclStmt *DS = cast<DeclStmt>(S);
5096       for (const auto *D : DS->decls()) {
5097         if (const auto *VD = dyn_cast<VarDecl>(D)) {
5098           if (VD->hasLocalStorage() && !VD->getInit())
5099             if (!EvaluateVarDecl(Info, VD))
5100               return ESR_Failed;
5101           // FIXME: If the variable has initialization that can't be jumped
5102           // over, bail out of any immediately-surrounding compound-statement
5103           // too. There can't be any case labels here.
5104         }
5105       }
5106       return ESR_CaseNotFound;
5107     }
5108 
5109     default:
5110       return ESR_CaseNotFound;
5111     }
5112   }
5113 
5114   switch (S->getStmtClass()) {
5115   default:
5116     if (const Expr *E = dyn_cast<Expr>(S)) {
5117       if (E->isValueDependent()) {
5118         if (!EvaluateDependentExpr(E, Info))
5119           return ESR_Failed;
5120       } else {
5121         // Don't bother evaluating beyond an expression-statement which couldn't
5122         // be evaluated.
5123         // FIXME: Do we need the FullExpressionRAII object here?
5124         // VisitExprWithCleanups should create one when necessary.
5125         FullExpressionRAII Scope(Info);
5126         if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5127           return ESR_Failed;
5128       }
5129       return ESR_Succeeded;
5130     }
5131 
5132     Info.FFDiag(S->getBeginLoc());
5133     return ESR_Failed;
5134 
5135   case Stmt::NullStmtClass:
5136     return ESR_Succeeded;
5137 
5138   case Stmt::DeclStmtClass: {
5139     const DeclStmt *DS = cast<DeclStmt>(S);
5140     for (const auto *D : DS->decls()) {
5141       // Each declaration initialization is its own full-expression.
5142       FullExpressionRAII Scope(Info);
5143       if (!EvaluateDecl(Info, D) && !Info.noteFailure())
5144         return ESR_Failed;
5145       if (!Scope.destroy())
5146         return ESR_Failed;
5147     }
5148     return ESR_Succeeded;
5149   }
5150 
5151   case Stmt::ReturnStmtClass: {
5152     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5153     FullExpressionRAII Scope(Info);
5154     if (RetExpr && RetExpr->isValueDependent()) {
5155       EvaluateDependentExpr(RetExpr, Info);
5156       // We know we returned, but we don't know what the value is.
5157       return ESR_Failed;
5158     }
5159     if (RetExpr &&
5160         !(Result.Slot
5161               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5162               : Evaluate(Result.Value, Info, RetExpr)))
5163       return ESR_Failed;
5164     return Scope.destroy() ? ESR_Returned : ESR_Failed;
5165   }
5166 
5167   case Stmt::CompoundStmtClass: {
5168     BlockScopeRAII Scope(Info);
5169 
5170     const CompoundStmt *CS = cast<CompoundStmt>(S);
5171     for (const auto *BI : CS->body()) {
5172       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5173       if (ESR == ESR_Succeeded)
5174         Case = nullptr;
5175       else if (ESR != ESR_CaseNotFound) {
5176         if (ESR != ESR_Failed && !Scope.destroy())
5177           return ESR_Failed;
5178         return ESR;
5179       }
5180     }
5181     if (Case)
5182       return ESR_CaseNotFound;
5183     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5184   }
5185 
5186   case Stmt::IfStmtClass: {
5187     const IfStmt *IS = cast<IfStmt>(S);
5188 
5189     // Evaluate the condition, as either a var decl or as an expression.
5190     BlockScopeRAII Scope(Info);
5191     if (const Stmt *Init = IS->getInit()) {
5192       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5193       if (ESR != ESR_Succeeded) {
5194         if (ESR != ESR_Failed && !Scope.destroy())
5195           return ESR_Failed;
5196         return ESR;
5197       }
5198     }
5199     bool Cond;
5200     if (IS->isConsteval())
5201       Cond = IS->isNonNegatedConsteval();
5202     else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
5203                            Cond))
5204       return ESR_Failed;
5205 
5206     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5207       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5208       if (ESR != ESR_Succeeded) {
5209         if (ESR != ESR_Failed && !Scope.destroy())
5210           return ESR_Failed;
5211         return ESR;
5212       }
5213     }
5214     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5215   }
5216 
5217   case Stmt::WhileStmtClass: {
5218     const WhileStmt *WS = cast<WhileStmt>(S);
5219     while (true) {
5220       BlockScopeRAII Scope(Info);
5221       bool Continue;
5222       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5223                         Continue))
5224         return ESR_Failed;
5225       if (!Continue)
5226         break;
5227 
5228       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5229       if (ESR != ESR_Continue) {
5230         if (ESR != ESR_Failed && !Scope.destroy())
5231           return ESR_Failed;
5232         return ESR;
5233       }
5234       if (!Scope.destroy())
5235         return ESR_Failed;
5236     }
5237     return ESR_Succeeded;
5238   }
5239 
5240   case Stmt::DoStmtClass: {
5241     const DoStmt *DS = cast<DoStmt>(S);
5242     bool Continue;
5243     do {
5244       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5245       if (ESR != ESR_Continue)
5246         return ESR;
5247       Case = nullptr;
5248 
5249       if (DS->getCond()->isValueDependent()) {
5250         EvaluateDependentExpr(DS->getCond(), Info);
5251         // Bailout as we don't know whether to keep going or terminate the loop.
5252         return ESR_Failed;
5253       }
5254       FullExpressionRAII CondScope(Info);
5255       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5256           !CondScope.destroy())
5257         return ESR_Failed;
5258     } while (Continue);
5259     return ESR_Succeeded;
5260   }
5261 
5262   case Stmt::ForStmtClass: {
5263     const ForStmt *FS = cast<ForStmt>(S);
5264     BlockScopeRAII ForScope(Info);
5265     if (FS->getInit()) {
5266       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5267       if (ESR != ESR_Succeeded) {
5268         if (ESR != ESR_Failed && !ForScope.destroy())
5269           return ESR_Failed;
5270         return ESR;
5271       }
5272     }
5273     while (true) {
5274       BlockScopeRAII IterScope(Info);
5275       bool Continue = true;
5276       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5277                                          FS->getCond(), Continue))
5278         return ESR_Failed;
5279       if (!Continue)
5280         break;
5281 
5282       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5283       if (ESR != ESR_Continue) {
5284         if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5285           return ESR_Failed;
5286         return ESR;
5287       }
5288 
5289       if (const auto *Inc = FS->getInc()) {
5290         if (Inc->isValueDependent()) {
5291           if (!EvaluateDependentExpr(Inc, Info))
5292             return ESR_Failed;
5293         } else {
5294           FullExpressionRAII IncScope(Info);
5295           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5296             return ESR_Failed;
5297         }
5298       }
5299 
5300       if (!IterScope.destroy())
5301         return ESR_Failed;
5302     }
5303     return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5304   }
5305 
5306   case Stmt::CXXForRangeStmtClass: {
5307     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5308     BlockScopeRAII Scope(Info);
5309 
5310     // Evaluate the init-statement if present.
5311     if (FS->getInit()) {
5312       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5313       if (ESR != ESR_Succeeded) {
5314         if (ESR != ESR_Failed && !Scope.destroy())
5315           return ESR_Failed;
5316         return ESR;
5317       }
5318     }
5319 
5320     // Initialize the __range variable.
5321     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5322     if (ESR != ESR_Succeeded) {
5323       if (ESR != ESR_Failed && !Scope.destroy())
5324         return ESR_Failed;
5325       return ESR;
5326     }
5327 
5328     // In error-recovery cases it's possible to get here even if we failed to
5329     // synthesize the __begin and __end variables.
5330     if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
5331       return ESR_Failed;
5332 
5333     // Create the __begin and __end iterators.
5334     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5335     if (ESR != ESR_Succeeded) {
5336       if (ESR != ESR_Failed && !Scope.destroy())
5337         return ESR_Failed;
5338       return ESR;
5339     }
5340     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5341     if (ESR != ESR_Succeeded) {
5342       if (ESR != ESR_Failed && !Scope.destroy())
5343         return ESR_Failed;
5344       return ESR;
5345     }
5346 
5347     while (true) {
5348       // Condition: __begin != __end.
5349       {
5350         if (FS->getCond()->isValueDependent()) {
5351           EvaluateDependentExpr(FS->getCond(), Info);
5352           // We don't know whether to keep going or terminate the loop.
5353           return ESR_Failed;
5354         }
5355         bool Continue = true;
5356         FullExpressionRAII CondExpr(Info);
5357         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5358           return ESR_Failed;
5359         if (!Continue)
5360           break;
5361       }
5362 
5363       // User's variable declaration, initialized by *__begin.
5364       BlockScopeRAII InnerScope(Info);
5365       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5366       if (ESR != ESR_Succeeded) {
5367         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5368           return ESR_Failed;
5369         return ESR;
5370       }
5371 
5372       // Loop body.
5373       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5374       if (ESR != ESR_Continue) {
5375         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5376           return ESR_Failed;
5377         return ESR;
5378       }
5379       if (FS->getInc()->isValueDependent()) {
5380         if (!EvaluateDependentExpr(FS->getInc(), Info))
5381           return ESR_Failed;
5382       } else {
5383         // Increment: ++__begin
5384         if (!EvaluateIgnoredValue(Info, FS->getInc()))
5385           return ESR_Failed;
5386       }
5387 
5388       if (!InnerScope.destroy())
5389         return ESR_Failed;
5390     }
5391 
5392     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5393   }
5394 
5395   case Stmt::SwitchStmtClass:
5396     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5397 
5398   case Stmt::ContinueStmtClass:
5399     return ESR_Continue;
5400 
5401   case Stmt::BreakStmtClass:
5402     return ESR_Break;
5403 
5404   case Stmt::LabelStmtClass:
5405     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5406 
5407   case Stmt::AttributedStmtClass:
5408     // As a general principle, C++11 attributes can be ignored without
5409     // any semantic impact.
5410     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
5411                         Case);
5412 
5413   case Stmt::CaseStmtClass:
5414   case Stmt::DefaultStmtClass:
5415     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5416   case Stmt::CXXTryStmtClass:
5417     // Evaluate try blocks by evaluating all sub statements.
5418     return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5419   }
5420 }
5421 
5422 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5423 /// default constructor. If so, we'll fold it whether or not it's marked as
5424 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
5425 /// so we need special handling.
5426 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5427                                            const CXXConstructorDecl *CD,
5428                                            bool IsValueInitialization) {
5429   if (!CD->isTrivial() || !CD->isDefaultConstructor())
5430     return false;
5431 
5432   // Value-initialization does not call a trivial default constructor, so such a
5433   // call is a core constant expression whether or not the constructor is
5434   // constexpr.
5435   if (!CD->isConstexpr() && !IsValueInitialization) {
5436     if (Info.getLangOpts().CPlusPlus11) {
5437       // FIXME: If DiagDecl is an implicitly-declared special member function,
5438       // we should be much more explicit about why it's not constexpr.
5439       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5440         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5441       Info.Note(CD->getLocation(), diag::note_declared_at);
5442     } else {
5443       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5444     }
5445   }
5446   return true;
5447 }
5448 
5449 /// CheckConstexprFunction - Check that a function can be called in a constant
5450 /// expression.
5451 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5452                                    const FunctionDecl *Declaration,
5453                                    const FunctionDecl *Definition,
5454                                    const Stmt *Body) {
5455   // Potential constant expressions can contain calls to declared, but not yet
5456   // defined, constexpr functions.
5457   if (Info.checkingPotentialConstantExpression() && !Definition &&
5458       Declaration->isConstexpr())
5459     return false;
5460 
5461   // Bail out if the function declaration itself is invalid.  We will
5462   // have produced a relevant diagnostic while parsing it, so just
5463   // note the problematic sub-expression.
5464   if (Declaration->isInvalidDecl()) {
5465     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5466     return false;
5467   }
5468 
5469   // DR1872: An instantiated virtual constexpr function can't be called in a
5470   // constant expression (prior to C++20). We can still constant-fold such a
5471   // call.
5472   if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5473       cast<CXXMethodDecl>(Declaration)->isVirtual())
5474     Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5475 
5476   if (Definition && Definition->isInvalidDecl()) {
5477     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5478     return false;
5479   }
5480 
5481   // Can we evaluate this function call?
5482   if (Definition && Definition->isConstexpr() && Body)
5483     return true;
5484 
5485   if (Info.getLangOpts().CPlusPlus11) {
5486     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5487 
5488     // If this function is not constexpr because it is an inherited
5489     // non-constexpr constructor, diagnose that directly.
5490     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5491     if (CD && CD->isInheritingConstructor()) {
5492       auto *Inherited = CD->getInheritedConstructor().getConstructor();
5493       if (!Inherited->isConstexpr())
5494         DiagDecl = CD = Inherited;
5495     }
5496 
5497     // FIXME: If DiagDecl is an implicitly-declared special member function
5498     // or an inheriting constructor, we should be much more explicit about why
5499     // it's not constexpr.
5500     if (CD && CD->isInheritingConstructor())
5501       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5502         << CD->getInheritedConstructor().getConstructor()->getParent();
5503     else
5504       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5505         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5506     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5507   } else {
5508     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5509   }
5510   return false;
5511 }
5512 
5513 namespace {
5514 struct CheckDynamicTypeHandler {
5515   AccessKinds AccessKind;
5516   typedef bool result_type;
5517   bool failed() { return false; }
5518   bool found(APValue &Subobj, QualType SubobjType) { return true; }
5519   bool found(APSInt &Value, QualType SubobjType) { return true; }
5520   bool found(APFloat &Value, QualType SubobjType) { return true; }
5521 };
5522 } // end anonymous namespace
5523 
5524 /// Check that we can access the notional vptr of an object / determine its
5525 /// dynamic type.
5526 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5527                              AccessKinds AK, bool Polymorphic) {
5528   if (This.Designator.Invalid)
5529     return false;
5530 
5531   CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5532 
5533   if (!Obj)
5534     return false;
5535 
5536   if (!Obj.Value) {
5537     // The object is not usable in constant expressions, so we can't inspect
5538     // its value to see if it's in-lifetime or what the active union members
5539     // are. We can still check for a one-past-the-end lvalue.
5540     if (This.Designator.isOnePastTheEnd() ||
5541         This.Designator.isMostDerivedAnUnsizedArray()) {
5542       Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5543                          ? diag::note_constexpr_access_past_end
5544                          : diag::note_constexpr_access_unsized_array)
5545           << AK;
5546       return false;
5547     } else if (Polymorphic) {
5548       // Conservatively refuse to perform a polymorphic operation if we would
5549       // not be able to read a notional 'vptr' value.
5550       APValue Val;
5551       This.moveInto(Val);
5552       QualType StarThisType =
5553           Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5554       Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5555           << AK << Val.getAsString(Info.Ctx, StarThisType);
5556       return false;
5557     }
5558     return true;
5559   }
5560 
5561   CheckDynamicTypeHandler Handler{AK};
5562   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5563 }
5564 
5565 /// Check that the pointee of the 'this' pointer in a member function call is
5566 /// either within its lifetime or in its period of construction or destruction.
5567 static bool
5568 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5569                                      const LValue &This,
5570                                      const CXXMethodDecl *NamedMember) {
5571   return checkDynamicType(
5572       Info, E, This,
5573       isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5574 }
5575 
5576 struct DynamicType {
5577   /// The dynamic class type of the object.
5578   const CXXRecordDecl *Type;
5579   /// The corresponding path length in the lvalue.
5580   unsigned PathLength;
5581 };
5582 
5583 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5584                                              unsigned PathLength) {
5585   assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5586       Designator.Entries.size() && "invalid path length");
5587   return (PathLength == Designator.MostDerivedPathLength)
5588              ? Designator.MostDerivedType->getAsCXXRecordDecl()
5589              : getAsBaseClass(Designator.Entries[PathLength - 1]);
5590 }
5591 
5592 /// Determine the dynamic type of an object.
5593 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
5594                                                 LValue &This, AccessKinds AK) {
5595   // If we don't have an lvalue denoting an object of class type, there is no
5596   // meaningful dynamic type. (We consider objects of non-class type to have no
5597   // dynamic type.)
5598   if (!checkDynamicType(Info, E, This, AK, true))
5599     return None;
5600 
5601   // Refuse to compute a dynamic type in the presence of virtual bases. This
5602   // shouldn't happen other than in constant-folding situations, since literal
5603   // types can't have virtual bases.
5604   //
5605   // Note that consumers of DynamicType assume that the type has no virtual
5606   // bases, and will need modifications if this restriction is relaxed.
5607   const CXXRecordDecl *Class =
5608       This.Designator.MostDerivedType->getAsCXXRecordDecl();
5609   if (!Class || Class->getNumVBases()) {
5610     Info.FFDiag(E);
5611     return None;
5612   }
5613 
5614   // FIXME: For very deep class hierarchies, it might be beneficial to use a
5615   // binary search here instead. But the overwhelmingly common case is that
5616   // we're not in the middle of a constructor, so it probably doesn't matter
5617   // in practice.
5618   ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5619   for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5620        PathLength <= Path.size(); ++PathLength) {
5621     switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5622                                       Path.slice(0, PathLength))) {
5623     case ConstructionPhase::Bases:
5624     case ConstructionPhase::DestroyingBases:
5625       // We're constructing or destroying a base class. This is not the dynamic
5626       // type.
5627       break;
5628 
5629     case ConstructionPhase::None:
5630     case ConstructionPhase::AfterBases:
5631     case ConstructionPhase::AfterFields:
5632     case ConstructionPhase::Destroying:
5633       // We've finished constructing the base classes and not yet started
5634       // destroying them again, so this is the dynamic type.
5635       return DynamicType{getBaseClassType(This.Designator, PathLength),
5636                          PathLength};
5637     }
5638   }
5639 
5640   // CWG issue 1517: we're constructing a base class of the object described by
5641   // 'This', so that object has not yet begun its period of construction and
5642   // any polymorphic operation on it results in undefined behavior.
5643   Info.FFDiag(E);
5644   return None;
5645 }
5646 
5647 /// Perform virtual dispatch.
5648 static const CXXMethodDecl *HandleVirtualDispatch(
5649     EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5650     llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5651   Optional<DynamicType> DynType = ComputeDynamicType(
5652       Info, E, This,
5653       isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5654   if (!DynType)
5655     return nullptr;
5656 
5657   // Find the final overrider. It must be declared in one of the classes on the
5658   // path from the dynamic type to the static type.
5659   // FIXME: If we ever allow literal types to have virtual base classes, that
5660   // won't be true.
5661   const CXXMethodDecl *Callee = Found;
5662   unsigned PathLength = DynType->PathLength;
5663   for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5664     const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5665     const CXXMethodDecl *Overrider =
5666         Found->getCorrespondingMethodDeclaredInClass(Class, false);
5667     if (Overrider) {
5668       Callee = Overrider;
5669       break;
5670     }
5671   }
5672 
5673   // C++2a [class.abstract]p6:
5674   //   the effect of making a virtual call to a pure virtual function [...] is
5675   //   undefined
5676   if (Callee->isPure()) {
5677     Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5678     Info.Note(Callee->getLocation(), diag::note_declared_at);
5679     return nullptr;
5680   }
5681 
5682   // If necessary, walk the rest of the path to determine the sequence of
5683   // covariant adjustment steps to apply.
5684   if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5685                                        Found->getReturnType())) {
5686     CovariantAdjustmentPath.push_back(Callee->getReturnType());
5687     for (unsigned CovariantPathLength = PathLength + 1;
5688          CovariantPathLength != This.Designator.Entries.size();
5689          ++CovariantPathLength) {
5690       const CXXRecordDecl *NextClass =
5691           getBaseClassType(This.Designator, CovariantPathLength);
5692       const CXXMethodDecl *Next =
5693           Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5694       if (Next && !Info.Ctx.hasSameUnqualifiedType(
5695                       Next->getReturnType(), CovariantAdjustmentPath.back()))
5696         CovariantAdjustmentPath.push_back(Next->getReturnType());
5697     }
5698     if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5699                                          CovariantAdjustmentPath.back()))
5700       CovariantAdjustmentPath.push_back(Found->getReturnType());
5701   }
5702 
5703   // Perform 'this' adjustment.
5704   if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5705     return nullptr;
5706 
5707   return Callee;
5708 }
5709 
5710 /// Perform the adjustment from a value returned by a virtual function to
5711 /// a value of the statically expected type, which may be a pointer or
5712 /// reference to a base class of the returned type.
5713 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5714                                             APValue &Result,
5715                                             ArrayRef<QualType> Path) {
5716   assert(Result.isLValue() &&
5717          "unexpected kind of APValue for covariant return");
5718   if (Result.isNullPointer())
5719     return true;
5720 
5721   LValue LVal;
5722   LVal.setFrom(Info.Ctx, Result);
5723 
5724   const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5725   for (unsigned I = 1; I != Path.size(); ++I) {
5726     const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5727     assert(OldClass && NewClass && "unexpected kind of covariant return");
5728     if (OldClass != NewClass &&
5729         !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5730       return false;
5731     OldClass = NewClass;
5732   }
5733 
5734   LVal.moveInto(Result);
5735   return true;
5736 }
5737 
5738 /// Determine whether \p Base, which is known to be a direct base class of
5739 /// \p Derived, is a public base class.
5740 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5741                               const CXXRecordDecl *Base) {
5742   for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5743     auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5744     if (BaseClass && declaresSameEntity(BaseClass, Base))
5745       return BaseSpec.getAccessSpecifier() == AS_public;
5746   }
5747   llvm_unreachable("Base is not a direct base of Derived");
5748 }
5749 
5750 /// Apply the given dynamic cast operation on the provided lvalue.
5751 ///
5752 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
5753 /// to find a suitable target subobject.
5754 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5755                               LValue &Ptr) {
5756   // We can't do anything with a non-symbolic pointer value.
5757   SubobjectDesignator &D = Ptr.Designator;
5758   if (D.Invalid)
5759     return false;
5760 
5761   // C++ [expr.dynamic.cast]p6:
5762   //   If v is a null pointer value, the result is a null pointer value.
5763   if (Ptr.isNullPointer() && !E->isGLValue())
5764     return true;
5765 
5766   // For all the other cases, we need the pointer to point to an object within
5767   // its lifetime / period of construction / destruction, and we need to know
5768   // its dynamic type.
5769   Optional<DynamicType> DynType =
5770       ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5771   if (!DynType)
5772     return false;
5773 
5774   // C++ [expr.dynamic.cast]p7:
5775   //   If T is "pointer to cv void", then the result is a pointer to the most
5776   //   derived object
5777   if (E->getType()->isVoidPointerType())
5778     return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5779 
5780   const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5781   assert(C && "dynamic_cast target is not void pointer nor class");
5782   CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5783 
5784   auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5785     // C++ [expr.dynamic.cast]p9:
5786     if (!E->isGLValue()) {
5787       //   The value of a failed cast to pointer type is the null pointer value
5788       //   of the required result type.
5789       Ptr.setNull(Info.Ctx, E->getType());
5790       return true;
5791     }
5792 
5793     //   A failed cast to reference type throws [...] std::bad_cast.
5794     unsigned DiagKind;
5795     if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5796                    DynType->Type->isDerivedFrom(C)))
5797       DiagKind = 0;
5798     else if (!Paths || Paths->begin() == Paths->end())
5799       DiagKind = 1;
5800     else if (Paths->isAmbiguous(CQT))
5801       DiagKind = 2;
5802     else {
5803       assert(Paths->front().Access != AS_public && "why did the cast fail?");
5804       DiagKind = 3;
5805     }
5806     Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5807         << DiagKind << Ptr.Designator.getType(Info.Ctx)
5808         << Info.Ctx.getRecordType(DynType->Type)
5809         << E->getType().getUnqualifiedType();
5810     return false;
5811   };
5812 
5813   // Runtime check, phase 1:
5814   //   Walk from the base subobject towards the derived object looking for the
5815   //   target type.
5816   for (int PathLength = Ptr.Designator.Entries.size();
5817        PathLength >= (int)DynType->PathLength; --PathLength) {
5818     const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5819     if (declaresSameEntity(Class, C))
5820       return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5821     // We can only walk across public inheritance edges.
5822     if (PathLength > (int)DynType->PathLength &&
5823         !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5824                            Class))
5825       return RuntimeCheckFailed(nullptr);
5826   }
5827 
5828   // Runtime check, phase 2:
5829   //   Search the dynamic type for an unambiguous public base of type C.
5830   CXXBasePaths Paths(/*FindAmbiguities=*/true,
5831                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
5832   if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5833       Paths.front().Access == AS_public) {
5834     // Downcast to the dynamic type...
5835     if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5836       return false;
5837     // ... then upcast to the chosen base class subobject.
5838     for (CXXBasePathElement &Elem : Paths.front())
5839       if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5840         return false;
5841     return true;
5842   }
5843 
5844   // Otherwise, the runtime check fails.
5845   return RuntimeCheckFailed(&Paths);
5846 }
5847 
5848 namespace {
5849 struct StartLifetimeOfUnionMemberHandler {
5850   EvalInfo &Info;
5851   const Expr *LHSExpr;
5852   const FieldDecl *Field;
5853   bool DuringInit;
5854   bool Failed = false;
5855   static const AccessKinds AccessKind = AK_Assign;
5856 
5857   typedef bool result_type;
5858   bool failed() { return Failed; }
5859   bool found(APValue &Subobj, QualType SubobjType) {
5860     // We are supposed to perform no initialization but begin the lifetime of
5861     // the object. We interpret that as meaning to do what default
5862     // initialization of the object would do if all constructors involved were
5863     // trivial:
5864     //  * All base, non-variant member, and array element subobjects' lifetimes
5865     //    begin
5866     //  * No variant members' lifetimes begin
5867     //  * All scalar subobjects whose lifetimes begin have indeterminate values
5868     assert(SubobjType->isUnionType());
5869     if (declaresSameEntity(Subobj.getUnionField(), Field)) {
5870       // This union member is already active. If it's also in-lifetime, there's
5871       // nothing to do.
5872       if (Subobj.getUnionValue().hasValue())
5873         return true;
5874     } else if (DuringInit) {
5875       // We're currently in the process of initializing a different union
5876       // member.  If we carried on, that initialization would attempt to
5877       // store to an inactive union member, resulting in undefined behavior.
5878       Info.FFDiag(LHSExpr,
5879                   diag::note_constexpr_union_member_change_during_init);
5880       return false;
5881     }
5882     APValue Result;
5883     Failed = !getDefaultInitValue(Field->getType(), Result);
5884     Subobj.setUnion(Field, Result);
5885     return true;
5886   }
5887   bool found(APSInt &Value, QualType SubobjType) {
5888     llvm_unreachable("wrong value kind for union object");
5889   }
5890   bool found(APFloat &Value, QualType SubobjType) {
5891     llvm_unreachable("wrong value kind for union object");
5892   }
5893 };
5894 } // end anonymous namespace
5895 
5896 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5897 
5898 /// Handle a builtin simple-assignment or a call to a trivial assignment
5899 /// operator whose left-hand side might involve a union member access. If it
5900 /// does, implicitly start the lifetime of any accessed union elements per
5901 /// C++20 [class.union]5.
5902 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5903                                           const LValue &LHS) {
5904   if (LHS.InvalidBase || LHS.Designator.Invalid)
5905     return false;
5906 
5907   llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5908   // C++ [class.union]p5:
5909   //   define the set S(E) of subexpressions of E as follows:
5910   unsigned PathLength = LHS.Designator.Entries.size();
5911   for (const Expr *E = LHSExpr; E != nullptr;) {
5912     //   -- If E is of the form A.B, S(E) contains the elements of S(A)...
5913     if (auto *ME = dyn_cast<MemberExpr>(E)) {
5914       auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5915       // Note that we can't implicitly start the lifetime of a reference,
5916       // so we don't need to proceed any further if we reach one.
5917       if (!FD || FD->getType()->isReferenceType())
5918         break;
5919 
5920       //    ... and also contains A.B if B names a union member ...
5921       if (FD->getParent()->isUnion()) {
5922         //    ... of a non-class, non-array type, or of a class type with a
5923         //    trivial default constructor that is not deleted, or an array of
5924         //    such types.
5925         auto *RD =
5926             FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5927         if (!RD || RD->hasTrivialDefaultConstructor())
5928           UnionPathLengths.push_back({PathLength - 1, FD});
5929       }
5930 
5931       E = ME->getBase();
5932       --PathLength;
5933       assert(declaresSameEntity(FD,
5934                                 LHS.Designator.Entries[PathLength]
5935                                     .getAsBaseOrMember().getPointer()));
5936 
5937       //   -- If E is of the form A[B] and is interpreted as a built-in array
5938       //      subscripting operator, S(E) is [S(the array operand, if any)].
5939     } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5940       // Step over an ArrayToPointerDecay implicit cast.
5941       auto *Base = ASE->getBase()->IgnoreImplicit();
5942       if (!Base->getType()->isArrayType())
5943         break;
5944 
5945       E = Base;
5946       --PathLength;
5947 
5948     } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5949       // Step over a derived-to-base conversion.
5950       E = ICE->getSubExpr();
5951       if (ICE->getCastKind() == CK_NoOp)
5952         continue;
5953       if (ICE->getCastKind() != CK_DerivedToBase &&
5954           ICE->getCastKind() != CK_UncheckedDerivedToBase)
5955         break;
5956       // Walk path backwards as we walk up from the base to the derived class.
5957       for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
5958         --PathLength;
5959         (void)Elt;
5960         assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
5961                                   LHS.Designator.Entries[PathLength]
5962                                       .getAsBaseOrMember().getPointer()));
5963       }
5964 
5965     //   -- Otherwise, S(E) is empty.
5966     } else {
5967       break;
5968     }
5969   }
5970 
5971   // Common case: no unions' lifetimes are started.
5972   if (UnionPathLengths.empty())
5973     return true;
5974 
5975   //   if modification of X [would access an inactive union member], an object
5976   //   of the type of X is implicitly created
5977   CompleteObject Obj =
5978       findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
5979   if (!Obj)
5980     return false;
5981   for (std::pair<unsigned, const FieldDecl *> LengthAndField :
5982            llvm::reverse(UnionPathLengths)) {
5983     // Form a designator for the union object.
5984     SubobjectDesignator D = LHS.Designator;
5985     D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
5986 
5987     bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
5988                       ConstructionPhase::AfterBases;
5989     StartLifetimeOfUnionMemberHandler StartLifetime{
5990         Info, LHSExpr, LengthAndField.second, DuringInit};
5991     if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
5992       return false;
5993   }
5994 
5995   return true;
5996 }
5997 
5998 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
5999                             CallRef Call, EvalInfo &Info,
6000                             bool NonNull = false) {
6001   LValue LV;
6002   // Create the parameter slot and register its destruction. For a vararg
6003   // argument, create a temporary.
6004   // FIXME: For calling conventions that destroy parameters in the callee,
6005   // should we consider performing destruction when the function returns
6006   // instead?
6007   APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6008                    : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6009                                                        ScopeKind::Call, LV);
6010   if (!EvaluateInPlace(V, Info, LV, Arg))
6011     return false;
6012 
6013   // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6014   // undefined behavior, so is non-constant.
6015   if (NonNull && V.isLValue() && V.isNullPointer()) {
6016     Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6017     return false;
6018   }
6019 
6020   return true;
6021 }
6022 
6023 /// Evaluate the arguments to a function call.
6024 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6025                          EvalInfo &Info, const FunctionDecl *Callee,
6026                          bool RightToLeft = false) {
6027   bool Success = true;
6028   llvm::SmallBitVector ForbiddenNullArgs;
6029   if (Callee->hasAttr<NonNullAttr>()) {
6030     ForbiddenNullArgs.resize(Args.size());
6031     for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6032       if (!Attr->args_size()) {
6033         ForbiddenNullArgs.set();
6034         break;
6035       } else
6036         for (auto Idx : Attr->args()) {
6037           unsigned ASTIdx = Idx.getASTIndex();
6038           if (ASTIdx >= Args.size())
6039             continue;
6040           ForbiddenNullArgs[ASTIdx] = 1;
6041         }
6042     }
6043   }
6044   for (unsigned I = 0; I < Args.size(); I++) {
6045     unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6046     const ParmVarDecl *PVD =
6047         Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6048     bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6049     if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) {
6050       // If we're checking for a potential constant expression, evaluate all
6051       // initializers even if some of them fail.
6052       if (!Info.noteFailure())
6053         return false;
6054       Success = false;
6055     }
6056   }
6057   return Success;
6058 }
6059 
6060 /// Perform a trivial copy from Param, which is the parameter of a copy or move
6061 /// constructor or assignment operator.
6062 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6063                               const Expr *E, APValue &Result,
6064                               bool CopyObjectRepresentation) {
6065   // Find the reference argument.
6066   CallStackFrame *Frame = Info.CurrentCall;
6067   APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6068   if (!RefValue) {
6069     Info.FFDiag(E);
6070     return false;
6071   }
6072 
6073   // Copy out the contents of the RHS object.
6074   LValue RefLValue;
6075   RefLValue.setFrom(Info.Ctx, *RefValue);
6076   return handleLValueToRValueConversion(
6077       Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6078       CopyObjectRepresentation);
6079 }
6080 
6081 /// Evaluate a function call.
6082 static bool HandleFunctionCall(SourceLocation CallLoc,
6083                                const FunctionDecl *Callee, const LValue *This,
6084                                ArrayRef<const Expr *> Args, CallRef Call,
6085                                const Stmt *Body, EvalInfo &Info,
6086                                APValue &Result, const LValue *ResultSlot) {
6087   if (!Info.CheckCallLimit(CallLoc))
6088     return false;
6089 
6090   CallStackFrame Frame(Info, CallLoc, Callee, This, Call);
6091 
6092   // For a trivial copy or move assignment, perform an APValue copy. This is
6093   // essential for unions, where the operations performed by the assignment
6094   // operator cannot be represented as statements.
6095   //
6096   // Skip this for non-union classes with no fields; in that case, the defaulted
6097   // copy/move does not actually read the object.
6098   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6099   if (MD && MD->isDefaulted() &&
6100       (MD->getParent()->isUnion() ||
6101        (MD->isTrivial() &&
6102         isReadByLvalueToRvalueConversion(MD->getParent())))) {
6103     assert(This &&
6104            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
6105     APValue RHSValue;
6106     if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6107                            MD->getParent()->isUnion()))
6108       return false;
6109     if (Info.getLangOpts().CPlusPlus20 && MD->isTrivial() &&
6110         !HandleUnionActiveMemberChange(Info, Args[0], *This))
6111       return false;
6112     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
6113                           RHSValue))
6114       return false;
6115     This->moveInto(Result);
6116     return true;
6117   } else if (MD && isLambdaCallOperator(MD)) {
6118     // We're in a lambda; determine the lambda capture field maps unless we're
6119     // just constexpr checking a lambda's call operator. constexpr checking is
6120     // done before the captures have been added to the closure object (unless
6121     // we're inferring constexpr-ness), so we don't have access to them in this
6122     // case. But since we don't need the captures to constexpr check, we can
6123     // just ignore them.
6124     if (!Info.checkingPotentialConstantExpression())
6125       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6126                                         Frame.LambdaThisCaptureField);
6127   }
6128 
6129   StmtResult Ret = {Result, ResultSlot};
6130   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6131   if (ESR == ESR_Succeeded) {
6132     if (Callee->getReturnType()->isVoidType())
6133       return true;
6134     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6135   }
6136   return ESR == ESR_Returned;
6137 }
6138 
6139 /// Evaluate a constructor call.
6140 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6141                                   CallRef Call,
6142                                   const CXXConstructorDecl *Definition,
6143                                   EvalInfo &Info, APValue &Result) {
6144   SourceLocation CallLoc = E->getExprLoc();
6145   if (!Info.CheckCallLimit(CallLoc))
6146     return false;
6147 
6148   const CXXRecordDecl *RD = Definition->getParent();
6149   if (RD->getNumVBases()) {
6150     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6151     return false;
6152   }
6153 
6154   EvalInfo::EvaluatingConstructorRAII EvalObj(
6155       Info,
6156       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6157       RD->getNumBases());
6158   CallStackFrame Frame(Info, CallLoc, Definition, &This, Call);
6159 
6160   // FIXME: Creating an APValue just to hold a nonexistent return value is
6161   // wasteful.
6162   APValue RetVal;
6163   StmtResult Ret = {RetVal, nullptr};
6164 
6165   // If it's a delegating constructor, delegate.
6166   if (Definition->isDelegatingConstructor()) {
6167     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
6168     if ((*I)->getInit()->isValueDependent()) {
6169       if (!EvaluateDependentExpr((*I)->getInit(), Info))
6170         return false;
6171     } else {
6172       FullExpressionRAII InitScope(Info);
6173       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6174           !InitScope.destroy())
6175         return false;
6176     }
6177     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6178   }
6179 
6180   // For a trivial copy or move constructor, perform an APValue copy. This is
6181   // essential for unions (or classes with anonymous union members), where the
6182   // operations performed by the constructor cannot be represented by
6183   // ctor-initializers.
6184   //
6185   // Skip this for empty non-union classes; we should not perform an
6186   // lvalue-to-rvalue conversion on them because their copy constructor does not
6187   // actually read them.
6188   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6189       (Definition->getParent()->isUnion() ||
6190        (Definition->isTrivial() &&
6191         isReadByLvalueToRvalueConversion(Definition->getParent())))) {
6192     return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6193                              Definition->getParent()->isUnion());
6194   }
6195 
6196   // Reserve space for the struct members.
6197   if (!Result.hasValue()) {
6198     if (!RD->isUnion())
6199       Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6200                        std::distance(RD->field_begin(), RD->field_end()));
6201     else
6202       // A union starts with no active member.
6203       Result = APValue((const FieldDecl*)nullptr);
6204   }
6205 
6206   if (RD->isInvalidDecl()) return false;
6207   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6208 
6209   // A scope for temporaries lifetime-extended by reference members.
6210   BlockScopeRAII LifetimeExtendedScope(Info);
6211 
6212   bool Success = true;
6213   unsigned BasesSeen = 0;
6214 #ifndef NDEBUG
6215   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
6216 #endif
6217   CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
6218   auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6219     // We might be initializing the same field again if this is an indirect
6220     // field initialization.
6221     if (FieldIt == RD->field_end() ||
6222         FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6223       assert(Indirect && "fields out of order?");
6224       return;
6225     }
6226 
6227     // Default-initialize any fields with no explicit initializer.
6228     for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6229       assert(FieldIt != RD->field_end() && "missing field?");
6230       if (!FieldIt->isUnnamedBitfield())
6231         Success &= getDefaultInitValue(
6232             FieldIt->getType(),
6233             Result.getStructField(FieldIt->getFieldIndex()));
6234     }
6235     ++FieldIt;
6236   };
6237   for (const auto *I : Definition->inits()) {
6238     LValue Subobject = This;
6239     LValue SubobjectParent = This;
6240     APValue *Value = &Result;
6241 
6242     // Determine the subobject to initialize.
6243     FieldDecl *FD = nullptr;
6244     if (I->isBaseInitializer()) {
6245       QualType BaseType(I->getBaseClass(), 0);
6246 #ifndef NDEBUG
6247       // Non-virtual base classes are initialized in the order in the class
6248       // definition. We have already checked for virtual base classes.
6249       assert(!BaseIt->isVirtual() && "virtual base for literal type");
6250       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
6251              "base class initializers not in expected order");
6252       ++BaseIt;
6253 #endif
6254       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6255                                   BaseType->getAsCXXRecordDecl(), &Layout))
6256         return false;
6257       Value = &Result.getStructBase(BasesSeen++);
6258     } else if ((FD = I->getMember())) {
6259       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6260         return false;
6261       if (RD->isUnion()) {
6262         Result = APValue(FD);
6263         Value = &Result.getUnionValue();
6264       } else {
6265         SkipToField(FD, false);
6266         Value = &Result.getStructField(FD->getFieldIndex());
6267       }
6268     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6269       // Walk the indirect field decl's chain to find the object to initialize,
6270       // and make sure we've initialized every step along it.
6271       auto IndirectFieldChain = IFD->chain();
6272       for (auto *C : IndirectFieldChain) {
6273         FD = cast<FieldDecl>(C);
6274         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6275         // Switch the union field if it differs. This happens if we had
6276         // preceding zero-initialization, and we're now initializing a union
6277         // subobject other than the first.
6278         // FIXME: In this case, the values of the other subobjects are
6279         // specified, since zero-initialization sets all padding bits to zero.
6280         if (!Value->hasValue() ||
6281             (Value->isUnion() && Value->getUnionField() != FD)) {
6282           if (CD->isUnion())
6283             *Value = APValue(FD);
6284           else
6285             // FIXME: This immediately starts the lifetime of all members of
6286             // an anonymous struct. It would be preferable to strictly start
6287             // member lifetime in initialization order.
6288             Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
6289         }
6290         // Store Subobject as its parent before updating it for the last element
6291         // in the chain.
6292         if (C == IndirectFieldChain.back())
6293           SubobjectParent = Subobject;
6294         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6295           return false;
6296         if (CD->isUnion())
6297           Value = &Value->getUnionValue();
6298         else {
6299           if (C == IndirectFieldChain.front() && !RD->isUnion())
6300             SkipToField(FD, true);
6301           Value = &Value->getStructField(FD->getFieldIndex());
6302         }
6303       }
6304     } else {
6305       llvm_unreachable("unknown base initializer kind");
6306     }
6307 
6308     // Need to override This for implicit field initializers as in this case
6309     // This refers to innermost anonymous struct/union containing initializer,
6310     // not to currently constructed class.
6311     const Expr *Init = I->getInit();
6312     if (Init->isValueDependent()) {
6313       if (!EvaluateDependentExpr(Init, Info))
6314         return false;
6315     } else {
6316       ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6317                                     isa<CXXDefaultInitExpr>(Init));
6318       FullExpressionRAII InitScope(Info);
6319       if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6320           (FD && FD->isBitField() &&
6321            !truncateBitfieldValue(Info, Init, *Value, FD))) {
6322         // If we're checking for a potential constant expression, evaluate all
6323         // initializers even if some of them fail.
6324         if (!Info.noteFailure())
6325           return false;
6326         Success = false;
6327       }
6328     }
6329 
6330     // This is the point at which the dynamic type of the object becomes this
6331     // class type.
6332     if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6333       EvalObj.finishedConstructingBases();
6334   }
6335 
6336   // Default-initialize any remaining fields.
6337   if (!RD->isUnion()) {
6338     for (; FieldIt != RD->field_end(); ++FieldIt) {
6339       if (!FieldIt->isUnnamedBitfield())
6340         Success &= getDefaultInitValue(
6341             FieldIt->getType(),
6342             Result.getStructField(FieldIt->getFieldIndex()));
6343     }
6344   }
6345 
6346   EvalObj.finishedConstructingFields();
6347 
6348   return Success &&
6349          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6350          LifetimeExtendedScope.destroy();
6351 }
6352 
6353 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6354                                   ArrayRef<const Expr*> Args,
6355                                   const CXXConstructorDecl *Definition,
6356                                   EvalInfo &Info, APValue &Result) {
6357   CallScopeRAII CallScope(Info);
6358   CallRef Call = Info.CurrentCall->createCall(Definition);
6359   if (!EvaluateArgs(Args, Call, Info, Definition))
6360     return false;
6361 
6362   return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6363          CallScope.destroy();
6364 }
6365 
6366 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
6367                                   const LValue &This, APValue &Value,
6368                                   QualType T) {
6369   // Objects can only be destroyed while they're within their lifetimes.
6370   // FIXME: We have no representation for whether an object of type nullptr_t
6371   // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6372   // as indeterminate instead?
6373   if (Value.isAbsent() && !T->isNullPtrType()) {
6374     APValue Printable;
6375     This.moveInto(Printable);
6376     Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
6377       << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6378     return false;
6379   }
6380 
6381   // Invent an expression for location purposes.
6382   // FIXME: We shouldn't need to do this.
6383   OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_PRValue);
6384 
6385   // For arrays, destroy elements right-to-left.
6386   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6387     uint64_t Size = CAT->getSize().getZExtValue();
6388     QualType ElemT = CAT->getElementType();
6389 
6390     LValue ElemLV = This;
6391     ElemLV.addArray(Info, &LocE, CAT);
6392     if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6393       return false;
6394 
6395     // Ensure that we have actual array elements available to destroy; the
6396     // destructors might mutate the value, so we can't run them on the array
6397     // filler.
6398     if (Size && Size > Value.getArrayInitializedElts())
6399       expandArray(Value, Value.getArraySize() - 1);
6400 
6401     for (; Size != 0; --Size) {
6402       APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6403       if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6404           !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
6405         return false;
6406     }
6407 
6408     // End the lifetime of this array now.
6409     Value = APValue();
6410     return true;
6411   }
6412 
6413   const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6414   if (!RD) {
6415     if (T.isDestructedType()) {
6416       Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
6417       return false;
6418     }
6419 
6420     Value = APValue();
6421     return true;
6422   }
6423 
6424   if (RD->getNumVBases()) {
6425     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6426     return false;
6427   }
6428 
6429   const CXXDestructorDecl *DD = RD->getDestructor();
6430   if (!DD && !RD->hasTrivialDestructor()) {
6431     Info.FFDiag(CallLoc);
6432     return false;
6433   }
6434 
6435   if (!DD || DD->isTrivial() ||
6436       (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6437     // A trivial destructor just ends the lifetime of the object. Check for
6438     // this case before checking for a body, because we might not bother
6439     // building a body for a trivial destructor. Note that it doesn't matter
6440     // whether the destructor is constexpr in this case; all trivial
6441     // destructors are constexpr.
6442     //
6443     // If an anonymous union would be destroyed, some enclosing destructor must
6444     // have been explicitly defined, and the anonymous union destruction should
6445     // have no effect.
6446     Value = APValue();
6447     return true;
6448   }
6449 
6450   if (!Info.CheckCallLimit(CallLoc))
6451     return false;
6452 
6453   const FunctionDecl *Definition = nullptr;
6454   const Stmt *Body = DD->getBody(Definition);
6455 
6456   if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
6457     return false;
6458 
6459   CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef());
6460 
6461   // We're now in the period of destruction of this object.
6462   unsigned BasesLeft = RD->getNumBases();
6463   EvalInfo::EvaluatingDestructorRAII EvalObj(
6464       Info,
6465       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6466   if (!EvalObj.DidInsert) {
6467     // C++2a [class.dtor]p19:
6468     //   the behavior is undefined if the destructor is invoked for an object
6469     //   whose lifetime has ended
6470     // (Note that formally the lifetime ends when the period of destruction
6471     // begins, even though certain uses of the object remain valid until the
6472     // period of destruction ends.)
6473     Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
6474     return false;
6475   }
6476 
6477   // FIXME: Creating an APValue just to hold a nonexistent return value is
6478   // wasteful.
6479   APValue RetVal;
6480   StmtResult Ret = {RetVal, nullptr};
6481   if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6482     return false;
6483 
6484   // A union destructor does not implicitly destroy its members.
6485   if (RD->isUnion())
6486     return true;
6487 
6488   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6489 
6490   // We don't have a good way to iterate fields in reverse, so collect all the
6491   // fields first and then walk them backwards.
6492   SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
6493   for (const FieldDecl *FD : llvm::reverse(Fields)) {
6494     if (FD->isUnnamedBitfield())
6495       continue;
6496 
6497     LValue Subobject = This;
6498     if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6499       return false;
6500 
6501     APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6502     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6503                                FD->getType()))
6504       return false;
6505   }
6506 
6507   if (BasesLeft != 0)
6508     EvalObj.startedDestroyingBases();
6509 
6510   // Destroy base classes in reverse order.
6511   for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6512     --BasesLeft;
6513 
6514     QualType BaseType = Base.getType();
6515     LValue Subobject = This;
6516     if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
6517                                 BaseType->getAsCXXRecordDecl(), &Layout))
6518       return false;
6519 
6520     APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
6521     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6522                                BaseType))
6523       return false;
6524   }
6525   assert(BasesLeft == 0 && "NumBases was wrong?");
6526 
6527   // The period of destruction ends now. The object is gone.
6528   Value = APValue();
6529   return true;
6530 }
6531 
6532 namespace {
6533 struct DestroyObjectHandler {
6534   EvalInfo &Info;
6535   const Expr *E;
6536   const LValue &This;
6537   const AccessKinds AccessKind;
6538 
6539   typedef bool result_type;
6540   bool failed() { return false; }
6541   bool found(APValue &Subobj, QualType SubobjType) {
6542     return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
6543                                  SubobjType);
6544   }
6545   bool found(APSInt &Value, QualType SubobjType) {
6546     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6547     return false;
6548   }
6549   bool found(APFloat &Value, QualType SubobjType) {
6550     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6551     return false;
6552   }
6553 };
6554 }
6555 
6556 /// Perform a destructor or pseudo-destructor call on the given object, which
6557 /// might in general not be a complete object.
6558 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6559                               const LValue &This, QualType ThisType) {
6560   CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6561   DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6562   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6563 }
6564 
6565 /// Destroy and end the lifetime of the given complete object.
6566 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6567                               APValue::LValueBase LVBase, APValue &Value,
6568                               QualType T) {
6569   // If we've had an unmodeled side-effect, we can't rely on mutable state
6570   // (such as the object we're about to destroy) being correct.
6571   if (Info.EvalStatus.HasSideEffects)
6572     return false;
6573 
6574   LValue LV;
6575   LV.set({LVBase});
6576   return HandleDestructionImpl(Info, Loc, LV, Value, T);
6577 }
6578 
6579 /// Perform a call to 'perator new' or to `__builtin_operator_new'.
6580 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6581                                   LValue &Result) {
6582   if (Info.checkingPotentialConstantExpression() ||
6583       Info.SpeculativeEvaluationDepth)
6584     return false;
6585 
6586   // This is permitted only within a call to std::allocator<T>::allocate.
6587   auto Caller = Info.getStdAllocatorCaller("allocate");
6588   if (!Caller) {
6589     Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
6590                                      ? diag::note_constexpr_new_untyped
6591                                      : diag::note_constexpr_new);
6592     return false;
6593   }
6594 
6595   QualType ElemType = Caller.ElemType;
6596   if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6597     Info.FFDiag(E->getExprLoc(),
6598                 diag::note_constexpr_new_not_complete_object_type)
6599         << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6600     return false;
6601   }
6602 
6603   APSInt ByteSize;
6604   if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6605     return false;
6606   bool IsNothrow = false;
6607   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6608     EvaluateIgnoredValue(Info, E->getArg(I));
6609     IsNothrow |= E->getType()->isNothrowT();
6610   }
6611 
6612   CharUnits ElemSize;
6613   if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6614     return false;
6615   APInt Size, Remainder;
6616   APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6617   APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6618   if (Remainder != 0) {
6619     // This likely indicates a bug in the implementation of 'std::allocator'.
6620     Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6621         << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6622     return false;
6623   }
6624 
6625   if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
6626     if (IsNothrow) {
6627       Result.setNull(Info.Ctx, E->getType());
6628       return true;
6629     }
6630 
6631     Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
6632     return false;
6633   }
6634 
6635   QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
6636                                                      ArrayType::Normal, 0);
6637   APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6638   *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6639   Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6640   return true;
6641 }
6642 
6643 static bool hasVirtualDestructor(QualType T) {
6644   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6645     if (CXXDestructorDecl *DD = RD->getDestructor())
6646       return DD->isVirtual();
6647   return false;
6648 }
6649 
6650 static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6651   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6652     if (CXXDestructorDecl *DD = RD->getDestructor())
6653       return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6654   return nullptr;
6655 }
6656 
6657 /// Check that the given object is a suitable pointer to a heap allocation that
6658 /// still exists and is of the right kind for the purpose of a deletion.
6659 ///
6660 /// On success, returns the heap allocation to deallocate. On failure, produces
6661 /// a diagnostic and returns None.
6662 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6663                                             const LValue &Pointer,
6664                                             DynAlloc::Kind DeallocKind) {
6665   auto PointerAsString = [&] {
6666     return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6667   };
6668 
6669   DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6670   if (!DA) {
6671     Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6672         << PointerAsString();
6673     if (Pointer.Base)
6674       NoteLValueLocation(Info, Pointer.Base);
6675     return None;
6676   }
6677 
6678   Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6679   if (!Alloc) {
6680     Info.FFDiag(E, diag::note_constexpr_double_delete);
6681     return None;
6682   }
6683 
6684   QualType AllocType = Pointer.Base.getDynamicAllocType();
6685   if (DeallocKind != (*Alloc)->getKind()) {
6686     Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6687         << DeallocKind << (*Alloc)->getKind() << AllocType;
6688     NoteLValueLocation(Info, Pointer.Base);
6689     return None;
6690   }
6691 
6692   bool Subobject = false;
6693   if (DeallocKind == DynAlloc::New) {
6694     Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6695                 Pointer.Designator.isOnePastTheEnd();
6696   } else {
6697     Subobject = Pointer.Designator.Entries.size() != 1 ||
6698                 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6699   }
6700   if (Subobject) {
6701     Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6702         << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6703     return None;
6704   }
6705 
6706   return Alloc;
6707 }
6708 
6709 // Perform a call to 'operator delete' or '__builtin_operator_delete'.
6710 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6711   if (Info.checkingPotentialConstantExpression() ||
6712       Info.SpeculativeEvaluationDepth)
6713     return false;
6714 
6715   // This is permitted only within a call to std::allocator<T>::deallocate.
6716   if (!Info.getStdAllocatorCaller("deallocate")) {
6717     Info.FFDiag(E->getExprLoc());
6718     return true;
6719   }
6720 
6721   LValue Pointer;
6722   if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6723     return false;
6724   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6725     EvaluateIgnoredValue(Info, E->getArg(I));
6726 
6727   if (Pointer.Designator.Invalid)
6728     return false;
6729 
6730   // Deleting a null pointer would have no effect, but it's not permitted by
6731   // std::allocator<T>::deallocate's contract.
6732   if (Pointer.isNullPointer()) {
6733     Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
6734     return true;
6735   }
6736 
6737   if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6738     return false;
6739 
6740   Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6741   return true;
6742 }
6743 
6744 //===----------------------------------------------------------------------===//
6745 // Generic Evaluation
6746 //===----------------------------------------------------------------------===//
6747 namespace {
6748 
6749 class BitCastBuffer {
6750   // FIXME: We're going to need bit-level granularity when we support
6751   // bit-fields.
6752   // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6753   // we don't support a host or target where that is the case. Still, we should
6754   // use a more generic type in case we ever do.
6755   SmallVector<Optional<unsigned char>, 32> Bytes;
6756 
6757   static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6758                 "Need at least 8 bit unsigned char");
6759 
6760   bool TargetIsLittleEndian;
6761 
6762 public:
6763   BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6764       : Bytes(Width.getQuantity()),
6765         TargetIsLittleEndian(TargetIsLittleEndian) {}
6766 
6767   LLVM_NODISCARD
6768   bool readObject(CharUnits Offset, CharUnits Width,
6769                   SmallVectorImpl<unsigned char> &Output) const {
6770     for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6771       // If a byte of an integer is uninitialized, then the whole integer is
6772       // uninitialized.
6773       if (!Bytes[I.getQuantity()])
6774         return false;
6775       Output.push_back(*Bytes[I.getQuantity()]);
6776     }
6777     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6778       std::reverse(Output.begin(), Output.end());
6779     return true;
6780   }
6781 
6782   void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6783     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6784       std::reverse(Input.begin(), Input.end());
6785 
6786     size_t Index = 0;
6787     for (unsigned char Byte : Input) {
6788       assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
6789       Bytes[Offset.getQuantity() + Index] = Byte;
6790       ++Index;
6791     }
6792   }
6793 
6794   size_t size() { return Bytes.size(); }
6795 };
6796 
6797 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6798 /// target would represent the value at runtime.
6799 class APValueToBufferConverter {
6800   EvalInfo &Info;
6801   BitCastBuffer Buffer;
6802   const CastExpr *BCE;
6803 
6804   APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6805                            const CastExpr *BCE)
6806       : Info(Info),
6807         Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6808         BCE(BCE) {}
6809 
6810   bool visit(const APValue &Val, QualType Ty) {
6811     return visit(Val, Ty, CharUnits::fromQuantity(0));
6812   }
6813 
6814   // Write out Val with type Ty into Buffer starting at Offset.
6815   bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6816     assert((size_t)Offset.getQuantity() <= Buffer.size());
6817 
6818     // As a special case, nullptr_t has an indeterminate value.
6819     if (Ty->isNullPtrType())
6820       return true;
6821 
6822     // Dig through Src to find the byte at SrcOffset.
6823     switch (Val.getKind()) {
6824     case APValue::Indeterminate:
6825     case APValue::None:
6826       return true;
6827 
6828     case APValue::Int:
6829       return visitInt(Val.getInt(), Ty, Offset);
6830     case APValue::Float:
6831       return visitFloat(Val.getFloat(), Ty, Offset);
6832     case APValue::Array:
6833       return visitArray(Val, Ty, Offset);
6834     case APValue::Struct:
6835       return visitRecord(Val, Ty, Offset);
6836 
6837     case APValue::ComplexInt:
6838     case APValue::ComplexFloat:
6839     case APValue::Vector:
6840     case APValue::FixedPoint:
6841       // FIXME: We should support these.
6842 
6843     case APValue::Union:
6844     case APValue::MemberPointer:
6845     case APValue::AddrLabelDiff: {
6846       Info.FFDiag(BCE->getBeginLoc(),
6847                   diag::note_constexpr_bit_cast_unsupported_type)
6848           << Ty;
6849       return false;
6850     }
6851 
6852     case APValue::LValue:
6853       llvm_unreachable("LValue subobject in bit_cast?");
6854     }
6855     llvm_unreachable("Unhandled APValue::ValueKind");
6856   }
6857 
6858   bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
6859     const RecordDecl *RD = Ty->getAsRecordDecl();
6860     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6861 
6862     // Visit the base classes.
6863     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6864       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6865         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6866         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6867 
6868         if (!visitRecord(Val.getStructBase(I), BS.getType(),
6869                          Layout.getBaseClassOffset(BaseDecl) + Offset))
6870           return false;
6871       }
6872     }
6873 
6874     // Visit the fields.
6875     unsigned FieldIdx = 0;
6876     for (FieldDecl *FD : RD->fields()) {
6877       if (FD->isBitField()) {
6878         Info.FFDiag(BCE->getBeginLoc(),
6879                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6880         return false;
6881       }
6882 
6883       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6884 
6885       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
6886              "only bit-fields can have sub-char alignment");
6887       CharUnits FieldOffset =
6888           Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
6889       QualType FieldTy = FD->getType();
6890       if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
6891         return false;
6892       ++FieldIdx;
6893     }
6894 
6895     return true;
6896   }
6897 
6898   bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
6899     const auto *CAT =
6900         dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
6901     if (!CAT)
6902       return false;
6903 
6904     CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
6905     unsigned NumInitializedElts = Val.getArrayInitializedElts();
6906     unsigned ArraySize = Val.getArraySize();
6907     // First, initialize the initialized elements.
6908     for (unsigned I = 0; I != NumInitializedElts; ++I) {
6909       const APValue &SubObj = Val.getArrayInitializedElt(I);
6910       if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
6911         return false;
6912     }
6913 
6914     // Next, initialize the rest of the array using the filler.
6915     if (Val.hasArrayFiller()) {
6916       const APValue &Filler = Val.getArrayFiller();
6917       for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
6918         if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
6919           return false;
6920       }
6921     }
6922 
6923     return true;
6924   }
6925 
6926   bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
6927     APSInt AdjustedVal = Val;
6928     unsigned Width = AdjustedVal.getBitWidth();
6929     if (Ty->isBooleanType()) {
6930       Width = Info.Ctx.getTypeSize(Ty);
6931       AdjustedVal = AdjustedVal.extend(Width);
6932     }
6933 
6934     SmallVector<unsigned char, 8> Bytes(Width / 8);
6935     llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
6936     Buffer.writeObject(Offset, Bytes);
6937     return true;
6938   }
6939 
6940   bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
6941     APSInt AsInt(Val.bitcastToAPInt());
6942     return visitInt(AsInt, Ty, Offset);
6943   }
6944 
6945 public:
6946   static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
6947                                          const CastExpr *BCE) {
6948     CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
6949     APValueToBufferConverter Converter(Info, DstSize, BCE);
6950     if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
6951       return None;
6952     return Converter.Buffer;
6953   }
6954 };
6955 
6956 /// Write an BitCastBuffer into an APValue.
6957 class BufferToAPValueConverter {
6958   EvalInfo &Info;
6959   const BitCastBuffer &Buffer;
6960   const CastExpr *BCE;
6961 
6962   BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
6963                            const CastExpr *BCE)
6964       : Info(Info), Buffer(Buffer), BCE(BCE) {}
6965 
6966   // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
6967   // with an invalid type, so anything left is a deficiency on our part (FIXME).
6968   // Ideally this will be unreachable.
6969   llvm::NoneType unsupportedType(QualType Ty) {
6970     Info.FFDiag(BCE->getBeginLoc(),
6971                 diag::note_constexpr_bit_cast_unsupported_type)
6972         << Ty;
6973     return None;
6974   }
6975 
6976   llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) {
6977     Info.FFDiag(BCE->getBeginLoc(),
6978                 diag::note_constexpr_bit_cast_unrepresentable_value)
6979         << Ty << toString(Val, /*Radix=*/10);
6980     return None;
6981   }
6982 
6983   Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
6984                           const EnumType *EnumSugar = nullptr) {
6985     if (T->isNullPtrType()) {
6986       uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
6987       return APValue((Expr *)nullptr,
6988                      /*Offset=*/CharUnits::fromQuantity(NullValue),
6989                      APValue::NoLValuePath{}, /*IsNullPtr=*/true);
6990     }
6991 
6992     CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
6993 
6994     // Work around floating point types that contain unused padding bytes. This
6995     // is really just `long double` on x86, which is the only fundamental type
6996     // with padding bytes.
6997     if (T->isRealFloatingType()) {
6998       const llvm::fltSemantics &Semantics =
6999           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7000       unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
7001       assert(NumBits % 8 == 0);
7002       CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
7003       if (NumBytes != SizeOf)
7004         SizeOf = NumBytes;
7005     }
7006 
7007     SmallVector<uint8_t, 8> Bytes;
7008     if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
7009       // If this is std::byte or unsigned char, then its okay to store an
7010       // indeterminate value.
7011       bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
7012       bool IsUChar =
7013           !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
7014                          T->isSpecificBuiltinType(BuiltinType::Char_U));
7015       if (!IsStdByte && !IsUChar) {
7016         QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
7017         Info.FFDiag(BCE->getExprLoc(),
7018                     diag::note_constexpr_bit_cast_indet_dest)
7019             << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
7020         return None;
7021       }
7022 
7023       return APValue::IndeterminateValue();
7024     }
7025 
7026     APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
7027     llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
7028 
7029     if (T->isIntegralOrEnumerationType()) {
7030       Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7031 
7032       unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
7033       if (IntWidth != Val.getBitWidth()) {
7034         APSInt Truncated = Val.trunc(IntWidth);
7035         if (Truncated.extend(Val.getBitWidth()) != Val)
7036           return unrepresentableValue(QualType(T, 0), Val);
7037         Val = Truncated;
7038       }
7039 
7040       return APValue(Val);
7041     }
7042 
7043     if (T->isRealFloatingType()) {
7044       const llvm::fltSemantics &Semantics =
7045           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7046       return APValue(APFloat(Semantics, Val));
7047     }
7048 
7049     return unsupportedType(QualType(T, 0));
7050   }
7051 
7052   Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7053     const RecordDecl *RD = RTy->getAsRecordDecl();
7054     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7055 
7056     unsigned NumBases = 0;
7057     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7058       NumBases = CXXRD->getNumBases();
7059 
7060     APValue ResultVal(APValue::UninitStruct(), NumBases,
7061                       std::distance(RD->field_begin(), RD->field_end()));
7062 
7063     // Visit the base classes.
7064     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7065       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7066         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7067         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7068         if (BaseDecl->isEmpty() ||
7069             Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
7070           continue;
7071 
7072         Optional<APValue> SubObj = visitType(
7073             BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7074         if (!SubObj)
7075           return None;
7076         ResultVal.getStructBase(I) = *SubObj;
7077       }
7078     }
7079 
7080     // Visit the fields.
7081     unsigned FieldIdx = 0;
7082     for (FieldDecl *FD : RD->fields()) {
7083       // FIXME: We don't currently support bit-fields. A lot of the logic for
7084       // this is in CodeGen, so we need to factor it around.
7085       if (FD->isBitField()) {
7086         Info.FFDiag(BCE->getBeginLoc(),
7087                     diag::note_constexpr_bit_cast_unsupported_bitfield);
7088         return None;
7089       }
7090 
7091       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7092       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
7093 
7094       CharUnits FieldOffset =
7095           CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7096           Offset;
7097       QualType FieldTy = FD->getType();
7098       Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7099       if (!SubObj)
7100         return None;
7101       ResultVal.getStructField(FieldIdx) = *SubObj;
7102       ++FieldIdx;
7103     }
7104 
7105     return ResultVal;
7106   }
7107 
7108   Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7109     QualType RepresentationType = Ty->getDecl()->getIntegerType();
7110     assert(!RepresentationType.isNull() &&
7111            "enum forward decl should be caught by Sema");
7112     const auto *AsBuiltin =
7113         RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7114     // Recurse into the underlying type. Treat std::byte transparently as
7115     // unsigned char.
7116     return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7117   }
7118 
7119   Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7120     size_t Size = Ty->getSize().getLimitedValue();
7121     CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7122 
7123     APValue ArrayValue(APValue::UninitArray(), Size, Size);
7124     for (size_t I = 0; I != Size; ++I) {
7125       Optional<APValue> ElementValue =
7126           visitType(Ty->getElementType(), Offset + I * ElementWidth);
7127       if (!ElementValue)
7128         return None;
7129       ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7130     }
7131 
7132     return ArrayValue;
7133   }
7134 
7135   Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7136     return unsupportedType(QualType(Ty, 0));
7137   }
7138 
7139   Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7140     QualType Can = Ty.getCanonicalType();
7141 
7142     switch (Can->getTypeClass()) {
7143 #define TYPE(Class, Base)                                                      \
7144   case Type::Class:                                                            \
7145     return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7146 #define ABSTRACT_TYPE(Class, Base)
7147 #define NON_CANONICAL_TYPE(Class, Base)                                        \
7148   case Type::Class:                                                            \
7149     llvm_unreachable("non-canonical type should be impossible!");
7150 #define DEPENDENT_TYPE(Class, Base)                                            \
7151   case Type::Class:                                                            \
7152     llvm_unreachable(                                                          \
7153         "dependent types aren't supported in the constant evaluator!");
7154 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)                            \
7155   case Type::Class:                                                            \
7156     llvm_unreachable("either dependent or not canonical!");
7157 #include "clang/AST/TypeNodes.inc"
7158     }
7159     llvm_unreachable("Unhandled Type::TypeClass");
7160   }
7161 
7162 public:
7163   // Pull out a full value of type DstType.
7164   static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7165                                    const CastExpr *BCE) {
7166     BufferToAPValueConverter Converter(Info, Buffer, BCE);
7167     return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7168   }
7169 };
7170 
7171 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7172                                                  QualType Ty, EvalInfo *Info,
7173                                                  const ASTContext &Ctx,
7174                                                  bool CheckingDest) {
7175   Ty = Ty.getCanonicalType();
7176 
7177   auto diag = [&](int Reason) {
7178     if (Info)
7179       Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7180           << CheckingDest << (Reason == 4) << Reason;
7181     return false;
7182   };
7183   auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7184     if (Info)
7185       Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7186           << NoteTy << Construct << Ty;
7187     return false;
7188   };
7189 
7190   if (Ty->isUnionType())
7191     return diag(0);
7192   if (Ty->isPointerType())
7193     return diag(1);
7194   if (Ty->isMemberPointerType())
7195     return diag(2);
7196   if (Ty.isVolatileQualified())
7197     return diag(3);
7198 
7199   if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7200     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7201       for (CXXBaseSpecifier &BS : CXXRD->bases())
7202         if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7203                                                   CheckingDest))
7204           return note(1, BS.getType(), BS.getBeginLoc());
7205     }
7206     for (FieldDecl *FD : Record->fields()) {
7207       if (FD->getType()->isReferenceType())
7208         return diag(4);
7209       if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7210                                                 CheckingDest))
7211         return note(0, FD->getType(), FD->getBeginLoc());
7212     }
7213   }
7214 
7215   if (Ty->isArrayType() &&
7216       !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7217                                             Info, Ctx, CheckingDest))
7218     return false;
7219 
7220   return true;
7221 }
7222 
7223 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
7224                                              const ASTContext &Ctx,
7225                                              const CastExpr *BCE) {
7226   bool DestOK = checkBitCastConstexprEligibilityType(
7227       BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
7228   bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
7229                                 BCE->getBeginLoc(),
7230                                 BCE->getSubExpr()->getType(), Info, Ctx, false);
7231   return SourceOK;
7232 }
7233 
7234 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7235                                         APValue &SourceValue,
7236                                         const CastExpr *BCE) {
7237   assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7238          "no host or target supports non 8-bit chars");
7239   assert(SourceValue.isLValue() &&
7240          "LValueToRValueBitcast requires an lvalue operand!");
7241 
7242   if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
7243     return false;
7244 
7245   LValue SourceLValue;
7246   APValue SourceRValue;
7247   SourceLValue.setFrom(Info.Ctx, SourceValue);
7248   if (!handleLValueToRValueConversion(
7249           Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
7250           SourceRValue, /*WantObjectRepresentation=*/true))
7251     return false;
7252 
7253   // Read out SourceValue into a char buffer.
7254   Optional<BitCastBuffer> Buffer =
7255       APValueToBufferConverter::convert(Info, SourceRValue, BCE);
7256   if (!Buffer)
7257     return false;
7258 
7259   // Write out the buffer into a new APValue.
7260   Optional<APValue> MaybeDestValue =
7261       BufferToAPValueConverter::convert(Info, *Buffer, BCE);
7262   if (!MaybeDestValue)
7263     return false;
7264 
7265   DestValue = std::move(*MaybeDestValue);
7266   return true;
7267 }
7268 
7269 template <class Derived>
7270 class ExprEvaluatorBase
7271   : public ConstStmtVisitor<Derived, bool> {
7272 private:
7273   Derived &getDerived() { return static_cast<Derived&>(*this); }
7274   bool DerivedSuccess(const APValue &V, const Expr *E) {
7275     return getDerived().Success(V, E);
7276   }
7277   bool DerivedZeroInitialization(const Expr *E) {
7278     return getDerived().ZeroInitialization(E);
7279   }
7280 
7281   // Check whether a conditional operator with a non-constant condition is a
7282   // potential constant expression. If neither arm is a potential constant
7283   // expression, then the conditional operator is not either.
7284   template<typename ConditionalOperator>
7285   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7286     assert(Info.checkingPotentialConstantExpression());
7287 
7288     // Speculatively evaluate both arms.
7289     SmallVector<PartialDiagnosticAt, 8> Diag;
7290     {
7291       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7292       StmtVisitorTy::Visit(E->getFalseExpr());
7293       if (Diag.empty())
7294         return;
7295     }
7296 
7297     {
7298       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7299       Diag.clear();
7300       StmtVisitorTy::Visit(E->getTrueExpr());
7301       if (Diag.empty())
7302         return;
7303     }
7304 
7305     Error(E, diag::note_constexpr_conditional_never_const);
7306   }
7307 
7308 
7309   template<typename ConditionalOperator>
7310   bool HandleConditionalOperator(const ConditionalOperator *E) {
7311     bool BoolResult;
7312     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7313       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7314         CheckPotentialConstantConditional(E);
7315         return false;
7316       }
7317       if (Info.noteFailure()) {
7318         StmtVisitorTy::Visit(E->getTrueExpr());
7319         StmtVisitorTy::Visit(E->getFalseExpr());
7320       }
7321       return false;
7322     }
7323 
7324     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
7325     return StmtVisitorTy::Visit(EvalExpr);
7326   }
7327 
7328 protected:
7329   EvalInfo &Info;
7330   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
7331   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
7332 
7333   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7334     return Info.CCEDiag(E, D);
7335   }
7336 
7337   bool ZeroInitialization(const Expr *E) { return Error(E); }
7338 
7339 public:
7340   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
7341 
7342   EvalInfo &getEvalInfo() { return Info; }
7343 
7344   /// Report an evaluation error. This should only be called when an error is
7345   /// first discovered. When propagating an error, just return false.
7346   bool Error(const Expr *E, diag::kind D) {
7347     Info.FFDiag(E, D);
7348     return false;
7349   }
7350   bool Error(const Expr *E) {
7351     return Error(E, diag::note_invalid_subexpr_in_const_expr);
7352   }
7353 
7354   bool VisitStmt(const Stmt *) {
7355     llvm_unreachable("Expression evaluator should not be called on stmts");
7356   }
7357   bool VisitExpr(const Expr *E) {
7358     return Error(E);
7359   }
7360 
7361   bool VisitConstantExpr(const ConstantExpr *E) {
7362     if (E->hasAPValueResult())
7363       return DerivedSuccess(E->getAPValueResult(), E);
7364 
7365     return StmtVisitorTy::Visit(E->getSubExpr());
7366   }
7367 
7368   bool VisitParenExpr(const ParenExpr *E)
7369     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7370   bool VisitUnaryExtension(const UnaryOperator *E)
7371     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7372   bool VisitUnaryPlus(const UnaryOperator *E)
7373     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7374   bool VisitChooseExpr(const ChooseExpr *E)
7375     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
7376   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
7377     { return StmtVisitorTy::Visit(E->getResultExpr()); }
7378   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
7379     { return StmtVisitorTy::Visit(E->getReplacement()); }
7380   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7381     TempVersionRAII RAII(*Info.CurrentCall);
7382     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7383     return StmtVisitorTy::Visit(E->getExpr());
7384   }
7385   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7386     TempVersionRAII RAII(*Info.CurrentCall);
7387     // The initializer may not have been parsed yet, or might be erroneous.
7388     if (!E->getExpr())
7389       return Error(E);
7390     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7391     return StmtVisitorTy::Visit(E->getExpr());
7392   }
7393 
7394   bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7395     FullExpressionRAII Scope(Info);
7396     return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
7397   }
7398 
7399   // Temporaries are registered when created, so we don't care about
7400   // CXXBindTemporaryExpr.
7401   bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7402     return StmtVisitorTy::Visit(E->getSubExpr());
7403   }
7404 
7405   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7406     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7407     return static_cast<Derived*>(this)->VisitCastExpr(E);
7408   }
7409   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7410     if (!Info.Ctx.getLangOpts().CPlusPlus20)
7411       CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
7412     return static_cast<Derived*>(this)->VisitCastExpr(E);
7413   }
7414   bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7415     return static_cast<Derived*>(this)->VisitCastExpr(E);
7416   }
7417 
7418   bool VisitBinaryOperator(const BinaryOperator *E) {
7419     switch (E->getOpcode()) {
7420     default:
7421       return Error(E);
7422 
7423     case BO_Comma:
7424       VisitIgnoredValue(E->getLHS());
7425       return StmtVisitorTy::Visit(E->getRHS());
7426 
7427     case BO_PtrMemD:
7428     case BO_PtrMemI: {
7429       LValue Obj;
7430       if (!HandleMemberPointerAccess(Info, E, Obj))
7431         return false;
7432       APValue Result;
7433       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7434         return false;
7435       return DerivedSuccess(Result, E);
7436     }
7437     }
7438   }
7439 
7440   bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
7441     return StmtVisitorTy::Visit(E->getSemanticForm());
7442   }
7443 
7444   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7445     // Evaluate and cache the common expression. We treat it as a temporary,
7446     // even though it's not quite the same thing.
7447     LValue CommonLV;
7448     if (!Evaluate(Info.CurrentCall->createTemporary(
7449                       E->getOpaqueValue(),
7450                       getStorageType(Info.Ctx, E->getOpaqueValue()),
7451                       ScopeKind::FullExpression, CommonLV),
7452                   Info, E->getCommon()))
7453       return false;
7454 
7455     return HandleConditionalOperator(E);
7456   }
7457 
7458   bool VisitConditionalOperator(const ConditionalOperator *E) {
7459     bool IsBcpCall = false;
7460     // If the condition (ignoring parens) is a __builtin_constant_p call,
7461     // the result is a constant expression if it can be folded without
7462     // side-effects. This is an important GNU extension. See GCC PR38377
7463     // for discussion.
7464     if (const CallExpr *CallCE =
7465           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7466       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7467         IsBcpCall = true;
7468 
7469     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7470     // constant expression; we can't check whether it's potentially foldable.
7471     // FIXME: We should instead treat __builtin_constant_p as non-constant if
7472     // it would return 'false' in this mode.
7473     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
7474       return false;
7475 
7476     FoldConstant Fold(Info, IsBcpCall);
7477     if (!HandleConditionalOperator(E)) {
7478       Fold.keepDiagnostics();
7479       return false;
7480     }
7481 
7482     return true;
7483   }
7484 
7485   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7486     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
7487       return DerivedSuccess(*Value, E);
7488 
7489     const Expr *Source = E->getSourceExpr();
7490     if (!Source)
7491       return Error(E);
7492     if (Source == E) {
7493       assert(0 && "OpaqueValueExpr recursively refers to itself");
7494       return Error(E);
7495     }
7496     return StmtVisitorTy::Visit(Source);
7497   }
7498 
7499   bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7500     for (const Expr *SemE : E->semantics()) {
7501       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7502         // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7503         // result expression: there could be two different LValues that would
7504         // refer to the same object in that case, and we can't model that.
7505         if (SemE == E->getResultExpr())
7506           return Error(E);
7507 
7508         // Unique OVEs get evaluated if and when we encounter them when
7509         // emitting the rest of the semantic form, rather than eagerly.
7510         if (OVE->isUnique())
7511           continue;
7512 
7513         LValue LV;
7514         if (!Evaluate(Info.CurrentCall->createTemporary(
7515                           OVE, getStorageType(Info.Ctx, OVE),
7516                           ScopeKind::FullExpression, LV),
7517                       Info, OVE->getSourceExpr()))
7518           return false;
7519       } else if (SemE == E->getResultExpr()) {
7520         if (!StmtVisitorTy::Visit(SemE))
7521           return false;
7522       } else {
7523         if (!EvaluateIgnoredValue(Info, SemE))
7524           return false;
7525       }
7526     }
7527     return true;
7528   }
7529 
7530   bool VisitCallExpr(const CallExpr *E) {
7531     APValue Result;
7532     if (!handleCallExpr(E, Result, nullptr))
7533       return false;
7534     return DerivedSuccess(Result, E);
7535   }
7536 
7537   bool handleCallExpr(const CallExpr *E, APValue &Result,
7538                      const LValue *ResultSlot) {
7539     CallScopeRAII CallScope(Info);
7540 
7541     const Expr *Callee = E->getCallee()->IgnoreParens();
7542     QualType CalleeType = Callee->getType();
7543 
7544     const FunctionDecl *FD = nullptr;
7545     LValue *This = nullptr, ThisVal;
7546     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
7547     bool HasQualifier = false;
7548 
7549     CallRef Call;
7550 
7551     // Extract function decl and 'this' pointer from the callee.
7552     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7553       const CXXMethodDecl *Member = nullptr;
7554       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7555         // Explicit bound member calls, such as x.f() or p->g();
7556         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7557           return false;
7558         Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7559         if (!Member)
7560           return Error(Callee);
7561         This = &ThisVal;
7562         HasQualifier = ME->hasQualifier();
7563       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
7564         // Indirect bound member calls ('.*' or '->*').
7565         const ValueDecl *D =
7566             HandleMemberPointerAccess(Info, BE, ThisVal, false);
7567         if (!D)
7568           return false;
7569         Member = dyn_cast<CXXMethodDecl>(D);
7570         if (!Member)
7571           return Error(Callee);
7572         This = &ThisVal;
7573       } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7574         if (!Info.getLangOpts().CPlusPlus20)
7575           Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7576         return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7577                HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7578       } else
7579         return Error(Callee);
7580       FD = Member;
7581     } else if (CalleeType->isFunctionPointerType()) {
7582       LValue CalleeLV;
7583       if (!EvaluatePointer(Callee, CalleeLV, Info))
7584         return false;
7585 
7586       if (!CalleeLV.getLValueOffset().isZero())
7587         return Error(Callee);
7588       FD = dyn_cast_or_null<FunctionDecl>(
7589           CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
7590       if (!FD)
7591         return Error(Callee);
7592       // Don't call function pointers which have been cast to some other type.
7593       // Per DR (no number yet), the caller and callee can differ in noexcept.
7594       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7595         CalleeType->getPointeeType(), FD->getType())) {
7596         return Error(E);
7597       }
7598 
7599       // For an (overloaded) assignment expression, evaluate the RHS before the
7600       // LHS.
7601       auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
7602       if (OCE && OCE->isAssignmentOp()) {
7603         assert(Args.size() == 2 && "wrong number of arguments in assignment");
7604         Call = Info.CurrentCall->createCall(FD);
7605         if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call,
7606                           Info, FD, /*RightToLeft=*/true))
7607           return false;
7608       }
7609 
7610       // Overloaded operator calls to member functions are represented as normal
7611       // calls with '*this' as the first argument.
7612       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7613       if (MD && !MD->isStatic()) {
7614         // FIXME: When selecting an implicit conversion for an overloaded
7615         // operator delete, we sometimes try to evaluate calls to conversion
7616         // operators without a 'this' parameter!
7617         if (Args.empty())
7618           return Error(E);
7619 
7620         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7621           return false;
7622         This = &ThisVal;
7623         Args = Args.slice(1);
7624       } else if (MD && MD->isLambdaStaticInvoker()) {
7625         // Map the static invoker for the lambda back to the call operator.
7626         // Conveniently, we don't have to slice out the 'this' argument (as is
7627         // being done for the non-static case), since a static member function
7628         // doesn't have an implicit argument passed in.
7629         const CXXRecordDecl *ClosureClass = MD->getParent();
7630         assert(
7631             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7632             "Number of captures must be zero for conversion to function-ptr");
7633 
7634         const CXXMethodDecl *LambdaCallOp =
7635             ClosureClass->getLambdaCallOperator();
7636 
7637         // Set 'FD', the function that will be called below, to the call
7638         // operator.  If the closure object represents a generic lambda, find
7639         // the corresponding specialization of the call operator.
7640 
7641         if (ClosureClass->isGenericLambda()) {
7642           assert(MD->isFunctionTemplateSpecialization() &&
7643                  "A generic lambda's static-invoker function must be a "
7644                  "template specialization");
7645           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7646           FunctionTemplateDecl *CallOpTemplate =
7647               LambdaCallOp->getDescribedFunctionTemplate();
7648           void *InsertPos = nullptr;
7649           FunctionDecl *CorrespondingCallOpSpecialization =
7650               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7651           assert(CorrespondingCallOpSpecialization &&
7652                  "We must always have a function call operator specialization "
7653                  "that corresponds to our static invoker specialization");
7654           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7655         } else
7656           FD = LambdaCallOp;
7657       } else if (FD->isReplaceableGlobalAllocationFunction()) {
7658         if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7659             FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7660           LValue Ptr;
7661           if (!HandleOperatorNewCall(Info, E, Ptr))
7662             return false;
7663           Ptr.moveInto(Result);
7664           return CallScope.destroy();
7665         } else {
7666           return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
7667         }
7668       }
7669     } else
7670       return Error(E);
7671 
7672     // Evaluate the arguments now if we've not already done so.
7673     if (!Call) {
7674       Call = Info.CurrentCall->createCall(FD);
7675       if (!EvaluateArgs(Args, Call, Info, FD))
7676         return false;
7677     }
7678 
7679     SmallVector<QualType, 4> CovariantAdjustmentPath;
7680     if (This) {
7681       auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7682       if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
7683         // Perform virtual dispatch, if necessary.
7684         FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
7685                                    CovariantAdjustmentPath);
7686         if (!FD)
7687           return false;
7688       } else {
7689         // Check that the 'this' pointer points to an object of the right type.
7690         // FIXME: If this is an assignment operator call, we may need to change
7691         // the active union member before we check this.
7692         if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
7693           return false;
7694       }
7695     }
7696 
7697     // Destructor calls are different enough that they have their own codepath.
7698     if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
7699       assert(This && "no 'this' pointer for destructor call");
7700       return HandleDestruction(Info, E, *This,
7701                                Info.Ctx.getRecordType(DD->getParent())) &&
7702              CallScope.destroy();
7703     }
7704 
7705     const FunctionDecl *Definition = nullptr;
7706     Stmt *Body = FD->getBody(Definition);
7707 
7708     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
7709         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call,
7710                             Body, Info, Result, ResultSlot))
7711       return false;
7712 
7713     if (!CovariantAdjustmentPath.empty() &&
7714         !HandleCovariantReturnAdjustment(Info, E, Result,
7715                                          CovariantAdjustmentPath))
7716       return false;
7717 
7718     return CallScope.destroy();
7719   }
7720 
7721   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7722     return StmtVisitorTy::Visit(E->getInitializer());
7723   }
7724   bool VisitInitListExpr(const InitListExpr *E) {
7725     if (E->getNumInits() == 0)
7726       return DerivedZeroInitialization(E);
7727     if (E->getNumInits() == 1)
7728       return StmtVisitorTy::Visit(E->getInit(0));
7729     return Error(E);
7730   }
7731   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
7732     return DerivedZeroInitialization(E);
7733   }
7734   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
7735     return DerivedZeroInitialization(E);
7736   }
7737   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
7738     return DerivedZeroInitialization(E);
7739   }
7740 
7741   /// A member expression where the object is a prvalue is itself a prvalue.
7742   bool VisitMemberExpr(const MemberExpr *E) {
7743     assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
7744            "missing temporary materialization conversion");
7745     assert(!E->isArrow() && "missing call to bound member function?");
7746 
7747     APValue Val;
7748     if (!Evaluate(Val, Info, E->getBase()))
7749       return false;
7750 
7751     QualType BaseTy = E->getBase()->getType();
7752 
7753     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
7754     if (!FD) return Error(E);
7755     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
7756     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7757            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7758 
7759     // Note: there is no lvalue base here. But this case should only ever
7760     // happen in C or in C++98, where we cannot be evaluating a constexpr
7761     // constructor, which is the only case the base matters.
7762     CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
7763     SubobjectDesignator Designator(BaseTy);
7764     Designator.addDeclUnchecked(FD);
7765 
7766     APValue Result;
7767     return extractSubobject(Info, E, Obj, Designator, Result) &&
7768            DerivedSuccess(Result, E);
7769   }
7770 
7771   bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
7772     APValue Val;
7773     if (!Evaluate(Val, Info, E->getBase()))
7774       return false;
7775 
7776     if (Val.isVector()) {
7777       SmallVector<uint32_t, 4> Indices;
7778       E->getEncodedElementAccess(Indices);
7779       if (Indices.size() == 1) {
7780         // Return scalar.
7781         return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
7782       } else {
7783         // Construct new APValue vector.
7784         SmallVector<APValue, 4> Elts;
7785         for (unsigned I = 0; I < Indices.size(); ++I) {
7786           Elts.push_back(Val.getVectorElt(Indices[I]));
7787         }
7788         APValue VecResult(Elts.data(), Indices.size());
7789         return DerivedSuccess(VecResult, E);
7790       }
7791     }
7792 
7793     return false;
7794   }
7795 
7796   bool VisitCastExpr(const CastExpr *E) {
7797     switch (E->getCastKind()) {
7798     default:
7799       break;
7800 
7801     case CK_AtomicToNonAtomic: {
7802       APValue AtomicVal;
7803       // This does not need to be done in place even for class/array types:
7804       // atomic-to-non-atomic conversion implies copying the object
7805       // representation.
7806       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
7807         return false;
7808       return DerivedSuccess(AtomicVal, E);
7809     }
7810 
7811     case CK_NoOp:
7812     case CK_UserDefinedConversion:
7813       return StmtVisitorTy::Visit(E->getSubExpr());
7814 
7815     case CK_LValueToRValue: {
7816       LValue LVal;
7817       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
7818         return false;
7819       APValue RVal;
7820       // Note, we use the subexpression's type in order to retain cv-qualifiers.
7821       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7822                                           LVal, RVal))
7823         return false;
7824       return DerivedSuccess(RVal, E);
7825     }
7826     case CK_LValueToRValueBitCast: {
7827       APValue DestValue, SourceValue;
7828       if (!Evaluate(SourceValue, Info, E->getSubExpr()))
7829         return false;
7830       if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
7831         return false;
7832       return DerivedSuccess(DestValue, E);
7833     }
7834 
7835     case CK_AddressSpaceConversion: {
7836       APValue Value;
7837       if (!Evaluate(Value, Info, E->getSubExpr()))
7838         return false;
7839       return DerivedSuccess(Value, E);
7840     }
7841     }
7842 
7843     return Error(E);
7844   }
7845 
7846   bool VisitUnaryPostInc(const UnaryOperator *UO) {
7847     return VisitUnaryPostIncDec(UO);
7848   }
7849   bool VisitUnaryPostDec(const UnaryOperator *UO) {
7850     return VisitUnaryPostIncDec(UO);
7851   }
7852   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
7853     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7854       return Error(UO);
7855 
7856     LValue LVal;
7857     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
7858       return false;
7859     APValue RVal;
7860     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
7861                       UO->isIncrementOp(), &RVal))
7862       return false;
7863     return DerivedSuccess(RVal, UO);
7864   }
7865 
7866   bool VisitStmtExpr(const StmtExpr *E) {
7867     // We will have checked the full-expressions inside the statement expression
7868     // when they were completed, and don't need to check them again now.
7869     llvm::SaveAndRestore<bool> NotCheckingForUB(
7870         Info.CheckingForUndefinedBehavior, false);
7871 
7872     const CompoundStmt *CS = E->getSubStmt();
7873     if (CS->body_empty())
7874       return true;
7875 
7876     BlockScopeRAII Scope(Info);
7877     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
7878                                            BE = CS->body_end();
7879          /**/; ++BI) {
7880       if (BI + 1 == BE) {
7881         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
7882         if (!FinalExpr) {
7883           Info.FFDiag((*BI)->getBeginLoc(),
7884                       diag::note_constexpr_stmt_expr_unsupported);
7885           return false;
7886         }
7887         return this->Visit(FinalExpr) && Scope.destroy();
7888       }
7889 
7890       APValue ReturnValue;
7891       StmtResult Result = { ReturnValue, nullptr };
7892       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
7893       if (ESR != ESR_Succeeded) {
7894         // FIXME: If the statement-expression terminated due to 'return',
7895         // 'break', or 'continue', it would be nice to propagate that to
7896         // the outer statement evaluation rather than bailing out.
7897         if (ESR != ESR_Failed)
7898           Info.FFDiag((*BI)->getBeginLoc(),
7899                       diag::note_constexpr_stmt_expr_unsupported);
7900         return false;
7901       }
7902     }
7903 
7904     llvm_unreachable("Return from function from the loop above.");
7905   }
7906 
7907   /// Visit a value which is evaluated, but whose value is ignored.
7908   void VisitIgnoredValue(const Expr *E) {
7909     EvaluateIgnoredValue(Info, E);
7910   }
7911 
7912   /// Potentially visit a MemberExpr's base expression.
7913   void VisitIgnoredBaseExpression(const Expr *E) {
7914     // While MSVC doesn't evaluate the base expression, it does diagnose the
7915     // presence of side-effecting behavior.
7916     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
7917       return;
7918     VisitIgnoredValue(E);
7919   }
7920 };
7921 
7922 } // namespace
7923 
7924 //===----------------------------------------------------------------------===//
7925 // Common base class for lvalue and temporary evaluation.
7926 //===----------------------------------------------------------------------===//
7927 namespace {
7928 template<class Derived>
7929 class LValueExprEvaluatorBase
7930   : public ExprEvaluatorBase<Derived> {
7931 protected:
7932   LValue &Result;
7933   bool InvalidBaseOK;
7934   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
7935   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
7936 
7937   bool Success(APValue::LValueBase B) {
7938     Result.set(B);
7939     return true;
7940   }
7941 
7942   bool evaluatePointer(const Expr *E, LValue &Result) {
7943     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
7944   }
7945 
7946 public:
7947   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
7948       : ExprEvaluatorBaseTy(Info), Result(Result),
7949         InvalidBaseOK(InvalidBaseOK) {}
7950 
7951   bool Success(const APValue &V, const Expr *E) {
7952     Result.setFrom(this->Info.Ctx, V);
7953     return true;
7954   }
7955 
7956   bool VisitMemberExpr(const MemberExpr *E) {
7957     // Handle non-static data members.
7958     QualType BaseTy;
7959     bool EvalOK;
7960     if (E->isArrow()) {
7961       EvalOK = evaluatePointer(E->getBase(), Result);
7962       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
7963     } else if (E->getBase()->isPRValue()) {
7964       assert(E->getBase()->getType()->isRecordType());
7965       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
7966       BaseTy = E->getBase()->getType();
7967     } else {
7968       EvalOK = this->Visit(E->getBase());
7969       BaseTy = E->getBase()->getType();
7970     }
7971     if (!EvalOK) {
7972       if (!InvalidBaseOK)
7973         return false;
7974       Result.setInvalid(E);
7975       return true;
7976     }
7977 
7978     const ValueDecl *MD = E->getMemberDecl();
7979     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
7980       assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7981              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7982       (void)BaseTy;
7983       if (!HandleLValueMember(this->Info, E, Result, FD))
7984         return false;
7985     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
7986       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
7987         return false;
7988     } else
7989       return this->Error(E);
7990 
7991     if (MD->getType()->isReferenceType()) {
7992       APValue RefValue;
7993       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
7994                                           RefValue))
7995         return false;
7996       return Success(RefValue, E);
7997     }
7998     return true;
7999   }
8000 
8001   bool VisitBinaryOperator(const BinaryOperator *E) {
8002     switch (E->getOpcode()) {
8003     default:
8004       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8005 
8006     case BO_PtrMemD:
8007     case BO_PtrMemI:
8008       return HandleMemberPointerAccess(this->Info, E, Result);
8009     }
8010   }
8011 
8012   bool VisitCastExpr(const CastExpr *E) {
8013     switch (E->getCastKind()) {
8014     default:
8015       return ExprEvaluatorBaseTy::VisitCastExpr(E);
8016 
8017     case CK_DerivedToBase:
8018     case CK_UncheckedDerivedToBase:
8019       if (!this->Visit(E->getSubExpr()))
8020         return false;
8021 
8022       // Now figure out the necessary offset to add to the base LV to get from
8023       // the derived class to the base class.
8024       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8025                                   Result);
8026     }
8027   }
8028 };
8029 }
8030 
8031 //===----------------------------------------------------------------------===//
8032 // LValue Evaluation
8033 //
8034 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8035 // function designators (in C), decl references to void objects (in C), and
8036 // temporaries (if building with -Wno-address-of-temporary).
8037 //
8038 // LValue evaluation produces values comprising a base expression of one of the
8039 // following types:
8040 // - Declarations
8041 //  * VarDecl
8042 //  * FunctionDecl
8043 // - Literals
8044 //  * CompoundLiteralExpr in C (and in global scope in C++)
8045 //  * StringLiteral
8046 //  * PredefinedExpr
8047 //  * ObjCStringLiteralExpr
8048 //  * ObjCEncodeExpr
8049 //  * AddrLabelExpr
8050 //  * BlockExpr
8051 //  * CallExpr for a MakeStringConstant builtin
8052 // - typeid(T) expressions, as TypeInfoLValues
8053 // - Locals and temporaries
8054 //  * MaterializeTemporaryExpr
8055 //  * Any Expr, with a CallIndex indicating the function in which the temporary
8056 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
8057 //    from the AST (FIXME).
8058 //  * A MaterializeTemporaryExpr that has static storage duration, with no
8059 //    CallIndex, for a lifetime-extended temporary.
8060 //  * The ConstantExpr that is currently being evaluated during evaluation of an
8061 //    immediate invocation.
8062 // plus an offset in bytes.
8063 //===----------------------------------------------------------------------===//
8064 namespace {
8065 class LValueExprEvaluator
8066   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8067 public:
8068   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8069     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8070 
8071   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8072   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8073 
8074   bool VisitDeclRefExpr(const DeclRefExpr *E);
8075   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8076   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8077   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8078   bool VisitMemberExpr(const MemberExpr *E);
8079   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
8080   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8081   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8082   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8083   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8084   bool VisitUnaryDeref(const UnaryOperator *E);
8085   bool VisitUnaryReal(const UnaryOperator *E);
8086   bool VisitUnaryImag(const UnaryOperator *E);
8087   bool VisitUnaryPreInc(const UnaryOperator *UO) {
8088     return VisitUnaryPreIncDec(UO);
8089   }
8090   bool VisitUnaryPreDec(const UnaryOperator *UO) {
8091     return VisitUnaryPreIncDec(UO);
8092   }
8093   bool VisitBinAssign(const BinaryOperator *BO);
8094   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8095 
8096   bool VisitCastExpr(const CastExpr *E) {
8097     switch (E->getCastKind()) {
8098     default:
8099       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8100 
8101     case CK_LValueBitCast:
8102       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8103       if (!Visit(E->getSubExpr()))
8104         return false;
8105       Result.Designator.setInvalid();
8106       return true;
8107 
8108     case CK_BaseToDerived:
8109       if (!Visit(E->getSubExpr()))
8110         return false;
8111       return HandleBaseToDerivedCast(Info, E, Result);
8112 
8113     case CK_Dynamic:
8114       if (!Visit(E->getSubExpr()))
8115         return false;
8116       return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8117     }
8118   }
8119 };
8120 } // end anonymous namespace
8121 
8122 /// Evaluate an expression as an lvalue. This can be legitimately called on
8123 /// expressions which are not glvalues, in three cases:
8124 ///  * function designators in C, and
8125 ///  * "extern void" objects
8126 ///  * @selector() expressions in Objective-C
8127 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
8128                            bool InvalidBaseOK) {
8129   assert(!E->isValueDependent());
8130   assert(E->isGLValue() || E->getType()->isFunctionType() ||
8131          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
8132   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8133 }
8134 
8135 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
8136   const NamedDecl *D = E->getDecl();
8137   if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl>(D))
8138     return Success(cast<ValueDecl>(D));
8139   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
8140     return VisitVarDecl(E, VD);
8141   if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
8142     return Visit(BD->getBinding());
8143   return Error(E);
8144 }
8145 
8146 
8147 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
8148 
8149   // If we are within a lambda's call operator, check whether the 'VD' referred
8150   // to within 'E' actually represents a lambda-capture that maps to a
8151   // data-member/field within the closure object, and if so, evaluate to the
8152   // field or what the field refers to.
8153   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
8154       isa<DeclRefExpr>(E) &&
8155       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
8156     // We don't always have a complete capture-map when checking or inferring if
8157     // the function call operator meets the requirements of a constexpr function
8158     // - but we don't need to evaluate the captures to determine constexprness
8159     // (dcl.constexpr C++17).
8160     if (Info.checkingPotentialConstantExpression())
8161       return false;
8162 
8163     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
8164       // Start with 'Result' referring to the complete closure object...
8165       Result = *Info.CurrentCall->This;
8166       // ... then update it to refer to the field of the closure object
8167       // that represents the capture.
8168       if (!HandleLValueMember(Info, E, Result, FD))
8169         return false;
8170       // And if the field is of reference type, update 'Result' to refer to what
8171       // the field refers to.
8172       if (FD->getType()->isReferenceType()) {
8173         APValue RVal;
8174         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
8175                                             RVal))
8176           return false;
8177         Result.setFrom(Info.Ctx, RVal);
8178       }
8179       return true;
8180     }
8181   }
8182 
8183   CallStackFrame *Frame = nullptr;
8184   unsigned Version = 0;
8185   if (VD->hasLocalStorage()) {
8186     // Only if a local variable was declared in the function currently being
8187     // evaluated, do we expect to be able to find its value in the current
8188     // frame. (Otherwise it was likely declared in an enclosing context and
8189     // could either have a valid evaluatable value (for e.g. a constexpr
8190     // variable) or be ill-formed (and trigger an appropriate evaluation
8191     // diagnostic)).
8192     CallStackFrame *CurrFrame = Info.CurrentCall;
8193     if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
8194       // Function parameters are stored in some caller's frame. (Usually the
8195       // immediate caller, but for an inherited constructor they may be more
8196       // distant.)
8197       if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
8198         if (CurrFrame->Arguments) {
8199           VD = CurrFrame->Arguments.getOrigParam(PVD);
8200           Frame =
8201               Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
8202           Version = CurrFrame->Arguments.Version;
8203         }
8204       } else {
8205         Frame = CurrFrame;
8206         Version = CurrFrame->getCurrentTemporaryVersion(VD);
8207       }
8208     }
8209   }
8210 
8211   if (!VD->getType()->isReferenceType()) {
8212     if (Frame) {
8213       Result.set({VD, Frame->Index, Version});
8214       return true;
8215     }
8216     return Success(VD);
8217   }
8218 
8219   if (!Info.getLangOpts().CPlusPlus11) {
8220     Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
8221         << VD << VD->getType();
8222     Info.Note(VD->getLocation(), diag::note_declared_at);
8223   }
8224 
8225   APValue *V;
8226   if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
8227     return false;
8228   if (!V->hasValue()) {
8229     // FIXME: Is it possible for V to be indeterminate here? If so, we should
8230     // adjust the diagnostic to say that.
8231     if (!Info.checkingPotentialConstantExpression())
8232       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
8233     return false;
8234   }
8235   return Success(*V, E);
8236 }
8237 
8238 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
8239     const MaterializeTemporaryExpr *E) {
8240   // Walk through the expression to find the materialized temporary itself.
8241   SmallVector<const Expr *, 2> CommaLHSs;
8242   SmallVector<SubobjectAdjustment, 2> Adjustments;
8243   const Expr *Inner =
8244       E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
8245 
8246   // If we passed any comma operators, evaluate their LHSs.
8247   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
8248     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
8249       return false;
8250 
8251   // A materialized temporary with static storage duration can appear within the
8252   // result of a constant expression evaluation, so we need to preserve its
8253   // value for use outside this evaluation.
8254   APValue *Value;
8255   if (E->getStorageDuration() == SD_Static) {
8256     // FIXME: What about SD_Thread?
8257     Value = E->getOrCreateValue(true);
8258     *Value = APValue();
8259     Result.set(E);
8260   } else {
8261     Value = &Info.CurrentCall->createTemporary(
8262         E, E->getType(),
8263         E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
8264                                                      : ScopeKind::Block,
8265         Result);
8266   }
8267 
8268   QualType Type = Inner->getType();
8269 
8270   // Materialize the temporary itself.
8271   if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
8272     *Value = APValue();
8273     return false;
8274   }
8275 
8276   // Adjust our lvalue to refer to the desired subobject.
8277   for (unsigned I = Adjustments.size(); I != 0; /**/) {
8278     --I;
8279     switch (Adjustments[I].Kind) {
8280     case SubobjectAdjustment::DerivedToBaseAdjustment:
8281       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
8282                                 Type, Result))
8283         return false;
8284       Type = Adjustments[I].DerivedToBase.BasePath->getType();
8285       break;
8286 
8287     case SubobjectAdjustment::FieldAdjustment:
8288       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
8289         return false;
8290       Type = Adjustments[I].Field->getType();
8291       break;
8292 
8293     case SubobjectAdjustment::MemberPointerAdjustment:
8294       if (!HandleMemberPointerAccess(this->Info, Type, Result,
8295                                      Adjustments[I].Ptr.RHS))
8296         return false;
8297       Type = Adjustments[I].Ptr.MPT->getPointeeType();
8298       break;
8299     }
8300   }
8301 
8302   return true;
8303 }
8304 
8305 bool
8306 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8307   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
8308          "lvalue compound literal in c++?");
8309   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
8310   // only see this when folding in C, so there's no standard to follow here.
8311   return Success(E);
8312 }
8313 
8314 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
8315   TypeInfoLValue TypeInfo;
8316 
8317   if (!E->isPotentiallyEvaluated()) {
8318     if (E->isTypeOperand())
8319       TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
8320     else
8321       TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
8322   } else {
8323     if (!Info.Ctx.getLangOpts().CPlusPlus20) {
8324       Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
8325         << E->getExprOperand()->getType()
8326         << E->getExprOperand()->getSourceRange();
8327     }
8328 
8329     if (!Visit(E->getExprOperand()))
8330       return false;
8331 
8332     Optional<DynamicType> DynType =
8333         ComputeDynamicType(Info, E, Result, AK_TypeId);
8334     if (!DynType)
8335       return false;
8336 
8337     TypeInfo =
8338         TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
8339   }
8340 
8341   return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
8342 }
8343 
8344 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
8345   return Success(E->getGuidDecl());
8346 }
8347 
8348 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
8349   // Handle static data members.
8350   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
8351     VisitIgnoredBaseExpression(E->getBase());
8352     return VisitVarDecl(E, VD);
8353   }
8354 
8355   // Handle static member functions.
8356   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
8357     if (MD->isStatic()) {
8358       VisitIgnoredBaseExpression(E->getBase());
8359       return Success(MD);
8360     }
8361   }
8362 
8363   // Handle non-static data members.
8364   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
8365 }
8366 
8367 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
8368   // FIXME: Deal with vectors as array subscript bases.
8369   if (E->getBase()->getType()->isVectorType())
8370     return Error(E);
8371 
8372   APSInt Index;
8373   bool Success = true;
8374 
8375   // C++17's rules require us to evaluate the LHS first, regardless of which
8376   // side is the base.
8377   for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
8378     if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
8379                                 : !EvaluateInteger(SubExpr, Index, Info)) {
8380       if (!Info.noteFailure())
8381         return false;
8382       Success = false;
8383     }
8384   }
8385 
8386   return Success &&
8387          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
8388 }
8389 
8390 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
8391   return evaluatePointer(E->getSubExpr(), Result);
8392 }
8393 
8394 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8395   if (!Visit(E->getSubExpr()))
8396     return false;
8397   // __real is a no-op on scalar lvalues.
8398   if (E->getSubExpr()->getType()->isAnyComplexType())
8399     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
8400   return true;
8401 }
8402 
8403 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8404   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
8405          "lvalue __imag__ on scalar?");
8406   if (!Visit(E->getSubExpr()))
8407     return false;
8408   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
8409   return true;
8410 }
8411 
8412 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
8413   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8414     return Error(UO);
8415 
8416   if (!this->Visit(UO->getSubExpr()))
8417     return false;
8418 
8419   return handleIncDec(
8420       this->Info, UO, Result, UO->getSubExpr()->getType(),
8421       UO->isIncrementOp(), nullptr);
8422 }
8423 
8424 bool LValueExprEvaluator::VisitCompoundAssignOperator(
8425     const CompoundAssignOperator *CAO) {
8426   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8427     return Error(CAO);
8428 
8429   bool Success = true;
8430 
8431   // C++17 onwards require that we evaluate the RHS first.
8432   APValue RHS;
8433   if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
8434     if (!Info.noteFailure())
8435       return false;
8436     Success = false;
8437   }
8438 
8439   // The overall lvalue result is the result of evaluating the LHS.
8440   if (!this->Visit(CAO->getLHS()) || !Success)
8441     return false;
8442 
8443   return handleCompoundAssignment(
8444       this->Info, CAO,
8445       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
8446       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
8447 }
8448 
8449 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
8450   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8451     return Error(E);
8452 
8453   bool Success = true;
8454 
8455   // C++17 onwards require that we evaluate the RHS first.
8456   APValue NewVal;
8457   if (!Evaluate(NewVal, this->Info, E->getRHS())) {
8458     if (!Info.noteFailure())
8459       return false;
8460     Success = false;
8461   }
8462 
8463   if (!this->Visit(E->getLHS()) || !Success)
8464     return false;
8465 
8466   if (Info.getLangOpts().CPlusPlus20 &&
8467       !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
8468     return false;
8469 
8470   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
8471                           NewVal);
8472 }
8473 
8474 //===----------------------------------------------------------------------===//
8475 // Pointer Evaluation
8476 //===----------------------------------------------------------------------===//
8477 
8478 /// Attempts to compute the number of bytes available at the pointer
8479 /// returned by a function with the alloc_size attribute. Returns true if we
8480 /// were successful. Places an unsigned number into `Result`.
8481 ///
8482 /// This expects the given CallExpr to be a call to a function with an
8483 /// alloc_size attribute.
8484 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8485                                             const CallExpr *Call,
8486                                             llvm::APInt &Result) {
8487   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
8488 
8489   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
8490   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
8491   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
8492   if (Call->getNumArgs() <= SizeArgNo)
8493     return false;
8494 
8495   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
8496     Expr::EvalResult ExprResult;
8497     if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
8498       return false;
8499     Into = ExprResult.Val.getInt();
8500     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
8501       return false;
8502     Into = Into.zextOrSelf(BitsInSizeT);
8503     return true;
8504   };
8505 
8506   APSInt SizeOfElem;
8507   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
8508     return false;
8509 
8510   if (!AllocSize->getNumElemsParam().isValid()) {
8511     Result = std::move(SizeOfElem);
8512     return true;
8513   }
8514 
8515   APSInt NumberOfElems;
8516   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
8517   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
8518     return false;
8519 
8520   bool Overflow;
8521   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
8522   if (Overflow)
8523     return false;
8524 
8525   Result = std::move(BytesAvailable);
8526   return true;
8527 }
8528 
8529 /// Convenience function. LVal's base must be a call to an alloc_size
8530 /// function.
8531 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8532                                             const LValue &LVal,
8533                                             llvm::APInt &Result) {
8534   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8535          "Can't get the size of a non alloc_size function");
8536   const auto *Base = LVal.getLValueBase().get<const Expr *>();
8537   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
8538   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
8539 }
8540 
8541 /// Attempts to evaluate the given LValueBase as the result of a call to
8542 /// a function with the alloc_size attribute. If it was possible to do so, this
8543 /// function will return true, make Result's Base point to said function call,
8544 /// and mark Result's Base as invalid.
8545 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
8546                                       LValue &Result) {
8547   if (Base.isNull())
8548     return false;
8549 
8550   // Because we do no form of static analysis, we only support const variables.
8551   //
8552   // Additionally, we can't support parameters, nor can we support static
8553   // variables (in the latter case, use-before-assign isn't UB; in the former,
8554   // we have no clue what they'll be assigned to).
8555   const auto *VD =
8556       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
8557   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
8558     return false;
8559 
8560   const Expr *Init = VD->getAnyInitializer();
8561   if (!Init)
8562     return false;
8563 
8564   const Expr *E = Init->IgnoreParens();
8565   if (!tryUnwrapAllocSizeCall(E))
8566     return false;
8567 
8568   // Store E instead of E unwrapped so that the type of the LValue's base is
8569   // what the user wanted.
8570   Result.setInvalid(E);
8571 
8572   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
8573   Result.addUnsizedArray(Info, E, Pointee);
8574   return true;
8575 }
8576 
8577 namespace {
8578 class PointerExprEvaluator
8579   : public ExprEvaluatorBase<PointerExprEvaluator> {
8580   LValue &Result;
8581   bool InvalidBaseOK;
8582 
8583   bool Success(const Expr *E) {
8584     Result.set(E);
8585     return true;
8586   }
8587 
8588   bool evaluateLValue(const Expr *E, LValue &Result) {
8589     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
8590   }
8591 
8592   bool evaluatePointer(const Expr *E, LValue &Result) {
8593     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
8594   }
8595 
8596   bool visitNonBuiltinCallExpr(const CallExpr *E);
8597 public:
8598 
8599   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
8600       : ExprEvaluatorBaseTy(info), Result(Result),
8601         InvalidBaseOK(InvalidBaseOK) {}
8602 
8603   bool Success(const APValue &V, const Expr *E) {
8604     Result.setFrom(Info.Ctx, V);
8605     return true;
8606   }
8607   bool ZeroInitialization(const Expr *E) {
8608     Result.setNull(Info.Ctx, E->getType());
8609     return true;
8610   }
8611 
8612   bool VisitBinaryOperator(const BinaryOperator *E);
8613   bool VisitCastExpr(const CastExpr* E);
8614   bool VisitUnaryAddrOf(const UnaryOperator *E);
8615   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
8616       { return Success(E); }
8617   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
8618     if (E->isExpressibleAsConstantInitializer())
8619       return Success(E);
8620     if (Info.noteFailure())
8621       EvaluateIgnoredValue(Info, E->getSubExpr());
8622     return Error(E);
8623   }
8624   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
8625       { return Success(E); }
8626   bool VisitCallExpr(const CallExpr *E);
8627   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
8628   bool VisitBlockExpr(const BlockExpr *E) {
8629     if (!E->getBlockDecl()->hasCaptures())
8630       return Success(E);
8631     return Error(E);
8632   }
8633   bool VisitCXXThisExpr(const CXXThisExpr *E) {
8634     // Can't look at 'this' when checking a potential constant expression.
8635     if (Info.checkingPotentialConstantExpression())
8636       return false;
8637     if (!Info.CurrentCall->This) {
8638       if (Info.getLangOpts().CPlusPlus11)
8639         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
8640       else
8641         Info.FFDiag(E);
8642       return false;
8643     }
8644     Result = *Info.CurrentCall->This;
8645     // If we are inside a lambda's call operator, the 'this' expression refers
8646     // to the enclosing '*this' object (either by value or reference) which is
8647     // either copied into the closure object's field that represents the '*this'
8648     // or refers to '*this'.
8649     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
8650       // Ensure we actually have captured 'this'. (an error will have
8651       // been previously reported if not).
8652       if (!Info.CurrentCall->LambdaThisCaptureField)
8653         return false;
8654 
8655       // Update 'Result' to refer to the data member/field of the closure object
8656       // that represents the '*this' capture.
8657       if (!HandleLValueMember(Info, E, Result,
8658                              Info.CurrentCall->LambdaThisCaptureField))
8659         return false;
8660       // If we captured '*this' by reference, replace the field with its referent.
8661       if (Info.CurrentCall->LambdaThisCaptureField->getType()
8662               ->isPointerType()) {
8663         APValue RVal;
8664         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
8665                                             RVal))
8666           return false;
8667 
8668         Result.setFrom(Info.Ctx, RVal);
8669       }
8670     }
8671     return true;
8672   }
8673 
8674   bool VisitCXXNewExpr(const CXXNewExpr *E);
8675 
8676   bool VisitSourceLocExpr(const SourceLocExpr *E) {
8677     assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
8678     APValue LValResult = E->EvaluateInContext(
8679         Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8680     Result.setFrom(Info.Ctx, LValResult);
8681     return true;
8682   }
8683 
8684   bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
8685     std::string ResultStr = E->ComputeName(Info.Ctx);
8686 
8687     QualType CharTy = Info.Ctx.CharTy.withConst();
8688     APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
8689                ResultStr.size() + 1);
8690     QualType ArrayTy = Info.Ctx.getConstantArrayType(CharTy, Size, nullptr,
8691                                                      ArrayType::Normal, 0);
8692 
8693     StringLiteral *SL =
8694         StringLiteral::Create(Info.Ctx, ResultStr, StringLiteral::Ascii,
8695                               /*Pascal*/ false, ArrayTy, E->getLocation());
8696 
8697     evaluateLValue(SL, Result);
8698     Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
8699     return true;
8700   }
8701 
8702   // FIXME: Missing: @protocol, @selector
8703 };
8704 } // end anonymous namespace
8705 
8706 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
8707                             bool InvalidBaseOK) {
8708   assert(!E->isValueDependent());
8709   assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
8710   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8711 }
8712 
8713 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8714   if (E->getOpcode() != BO_Add &&
8715       E->getOpcode() != BO_Sub)
8716     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8717 
8718   const Expr *PExp = E->getLHS();
8719   const Expr *IExp = E->getRHS();
8720   if (IExp->getType()->isPointerType())
8721     std::swap(PExp, IExp);
8722 
8723   bool EvalPtrOK = evaluatePointer(PExp, Result);
8724   if (!EvalPtrOK && !Info.noteFailure())
8725     return false;
8726 
8727   llvm::APSInt Offset;
8728   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
8729     return false;
8730 
8731   if (E->getOpcode() == BO_Sub)
8732     negateAsSigned(Offset);
8733 
8734   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
8735   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
8736 }
8737 
8738 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8739   return evaluateLValue(E->getSubExpr(), Result);
8740 }
8741 
8742 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8743   const Expr *SubExpr = E->getSubExpr();
8744 
8745   switch (E->getCastKind()) {
8746   default:
8747     break;
8748   case CK_BitCast:
8749   case CK_CPointerToObjCPointerCast:
8750   case CK_BlockPointerToObjCPointerCast:
8751   case CK_AnyPointerToBlockPointerCast:
8752   case CK_AddressSpaceConversion:
8753     if (!Visit(SubExpr))
8754       return false;
8755     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
8756     // permitted in constant expressions in C++11. Bitcasts from cv void* are
8757     // also static_casts, but we disallow them as a resolution to DR1312.
8758     if (!E->getType()->isVoidPointerType()) {
8759       if (!Result.InvalidBase && !Result.Designator.Invalid &&
8760           !Result.IsNullPtr &&
8761           Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
8762                                           E->getType()->getPointeeType()) &&
8763           Info.getStdAllocatorCaller("allocate")) {
8764         // Inside a call to std::allocator::allocate and friends, we permit
8765         // casting from void* back to cv1 T* for a pointer that points to a
8766         // cv2 T.
8767       } else {
8768         Result.Designator.setInvalid();
8769         if (SubExpr->getType()->isVoidPointerType())
8770           CCEDiag(E, diag::note_constexpr_invalid_cast)
8771             << 3 << SubExpr->getType();
8772         else
8773           CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8774       }
8775     }
8776     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
8777       ZeroInitialization(E);
8778     return true;
8779 
8780   case CK_DerivedToBase:
8781   case CK_UncheckedDerivedToBase:
8782     if (!evaluatePointer(E->getSubExpr(), Result))
8783       return false;
8784     if (!Result.Base && Result.Offset.isZero())
8785       return true;
8786 
8787     // Now figure out the necessary offset to add to the base LV to get from
8788     // the derived class to the base class.
8789     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
8790                                   castAs<PointerType>()->getPointeeType(),
8791                                 Result);
8792 
8793   case CK_BaseToDerived:
8794     if (!Visit(E->getSubExpr()))
8795       return false;
8796     if (!Result.Base && Result.Offset.isZero())
8797       return true;
8798     return HandleBaseToDerivedCast(Info, E, Result);
8799 
8800   case CK_Dynamic:
8801     if (!Visit(E->getSubExpr()))
8802       return false;
8803     return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8804 
8805   case CK_NullToPointer:
8806     VisitIgnoredValue(E->getSubExpr());
8807     return ZeroInitialization(E);
8808 
8809   case CK_IntegralToPointer: {
8810     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8811 
8812     APValue Value;
8813     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
8814       break;
8815 
8816     if (Value.isInt()) {
8817       unsigned Size = Info.Ctx.getTypeSize(E->getType());
8818       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
8819       Result.Base = (Expr*)nullptr;
8820       Result.InvalidBase = false;
8821       Result.Offset = CharUnits::fromQuantity(N);
8822       Result.Designator.setInvalid();
8823       Result.IsNullPtr = false;
8824       return true;
8825     } else {
8826       // Cast is of an lvalue, no need to change value.
8827       Result.setFrom(Info.Ctx, Value);
8828       return true;
8829     }
8830   }
8831 
8832   case CK_ArrayToPointerDecay: {
8833     if (SubExpr->isGLValue()) {
8834       if (!evaluateLValue(SubExpr, Result))
8835         return false;
8836     } else {
8837       APValue &Value = Info.CurrentCall->createTemporary(
8838           SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
8839       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
8840         return false;
8841     }
8842     // The result is a pointer to the first element of the array.
8843     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
8844     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
8845       Result.addArray(Info, E, CAT);
8846     else
8847       Result.addUnsizedArray(Info, E, AT->getElementType());
8848     return true;
8849   }
8850 
8851   case CK_FunctionToPointerDecay:
8852     return evaluateLValue(SubExpr, Result);
8853 
8854   case CK_LValueToRValue: {
8855     LValue LVal;
8856     if (!evaluateLValue(E->getSubExpr(), LVal))
8857       return false;
8858 
8859     APValue RVal;
8860     // Note, we use the subexpression's type in order to retain cv-qualifiers.
8861     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8862                                         LVal, RVal))
8863       return InvalidBaseOK &&
8864              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
8865     return Success(RVal, E);
8866   }
8867   }
8868 
8869   return ExprEvaluatorBaseTy::VisitCastExpr(E);
8870 }
8871 
8872 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
8873                                 UnaryExprOrTypeTrait ExprKind) {
8874   // C++ [expr.alignof]p3:
8875   //     When alignof is applied to a reference type, the result is the
8876   //     alignment of the referenced type.
8877   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
8878     T = Ref->getPointeeType();
8879 
8880   if (T.getQualifiers().hasUnaligned())
8881     return CharUnits::One();
8882 
8883   const bool AlignOfReturnsPreferred =
8884       Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
8885 
8886   // __alignof is defined to return the preferred alignment.
8887   // Before 8, clang returned the preferred alignment for alignof and _Alignof
8888   // as well.
8889   if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
8890     return Info.Ctx.toCharUnitsFromBits(
8891       Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
8892   // alignof and _Alignof are defined to return the ABI alignment.
8893   else if (ExprKind == UETT_AlignOf)
8894     return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
8895   else
8896     llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
8897 }
8898 
8899 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
8900                                 UnaryExprOrTypeTrait ExprKind) {
8901   E = E->IgnoreParens();
8902 
8903   // The kinds of expressions that we have special-case logic here for
8904   // should be kept up to date with the special checks for those
8905   // expressions in Sema.
8906 
8907   // alignof decl is always accepted, even if it doesn't make sense: we default
8908   // to 1 in those cases.
8909   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8910     return Info.Ctx.getDeclAlign(DRE->getDecl(),
8911                                  /*RefAsPointee*/true);
8912 
8913   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
8914     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
8915                                  /*RefAsPointee*/true);
8916 
8917   return GetAlignOfType(Info, E->getType(), ExprKind);
8918 }
8919 
8920 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
8921   if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
8922     return Info.Ctx.getDeclAlign(VD);
8923   if (const auto *E = Value.Base.dyn_cast<const Expr *>())
8924     return GetAlignOfExpr(Info, E, UETT_AlignOf);
8925   return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
8926 }
8927 
8928 /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
8929 /// __builtin_is_aligned and __builtin_assume_aligned.
8930 static bool getAlignmentArgument(const Expr *E, QualType ForType,
8931                                  EvalInfo &Info, APSInt &Alignment) {
8932   if (!EvaluateInteger(E, Alignment, Info))
8933     return false;
8934   if (Alignment < 0 || !Alignment.isPowerOf2()) {
8935     Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
8936     return false;
8937   }
8938   unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
8939   APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
8940   if (APSInt::compareValues(Alignment, MaxValue) > 0) {
8941     Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
8942         << MaxValue << ForType << Alignment;
8943     return false;
8944   }
8945   // Ensure both alignment and source value have the same bit width so that we
8946   // don't assert when computing the resulting value.
8947   APSInt ExtAlignment =
8948       APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
8949   assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
8950          "Alignment should not be changed by ext/trunc");
8951   Alignment = ExtAlignment;
8952   assert(Alignment.getBitWidth() == SrcWidth);
8953   return true;
8954 }
8955 
8956 // To be clear: this happily visits unsupported builtins. Better name welcomed.
8957 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
8958   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
8959     return true;
8960 
8961   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
8962     return false;
8963 
8964   Result.setInvalid(E);
8965   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
8966   Result.addUnsizedArray(Info, E, PointeeTy);
8967   return true;
8968 }
8969 
8970 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
8971   if (IsConstantCall(E))
8972     return Success(E);
8973 
8974   if (unsigned BuiltinOp = E->getBuiltinCallee())
8975     return VisitBuiltinCallExpr(E, BuiltinOp);
8976 
8977   return visitNonBuiltinCallExpr(E);
8978 }
8979 
8980 // Determine if T is a character type for which we guarantee that
8981 // sizeof(T) == 1.
8982 static bool isOneByteCharacterType(QualType T) {
8983   return T->isCharType() || T->isChar8Type();
8984 }
8985 
8986 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8987                                                 unsigned BuiltinOp) {
8988   switch (BuiltinOp) {
8989   case Builtin::BI__builtin_addressof:
8990     return evaluateLValue(E->getArg(0), Result);
8991   case Builtin::BI__builtin_assume_aligned: {
8992     // We need to be very careful here because: if the pointer does not have the
8993     // asserted alignment, then the behavior is undefined, and undefined
8994     // behavior is non-constant.
8995     if (!evaluatePointer(E->getArg(0), Result))
8996       return false;
8997 
8998     LValue OffsetResult(Result);
8999     APSInt Alignment;
9000     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9001                               Alignment))
9002       return false;
9003     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
9004 
9005     if (E->getNumArgs() > 2) {
9006       APSInt Offset;
9007       if (!EvaluateInteger(E->getArg(2), Offset, Info))
9008         return false;
9009 
9010       int64_t AdditionalOffset = -Offset.getZExtValue();
9011       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
9012     }
9013 
9014     // If there is a base object, then it must have the correct alignment.
9015     if (OffsetResult.Base) {
9016       CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
9017 
9018       if (BaseAlignment < Align) {
9019         Result.Designator.setInvalid();
9020         // FIXME: Add support to Diagnostic for long / long long.
9021         CCEDiag(E->getArg(0),
9022                 diag::note_constexpr_baa_insufficient_alignment) << 0
9023           << (unsigned)BaseAlignment.getQuantity()
9024           << (unsigned)Align.getQuantity();
9025         return false;
9026       }
9027     }
9028 
9029     // The offset must also have the correct alignment.
9030     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
9031       Result.Designator.setInvalid();
9032 
9033       (OffsetResult.Base
9034            ? CCEDiag(E->getArg(0),
9035                      diag::note_constexpr_baa_insufficient_alignment) << 1
9036            : CCEDiag(E->getArg(0),
9037                      diag::note_constexpr_baa_value_insufficient_alignment))
9038         << (int)OffsetResult.Offset.getQuantity()
9039         << (unsigned)Align.getQuantity();
9040       return false;
9041     }
9042 
9043     return true;
9044   }
9045   case Builtin::BI__builtin_align_up:
9046   case Builtin::BI__builtin_align_down: {
9047     if (!evaluatePointer(E->getArg(0), Result))
9048       return false;
9049     APSInt Alignment;
9050     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9051                               Alignment))
9052       return false;
9053     CharUnits BaseAlignment = getBaseAlignment(Info, Result);
9054     CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
9055     // For align_up/align_down, we can return the same value if the alignment
9056     // is known to be greater or equal to the requested value.
9057     if (PtrAlign.getQuantity() >= Alignment)
9058       return true;
9059 
9060     // The alignment could be greater than the minimum at run-time, so we cannot
9061     // infer much about the resulting pointer value. One case is possible:
9062     // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
9063     // can infer the correct index if the requested alignment is smaller than
9064     // the base alignment so we can perform the computation on the offset.
9065     if (BaseAlignment.getQuantity() >= Alignment) {
9066       assert(Alignment.getBitWidth() <= 64 &&
9067              "Cannot handle > 64-bit address-space");
9068       uint64_t Alignment64 = Alignment.getZExtValue();
9069       CharUnits NewOffset = CharUnits::fromQuantity(
9070           BuiltinOp == Builtin::BI__builtin_align_down
9071               ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
9072               : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
9073       Result.adjustOffset(NewOffset - Result.Offset);
9074       // TODO: diagnose out-of-bounds values/only allow for arrays?
9075       return true;
9076     }
9077     // Otherwise, we cannot constant-evaluate the result.
9078     Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
9079         << Alignment;
9080     return false;
9081   }
9082   case Builtin::BI__builtin_operator_new:
9083     return HandleOperatorNewCall(Info, E, Result);
9084   case Builtin::BI__builtin_launder:
9085     return evaluatePointer(E->getArg(0), Result);
9086   case Builtin::BIstrchr:
9087   case Builtin::BIwcschr:
9088   case Builtin::BImemchr:
9089   case Builtin::BIwmemchr:
9090     if (Info.getLangOpts().CPlusPlus11)
9091       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9092         << /*isConstexpr*/0 << /*isConstructor*/0
9093         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9094     else
9095       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9096     LLVM_FALLTHROUGH;
9097   case Builtin::BI__builtin_strchr:
9098   case Builtin::BI__builtin_wcschr:
9099   case Builtin::BI__builtin_memchr:
9100   case Builtin::BI__builtin_char_memchr:
9101   case Builtin::BI__builtin_wmemchr: {
9102     if (!Visit(E->getArg(0)))
9103       return false;
9104     APSInt Desired;
9105     if (!EvaluateInteger(E->getArg(1), Desired, Info))
9106       return false;
9107     uint64_t MaxLength = uint64_t(-1);
9108     if (BuiltinOp != Builtin::BIstrchr &&
9109         BuiltinOp != Builtin::BIwcschr &&
9110         BuiltinOp != Builtin::BI__builtin_strchr &&
9111         BuiltinOp != Builtin::BI__builtin_wcschr) {
9112       APSInt N;
9113       if (!EvaluateInteger(E->getArg(2), N, Info))
9114         return false;
9115       MaxLength = N.getExtValue();
9116     }
9117     // We cannot find the value if there are no candidates to match against.
9118     if (MaxLength == 0u)
9119       return ZeroInitialization(E);
9120     if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9121         Result.Designator.Invalid)
9122       return false;
9123     QualType CharTy = Result.Designator.getType(Info.Ctx);
9124     bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
9125                      BuiltinOp == Builtin::BI__builtin_memchr;
9126     assert(IsRawByte ||
9127            Info.Ctx.hasSameUnqualifiedType(
9128                CharTy, E->getArg(0)->getType()->getPointeeType()));
9129     // Pointers to const void may point to objects of incomplete type.
9130     if (IsRawByte && CharTy->isIncompleteType()) {
9131       Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
9132       return false;
9133     }
9134     // Give up on byte-oriented matching against multibyte elements.
9135     // FIXME: We can compare the bytes in the correct order.
9136     if (IsRawByte && !isOneByteCharacterType(CharTy)) {
9137       Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
9138           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
9139           << CharTy;
9140       return false;
9141     }
9142     // Figure out what value we're actually looking for (after converting to
9143     // the corresponding unsigned type if necessary).
9144     uint64_t DesiredVal;
9145     bool StopAtNull = false;
9146     switch (BuiltinOp) {
9147     case Builtin::BIstrchr:
9148     case Builtin::BI__builtin_strchr:
9149       // strchr compares directly to the passed integer, and therefore
9150       // always fails if given an int that is not a char.
9151       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
9152                                                   E->getArg(1)->getType(),
9153                                                   Desired),
9154                                Desired))
9155         return ZeroInitialization(E);
9156       StopAtNull = true;
9157       LLVM_FALLTHROUGH;
9158     case Builtin::BImemchr:
9159     case Builtin::BI__builtin_memchr:
9160     case Builtin::BI__builtin_char_memchr:
9161       // memchr compares by converting both sides to unsigned char. That's also
9162       // correct for strchr if we get this far (to cope with plain char being
9163       // unsigned in the strchr case).
9164       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
9165       break;
9166 
9167     case Builtin::BIwcschr:
9168     case Builtin::BI__builtin_wcschr:
9169       StopAtNull = true;
9170       LLVM_FALLTHROUGH;
9171     case Builtin::BIwmemchr:
9172     case Builtin::BI__builtin_wmemchr:
9173       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
9174       DesiredVal = Desired.getZExtValue();
9175       break;
9176     }
9177 
9178     for (; MaxLength; --MaxLength) {
9179       APValue Char;
9180       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
9181           !Char.isInt())
9182         return false;
9183       if (Char.getInt().getZExtValue() == DesiredVal)
9184         return true;
9185       if (StopAtNull && !Char.getInt())
9186         break;
9187       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
9188         return false;
9189     }
9190     // Not found: return nullptr.
9191     return ZeroInitialization(E);
9192   }
9193 
9194   case Builtin::BImemcpy:
9195   case Builtin::BImemmove:
9196   case Builtin::BIwmemcpy:
9197   case Builtin::BIwmemmove:
9198     if (Info.getLangOpts().CPlusPlus11)
9199       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9200         << /*isConstexpr*/0 << /*isConstructor*/0
9201         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9202     else
9203       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9204     LLVM_FALLTHROUGH;
9205   case Builtin::BI__builtin_memcpy:
9206   case Builtin::BI__builtin_memmove:
9207   case Builtin::BI__builtin_wmemcpy:
9208   case Builtin::BI__builtin_wmemmove: {
9209     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
9210                  BuiltinOp == Builtin::BIwmemmove ||
9211                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
9212                  BuiltinOp == Builtin::BI__builtin_wmemmove;
9213     bool Move = BuiltinOp == Builtin::BImemmove ||
9214                 BuiltinOp == Builtin::BIwmemmove ||
9215                 BuiltinOp == Builtin::BI__builtin_memmove ||
9216                 BuiltinOp == Builtin::BI__builtin_wmemmove;
9217 
9218     // The result of mem* is the first argument.
9219     if (!Visit(E->getArg(0)))
9220       return false;
9221     LValue Dest = Result;
9222 
9223     LValue Src;
9224     if (!EvaluatePointer(E->getArg(1), Src, Info))
9225       return false;
9226 
9227     APSInt N;
9228     if (!EvaluateInteger(E->getArg(2), N, Info))
9229       return false;
9230     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
9231 
9232     // If the size is zero, we treat this as always being a valid no-op.
9233     // (Even if one of the src and dest pointers is null.)
9234     if (!N)
9235       return true;
9236 
9237     // Otherwise, if either of the operands is null, we can't proceed. Don't
9238     // try to determine the type of the copied objects, because there aren't
9239     // any.
9240     if (!Src.Base || !Dest.Base) {
9241       APValue Val;
9242       (!Src.Base ? Src : Dest).moveInto(Val);
9243       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
9244           << Move << WChar << !!Src.Base
9245           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
9246       return false;
9247     }
9248     if (Src.Designator.Invalid || Dest.Designator.Invalid)
9249       return false;
9250 
9251     // We require that Src and Dest are both pointers to arrays of
9252     // trivially-copyable type. (For the wide version, the designator will be
9253     // invalid if the designated object is not a wchar_t.)
9254     QualType T = Dest.Designator.getType(Info.Ctx);
9255     QualType SrcT = Src.Designator.getType(Info.Ctx);
9256     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
9257       // FIXME: Consider using our bit_cast implementation to support this.
9258       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
9259       return false;
9260     }
9261     if (T->isIncompleteType()) {
9262       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
9263       return false;
9264     }
9265     if (!T.isTriviallyCopyableType(Info.Ctx)) {
9266       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
9267       return false;
9268     }
9269 
9270     // Figure out how many T's we're copying.
9271     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
9272     if (!WChar) {
9273       uint64_t Remainder;
9274       llvm::APInt OrigN = N;
9275       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
9276       if (Remainder) {
9277         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9278             << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
9279             << (unsigned)TSize;
9280         return false;
9281       }
9282     }
9283 
9284     // Check that the copying will remain within the arrays, just so that we
9285     // can give a more meaningful diagnostic. This implicitly also checks that
9286     // N fits into 64 bits.
9287     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
9288     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
9289     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
9290       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9291           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
9292           << toString(N, 10, /*Signed*/false);
9293       return false;
9294     }
9295     uint64_t NElems = N.getZExtValue();
9296     uint64_t NBytes = NElems * TSize;
9297 
9298     // Check for overlap.
9299     int Direction = 1;
9300     if (HasSameBase(Src, Dest)) {
9301       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
9302       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
9303       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
9304         // Dest is inside the source region.
9305         if (!Move) {
9306           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9307           return false;
9308         }
9309         // For memmove and friends, copy backwards.
9310         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
9311             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
9312           return false;
9313         Direction = -1;
9314       } else if (!Move && SrcOffset >= DestOffset &&
9315                  SrcOffset - DestOffset < NBytes) {
9316         // Src is inside the destination region for memcpy: invalid.
9317         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9318         return false;
9319       }
9320     }
9321 
9322     while (true) {
9323       APValue Val;
9324       // FIXME: Set WantObjectRepresentation to true if we're copying a
9325       // char-like type?
9326       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
9327           !handleAssignment(Info, E, Dest, T, Val))
9328         return false;
9329       // Do not iterate past the last element; if we're copying backwards, that
9330       // might take us off the start of the array.
9331       if (--NElems == 0)
9332         return true;
9333       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
9334           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
9335         return false;
9336     }
9337   }
9338 
9339   default:
9340     break;
9341   }
9342 
9343   return visitNonBuiltinCallExpr(E);
9344 }
9345 
9346 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9347                                      APValue &Result, const InitListExpr *ILE,
9348                                      QualType AllocType);
9349 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
9350                                           APValue &Result,
9351                                           const CXXConstructExpr *CCE,
9352                                           QualType AllocType);
9353 
9354 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
9355   if (!Info.getLangOpts().CPlusPlus20)
9356     Info.CCEDiag(E, diag::note_constexpr_new);
9357 
9358   // We cannot speculatively evaluate a delete expression.
9359   if (Info.SpeculativeEvaluationDepth)
9360     return false;
9361 
9362   FunctionDecl *OperatorNew = E->getOperatorNew();
9363 
9364   bool IsNothrow = false;
9365   bool IsPlacement = false;
9366   if (OperatorNew->isReservedGlobalPlacementOperator() &&
9367       Info.CurrentCall->isStdFunction() && !E->isArray()) {
9368     // FIXME Support array placement new.
9369     assert(E->getNumPlacementArgs() == 1);
9370     if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
9371       return false;
9372     if (Result.Designator.Invalid)
9373       return false;
9374     IsPlacement = true;
9375   } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
9376     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
9377         << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
9378     return false;
9379   } else if (E->getNumPlacementArgs()) {
9380     // The only new-placement list we support is of the form (std::nothrow).
9381     //
9382     // FIXME: There is no restriction on this, but it's not clear that any
9383     // other form makes any sense. We get here for cases such as:
9384     //
9385     //   new (std::align_val_t{N}) X(int)
9386     //
9387     // (which should presumably be valid only if N is a multiple of
9388     // alignof(int), and in any case can't be deallocated unless N is
9389     // alignof(X) and X has new-extended alignment).
9390     if (E->getNumPlacementArgs() != 1 ||
9391         !E->getPlacementArg(0)->getType()->isNothrowT())
9392       return Error(E, diag::note_constexpr_new_placement);
9393 
9394     LValue Nothrow;
9395     if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
9396       return false;
9397     IsNothrow = true;
9398   }
9399 
9400   const Expr *Init = E->getInitializer();
9401   const InitListExpr *ResizedArrayILE = nullptr;
9402   const CXXConstructExpr *ResizedArrayCCE = nullptr;
9403   bool ValueInit = false;
9404 
9405   QualType AllocType = E->getAllocatedType();
9406   if (Optional<const Expr*> ArraySize = E->getArraySize()) {
9407     const Expr *Stripped = *ArraySize;
9408     for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
9409          Stripped = ICE->getSubExpr())
9410       if (ICE->getCastKind() != CK_NoOp &&
9411           ICE->getCastKind() != CK_IntegralCast)
9412         break;
9413 
9414     llvm::APSInt ArrayBound;
9415     if (!EvaluateInteger(Stripped, ArrayBound, Info))
9416       return false;
9417 
9418     // C++ [expr.new]p9:
9419     //   The expression is erroneous if:
9420     //   -- [...] its value before converting to size_t [or] applying the
9421     //      second standard conversion sequence is less than zero
9422     if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
9423       if (IsNothrow)
9424         return ZeroInitialization(E);
9425 
9426       Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
9427           << ArrayBound << (*ArraySize)->getSourceRange();
9428       return false;
9429     }
9430 
9431     //   -- its value is such that the size of the allocated object would
9432     //      exceed the implementation-defined limit
9433     if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
9434                                                 ArrayBound) >
9435         ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
9436       if (IsNothrow)
9437         return ZeroInitialization(E);
9438 
9439       Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
9440         << ArrayBound << (*ArraySize)->getSourceRange();
9441       return false;
9442     }
9443 
9444     //   -- the new-initializer is a braced-init-list and the number of
9445     //      array elements for which initializers are provided [...]
9446     //      exceeds the number of elements to initialize
9447     if (!Init) {
9448       // No initialization is performed.
9449     } else if (isa<CXXScalarValueInitExpr>(Init) ||
9450                isa<ImplicitValueInitExpr>(Init)) {
9451       ValueInit = true;
9452     } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
9453       ResizedArrayCCE = CCE;
9454     } else {
9455       auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
9456       assert(CAT && "unexpected type for array initializer");
9457 
9458       unsigned Bits =
9459           std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
9460       llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits);
9461       llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits);
9462       if (InitBound.ugt(AllocBound)) {
9463         if (IsNothrow)
9464           return ZeroInitialization(E);
9465 
9466         Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
9467             << toString(AllocBound, 10, /*Signed=*/false)
9468             << toString(InitBound, 10, /*Signed=*/false)
9469             << (*ArraySize)->getSourceRange();
9470         return false;
9471       }
9472 
9473       // If the sizes differ, we must have an initializer list, and we need
9474       // special handling for this case when we initialize.
9475       if (InitBound != AllocBound)
9476         ResizedArrayILE = cast<InitListExpr>(Init);
9477     }
9478 
9479     AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
9480                                               ArrayType::Normal, 0);
9481   } else {
9482     assert(!AllocType->isArrayType() &&
9483            "array allocation with non-array new");
9484   }
9485 
9486   APValue *Val;
9487   if (IsPlacement) {
9488     AccessKinds AK = AK_Construct;
9489     struct FindObjectHandler {
9490       EvalInfo &Info;
9491       const Expr *E;
9492       QualType AllocType;
9493       const AccessKinds AccessKind;
9494       APValue *Value;
9495 
9496       typedef bool result_type;
9497       bool failed() { return false; }
9498       bool found(APValue &Subobj, QualType SubobjType) {
9499         // FIXME: Reject the cases where [basic.life]p8 would not permit the
9500         // old name of the object to be used to name the new object.
9501         if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
9502           Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
9503             SubobjType << AllocType;
9504           return false;
9505         }
9506         Value = &Subobj;
9507         return true;
9508       }
9509       bool found(APSInt &Value, QualType SubobjType) {
9510         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9511         return false;
9512       }
9513       bool found(APFloat &Value, QualType SubobjType) {
9514         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9515         return false;
9516       }
9517     } Handler = {Info, E, AllocType, AK, nullptr};
9518 
9519     CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
9520     if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
9521       return false;
9522 
9523     Val = Handler.Value;
9524 
9525     // [basic.life]p1:
9526     //   The lifetime of an object o of type T ends when [...] the storage
9527     //   which the object occupies is [...] reused by an object that is not
9528     //   nested within o (6.6.2).
9529     *Val = APValue();
9530   } else {
9531     // Perform the allocation and obtain a pointer to the resulting object.
9532     Val = Info.createHeapAlloc(E, AllocType, Result);
9533     if (!Val)
9534       return false;
9535   }
9536 
9537   if (ValueInit) {
9538     ImplicitValueInitExpr VIE(AllocType);
9539     if (!EvaluateInPlace(*Val, Info, Result, &VIE))
9540       return false;
9541   } else if (ResizedArrayILE) {
9542     if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
9543                                   AllocType))
9544       return false;
9545   } else if (ResizedArrayCCE) {
9546     if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
9547                                        AllocType))
9548       return false;
9549   } else if (Init) {
9550     if (!EvaluateInPlace(*Val, Info, Result, Init))
9551       return false;
9552   } else if (!getDefaultInitValue(AllocType, *Val)) {
9553     return false;
9554   }
9555 
9556   // Array new returns a pointer to the first element, not a pointer to the
9557   // array.
9558   if (auto *AT = AllocType->getAsArrayTypeUnsafe())
9559     Result.addArray(Info, E, cast<ConstantArrayType>(AT));
9560 
9561   return true;
9562 }
9563 //===----------------------------------------------------------------------===//
9564 // Member Pointer Evaluation
9565 //===----------------------------------------------------------------------===//
9566 
9567 namespace {
9568 class MemberPointerExprEvaluator
9569   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
9570   MemberPtr &Result;
9571 
9572   bool Success(const ValueDecl *D) {
9573     Result = MemberPtr(D);
9574     return true;
9575   }
9576 public:
9577 
9578   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
9579     : ExprEvaluatorBaseTy(Info), Result(Result) {}
9580 
9581   bool Success(const APValue &V, const Expr *E) {
9582     Result.setFrom(V);
9583     return true;
9584   }
9585   bool ZeroInitialization(const Expr *E) {
9586     return Success((const ValueDecl*)nullptr);
9587   }
9588 
9589   bool VisitCastExpr(const CastExpr *E);
9590   bool VisitUnaryAddrOf(const UnaryOperator *E);
9591 };
9592 } // end anonymous namespace
9593 
9594 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
9595                                   EvalInfo &Info) {
9596   assert(!E->isValueDependent());
9597   assert(E->isPRValue() && E->getType()->isMemberPointerType());
9598   return MemberPointerExprEvaluator(Info, Result).Visit(E);
9599 }
9600 
9601 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9602   switch (E->getCastKind()) {
9603   default:
9604     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9605 
9606   case CK_NullToMemberPointer:
9607     VisitIgnoredValue(E->getSubExpr());
9608     return ZeroInitialization(E);
9609 
9610   case CK_BaseToDerivedMemberPointer: {
9611     if (!Visit(E->getSubExpr()))
9612       return false;
9613     if (E->path_empty())
9614       return true;
9615     // Base-to-derived member pointer casts store the path in derived-to-base
9616     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
9617     // the wrong end of the derived->base arc, so stagger the path by one class.
9618     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
9619     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
9620          PathI != PathE; ++PathI) {
9621       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9622       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
9623       if (!Result.castToDerived(Derived))
9624         return Error(E);
9625     }
9626     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
9627     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
9628       return Error(E);
9629     return true;
9630   }
9631 
9632   case CK_DerivedToBaseMemberPointer:
9633     if (!Visit(E->getSubExpr()))
9634       return false;
9635     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9636          PathE = E->path_end(); PathI != PathE; ++PathI) {
9637       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9638       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9639       if (!Result.castToBase(Base))
9640         return Error(E);
9641     }
9642     return true;
9643   }
9644 }
9645 
9646 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9647   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
9648   // member can be formed.
9649   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
9650 }
9651 
9652 //===----------------------------------------------------------------------===//
9653 // Record Evaluation
9654 //===----------------------------------------------------------------------===//
9655 
9656 namespace {
9657   class RecordExprEvaluator
9658   : public ExprEvaluatorBase<RecordExprEvaluator> {
9659     const LValue &This;
9660     APValue &Result;
9661   public:
9662 
9663     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
9664       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
9665 
9666     bool Success(const APValue &V, const Expr *E) {
9667       Result = V;
9668       return true;
9669     }
9670     bool ZeroInitialization(const Expr *E) {
9671       return ZeroInitialization(E, E->getType());
9672     }
9673     bool ZeroInitialization(const Expr *E, QualType T);
9674 
9675     bool VisitCallExpr(const CallExpr *E) {
9676       return handleCallExpr(E, Result, &This);
9677     }
9678     bool VisitCastExpr(const CastExpr *E);
9679     bool VisitInitListExpr(const InitListExpr *E);
9680     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9681       return VisitCXXConstructExpr(E, E->getType());
9682     }
9683     bool VisitLambdaExpr(const LambdaExpr *E);
9684     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
9685     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
9686     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
9687     bool VisitBinCmp(const BinaryOperator *E);
9688   };
9689 }
9690 
9691 /// Perform zero-initialization on an object of non-union class type.
9692 /// C++11 [dcl.init]p5:
9693 ///  To zero-initialize an object or reference of type T means:
9694 ///    [...]
9695 ///    -- if T is a (possibly cv-qualified) non-union class type,
9696 ///       each non-static data member and each base-class subobject is
9697 ///       zero-initialized
9698 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
9699                                           const RecordDecl *RD,
9700                                           const LValue &This, APValue &Result) {
9701   assert(!RD->isUnion() && "Expected non-union class type");
9702   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
9703   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
9704                    std::distance(RD->field_begin(), RD->field_end()));
9705 
9706   if (RD->isInvalidDecl()) return false;
9707   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9708 
9709   if (CD) {
9710     unsigned Index = 0;
9711     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
9712            End = CD->bases_end(); I != End; ++I, ++Index) {
9713       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
9714       LValue Subobject = This;
9715       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
9716         return false;
9717       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
9718                                          Result.getStructBase(Index)))
9719         return false;
9720     }
9721   }
9722 
9723   for (const auto *I : RD->fields()) {
9724     // -- if T is a reference type, no initialization is performed.
9725     if (I->isUnnamedBitfield() || I->getType()->isReferenceType())
9726       continue;
9727 
9728     LValue Subobject = This;
9729     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
9730       return false;
9731 
9732     ImplicitValueInitExpr VIE(I->getType());
9733     if (!EvaluateInPlace(
9734           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
9735       return false;
9736   }
9737 
9738   return true;
9739 }
9740 
9741 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
9742   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
9743   if (RD->isInvalidDecl()) return false;
9744   if (RD->isUnion()) {
9745     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
9746     // object's first non-static named data member is zero-initialized
9747     RecordDecl::field_iterator I = RD->field_begin();
9748     while (I != RD->field_end() && (*I)->isUnnamedBitfield())
9749       ++I;
9750     if (I == RD->field_end()) {
9751       Result = APValue((const FieldDecl*)nullptr);
9752       return true;
9753     }
9754 
9755     LValue Subobject = This;
9756     if (!HandleLValueMember(Info, E, Subobject, *I))
9757       return false;
9758     Result = APValue(*I);
9759     ImplicitValueInitExpr VIE(I->getType());
9760     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
9761   }
9762 
9763   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
9764     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
9765     return false;
9766   }
9767 
9768   return HandleClassZeroInitialization(Info, E, RD, This, Result);
9769 }
9770 
9771 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
9772   switch (E->getCastKind()) {
9773   default:
9774     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9775 
9776   case CK_ConstructorConversion:
9777     return Visit(E->getSubExpr());
9778 
9779   case CK_DerivedToBase:
9780   case CK_UncheckedDerivedToBase: {
9781     APValue DerivedObject;
9782     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
9783       return false;
9784     if (!DerivedObject.isStruct())
9785       return Error(E->getSubExpr());
9786 
9787     // Derived-to-base rvalue conversion: just slice off the derived part.
9788     APValue *Value = &DerivedObject;
9789     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
9790     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9791          PathE = E->path_end(); PathI != PathE; ++PathI) {
9792       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
9793       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9794       Value = &Value->getStructBase(getBaseIndex(RD, Base));
9795       RD = Base;
9796     }
9797     Result = *Value;
9798     return true;
9799   }
9800   }
9801 }
9802 
9803 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9804   if (E->isTransparent())
9805     return Visit(E->getInit(0));
9806 
9807   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
9808   if (RD->isInvalidDecl()) return false;
9809   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9810   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
9811 
9812   EvalInfo::EvaluatingConstructorRAII EvalObj(
9813       Info,
9814       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
9815       CXXRD && CXXRD->getNumBases());
9816 
9817   if (RD->isUnion()) {
9818     const FieldDecl *Field = E->getInitializedFieldInUnion();
9819     Result = APValue(Field);
9820     if (!Field)
9821       return true;
9822 
9823     // If the initializer list for a union does not contain any elements, the
9824     // first element of the union is value-initialized.
9825     // FIXME: The element should be initialized from an initializer list.
9826     //        Is this difference ever observable for initializer lists which
9827     //        we don't build?
9828     ImplicitValueInitExpr VIE(Field->getType());
9829     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
9830 
9831     LValue Subobject = This;
9832     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
9833       return false;
9834 
9835     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9836     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9837                                   isa<CXXDefaultInitExpr>(InitExpr));
9838 
9839     if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
9840       if (Field->isBitField())
9841         return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
9842                                      Field);
9843       return true;
9844     }
9845 
9846     return false;
9847   }
9848 
9849   if (!Result.hasValue())
9850     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
9851                      std::distance(RD->field_begin(), RD->field_end()));
9852   unsigned ElementNo = 0;
9853   bool Success = true;
9854 
9855   // Initialize base classes.
9856   if (CXXRD && CXXRD->getNumBases()) {
9857     for (const auto &Base : CXXRD->bases()) {
9858       assert(ElementNo < E->getNumInits() && "missing init for base class");
9859       const Expr *Init = E->getInit(ElementNo);
9860 
9861       LValue Subobject = This;
9862       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
9863         return false;
9864 
9865       APValue &FieldVal = Result.getStructBase(ElementNo);
9866       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
9867         if (!Info.noteFailure())
9868           return false;
9869         Success = false;
9870       }
9871       ++ElementNo;
9872     }
9873 
9874     EvalObj.finishedConstructingBases();
9875   }
9876 
9877   // Initialize members.
9878   for (const auto *Field : RD->fields()) {
9879     // Anonymous bit-fields are not considered members of the class for
9880     // purposes of aggregate initialization.
9881     if (Field->isUnnamedBitfield())
9882       continue;
9883 
9884     LValue Subobject = This;
9885 
9886     bool HaveInit = ElementNo < E->getNumInits();
9887 
9888     // FIXME: Diagnostics here should point to the end of the initializer
9889     // list, not the start.
9890     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
9891                             Subobject, Field, &Layout))
9892       return false;
9893 
9894     // Perform an implicit value-initialization for members beyond the end of
9895     // the initializer list.
9896     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
9897     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
9898 
9899     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9900     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9901                                   isa<CXXDefaultInitExpr>(Init));
9902 
9903     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9904     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
9905         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
9906                                                        FieldVal, Field))) {
9907       if (!Info.noteFailure())
9908         return false;
9909       Success = false;
9910     }
9911   }
9912 
9913   EvalObj.finishedConstructingFields();
9914 
9915   return Success;
9916 }
9917 
9918 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
9919                                                 QualType T) {
9920   // Note that E's type is not necessarily the type of our class here; we might
9921   // be initializing an array element instead.
9922   const CXXConstructorDecl *FD = E->getConstructor();
9923   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
9924 
9925   bool ZeroInit = E->requiresZeroInitialization();
9926   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
9927     // If we've already performed zero-initialization, we're already done.
9928     if (Result.hasValue())
9929       return true;
9930 
9931     if (ZeroInit)
9932       return ZeroInitialization(E, T);
9933 
9934     return getDefaultInitValue(T, Result);
9935   }
9936 
9937   const FunctionDecl *Definition = nullptr;
9938   auto Body = FD->getBody(Definition);
9939 
9940   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9941     return false;
9942 
9943   // Avoid materializing a temporary for an elidable copy/move constructor.
9944   if (E->isElidable() && !ZeroInit) {
9945     // FIXME: This only handles the simplest case, where the source object
9946     //        is passed directly as the first argument to the constructor.
9947     //        This should also handle stepping though implicit casts and
9948     //        and conversion sequences which involve two steps, with a
9949     //        conversion operator followed by a converting constructor.
9950     const Expr *SrcObj = E->getArg(0);
9951     assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
9952     assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
9953     if (const MaterializeTemporaryExpr *ME =
9954             dyn_cast<MaterializeTemporaryExpr>(SrcObj))
9955       return Visit(ME->getSubExpr());
9956   }
9957 
9958   if (ZeroInit && !ZeroInitialization(E, T))
9959     return false;
9960 
9961   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
9962   return HandleConstructorCall(E, This, Args,
9963                                cast<CXXConstructorDecl>(Definition), Info,
9964                                Result);
9965 }
9966 
9967 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
9968     const CXXInheritedCtorInitExpr *E) {
9969   if (!Info.CurrentCall) {
9970     assert(Info.checkingPotentialConstantExpression());
9971     return false;
9972   }
9973 
9974   const CXXConstructorDecl *FD = E->getConstructor();
9975   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
9976     return false;
9977 
9978   const FunctionDecl *Definition = nullptr;
9979   auto Body = FD->getBody(Definition);
9980 
9981   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9982     return false;
9983 
9984   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
9985                                cast<CXXConstructorDecl>(Definition), Info,
9986                                Result);
9987 }
9988 
9989 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
9990     const CXXStdInitializerListExpr *E) {
9991   const ConstantArrayType *ArrayType =
9992       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
9993 
9994   LValue Array;
9995   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
9996     return false;
9997 
9998   // Get a pointer to the first element of the array.
9999   Array.addArray(Info, E, ArrayType);
10000 
10001   auto InvalidType = [&] {
10002     Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
10003       << E->getType();
10004     return false;
10005   };
10006 
10007   // FIXME: Perform the checks on the field types in SemaInit.
10008   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
10009   RecordDecl::field_iterator Field = Record->field_begin();
10010   if (Field == Record->field_end())
10011     return InvalidType();
10012 
10013   // Start pointer.
10014   if (!Field->getType()->isPointerType() ||
10015       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10016                             ArrayType->getElementType()))
10017     return InvalidType();
10018 
10019   // FIXME: What if the initializer_list type has base classes, etc?
10020   Result = APValue(APValue::UninitStruct(), 0, 2);
10021   Array.moveInto(Result.getStructField(0));
10022 
10023   if (++Field == Record->field_end())
10024     return InvalidType();
10025 
10026   if (Field->getType()->isPointerType() &&
10027       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10028                            ArrayType->getElementType())) {
10029     // End pointer.
10030     if (!HandleLValueArrayAdjustment(Info, E, Array,
10031                                      ArrayType->getElementType(),
10032                                      ArrayType->getSize().getZExtValue()))
10033       return false;
10034     Array.moveInto(Result.getStructField(1));
10035   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
10036     // Length.
10037     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
10038   else
10039     return InvalidType();
10040 
10041   if (++Field != Record->field_end())
10042     return InvalidType();
10043 
10044   return true;
10045 }
10046 
10047 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
10048   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
10049   if (ClosureClass->isInvalidDecl())
10050     return false;
10051 
10052   const size_t NumFields =
10053       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
10054 
10055   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
10056                                             E->capture_init_end()) &&
10057          "The number of lambda capture initializers should equal the number of "
10058          "fields within the closure type");
10059 
10060   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
10061   // Iterate through all the lambda's closure object's fields and initialize
10062   // them.
10063   auto *CaptureInitIt = E->capture_init_begin();
10064   const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
10065   bool Success = true;
10066   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
10067   for (const auto *Field : ClosureClass->fields()) {
10068     assert(CaptureInitIt != E->capture_init_end());
10069     // Get the initializer for this field
10070     Expr *const CurFieldInit = *CaptureInitIt++;
10071 
10072     // If there is no initializer, either this is a VLA or an error has
10073     // occurred.
10074     if (!CurFieldInit)
10075       return Error(E);
10076 
10077     LValue Subobject = This;
10078 
10079     if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
10080       return false;
10081 
10082     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10083     if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
10084       if (!Info.keepEvaluatingAfterFailure())
10085         return false;
10086       Success = false;
10087     }
10088     ++CaptureIt;
10089   }
10090   return Success;
10091 }
10092 
10093 static bool EvaluateRecord(const Expr *E, const LValue &This,
10094                            APValue &Result, EvalInfo &Info) {
10095   assert(!E->isValueDependent());
10096   assert(E->isPRValue() && E->getType()->isRecordType() &&
10097          "can't evaluate expression as a record rvalue");
10098   return RecordExprEvaluator(Info, This, Result).Visit(E);
10099 }
10100 
10101 //===----------------------------------------------------------------------===//
10102 // Temporary Evaluation
10103 //
10104 // Temporaries are represented in the AST as rvalues, but generally behave like
10105 // lvalues. The full-object of which the temporary is a subobject is implicitly
10106 // materialized so that a reference can bind to it.
10107 //===----------------------------------------------------------------------===//
10108 namespace {
10109 class TemporaryExprEvaluator
10110   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
10111 public:
10112   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
10113     LValueExprEvaluatorBaseTy(Info, Result, false) {}
10114 
10115   /// Visit an expression which constructs the value of this temporary.
10116   bool VisitConstructExpr(const Expr *E) {
10117     APValue &Value = Info.CurrentCall->createTemporary(
10118         E, E->getType(), ScopeKind::FullExpression, Result);
10119     return EvaluateInPlace(Value, Info, Result, E);
10120   }
10121 
10122   bool VisitCastExpr(const CastExpr *E) {
10123     switch (E->getCastKind()) {
10124     default:
10125       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
10126 
10127     case CK_ConstructorConversion:
10128       return VisitConstructExpr(E->getSubExpr());
10129     }
10130   }
10131   bool VisitInitListExpr(const InitListExpr *E) {
10132     return VisitConstructExpr(E);
10133   }
10134   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10135     return VisitConstructExpr(E);
10136   }
10137   bool VisitCallExpr(const CallExpr *E) {
10138     return VisitConstructExpr(E);
10139   }
10140   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
10141     return VisitConstructExpr(E);
10142   }
10143   bool VisitLambdaExpr(const LambdaExpr *E) {
10144     return VisitConstructExpr(E);
10145   }
10146 };
10147 } // end anonymous namespace
10148 
10149 /// Evaluate an expression of record type as a temporary.
10150 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
10151   assert(!E->isValueDependent());
10152   assert(E->isPRValue() && E->getType()->isRecordType());
10153   return TemporaryExprEvaluator(Info, Result).Visit(E);
10154 }
10155 
10156 //===----------------------------------------------------------------------===//
10157 // Vector Evaluation
10158 //===----------------------------------------------------------------------===//
10159 
10160 namespace {
10161   class VectorExprEvaluator
10162   : public ExprEvaluatorBase<VectorExprEvaluator> {
10163     APValue &Result;
10164   public:
10165 
10166     VectorExprEvaluator(EvalInfo &info, APValue &Result)
10167       : ExprEvaluatorBaseTy(info), Result(Result) {}
10168 
10169     bool Success(ArrayRef<APValue> V, const Expr *E) {
10170       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
10171       // FIXME: remove this APValue copy.
10172       Result = APValue(V.data(), V.size());
10173       return true;
10174     }
10175     bool Success(const APValue &V, const Expr *E) {
10176       assert(V.isVector());
10177       Result = V;
10178       return true;
10179     }
10180     bool ZeroInitialization(const Expr *E);
10181 
10182     bool VisitUnaryReal(const UnaryOperator *E)
10183       { return Visit(E->getSubExpr()); }
10184     bool VisitCastExpr(const CastExpr* E);
10185     bool VisitInitListExpr(const InitListExpr *E);
10186     bool VisitUnaryImag(const UnaryOperator *E);
10187     bool VisitBinaryOperator(const BinaryOperator *E);
10188     bool VisitUnaryOperator(const UnaryOperator *E);
10189     // FIXME: Missing: conditional operator (for GNU
10190     //                 conditional select), shufflevector, ExtVectorElementExpr
10191   };
10192 } // end anonymous namespace
10193 
10194 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
10195   assert(E->isPRValue() && E->getType()->isVectorType() &&
10196          "not a vector prvalue");
10197   return VectorExprEvaluator(Info, Result).Visit(E);
10198 }
10199 
10200 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
10201   const VectorType *VTy = E->getType()->castAs<VectorType>();
10202   unsigned NElts = VTy->getNumElements();
10203 
10204   const Expr *SE = E->getSubExpr();
10205   QualType SETy = SE->getType();
10206 
10207   switch (E->getCastKind()) {
10208   case CK_VectorSplat: {
10209     APValue Val = APValue();
10210     if (SETy->isIntegerType()) {
10211       APSInt IntResult;
10212       if (!EvaluateInteger(SE, IntResult, Info))
10213         return false;
10214       Val = APValue(std::move(IntResult));
10215     } else if (SETy->isRealFloatingType()) {
10216       APFloat FloatResult(0.0);
10217       if (!EvaluateFloat(SE, FloatResult, Info))
10218         return false;
10219       Val = APValue(std::move(FloatResult));
10220     } else {
10221       return Error(E);
10222     }
10223 
10224     // Splat and create vector APValue.
10225     SmallVector<APValue, 4> Elts(NElts, Val);
10226     return Success(Elts, E);
10227   }
10228   case CK_BitCast: {
10229     // Evaluate the operand into an APInt we can extract from.
10230     llvm::APInt SValInt;
10231     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
10232       return false;
10233     // Extract the elements
10234     QualType EltTy = VTy->getElementType();
10235     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
10236     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
10237     SmallVector<APValue, 4> Elts;
10238     if (EltTy->isRealFloatingType()) {
10239       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
10240       unsigned FloatEltSize = EltSize;
10241       if (&Sem == &APFloat::x87DoubleExtended())
10242         FloatEltSize = 80;
10243       for (unsigned i = 0; i < NElts; i++) {
10244         llvm::APInt Elt;
10245         if (BigEndian)
10246           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
10247         else
10248           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
10249         Elts.push_back(APValue(APFloat(Sem, Elt)));
10250       }
10251     } else if (EltTy->isIntegerType()) {
10252       for (unsigned i = 0; i < NElts; i++) {
10253         llvm::APInt Elt;
10254         if (BigEndian)
10255           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
10256         else
10257           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
10258         Elts.push_back(APValue(APSInt(Elt, !EltTy->isSignedIntegerType())));
10259       }
10260     } else {
10261       return Error(E);
10262     }
10263     return Success(Elts, E);
10264   }
10265   default:
10266     return ExprEvaluatorBaseTy::VisitCastExpr(E);
10267   }
10268 }
10269 
10270 bool
10271 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10272   const VectorType *VT = E->getType()->castAs<VectorType>();
10273   unsigned NumInits = E->getNumInits();
10274   unsigned NumElements = VT->getNumElements();
10275 
10276   QualType EltTy = VT->getElementType();
10277   SmallVector<APValue, 4> Elements;
10278 
10279   // The number of initializers can be less than the number of
10280   // vector elements. For OpenCL, this can be due to nested vector
10281   // initialization. For GCC compatibility, missing trailing elements
10282   // should be initialized with zeroes.
10283   unsigned CountInits = 0, CountElts = 0;
10284   while (CountElts < NumElements) {
10285     // Handle nested vector initialization.
10286     if (CountInits < NumInits
10287         && E->getInit(CountInits)->getType()->isVectorType()) {
10288       APValue v;
10289       if (!EvaluateVector(E->getInit(CountInits), v, Info))
10290         return Error(E);
10291       unsigned vlen = v.getVectorLength();
10292       for (unsigned j = 0; j < vlen; j++)
10293         Elements.push_back(v.getVectorElt(j));
10294       CountElts += vlen;
10295     } else if (EltTy->isIntegerType()) {
10296       llvm::APSInt sInt(32);
10297       if (CountInits < NumInits) {
10298         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
10299           return false;
10300       } else // trailing integer zero.
10301         sInt = Info.Ctx.MakeIntValue(0, EltTy);
10302       Elements.push_back(APValue(sInt));
10303       CountElts++;
10304     } else {
10305       llvm::APFloat f(0.0);
10306       if (CountInits < NumInits) {
10307         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
10308           return false;
10309       } else // trailing float zero.
10310         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
10311       Elements.push_back(APValue(f));
10312       CountElts++;
10313     }
10314     CountInits++;
10315   }
10316   return Success(Elements, E);
10317 }
10318 
10319 bool
10320 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
10321   const auto *VT = E->getType()->castAs<VectorType>();
10322   QualType EltTy = VT->getElementType();
10323   APValue ZeroElement;
10324   if (EltTy->isIntegerType())
10325     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
10326   else
10327     ZeroElement =
10328         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
10329 
10330   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
10331   return Success(Elements, E);
10332 }
10333 
10334 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
10335   VisitIgnoredValue(E->getSubExpr());
10336   return ZeroInitialization(E);
10337 }
10338 
10339 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10340   BinaryOperatorKind Op = E->getOpcode();
10341   assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
10342          "Operation not supported on vector types");
10343 
10344   if (Op == BO_Comma)
10345     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10346 
10347   Expr *LHS = E->getLHS();
10348   Expr *RHS = E->getRHS();
10349 
10350   assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
10351          "Must both be vector types");
10352   // Checking JUST the types are the same would be fine, except shifts don't
10353   // need to have their types be the same (since you always shift by an int).
10354   assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
10355              E->getType()->castAs<VectorType>()->getNumElements() &&
10356          RHS->getType()->castAs<VectorType>()->getNumElements() ==
10357              E->getType()->castAs<VectorType>()->getNumElements() &&
10358          "All operands must be the same size.");
10359 
10360   APValue LHSValue;
10361   APValue RHSValue;
10362   bool LHSOK = Evaluate(LHSValue, Info, LHS);
10363   if (!LHSOK && !Info.noteFailure())
10364     return false;
10365   if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
10366     return false;
10367 
10368   if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
10369     return false;
10370 
10371   return Success(LHSValue, E);
10372 }
10373 
10374 static llvm::Optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
10375                                                          QualType ResultTy,
10376                                                          UnaryOperatorKind Op,
10377                                                          APValue Elt) {
10378   switch (Op) {
10379   case UO_Plus:
10380     // Nothing to do here.
10381     return Elt;
10382   case UO_Minus:
10383     if (Elt.getKind() == APValue::Int) {
10384       Elt.getInt().negate();
10385     } else {
10386       assert(Elt.getKind() == APValue::Float &&
10387              "Vector can only be int or float type");
10388       Elt.getFloat().changeSign();
10389     }
10390     return Elt;
10391   case UO_Not:
10392     // This is only valid for integral types anyway, so we don't have to handle
10393     // float here.
10394     assert(Elt.getKind() == APValue::Int &&
10395            "Vector operator ~ can only be int");
10396     Elt.getInt().flipAllBits();
10397     return Elt;
10398   case UO_LNot: {
10399     if (Elt.getKind() == APValue::Int) {
10400       Elt.getInt() = !Elt.getInt();
10401       // operator ! on vectors returns -1 for 'truth', so negate it.
10402       Elt.getInt().negate();
10403       return Elt;
10404     }
10405     assert(Elt.getKind() == APValue::Float &&
10406            "Vector can only be int or float type");
10407     // Float types result in an int of the same size, but -1 for true, or 0 for
10408     // false.
10409     APSInt EltResult{Ctx.getIntWidth(ResultTy),
10410                      ResultTy->isUnsignedIntegerType()};
10411     if (Elt.getFloat().isZero())
10412       EltResult.setAllBits();
10413     else
10414       EltResult.clearAllBits();
10415 
10416     return APValue{EltResult};
10417   }
10418   default:
10419     // FIXME: Implement the rest of the unary operators.
10420     return llvm::None;
10421   }
10422 }
10423 
10424 bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10425   Expr *SubExpr = E->getSubExpr();
10426   const auto *VD = SubExpr->getType()->castAs<VectorType>();
10427   // This result element type differs in the case of negating a floating point
10428   // vector, since the result type is the a vector of the equivilant sized
10429   // integer.
10430   const QualType ResultEltTy = VD->getElementType();
10431   UnaryOperatorKind Op = E->getOpcode();
10432 
10433   APValue SubExprValue;
10434   if (!Evaluate(SubExprValue, Info, SubExpr))
10435     return false;
10436 
10437   // FIXME: This vector evaluator someday needs to be changed to be LValue
10438   // aware/keep LValue information around, rather than dealing with just vector
10439   // types directly. Until then, we cannot handle cases where the operand to
10440   // these unary operators is an LValue. The only case I've been able to see
10441   // cause this is operator++ assigning to a member expression (only valid in
10442   // altivec compilations) in C mode, so this shouldn't limit us too much.
10443   if (SubExprValue.isLValue())
10444     return false;
10445 
10446   assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
10447          "Vector length doesn't match type?");
10448 
10449   SmallVector<APValue, 4> ResultElements;
10450   for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
10451     llvm::Optional<APValue> Elt = handleVectorUnaryOperator(
10452         Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
10453     if (!Elt)
10454       return false;
10455     ResultElements.push_back(*Elt);
10456   }
10457   return Success(APValue(ResultElements.data(), ResultElements.size()), E);
10458 }
10459 
10460 //===----------------------------------------------------------------------===//
10461 // Array Evaluation
10462 //===----------------------------------------------------------------------===//
10463 
10464 namespace {
10465   class ArrayExprEvaluator
10466   : public ExprEvaluatorBase<ArrayExprEvaluator> {
10467     const LValue &This;
10468     APValue &Result;
10469   public:
10470 
10471     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
10472       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
10473 
10474     bool Success(const APValue &V, const Expr *E) {
10475       assert(V.isArray() && "expected array");
10476       Result = V;
10477       return true;
10478     }
10479 
10480     bool ZeroInitialization(const Expr *E) {
10481       const ConstantArrayType *CAT =
10482           Info.Ctx.getAsConstantArrayType(E->getType());
10483       if (!CAT) {
10484         if (E->getType()->isIncompleteArrayType()) {
10485           // We can be asked to zero-initialize a flexible array member; this
10486           // is represented as an ImplicitValueInitExpr of incomplete array
10487           // type. In this case, the array has zero elements.
10488           Result = APValue(APValue::UninitArray(), 0, 0);
10489           return true;
10490         }
10491         // FIXME: We could handle VLAs here.
10492         return Error(E);
10493       }
10494 
10495       Result = APValue(APValue::UninitArray(), 0,
10496                        CAT->getSize().getZExtValue());
10497       if (!Result.hasArrayFiller())
10498         return true;
10499 
10500       // Zero-initialize all elements.
10501       LValue Subobject = This;
10502       Subobject.addArray(Info, E, CAT);
10503       ImplicitValueInitExpr VIE(CAT->getElementType());
10504       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
10505     }
10506 
10507     bool VisitCallExpr(const CallExpr *E) {
10508       return handleCallExpr(E, Result, &This);
10509     }
10510     bool VisitInitListExpr(const InitListExpr *E,
10511                            QualType AllocType = QualType());
10512     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
10513     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
10514     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
10515                                const LValue &Subobject,
10516                                APValue *Value, QualType Type);
10517     bool VisitStringLiteral(const StringLiteral *E,
10518                             QualType AllocType = QualType()) {
10519       expandStringLiteral(Info, E, Result, AllocType);
10520       return true;
10521     }
10522   };
10523 } // end anonymous namespace
10524 
10525 static bool EvaluateArray(const Expr *E, const LValue &This,
10526                           APValue &Result, EvalInfo &Info) {
10527   assert(!E->isValueDependent());
10528   assert(E->isPRValue() && E->getType()->isArrayType() &&
10529          "not an array prvalue");
10530   return ArrayExprEvaluator(Info, This, Result).Visit(E);
10531 }
10532 
10533 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10534                                      APValue &Result, const InitListExpr *ILE,
10535                                      QualType AllocType) {
10536   assert(!ILE->isValueDependent());
10537   assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
10538          "not an array prvalue");
10539   return ArrayExprEvaluator(Info, This, Result)
10540       .VisitInitListExpr(ILE, AllocType);
10541 }
10542 
10543 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10544                                           APValue &Result,
10545                                           const CXXConstructExpr *CCE,
10546                                           QualType AllocType) {
10547   assert(!CCE->isValueDependent());
10548   assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
10549          "not an array prvalue");
10550   return ArrayExprEvaluator(Info, This, Result)
10551       .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
10552 }
10553 
10554 // Return true iff the given array filler may depend on the element index.
10555 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
10556   // For now, just allow non-class value-initialization and initialization
10557   // lists comprised of them.
10558   if (isa<ImplicitValueInitExpr>(FillerExpr))
10559     return false;
10560   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
10561     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
10562       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
10563         return true;
10564     }
10565     return false;
10566   }
10567   return true;
10568 }
10569 
10570 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
10571                                            QualType AllocType) {
10572   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
10573       AllocType.isNull() ? E->getType() : AllocType);
10574   if (!CAT)
10575     return Error(E);
10576 
10577   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
10578   // an appropriately-typed string literal enclosed in braces.
10579   if (E->isStringLiteralInit()) {
10580     auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
10581     // FIXME: Support ObjCEncodeExpr here once we support it in
10582     // ArrayExprEvaluator generally.
10583     if (!SL)
10584       return Error(E);
10585     return VisitStringLiteral(SL, AllocType);
10586   }
10587   // Any other transparent list init will need proper handling of the
10588   // AllocType; we can't just recurse to the inner initializer.
10589   assert(!E->isTransparent() &&
10590          "transparent array list initialization is not string literal init?");
10591 
10592   bool Success = true;
10593 
10594   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
10595          "zero-initialized array shouldn't have any initialized elts");
10596   APValue Filler;
10597   if (Result.isArray() && Result.hasArrayFiller())
10598     Filler = Result.getArrayFiller();
10599 
10600   unsigned NumEltsToInit = E->getNumInits();
10601   unsigned NumElts = CAT->getSize().getZExtValue();
10602   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
10603 
10604   // If the initializer might depend on the array index, run it for each
10605   // array element.
10606   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
10607     NumEltsToInit = NumElts;
10608 
10609   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
10610                           << NumEltsToInit << ".\n");
10611 
10612   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
10613 
10614   // If the array was previously zero-initialized, preserve the
10615   // zero-initialized values.
10616   if (Filler.hasValue()) {
10617     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
10618       Result.getArrayInitializedElt(I) = Filler;
10619     if (Result.hasArrayFiller())
10620       Result.getArrayFiller() = Filler;
10621   }
10622 
10623   LValue Subobject = This;
10624   Subobject.addArray(Info, E, CAT);
10625   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
10626     const Expr *Init =
10627         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
10628     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10629                          Info, Subobject, Init) ||
10630         !HandleLValueArrayAdjustment(Info, Init, Subobject,
10631                                      CAT->getElementType(), 1)) {
10632       if (!Info.noteFailure())
10633         return false;
10634       Success = false;
10635     }
10636   }
10637 
10638   if (!Result.hasArrayFiller())
10639     return Success;
10640 
10641   // If we get here, we have a trivial filler, which we can just evaluate
10642   // once and splat over the rest of the array elements.
10643   assert(FillerExpr && "no array filler for incomplete init list");
10644   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
10645                          FillerExpr) && Success;
10646 }
10647 
10648 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
10649   LValue CommonLV;
10650   if (E->getCommonExpr() &&
10651       !Evaluate(Info.CurrentCall->createTemporary(
10652                     E->getCommonExpr(),
10653                     getStorageType(Info.Ctx, E->getCommonExpr()),
10654                     ScopeKind::FullExpression, CommonLV),
10655                 Info, E->getCommonExpr()->getSourceExpr()))
10656     return false;
10657 
10658   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
10659 
10660   uint64_t Elements = CAT->getSize().getZExtValue();
10661   Result = APValue(APValue::UninitArray(), Elements, Elements);
10662 
10663   LValue Subobject = This;
10664   Subobject.addArray(Info, E, CAT);
10665 
10666   bool Success = true;
10667   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
10668     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10669                          Info, Subobject, E->getSubExpr()) ||
10670         !HandleLValueArrayAdjustment(Info, E, Subobject,
10671                                      CAT->getElementType(), 1)) {
10672       if (!Info.noteFailure())
10673         return false;
10674       Success = false;
10675     }
10676   }
10677 
10678   return Success;
10679 }
10680 
10681 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
10682   return VisitCXXConstructExpr(E, This, &Result, E->getType());
10683 }
10684 
10685 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10686                                                const LValue &Subobject,
10687                                                APValue *Value,
10688                                                QualType Type) {
10689   bool HadZeroInit = Value->hasValue();
10690 
10691   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
10692     unsigned FinalSize = CAT->getSize().getZExtValue();
10693 
10694     // Preserve the array filler if we had prior zero-initialization.
10695     APValue Filler =
10696       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
10697                                              : APValue();
10698 
10699     *Value = APValue(APValue::UninitArray(), 0, FinalSize);
10700     if (FinalSize == 0)
10701       return true;
10702 
10703     LValue ArrayElt = Subobject;
10704     ArrayElt.addArray(Info, E, CAT);
10705     // We do the whole initialization in two passes, first for just one element,
10706     // then for the whole array. It's possible we may find out we can't do const
10707     // init in the first pass, in which case we avoid allocating a potentially
10708     // large array. We don't do more passes because expanding array requires
10709     // copying the data, which is wasteful.
10710     for (const unsigned N : {1u, FinalSize}) {
10711       unsigned OldElts = Value->getArrayInitializedElts();
10712       if (OldElts == N)
10713         break;
10714 
10715       // Expand the array to appropriate size.
10716       APValue NewValue(APValue::UninitArray(), N, FinalSize);
10717       for (unsigned I = 0; I < OldElts; ++I)
10718         NewValue.getArrayInitializedElt(I).swap(
10719             Value->getArrayInitializedElt(I));
10720       Value->swap(NewValue);
10721 
10722       if (HadZeroInit)
10723         for (unsigned I = OldElts; I < N; ++I)
10724           Value->getArrayInitializedElt(I) = Filler;
10725 
10726       // Initialize the elements.
10727       for (unsigned I = OldElts; I < N; ++I) {
10728         if (!VisitCXXConstructExpr(E, ArrayElt,
10729                                    &Value->getArrayInitializedElt(I),
10730                                    CAT->getElementType()) ||
10731             !HandleLValueArrayAdjustment(Info, E, ArrayElt,
10732                                          CAT->getElementType(), 1))
10733           return false;
10734         // When checking for const initilization any diagnostic is considered
10735         // an error.
10736         if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
10737             !Info.keepEvaluatingAfterFailure())
10738           return false;
10739       }
10740     }
10741 
10742     return true;
10743   }
10744 
10745   if (!Type->isRecordType())
10746     return Error(E);
10747 
10748   return RecordExprEvaluator(Info, Subobject, *Value)
10749              .VisitCXXConstructExpr(E, Type);
10750 }
10751 
10752 //===----------------------------------------------------------------------===//
10753 // Integer Evaluation
10754 //
10755 // As a GNU extension, we support casting pointers to sufficiently-wide integer
10756 // types and back in constant folding. Integer values are thus represented
10757 // either as an integer-valued APValue, or as an lvalue-valued APValue.
10758 //===----------------------------------------------------------------------===//
10759 
10760 namespace {
10761 class IntExprEvaluator
10762         : public ExprEvaluatorBase<IntExprEvaluator> {
10763   APValue &Result;
10764 public:
10765   IntExprEvaluator(EvalInfo &info, APValue &result)
10766       : ExprEvaluatorBaseTy(info), Result(result) {}
10767 
10768   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
10769     assert(E->getType()->isIntegralOrEnumerationType() &&
10770            "Invalid evaluation result.");
10771     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
10772            "Invalid evaluation result.");
10773     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10774            "Invalid evaluation result.");
10775     Result = APValue(SI);
10776     return true;
10777   }
10778   bool Success(const llvm::APSInt &SI, const Expr *E) {
10779     return Success(SI, E, Result);
10780   }
10781 
10782   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
10783     assert(E->getType()->isIntegralOrEnumerationType() &&
10784            "Invalid evaluation result.");
10785     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10786            "Invalid evaluation result.");
10787     Result = APValue(APSInt(I));
10788     Result.getInt().setIsUnsigned(
10789                             E->getType()->isUnsignedIntegerOrEnumerationType());
10790     return true;
10791   }
10792   bool Success(const llvm::APInt &I, const Expr *E) {
10793     return Success(I, E, Result);
10794   }
10795 
10796   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
10797     assert(E->getType()->isIntegralOrEnumerationType() &&
10798            "Invalid evaluation result.");
10799     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
10800     return true;
10801   }
10802   bool Success(uint64_t Value, const Expr *E) {
10803     return Success(Value, E, Result);
10804   }
10805 
10806   bool Success(CharUnits Size, const Expr *E) {
10807     return Success(Size.getQuantity(), E);
10808   }
10809 
10810   bool Success(const APValue &V, const Expr *E) {
10811     if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
10812       Result = V;
10813       return true;
10814     }
10815     return Success(V.getInt(), E);
10816   }
10817 
10818   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
10819 
10820   //===--------------------------------------------------------------------===//
10821   //                            Visitor Methods
10822   //===--------------------------------------------------------------------===//
10823 
10824   bool VisitIntegerLiteral(const IntegerLiteral *E) {
10825     return Success(E->getValue(), E);
10826   }
10827   bool VisitCharacterLiteral(const CharacterLiteral *E) {
10828     return Success(E->getValue(), E);
10829   }
10830 
10831   bool CheckReferencedDecl(const Expr *E, const Decl *D);
10832   bool VisitDeclRefExpr(const DeclRefExpr *E) {
10833     if (CheckReferencedDecl(E, E->getDecl()))
10834       return true;
10835 
10836     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
10837   }
10838   bool VisitMemberExpr(const MemberExpr *E) {
10839     if (CheckReferencedDecl(E, E->getMemberDecl())) {
10840       VisitIgnoredBaseExpression(E->getBase());
10841       return true;
10842     }
10843 
10844     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
10845   }
10846 
10847   bool VisitCallExpr(const CallExpr *E);
10848   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
10849   bool VisitBinaryOperator(const BinaryOperator *E);
10850   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
10851   bool VisitUnaryOperator(const UnaryOperator *E);
10852 
10853   bool VisitCastExpr(const CastExpr* E);
10854   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
10855 
10856   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
10857     return Success(E->getValue(), E);
10858   }
10859 
10860   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
10861     return Success(E->getValue(), E);
10862   }
10863 
10864   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
10865     if (Info.ArrayInitIndex == uint64_t(-1)) {
10866       // We were asked to evaluate this subexpression independent of the
10867       // enclosing ArrayInitLoopExpr. We can't do that.
10868       Info.FFDiag(E);
10869       return false;
10870     }
10871     return Success(Info.ArrayInitIndex, E);
10872   }
10873 
10874   // Note, GNU defines __null as an integer, not a pointer.
10875   bool VisitGNUNullExpr(const GNUNullExpr *E) {
10876     return ZeroInitialization(E);
10877   }
10878 
10879   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
10880     return Success(E->getValue(), E);
10881   }
10882 
10883   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
10884     return Success(E->getValue(), E);
10885   }
10886 
10887   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
10888     return Success(E->getValue(), E);
10889   }
10890 
10891   bool VisitUnaryReal(const UnaryOperator *E);
10892   bool VisitUnaryImag(const UnaryOperator *E);
10893 
10894   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
10895   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
10896   bool VisitSourceLocExpr(const SourceLocExpr *E);
10897   bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
10898   bool VisitRequiresExpr(const RequiresExpr *E);
10899   // FIXME: Missing: array subscript of vector, member of vector
10900 };
10901 
10902 class FixedPointExprEvaluator
10903     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
10904   APValue &Result;
10905 
10906  public:
10907   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
10908       : ExprEvaluatorBaseTy(info), Result(result) {}
10909 
10910   bool Success(const llvm::APInt &I, const Expr *E) {
10911     return Success(
10912         APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10913   }
10914 
10915   bool Success(uint64_t Value, const Expr *E) {
10916     return Success(
10917         APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10918   }
10919 
10920   bool Success(const APValue &V, const Expr *E) {
10921     return Success(V.getFixedPoint(), E);
10922   }
10923 
10924   bool Success(const APFixedPoint &V, const Expr *E) {
10925     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
10926     assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10927            "Invalid evaluation result.");
10928     Result = APValue(V);
10929     return true;
10930   }
10931 
10932   //===--------------------------------------------------------------------===//
10933   //                            Visitor Methods
10934   //===--------------------------------------------------------------------===//
10935 
10936   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
10937     return Success(E->getValue(), E);
10938   }
10939 
10940   bool VisitCastExpr(const CastExpr *E);
10941   bool VisitUnaryOperator(const UnaryOperator *E);
10942   bool VisitBinaryOperator(const BinaryOperator *E);
10943 };
10944 } // end anonymous namespace
10945 
10946 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
10947 /// produce either the integer value or a pointer.
10948 ///
10949 /// GCC has a heinous extension which folds casts between pointer types and
10950 /// pointer-sized integral types. We support this by allowing the evaluation of
10951 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
10952 /// Some simple arithmetic on such values is supported (they are treated much
10953 /// like char*).
10954 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
10955                                     EvalInfo &Info) {
10956   assert(!E->isValueDependent());
10957   assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
10958   return IntExprEvaluator(Info, Result).Visit(E);
10959 }
10960 
10961 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
10962   assert(!E->isValueDependent());
10963   APValue Val;
10964   if (!EvaluateIntegerOrLValue(E, Val, Info))
10965     return false;
10966   if (!Val.isInt()) {
10967     // FIXME: It would be better to produce the diagnostic for casting
10968     //        a pointer to an integer.
10969     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10970     return false;
10971   }
10972   Result = Val.getInt();
10973   return true;
10974 }
10975 
10976 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
10977   APValue Evaluated = E->EvaluateInContext(
10978       Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
10979   return Success(Evaluated, E);
10980 }
10981 
10982 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
10983                                EvalInfo &Info) {
10984   assert(!E->isValueDependent());
10985   if (E->getType()->isFixedPointType()) {
10986     APValue Val;
10987     if (!FixedPointExprEvaluator(Info, Val).Visit(E))
10988       return false;
10989     if (!Val.isFixedPoint())
10990       return false;
10991 
10992     Result = Val.getFixedPoint();
10993     return true;
10994   }
10995   return false;
10996 }
10997 
10998 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
10999                                         EvalInfo &Info) {
11000   assert(!E->isValueDependent());
11001   if (E->getType()->isIntegerType()) {
11002     auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
11003     APSInt Val;
11004     if (!EvaluateInteger(E, Val, Info))
11005       return false;
11006     Result = APFixedPoint(Val, FXSema);
11007     return true;
11008   } else if (E->getType()->isFixedPointType()) {
11009     return EvaluateFixedPoint(E, Result, Info);
11010   }
11011   return false;
11012 }
11013 
11014 /// Check whether the given declaration can be directly converted to an integral
11015 /// rvalue. If not, no diagnostic is produced; there are other things we can
11016 /// try.
11017 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
11018   // Enums are integer constant exprs.
11019   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
11020     // Check for signedness/width mismatches between E type and ECD value.
11021     bool SameSign = (ECD->getInitVal().isSigned()
11022                      == E->getType()->isSignedIntegerOrEnumerationType());
11023     bool SameWidth = (ECD->getInitVal().getBitWidth()
11024                       == Info.Ctx.getIntWidth(E->getType()));
11025     if (SameSign && SameWidth)
11026       return Success(ECD->getInitVal(), E);
11027     else {
11028       // Get rid of mismatch (otherwise Success assertions will fail)
11029       // by computing a new value matching the type of E.
11030       llvm::APSInt Val = ECD->getInitVal();
11031       if (!SameSign)
11032         Val.setIsSigned(!ECD->getInitVal().isSigned());
11033       if (!SameWidth)
11034         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
11035       return Success(Val, E);
11036     }
11037   }
11038   return false;
11039 }
11040 
11041 /// Values returned by __builtin_classify_type, chosen to match the values
11042 /// produced by GCC's builtin.
11043 enum class GCCTypeClass {
11044   None = -1,
11045   Void = 0,
11046   Integer = 1,
11047   // GCC reserves 2 for character types, but instead classifies them as
11048   // integers.
11049   Enum = 3,
11050   Bool = 4,
11051   Pointer = 5,
11052   // GCC reserves 6 for references, but appears to never use it (because
11053   // expressions never have reference type, presumably).
11054   PointerToDataMember = 7,
11055   RealFloat = 8,
11056   Complex = 9,
11057   // GCC reserves 10 for functions, but does not use it since GCC version 6 due
11058   // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
11059   // GCC claims to reserve 11 for pointers to member functions, but *actually*
11060   // uses 12 for that purpose, same as for a class or struct. Maybe it
11061   // internally implements a pointer to member as a struct?  Who knows.
11062   PointerToMemberFunction = 12, // Not a bug, see above.
11063   ClassOrStruct = 12,
11064   Union = 13,
11065   // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
11066   // decay to pointer. (Prior to version 6 it was only used in C++ mode).
11067   // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
11068   // literals.
11069 };
11070 
11071 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11072 /// as GCC.
11073 static GCCTypeClass
11074 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
11075   assert(!T->isDependentType() && "unexpected dependent type");
11076 
11077   QualType CanTy = T.getCanonicalType();
11078   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
11079 
11080   switch (CanTy->getTypeClass()) {
11081 #define TYPE(ID, BASE)
11082 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
11083 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
11084 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
11085 #include "clang/AST/TypeNodes.inc"
11086   case Type::Auto:
11087   case Type::DeducedTemplateSpecialization:
11088       llvm_unreachable("unexpected non-canonical or dependent type");
11089 
11090   case Type::Builtin:
11091     switch (BT->getKind()) {
11092 #define BUILTIN_TYPE(ID, SINGLETON_ID)
11093 #define SIGNED_TYPE(ID, SINGLETON_ID) \
11094     case BuiltinType::ID: return GCCTypeClass::Integer;
11095 #define FLOATING_TYPE(ID, SINGLETON_ID) \
11096     case BuiltinType::ID: return GCCTypeClass::RealFloat;
11097 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
11098     case BuiltinType::ID: break;
11099 #include "clang/AST/BuiltinTypes.def"
11100     case BuiltinType::Void:
11101       return GCCTypeClass::Void;
11102 
11103     case BuiltinType::Bool:
11104       return GCCTypeClass::Bool;
11105 
11106     case BuiltinType::Char_U:
11107     case BuiltinType::UChar:
11108     case BuiltinType::WChar_U:
11109     case BuiltinType::Char8:
11110     case BuiltinType::Char16:
11111     case BuiltinType::Char32:
11112     case BuiltinType::UShort:
11113     case BuiltinType::UInt:
11114     case BuiltinType::ULong:
11115     case BuiltinType::ULongLong:
11116     case BuiltinType::UInt128:
11117       return GCCTypeClass::Integer;
11118 
11119     case BuiltinType::UShortAccum:
11120     case BuiltinType::UAccum:
11121     case BuiltinType::ULongAccum:
11122     case BuiltinType::UShortFract:
11123     case BuiltinType::UFract:
11124     case BuiltinType::ULongFract:
11125     case BuiltinType::SatUShortAccum:
11126     case BuiltinType::SatUAccum:
11127     case BuiltinType::SatULongAccum:
11128     case BuiltinType::SatUShortFract:
11129     case BuiltinType::SatUFract:
11130     case BuiltinType::SatULongFract:
11131       return GCCTypeClass::None;
11132 
11133     case BuiltinType::NullPtr:
11134 
11135     case BuiltinType::ObjCId:
11136     case BuiltinType::ObjCClass:
11137     case BuiltinType::ObjCSel:
11138 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
11139     case BuiltinType::Id:
11140 #include "clang/Basic/OpenCLImageTypes.def"
11141 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
11142     case BuiltinType::Id:
11143 #include "clang/Basic/OpenCLExtensionTypes.def"
11144     case BuiltinType::OCLSampler:
11145     case BuiltinType::OCLEvent:
11146     case BuiltinType::OCLClkEvent:
11147     case BuiltinType::OCLQueue:
11148     case BuiltinType::OCLReserveID:
11149 #define SVE_TYPE(Name, Id, SingletonId) \
11150     case BuiltinType::Id:
11151 #include "clang/Basic/AArch64SVEACLETypes.def"
11152 #define PPC_VECTOR_TYPE(Name, Id, Size) \
11153     case BuiltinType::Id:
11154 #include "clang/Basic/PPCTypes.def"
11155 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
11156 #include "clang/Basic/RISCVVTypes.def"
11157       return GCCTypeClass::None;
11158 
11159     case BuiltinType::Dependent:
11160       llvm_unreachable("unexpected dependent type");
11161     };
11162     llvm_unreachable("unexpected placeholder type");
11163 
11164   case Type::Enum:
11165     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
11166 
11167   case Type::Pointer:
11168   case Type::ConstantArray:
11169   case Type::VariableArray:
11170   case Type::IncompleteArray:
11171   case Type::FunctionNoProto:
11172   case Type::FunctionProto:
11173     return GCCTypeClass::Pointer;
11174 
11175   case Type::MemberPointer:
11176     return CanTy->isMemberDataPointerType()
11177                ? GCCTypeClass::PointerToDataMember
11178                : GCCTypeClass::PointerToMemberFunction;
11179 
11180   case Type::Complex:
11181     return GCCTypeClass::Complex;
11182 
11183   case Type::Record:
11184     return CanTy->isUnionType() ? GCCTypeClass::Union
11185                                 : GCCTypeClass::ClassOrStruct;
11186 
11187   case Type::Atomic:
11188     // GCC classifies _Atomic T the same as T.
11189     return EvaluateBuiltinClassifyType(
11190         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
11191 
11192   case Type::BlockPointer:
11193   case Type::Vector:
11194   case Type::ExtVector:
11195   case Type::ConstantMatrix:
11196   case Type::ObjCObject:
11197   case Type::ObjCInterface:
11198   case Type::ObjCObjectPointer:
11199   case Type::Pipe:
11200   case Type::BitInt:
11201     // GCC classifies vectors as None. We follow its lead and classify all
11202     // other types that don't fit into the regular classification the same way.
11203     return GCCTypeClass::None;
11204 
11205   case Type::LValueReference:
11206   case Type::RValueReference:
11207     llvm_unreachable("invalid type for expression");
11208   }
11209 
11210   llvm_unreachable("unexpected type class");
11211 }
11212 
11213 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11214 /// as GCC.
11215 static GCCTypeClass
11216 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
11217   // If no argument was supplied, default to None. This isn't
11218   // ideal, however it is what gcc does.
11219   if (E->getNumArgs() == 0)
11220     return GCCTypeClass::None;
11221 
11222   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
11223   // being an ICE, but still folds it to a constant using the type of the first
11224   // argument.
11225   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
11226 }
11227 
11228 /// EvaluateBuiltinConstantPForLValue - Determine the result of
11229 /// __builtin_constant_p when applied to the given pointer.
11230 ///
11231 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
11232 /// or it points to the first character of a string literal.
11233 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
11234   APValue::LValueBase Base = LV.getLValueBase();
11235   if (Base.isNull()) {
11236     // A null base is acceptable.
11237     return true;
11238   } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
11239     if (!isa<StringLiteral>(E))
11240       return false;
11241     return LV.getLValueOffset().isZero();
11242   } else if (Base.is<TypeInfoLValue>()) {
11243     // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
11244     // evaluate to true.
11245     return true;
11246   } else {
11247     // Any other base is not constant enough for GCC.
11248     return false;
11249   }
11250 }
11251 
11252 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
11253 /// GCC as we can manage.
11254 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
11255   // This evaluation is not permitted to have side-effects, so evaluate it in
11256   // a speculative evaluation context.
11257   SpeculativeEvaluationRAII SpeculativeEval(Info);
11258 
11259   // Constant-folding is always enabled for the operand of __builtin_constant_p
11260   // (even when the enclosing evaluation context otherwise requires a strict
11261   // language-specific constant expression).
11262   FoldConstant Fold(Info, true);
11263 
11264   QualType ArgType = Arg->getType();
11265 
11266   // __builtin_constant_p always has one operand. The rules which gcc follows
11267   // are not precisely documented, but are as follows:
11268   //
11269   //  - If the operand is of integral, floating, complex or enumeration type,
11270   //    and can be folded to a known value of that type, it returns 1.
11271   //  - If the operand can be folded to a pointer to the first character
11272   //    of a string literal (or such a pointer cast to an integral type)
11273   //    or to a null pointer or an integer cast to a pointer, it returns 1.
11274   //
11275   // Otherwise, it returns 0.
11276   //
11277   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
11278   // its support for this did not work prior to GCC 9 and is not yet well
11279   // understood.
11280   if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
11281       ArgType->isAnyComplexType() || ArgType->isPointerType() ||
11282       ArgType->isNullPtrType()) {
11283     APValue V;
11284     if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
11285       Fold.keepDiagnostics();
11286       return false;
11287     }
11288 
11289     // For a pointer (possibly cast to integer), there are special rules.
11290     if (V.getKind() == APValue::LValue)
11291       return EvaluateBuiltinConstantPForLValue(V);
11292 
11293     // Otherwise, any constant value is good enough.
11294     return V.hasValue();
11295   }
11296 
11297   // Anything else isn't considered to be sufficiently constant.
11298   return false;
11299 }
11300 
11301 /// Retrieves the "underlying object type" of the given expression,
11302 /// as used by __builtin_object_size.
11303 static QualType getObjectType(APValue::LValueBase B) {
11304   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
11305     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
11306       return VD->getType();
11307   } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
11308     if (isa<CompoundLiteralExpr>(E))
11309       return E->getType();
11310   } else if (B.is<TypeInfoLValue>()) {
11311     return B.getTypeInfoType();
11312   } else if (B.is<DynamicAllocLValue>()) {
11313     return B.getDynamicAllocType();
11314   }
11315 
11316   return QualType();
11317 }
11318 
11319 /// A more selective version of E->IgnoreParenCasts for
11320 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
11321 /// to change the type of E.
11322 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
11323 ///
11324 /// Always returns an RValue with a pointer representation.
11325 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
11326   assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
11327 
11328   auto *NoParens = E->IgnoreParens();
11329   auto *Cast = dyn_cast<CastExpr>(NoParens);
11330   if (Cast == nullptr)
11331     return NoParens;
11332 
11333   // We only conservatively allow a few kinds of casts, because this code is
11334   // inherently a simple solution that seeks to support the common case.
11335   auto CastKind = Cast->getCastKind();
11336   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
11337       CastKind != CK_AddressSpaceConversion)
11338     return NoParens;
11339 
11340   auto *SubExpr = Cast->getSubExpr();
11341   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
11342     return NoParens;
11343   return ignorePointerCastsAndParens(SubExpr);
11344 }
11345 
11346 /// Checks to see if the given LValue's Designator is at the end of the LValue's
11347 /// record layout. e.g.
11348 ///   struct { struct { int a, b; } fst, snd; } obj;
11349 ///   obj.fst   // no
11350 ///   obj.snd   // yes
11351 ///   obj.fst.a // no
11352 ///   obj.fst.b // no
11353 ///   obj.snd.a // no
11354 ///   obj.snd.b // yes
11355 ///
11356 /// Please note: this function is specialized for how __builtin_object_size
11357 /// views "objects".
11358 ///
11359 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
11360 /// correct result, it will always return true.
11361 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
11362   assert(!LVal.Designator.Invalid);
11363 
11364   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
11365     const RecordDecl *Parent = FD->getParent();
11366     Invalid = Parent->isInvalidDecl();
11367     if (Invalid || Parent->isUnion())
11368       return true;
11369     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
11370     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
11371   };
11372 
11373   auto &Base = LVal.getLValueBase();
11374   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
11375     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
11376       bool Invalid;
11377       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11378         return Invalid;
11379     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
11380       for (auto *FD : IFD->chain()) {
11381         bool Invalid;
11382         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
11383           return Invalid;
11384       }
11385     }
11386   }
11387 
11388   unsigned I = 0;
11389   QualType BaseType = getType(Base);
11390   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
11391     // If we don't know the array bound, conservatively assume we're looking at
11392     // the final array element.
11393     ++I;
11394     if (BaseType->isIncompleteArrayType())
11395       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
11396     else
11397       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
11398   }
11399 
11400   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
11401     const auto &Entry = LVal.Designator.Entries[I];
11402     if (BaseType->isArrayType()) {
11403       // Because __builtin_object_size treats arrays as objects, we can ignore
11404       // the index iff this is the last array in the Designator.
11405       if (I + 1 == E)
11406         return true;
11407       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
11408       uint64_t Index = Entry.getAsArrayIndex();
11409       if (Index + 1 != CAT->getSize())
11410         return false;
11411       BaseType = CAT->getElementType();
11412     } else if (BaseType->isAnyComplexType()) {
11413       const auto *CT = BaseType->castAs<ComplexType>();
11414       uint64_t Index = Entry.getAsArrayIndex();
11415       if (Index != 1)
11416         return false;
11417       BaseType = CT->getElementType();
11418     } else if (auto *FD = getAsField(Entry)) {
11419       bool Invalid;
11420       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11421         return Invalid;
11422       BaseType = FD->getType();
11423     } else {
11424       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
11425       return false;
11426     }
11427   }
11428   return true;
11429 }
11430 
11431 /// Tests to see if the LValue has a user-specified designator (that isn't
11432 /// necessarily valid). Note that this always returns 'true' if the LValue has
11433 /// an unsized array as its first designator entry, because there's currently no
11434 /// way to tell if the user typed *foo or foo[0].
11435 static bool refersToCompleteObject(const LValue &LVal) {
11436   if (LVal.Designator.Invalid)
11437     return false;
11438 
11439   if (!LVal.Designator.Entries.empty())
11440     return LVal.Designator.isMostDerivedAnUnsizedArray();
11441 
11442   if (!LVal.InvalidBase)
11443     return true;
11444 
11445   // If `E` is a MemberExpr, then the first part of the designator is hiding in
11446   // the LValueBase.
11447   const auto *E = LVal.Base.dyn_cast<const Expr *>();
11448   return !E || !isa<MemberExpr>(E);
11449 }
11450 
11451 /// Attempts to detect a user writing into a piece of memory that's impossible
11452 /// to figure out the size of by just using types.
11453 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
11454   const SubobjectDesignator &Designator = LVal.Designator;
11455   // Notes:
11456   // - Users can only write off of the end when we have an invalid base. Invalid
11457   //   bases imply we don't know where the memory came from.
11458   // - We used to be a bit more aggressive here; we'd only be conservative if
11459   //   the array at the end was flexible, or if it had 0 or 1 elements. This
11460   //   broke some common standard library extensions (PR30346), but was
11461   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
11462   //   with some sort of list. OTOH, it seems that GCC is always
11463   //   conservative with the last element in structs (if it's an array), so our
11464   //   current behavior is more compatible than an explicit list approach would
11465   //   be.
11466   return LVal.InvalidBase &&
11467          Designator.Entries.size() == Designator.MostDerivedPathLength &&
11468          Designator.MostDerivedIsArrayElement &&
11469          isDesignatorAtObjectEnd(Ctx, LVal);
11470 }
11471 
11472 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
11473 /// Fails if the conversion would cause loss of precision.
11474 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
11475                                             CharUnits &Result) {
11476   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
11477   if (Int.ugt(CharUnitsMax))
11478     return false;
11479   Result = CharUnits::fromQuantity(Int.getZExtValue());
11480   return true;
11481 }
11482 
11483 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
11484 /// determine how many bytes exist from the beginning of the object to either
11485 /// the end of the current subobject, or the end of the object itself, depending
11486 /// on what the LValue looks like + the value of Type.
11487 ///
11488 /// If this returns false, the value of Result is undefined.
11489 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
11490                                unsigned Type, const LValue &LVal,
11491                                CharUnits &EndOffset) {
11492   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
11493 
11494   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
11495     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
11496       return false;
11497     return HandleSizeof(Info, ExprLoc, Ty, Result);
11498   };
11499 
11500   // We want to evaluate the size of the entire object. This is a valid fallback
11501   // for when Type=1 and the designator is invalid, because we're asked for an
11502   // upper-bound.
11503   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
11504     // Type=3 wants a lower bound, so we can't fall back to this.
11505     if (Type == 3 && !DetermineForCompleteObject)
11506       return false;
11507 
11508     llvm::APInt APEndOffset;
11509     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11510         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11511       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11512 
11513     if (LVal.InvalidBase)
11514       return false;
11515 
11516     QualType BaseTy = getObjectType(LVal.getLValueBase());
11517     return CheckedHandleSizeof(BaseTy, EndOffset);
11518   }
11519 
11520   // We want to evaluate the size of a subobject.
11521   const SubobjectDesignator &Designator = LVal.Designator;
11522 
11523   // The following is a moderately common idiom in C:
11524   //
11525   // struct Foo { int a; char c[1]; };
11526   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
11527   // strcpy(&F->c[0], Bar);
11528   //
11529   // In order to not break too much legacy code, we need to support it.
11530   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
11531     // If we can resolve this to an alloc_size call, we can hand that back,
11532     // because we know for certain how many bytes there are to write to.
11533     llvm::APInt APEndOffset;
11534     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11535         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11536       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11537 
11538     // If we cannot determine the size of the initial allocation, then we can't
11539     // given an accurate upper-bound. However, we are still able to give
11540     // conservative lower-bounds for Type=3.
11541     if (Type == 1)
11542       return false;
11543   }
11544 
11545   CharUnits BytesPerElem;
11546   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
11547     return false;
11548 
11549   // According to the GCC documentation, we want the size of the subobject
11550   // denoted by the pointer. But that's not quite right -- what we actually
11551   // want is the size of the immediately-enclosing array, if there is one.
11552   int64_t ElemsRemaining;
11553   if (Designator.MostDerivedIsArrayElement &&
11554       Designator.Entries.size() == Designator.MostDerivedPathLength) {
11555     uint64_t ArraySize = Designator.getMostDerivedArraySize();
11556     uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
11557     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
11558   } else {
11559     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
11560   }
11561 
11562   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
11563   return true;
11564 }
11565 
11566 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
11567 /// returns true and stores the result in @p Size.
11568 ///
11569 /// If @p WasError is non-null, this will report whether the failure to evaluate
11570 /// is to be treated as an Error in IntExprEvaluator.
11571 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
11572                                          EvalInfo &Info, uint64_t &Size) {
11573   // Determine the denoted object.
11574   LValue LVal;
11575   {
11576     // The operand of __builtin_object_size is never evaluated for side-effects.
11577     // If there are any, but we can determine the pointed-to object anyway, then
11578     // ignore the side-effects.
11579     SpeculativeEvaluationRAII SpeculativeEval(Info);
11580     IgnoreSideEffectsRAII Fold(Info);
11581 
11582     if (E->isGLValue()) {
11583       // It's possible for us to be given GLValues if we're called via
11584       // Expr::tryEvaluateObjectSize.
11585       APValue RVal;
11586       if (!EvaluateAsRValue(Info, E, RVal))
11587         return false;
11588       LVal.setFrom(Info.Ctx, RVal);
11589     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
11590                                 /*InvalidBaseOK=*/true))
11591       return false;
11592   }
11593 
11594   // If we point to before the start of the object, there are no accessible
11595   // bytes.
11596   if (LVal.getLValueOffset().isNegative()) {
11597     Size = 0;
11598     return true;
11599   }
11600 
11601   CharUnits EndOffset;
11602   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
11603     return false;
11604 
11605   // If we've fallen outside of the end offset, just pretend there's nothing to
11606   // write to/read from.
11607   if (EndOffset <= LVal.getLValueOffset())
11608     Size = 0;
11609   else
11610     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
11611   return true;
11612 }
11613 
11614 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
11615   if (unsigned BuiltinOp = E->getBuiltinCallee())
11616     return VisitBuiltinCallExpr(E, BuiltinOp);
11617 
11618   return ExprEvaluatorBaseTy::VisitCallExpr(E);
11619 }
11620 
11621 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
11622                                      APValue &Val, APSInt &Alignment) {
11623   QualType SrcTy = E->getArg(0)->getType();
11624   if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
11625     return false;
11626   // Even though we are evaluating integer expressions we could get a pointer
11627   // argument for the __builtin_is_aligned() case.
11628   if (SrcTy->isPointerType()) {
11629     LValue Ptr;
11630     if (!EvaluatePointer(E->getArg(0), Ptr, Info))
11631       return false;
11632     Ptr.moveInto(Val);
11633   } else if (!SrcTy->isIntegralOrEnumerationType()) {
11634     Info.FFDiag(E->getArg(0));
11635     return false;
11636   } else {
11637     APSInt SrcInt;
11638     if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
11639       return false;
11640     assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
11641            "Bit widths must be the same");
11642     Val = APValue(SrcInt);
11643   }
11644   assert(Val.hasValue());
11645   return true;
11646 }
11647 
11648 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
11649                                             unsigned BuiltinOp) {
11650   switch (BuiltinOp) {
11651   default:
11652     return ExprEvaluatorBaseTy::VisitCallExpr(E);
11653 
11654   case Builtin::BI__builtin_dynamic_object_size:
11655   case Builtin::BI__builtin_object_size: {
11656     // The type was checked when we built the expression.
11657     unsigned Type =
11658         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11659     assert(Type <= 3 && "unexpected type");
11660 
11661     uint64_t Size;
11662     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
11663       return Success(Size, E);
11664 
11665     if (E->getArg(0)->HasSideEffects(Info.Ctx))
11666       return Success((Type & 2) ? 0 : -1, E);
11667 
11668     // Expression had no side effects, but we couldn't statically determine the
11669     // size of the referenced object.
11670     switch (Info.EvalMode) {
11671     case EvalInfo::EM_ConstantExpression:
11672     case EvalInfo::EM_ConstantFold:
11673     case EvalInfo::EM_IgnoreSideEffects:
11674       // Leave it to IR generation.
11675       return Error(E);
11676     case EvalInfo::EM_ConstantExpressionUnevaluated:
11677       // Reduce it to a constant now.
11678       return Success((Type & 2) ? 0 : -1, E);
11679     }
11680 
11681     llvm_unreachable("unexpected EvalMode");
11682   }
11683 
11684   case Builtin::BI__builtin_os_log_format_buffer_size: {
11685     analyze_os_log::OSLogBufferLayout Layout;
11686     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
11687     return Success(Layout.size().getQuantity(), E);
11688   }
11689 
11690   case Builtin::BI__builtin_is_aligned: {
11691     APValue Src;
11692     APSInt Alignment;
11693     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11694       return false;
11695     if (Src.isLValue()) {
11696       // If we evaluated a pointer, check the minimum known alignment.
11697       LValue Ptr;
11698       Ptr.setFrom(Info.Ctx, Src);
11699       CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
11700       CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
11701       // We can return true if the known alignment at the computed offset is
11702       // greater than the requested alignment.
11703       assert(PtrAlign.isPowerOfTwo());
11704       assert(Alignment.isPowerOf2());
11705       if (PtrAlign.getQuantity() >= Alignment)
11706         return Success(1, E);
11707       // If the alignment is not known to be sufficient, some cases could still
11708       // be aligned at run time. However, if the requested alignment is less or
11709       // equal to the base alignment and the offset is not aligned, we know that
11710       // the run-time value can never be aligned.
11711       if (BaseAlignment.getQuantity() >= Alignment &&
11712           PtrAlign.getQuantity() < Alignment)
11713         return Success(0, E);
11714       // Otherwise we can't infer whether the value is sufficiently aligned.
11715       // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
11716       //  in cases where we can't fully evaluate the pointer.
11717       Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
11718           << Alignment;
11719       return false;
11720     }
11721     assert(Src.isInt());
11722     return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
11723   }
11724   case Builtin::BI__builtin_align_up: {
11725     APValue Src;
11726     APSInt Alignment;
11727     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11728       return false;
11729     if (!Src.isInt())
11730       return Error(E);
11731     APSInt AlignedVal =
11732         APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
11733                Src.getInt().isUnsigned());
11734     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11735     return Success(AlignedVal, E);
11736   }
11737   case Builtin::BI__builtin_align_down: {
11738     APValue Src;
11739     APSInt Alignment;
11740     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11741       return false;
11742     if (!Src.isInt())
11743       return Error(E);
11744     APSInt AlignedVal =
11745         APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
11746     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11747     return Success(AlignedVal, E);
11748   }
11749 
11750   case Builtin::BI__builtin_bitreverse8:
11751   case Builtin::BI__builtin_bitreverse16:
11752   case Builtin::BI__builtin_bitreverse32:
11753   case Builtin::BI__builtin_bitreverse64: {
11754     APSInt Val;
11755     if (!EvaluateInteger(E->getArg(0), Val, Info))
11756       return false;
11757 
11758     return Success(Val.reverseBits(), E);
11759   }
11760 
11761   case Builtin::BI__builtin_bswap16:
11762   case Builtin::BI__builtin_bswap32:
11763   case Builtin::BI__builtin_bswap64: {
11764     APSInt Val;
11765     if (!EvaluateInteger(E->getArg(0), Val, Info))
11766       return false;
11767 
11768     return Success(Val.byteSwap(), E);
11769   }
11770 
11771   case Builtin::BI__builtin_classify_type:
11772     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
11773 
11774   case Builtin::BI__builtin_clrsb:
11775   case Builtin::BI__builtin_clrsbl:
11776   case Builtin::BI__builtin_clrsbll: {
11777     APSInt Val;
11778     if (!EvaluateInteger(E->getArg(0), Val, Info))
11779       return false;
11780 
11781     return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
11782   }
11783 
11784   case Builtin::BI__builtin_clz:
11785   case Builtin::BI__builtin_clzl:
11786   case Builtin::BI__builtin_clzll:
11787   case Builtin::BI__builtin_clzs: {
11788     APSInt Val;
11789     if (!EvaluateInteger(E->getArg(0), Val, Info))
11790       return false;
11791     if (!Val)
11792       return Error(E);
11793 
11794     return Success(Val.countLeadingZeros(), E);
11795   }
11796 
11797   case Builtin::BI__builtin_constant_p: {
11798     const Expr *Arg = E->getArg(0);
11799     if (EvaluateBuiltinConstantP(Info, Arg))
11800       return Success(true, E);
11801     if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
11802       // Outside a constant context, eagerly evaluate to false in the presence
11803       // of side-effects in order to avoid -Wunsequenced false-positives in
11804       // a branch on __builtin_constant_p(expr).
11805       return Success(false, E);
11806     }
11807     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11808     return false;
11809   }
11810 
11811   case Builtin::BI__builtin_is_constant_evaluated: {
11812     const auto *Callee = Info.CurrentCall->getCallee();
11813     if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
11814         (Info.CallStackDepth == 1 ||
11815          (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
11816           Callee->getIdentifier() &&
11817           Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
11818       // FIXME: Find a better way to avoid duplicated diagnostics.
11819       if (Info.EvalStatus.Diag)
11820         Info.report((Info.CallStackDepth == 1) ? E->getExprLoc()
11821                                                : Info.CurrentCall->CallLoc,
11822                     diag::warn_is_constant_evaluated_always_true_constexpr)
11823             << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
11824                                          : "std::is_constant_evaluated");
11825     }
11826 
11827     return Success(Info.InConstantContext, E);
11828   }
11829 
11830   case Builtin::BI__builtin_ctz:
11831   case Builtin::BI__builtin_ctzl:
11832   case Builtin::BI__builtin_ctzll:
11833   case Builtin::BI__builtin_ctzs: {
11834     APSInt Val;
11835     if (!EvaluateInteger(E->getArg(0), Val, Info))
11836       return false;
11837     if (!Val)
11838       return Error(E);
11839 
11840     return Success(Val.countTrailingZeros(), E);
11841   }
11842 
11843   case Builtin::BI__builtin_eh_return_data_regno: {
11844     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11845     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
11846     return Success(Operand, E);
11847   }
11848 
11849   case Builtin::BI__builtin_expect:
11850   case Builtin::BI__builtin_expect_with_probability:
11851     return Visit(E->getArg(0));
11852 
11853   case Builtin::BI__builtin_ffs:
11854   case Builtin::BI__builtin_ffsl:
11855   case Builtin::BI__builtin_ffsll: {
11856     APSInt Val;
11857     if (!EvaluateInteger(E->getArg(0), Val, Info))
11858       return false;
11859 
11860     unsigned N = Val.countTrailingZeros();
11861     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
11862   }
11863 
11864   case Builtin::BI__builtin_fpclassify: {
11865     APFloat Val(0.0);
11866     if (!EvaluateFloat(E->getArg(5), Val, Info))
11867       return false;
11868     unsigned Arg;
11869     switch (Val.getCategory()) {
11870     case APFloat::fcNaN: Arg = 0; break;
11871     case APFloat::fcInfinity: Arg = 1; break;
11872     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
11873     case APFloat::fcZero: Arg = 4; break;
11874     }
11875     return Visit(E->getArg(Arg));
11876   }
11877 
11878   case Builtin::BI__builtin_isinf_sign: {
11879     APFloat Val(0.0);
11880     return EvaluateFloat(E->getArg(0), Val, Info) &&
11881            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
11882   }
11883 
11884   case Builtin::BI__builtin_isinf: {
11885     APFloat Val(0.0);
11886     return EvaluateFloat(E->getArg(0), Val, Info) &&
11887            Success(Val.isInfinity() ? 1 : 0, E);
11888   }
11889 
11890   case Builtin::BI__builtin_isfinite: {
11891     APFloat Val(0.0);
11892     return EvaluateFloat(E->getArg(0), Val, Info) &&
11893            Success(Val.isFinite() ? 1 : 0, E);
11894   }
11895 
11896   case Builtin::BI__builtin_isnan: {
11897     APFloat Val(0.0);
11898     return EvaluateFloat(E->getArg(0), Val, Info) &&
11899            Success(Val.isNaN() ? 1 : 0, E);
11900   }
11901 
11902   case Builtin::BI__builtin_isnormal: {
11903     APFloat Val(0.0);
11904     return EvaluateFloat(E->getArg(0), Val, Info) &&
11905            Success(Val.isNormal() ? 1 : 0, E);
11906   }
11907 
11908   case Builtin::BI__builtin_parity:
11909   case Builtin::BI__builtin_parityl:
11910   case Builtin::BI__builtin_parityll: {
11911     APSInt Val;
11912     if (!EvaluateInteger(E->getArg(0), Val, Info))
11913       return false;
11914 
11915     return Success(Val.countPopulation() % 2, E);
11916   }
11917 
11918   case Builtin::BI__builtin_popcount:
11919   case Builtin::BI__builtin_popcountl:
11920   case Builtin::BI__builtin_popcountll: {
11921     APSInt Val;
11922     if (!EvaluateInteger(E->getArg(0), Val, Info))
11923       return false;
11924 
11925     return Success(Val.countPopulation(), E);
11926   }
11927 
11928   case Builtin::BI__builtin_rotateleft8:
11929   case Builtin::BI__builtin_rotateleft16:
11930   case Builtin::BI__builtin_rotateleft32:
11931   case Builtin::BI__builtin_rotateleft64:
11932   case Builtin::BI_rotl8: // Microsoft variants of rotate right
11933   case Builtin::BI_rotl16:
11934   case Builtin::BI_rotl:
11935   case Builtin::BI_lrotl:
11936   case Builtin::BI_rotl64: {
11937     APSInt Val, Amt;
11938     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
11939         !EvaluateInteger(E->getArg(1), Amt, Info))
11940       return false;
11941 
11942     return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
11943   }
11944 
11945   case Builtin::BI__builtin_rotateright8:
11946   case Builtin::BI__builtin_rotateright16:
11947   case Builtin::BI__builtin_rotateright32:
11948   case Builtin::BI__builtin_rotateright64:
11949   case Builtin::BI_rotr8: // Microsoft variants of rotate right
11950   case Builtin::BI_rotr16:
11951   case Builtin::BI_rotr:
11952   case Builtin::BI_lrotr:
11953   case Builtin::BI_rotr64: {
11954     APSInt Val, Amt;
11955     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
11956         !EvaluateInteger(E->getArg(1), Amt, Info))
11957       return false;
11958 
11959     return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
11960   }
11961 
11962   case Builtin::BIstrlen:
11963   case Builtin::BIwcslen:
11964     // A call to strlen is not a constant expression.
11965     if (Info.getLangOpts().CPlusPlus11)
11966       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11967         << /*isConstexpr*/0 << /*isConstructor*/0
11968         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11969     else
11970       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11971     LLVM_FALLTHROUGH;
11972   case Builtin::BI__builtin_strlen:
11973   case Builtin::BI__builtin_wcslen: {
11974     // As an extension, we support __builtin_strlen() as a constant expression,
11975     // and support folding strlen() to a constant.
11976     uint64_t StrLen;
11977     if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
11978       return Success(StrLen, E);
11979     return false;
11980   }
11981 
11982   case Builtin::BIstrcmp:
11983   case Builtin::BIwcscmp:
11984   case Builtin::BIstrncmp:
11985   case Builtin::BIwcsncmp:
11986   case Builtin::BImemcmp:
11987   case Builtin::BIbcmp:
11988   case Builtin::BIwmemcmp:
11989     // A call to strlen is not a constant expression.
11990     if (Info.getLangOpts().CPlusPlus11)
11991       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11992         << /*isConstexpr*/0 << /*isConstructor*/0
11993         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11994     else
11995       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11996     LLVM_FALLTHROUGH;
11997   case Builtin::BI__builtin_strcmp:
11998   case Builtin::BI__builtin_wcscmp:
11999   case Builtin::BI__builtin_strncmp:
12000   case Builtin::BI__builtin_wcsncmp:
12001   case Builtin::BI__builtin_memcmp:
12002   case Builtin::BI__builtin_bcmp:
12003   case Builtin::BI__builtin_wmemcmp: {
12004     LValue String1, String2;
12005     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
12006         !EvaluatePointer(E->getArg(1), String2, Info))
12007       return false;
12008 
12009     uint64_t MaxLength = uint64_t(-1);
12010     if (BuiltinOp != Builtin::BIstrcmp &&
12011         BuiltinOp != Builtin::BIwcscmp &&
12012         BuiltinOp != Builtin::BI__builtin_strcmp &&
12013         BuiltinOp != Builtin::BI__builtin_wcscmp) {
12014       APSInt N;
12015       if (!EvaluateInteger(E->getArg(2), N, Info))
12016         return false;
12017       MaxLength = N.getExtValue();
12018     }
12019 
12020     // Empty substrings compare equal by definition.
12021     if (MaxLength == 0u)
12022       return Success(0, E);
12023 
12024     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
12025         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
12026         String1.Designator.Invalid || String2.Designator.Invalid)
12027       return false;
12028 
12029     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
12030     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
12031 
12032     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
12033                      BuiltinOp == Builtin::BIbcmp ||
12034                      BuiltinOp == Builtin::BI__builtin_memcmp ||
12035                      BuiltinOp == Builtin::BI__builtin_bcmp;
12036 
12037     assert(IsRawByte ||
12038            (Info.Ctx.hasSameUnqualifiedType(
12039                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
12040             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
12041 
12042     // For memcmp, allow comparing any arrays of '[[un]signed] char' or
12043     // 'char8_t', but no other types.
12044     if (IsRawByte &&
12045         !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
12046       // FIXME: Consider using our bit_cast implementation to support this.
12047       Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
12048           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
12049           << CharTy1 << CharTy2;
12050       return false;
12051     }
12052 
12053     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
12054       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
12055              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
12056              Char1.isInt() && Char2.isInt();
12057     };
12058     const auto &AdvanceElems = [&] {
12059       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
12060              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
12061     };
12062 
12063     bool StopAtNull =
12064         (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
12065          BuiltinOp != Builtin::BIwmemcmp &&
12066          BuiltinOp != Builtin::BI__builtin_memcmp &&
12067          BuiltinOp != Builtin::BI__builtin_bcmp &&
12068          BuiltinOp != Builtin::BI__builtin_wmemcmp);
12069     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
12070                   BuiltinOp == Builtin::BIwcsncmp ||
12071                   BuiltinOp == Builtin::BIwmemcmp ||
12072                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
12073                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
12074                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
12075 
12076     for (; MaxLength; --MaxLength) {
12077       APValue Char1, Char2;
12078       if (!ReadCurElems(Char1, Char2))
12079         return false;
12080       if (Char1.getInt().ne(Char2.getInt())) {
12081         if (IsWide) // wmemcmp compares with wchar_t signedness.
12082           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
12083         // memcmp always compares unsigned chars.
12084         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
12085       }
12086       if (StopAtNull && !Char1.getInt())
12087         return Success(0, E);
12088       assert(!(StopAtNull && !Char2.getInt()));
12089       if (!AdvanceElems())
12090         return false;
12091     }
12092     // We hit the strncmp / memcmp limit.
12093     return Success(0, E);
12094   }
12095 
12096   case Builtin::BI__atomic_always_lock_free:
12097   case Builtin::BI__atomic_is_lock_free:
12098   case Builtin::BI__c11_atomic_is_lock_free: {
12099     APSInt SizeVal;
12100     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
12101       return false;
12102 
12103     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
12104     // of two less than or equal to the maximum inline atomic width, we know it
12105     // is lock-free.  If the size isn't a power of two, or greater than the
12106     // maximum alignment where we promote atomics, we know it is not lock-free
12107     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
12108     // the answer can only be determined at runtime; for example, 16-byte
12109     // atomics have lock-free implementations on some, but not all,
12110     // x86-64 processors.
12111 
12112     // Check power-of-two.
12113     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
12114     if (Size.isPowerOfTwo()) {
12115       // Check against inlining width.
12116       unsigned InlineWidthBits =
12117           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
12118       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
12119         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
12120             Size == CharUnits::One() ||
12121             E->getArg(1)->isNullPointerConstant(Info.Ctx,
12122                                                 Expr::NPC_NeverValueDependent))
12123           // OK, we will inline appropriately-aligned operations of this size,
12124           // and _Atomic(T) is appropriately-aligned.
12125           return Success(1, E);
12126 
12127         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
12128           castAs<PointerType>()->getPointeeType();
12129         if (!PointeeType->isIncompleteType() &&
12130             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
12131           // OK, we will inline operations on this object.
12132           return Success(1, E);
12133         }
12134       }
12135     }
12136 
12137     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
12138         Success(0, E) : Error(E);
12139   }
12140   case Builtin::BI__builtin_add_overflow:
12141   case Builtin::BI__builtin_sub_overflow:
12142   case Builtin::BI__builtin_mul_overflow:
12143   case Builtin::BI__builtin_sadd_overflow:
12144   case Builtin::BI__builtin_uadd_overflow:
12145   case Builtin::BI__builtin_uaddl_overflow:
12146   case Builtin::BI__builtin_uaddll_overflow:
12147   case Builtin::BI__builtin_usub_overflow:
12148   case Builtin::BI__builtin_usubl_overflow:
12149   case Builtin::BI__builtin_usubll_overflow:
12150   case Builtin::BI__builtin_umul_overflow:
12151   case Builtin::BI__builtin_umull_overflow:
12152   case Builtin::BI__builtin_umulll_overflow:
12153   case Builtin::BI__builtin_saddl_overflow:
12154   case Builtin::BI__builtin_saddll_overflow:
12155   case Builtin::BI__builtin_ssub_overflow:
12156   case Builtin::BI__builtin_ssubl_overflow:
12157   case Builtin::BI__builtin_ssubll_overflow:
12158   case Builtin::BI__builtin_smul_overflow:
12159   case Builtin::BI__builtin_smull_overflow:
12160   case Builtin::BI__builtin_smulll_overflow: {
12161     LValue ResultLValue;
12162     APSInt LHS, RHS;
12163 
12164     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
12165     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
12166         !EvaluateInteger(E->getArg(1), RHS, Info) ||
12167         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
12168       return false;
12169 
12170     APSInt Result;
12171     bool DidOverflow = false;
12172 
12173     // If the types don't have to match, enlarge all 3 to the largest of them.
12174     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12175         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12176         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12177       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
12178                       ResultType->isSignedIntegerOrEnumerationType();
12179       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
12180                       ResultType->isSignedIntegerOrEnumerationType();
12181       uint64_t LHSSize = LHS.getBitWidth();
12182       uint64_t RHSSize = RHS.getBitWidth();
12183       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
12184       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
12185 
12186       // Add an additional bit if the signedness isn't uniformly agreed to. We
12187       // could do this ONLY if there is a signed and an unsigned that both have
12188       // MaxBits, but the code to check that is pretty nasty.  The issue will be
12189       // caught in the shrink-to-result later anyway.
12190       if (IsSigned && !AllSigned)
12191         ++MaxBits;
12192 
12193       LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
12194       RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
12195       Result = APSInt(MaxBits, !IsSigned);
12196     }
12197 
12198     // Find largest int.
12199     switch (BuiltinOp) {
12200     default:
12201       llvm_unreachable("Invalid value for BuiltinOp");
12202     case Builtin::BI__builtin_add_overflow:
12203     case Builtin::BI__builtin_sadd_overflow:
12204     case Builtin::BI__builtin_saddl_overflow:
12205     case Builtin::BI__builtin_saddll_overflow:
12206     case Builtin::BI__builtin_uadd_overflow:
12207     case Builtin::BI__builtin_uaddl_overflow:
12208     case Builtin::BI__builtin_uaddll_overflow:
12209       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
12210                               : LHS.uadd_ov(RHS, DidOverflow);
12211       break;
12212     case Builtin::BI__builtin_sub_overflow:
12213     case Builtin::BI__builtin_ssub_overflow:
12214     case Builtin::BI__builtin_ssubl_overflow:
12215     case Builtin::BI__builtin_ssubll_overflow:
12216     case Builtin::BI__builtin_usub_overflow:
12217     case Builtin::BI__builtin_usubl_overflow:
12218     case Builtin::BI__builtin_usubll_overflow:
12219       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
12220                               : LHS.usub_ov(RHS, DidOverflow);
12221       break;
12222     case Builtin::BI__builtin_mul_overflow:
12223     case Builtin::BI__builtin_smul_overflow:
12224     case Builtin::BI__builtin_smull_overflow:
12225     case Builtin::BI__builtin_smulll_overflow:
12226     case Builtin::BI__builtin_umul_overflow:
12227     case Builtin::BI__builtin_umull_overflow:
12228     case Builtin::BI__builtin_umulll_overflow:
12229       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
12230                               : LHS.umul_ov(RHS, DidOverflow);
12231       break;
12232     }
12233 
12234     // In the case where multiple sizes are allowed, truncate and see if
12235     // the values are the same.
12236     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12237         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12238         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12239       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
12240       // since it will give us the behavior of a TruncOrSelf in the case where
12241       // its parameter <= its size.  We previously set Result to be at least the
12242       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
12243       // will work exactly like TruncOrSelf.
12244       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
12245       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
12246 
12247       if (!APSInt::isSameValue(Temp, Result))
12248         DidOverflow = true;
12249       Result = Temp;
12250     }
12251 
12252     APValue APV{Result};
12253     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
12254       return false;
12255     return Success(DidOverflow, E);
12256   }
12257   }
12258 }
12259 
12260 /// Determine whether this is a pointer past the end of the complete
12261 /// object referred to by the lvalue.
12262 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
12263                                             const LValue &LV) {
12264   // A null pointer can be viewed as being "past the end" but we don't
12265   // choose to look at it that way here.
12266   if (!LV.getLValueBase())
12267     return false;
12268 
12269   // If the designator is valid and refers to a subobject, we're not pointing
12270   // past the end.
12271   if (!LV.getLValueDesignator().Invalid &&
12272       !LV.getLValueDesignator().isOnePastTheEnd())
12273     return false;
12274 
12275   // A pointer to an incomplete type might be past-the-end if the type's size is
12276   // zero.  We cannot tell because the type is incomplete.
12277   QualType Ty = getType(LV.getLValueBase());
12278   if (Ty->isIncompleteType())
12279     return true;
12280 
12281   // We're a past-the-end pointer if we point to the byte after the object,
12282   // no matter what our type or path is.
12283   auto Size = Ctx.getTypeSizeInChars(Ty);
12284   return LV.getLValueOffset() == Size;
12285 }
12286 
12287 namespace {
12288 
12289 /// Data recursive integer evaluator of certain binary operators.
12290 ///
12291 /// We use a data recursive algorithm for binary operators so that we are able
12292 /// to handle extreme cases of chained binary operators without causing stack
12293 /// overflow.
12294 class DataRecursiveIntBinOpEvaluator {
12295   struct EvalResult {
12296     APValue Val;
12297     bool Failed;
12298 
12299     EvalResult() : Failed(false) { }
12300 
12301     void swap(EvalResult &RHS) {
12302       Val.swap(RHS.Val);
12303       Failed = RHS.Failed;
12304       RHS.Failed = false;
12305     }
12306   };
12307 
12308   struct Job {
12309     const Expr *E;
12310     EvalResult LHSResult; // meaningful only for binary operator expression.
12311     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
12312 
12313     Job() = default;
12314     Job(Job &&) = default;
12315 
12316     void startSpeculativeEval(EvalInfo &Info) {
12317       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
12318     }
12319 
12320   private:
12321     SpeculativeEvaluationRAII SpecEvalRAII;
12322   };
12323 
12324   SmallVector<Job, 16> Queue;
12325 
12326   IntExprEvaluator &IntEval;
12327   EvalInfo &Info;
12328   APValue &FinalResult;
12329 
12330 public:
12331   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
12332     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
12333 
12334   /// True if \param E is a binary operator that we are going to handle
12335   /// data recursively.
12336   /// We handle binary operators that are comma, logical, or that have operands
12337   /// with integral or enumeration type.
12338   static bool shouldEnqueue(const BinaryOperator *E) {
12339     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
12340            (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() &&
12341             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12342             E->getRHS()->getType()->isIntegralOrEnumerationType());
12343   }
12344 
12345   bool Traverse(const BinaryOperator *E) {
12346     enqueue(E);
12347     EvalResult PrevResult;
12348     while (!Queue.empty())
12349       process(PrevResult);
12350 
12351     if (PrevResult.Failed) return false;
12352 
12353     FinalResult.swap(PrevResult.Val);
12354     return true;
12355   }
12356 
12357 private:
12358   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
12359     return IntEval.Success(Value, E, Result);
12360   }
12361   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
12362     return IntEval.Success(Value, E, Result);
12363   }
12364   bool Error(const Expr *E) {
12365     return IntEval.Error(E);
12366   }
12367   bool Error(const Expr *E, diag::kind D) {
12368     return IntEval.Error(E, D);
12369   }
12370 
12371   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
12372     return Info.CCEDiag(E, D);
12373   }
12374 
12375   // Returns true if visiting the RHS is necessary, false otherwise.
12376   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12377                          bool &SuppressRHSDiags);
12378 
12379   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12380                   const BinaryOperator *E, APValue &Result);
12381 
12382   void EvaluateExpr(const Expr *E, EvalResult &Result) {
12383     Result.Failed = !Evaluate(Result.Val, Info, E);
12384     if (Result.Failed)
12385       Result.Val = APValue();
12386   }
12387 
12388   void process(EvalResult &Result);
12389 
12390   void enqueue(const Expr *E) {
12391     E = E->IgnoreParens();
12392     Queue.resize(Queue.size()+1);
12393     Queue.back().E = E;
12394     Queue.back().Kind = Job::AnyExprKind;
12395   }
12396 };
12397 
12398 }
12399 
12400 bool DataRecursiveIntBinOpEvaluator::
12401        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12402                          bool &SuppressRHSDiags) {
12403   if (E->getOpcode() == BO_Comma) {
12404     // Ignore LHS but note if we could not evaluate it.
12405     if (LHSResult.Failed)
12406       return Info.noteSideEffect();
12407     return true;
12408   }
12409 
12410   if (E->isLogicalOp()) {
12411     bool LHSAsBool;
12412     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
12413       // We were able to evaluate the LHS, see if we can get away with not
12414       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
12415       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
12416         Success(LHSAsBool, E, LHSResult.Val);
12417         return false; // Ignore RHS
12418       }
12419     } else {
12420       LHSResult.Failed = true;
12421 
12422       // Since we weren't able to evaluate the left hand side, it
12423       // might have had side effects.
12424       if (!Info.noteSideEffect())
12425         return false;
12426 
12427       // We can't evaluate the LHS; however, sometimes the result
12428       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12429       // Don't ignore RHS and suppress diagnostics from this arm.
12430       SuppressRHSDiags = true;
12431     }
12432 
12433     return true;
12434   }
12435 
12436   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12437          E->getRHS()->getType()->isIntegralOrEnumerationType());
12438 
12439   if (LHSResult.Failed && !Info.noteFailure())
12440     return false; // Ignore RHS;
12441 
12442   return true;
12443 }
12444 
12445 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
12446                                     bool IsSub) {
12447   // Compute the new offset in the appropriate width, wrapping at 64 bits.
12448   // FIXME: When compiling for a 32-bit target, we should use 32-bit
12449   // offsets.
12450   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
12451   CharUnits &Offset = LVal.getLValueOffset();
12452   uint64_t Offset64 = Offset.getQuantity();
12453   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
12454   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
12455                                          : Offset64 + Index64);
12456 }
12457 
12458 bool DataRecursiveIntBinOpEvaluator::
12459        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12460                   const BinaryOperator *E, APValue &Result) {
12461   if (E->getOpcode() == BO_Comma) {
12462     if (RHSResult.Failed)
12463       return false;
12464     Result = RHSResult.Val;
12465     return true;
12466   }
12467 
12468   if (E->isLogicalOp()) {
12469     bool lhsResult, rhsResult;
12470     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
12471     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
12472 
12473     if (LHSIsOK) {
12474       if (RHSIsOK) {
12475         if (E->getOpcode() == BO_LOr)
12476           return Success(lhsResult || rhsResult, E, Result);
12477         else
12478           return Success(lhsResult && rhsResult, E, Result);
12479       }
12480     } else {
12481       if (RHSIsOK) {
12482         // We can't evaluate the LHS; however, sometimes the result
12483         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12484         if (rhsResult == (E->getOpcode() == BO_LOr))
12485           return Success(rhsResult, E, Result);
12486       }
12487     }
12488 
12489     return false;
12490   }
12491 
12492   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12493          E->getRHS()->getType()->isIntegralOrEnumerationType());
12494 
12495   if (LHSResult.Failed || RHSResult.Failed)
12496     return false;
12497 
12498   const APValue &LHSVal = LHSResult.Val;
12499   const APValue &RHSVal = RHSResult.Val;
12500 
12501   // Handle cases like (unsigned long)&a + 4.
12502   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
12503     Result = LHSVal;
12504     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
12505     return true;
12506   }
12507 
12508   // Handle cases like 4 + (unsigned long)&a
12509   if (E->getOpcode() == BO_Add &&
12510       RHSVal.isLValue() && LHSVal.isInt()) {
12511     Result = RHSVal;
12512     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
12513     return true;
12514   }
12515 
12516   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
12517     // Handle (intptr_t)&&A - (intptr_t)&&B.
12518     if (!LHSVal.getLValueOffset().isZero() ||
12519         !RHSVal.getLValueOffset().isZero())
12520       return false;
12521     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
12522     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
12523     if (!LHSExpr || !RHSExpr)
12524       return false;
12525     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12526     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12527     if (!LHSAddrExpr || !RHSAddrExpr)
12528       return false;
12529     // Make sure both labels come from the same function.
12530     if (LHSAddrExpr->getLabel()->getDeclContext() !=
12531         RHSAddrExpr->getLabel()->getDeclContext())
12532       return false;
12533     Result = APValue(LHSAddrExpr, RHSAddrExpr);
12534     return true;
12535   }
12536 
12537   // All the remaining cases expect both operands to be an integer
12538   if (!LHSVal.isInt() || !RHSVal.isInt())
12539     return Error(E);
12540 
12541   // Set up the width and signedness manually, in case it can't be deduced
12542   // from the operation we're performing.
12543   // FIXME: Don't do this in the cases where we can deduce it.
12544   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
12545                E->getType()->isUnsignedIntegerOrEnumerationType());
12546   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
12547                          RHSVal.getInt(), Value))
12548     return false;
12549   return Success(Value, E, Result);
12550 }
12551 
12552 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
12553   Job &job = Queue.back();
12554 
12555   switch (job.Kind) {
12556     case Job::AnyExprKind: {
12557       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
12558         if (shouldEnqueue(Bop)) {
12559           job.Kind = Job::BinOpKind;
12560           enqueue(Bop->getLHS());
12561           return;
12562         }
12563       }
12564 
12565       EvaluateExpr(job.E, Result);
12566       Queue.pop_back();
12567       return;
12568     }
12569 
12570     case Job::BinOpKind: {
12571       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12572       bool SuppressRHSDiags = false;
12573       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
12574         Queue.pop_back();
12575         return;
12576       }
12577       if (SuppressRHSDiags)
12578         job.startSpeculativeEval(Info);
12579       job.LHSResult.swap(Result);
12580       job.Kind = Job::BinOpVisitedLHSKind;
12581       enqueue(Bop->getRHS());
12582       return;
12583     }
12584 
12585     case Job::BinOpVisitedLHSKind: {
12586       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12587       EvalResult RHS;
12588       RHS.swap(Result);
12589       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
12590       Queue.pop_back();
12591       return;
12592     }
12593   }
12594 
12595   llvm_unreachable("Invalid Job::Kind!");
12596 }
12597 
12598 namespace {
12599 enum class CmpResult {
12600   Unequal,
12601   Less,
12602   Equal,
12603   Greater,
12604   Unordered,
12605 };
12606 }
12607 
12608 template <class SuccessCB, class AfterCB>
12609 static bool
12610 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
12611                                  SuccessCB &&Success, AfterCB &&DoAfter) {
12612   assert(!E->isValueDependent());
12613   assert(E->isComparisonOp() && "expected comparison operator");
12614   assert((E->getOpcode() == BO_Cmp ||
12615           E->getType()->isIntegralOrEnumerationType()) &&
12616          "unsupported binary expression evaluation");
12617   auto Error = [&](const Expr *E) {
12618     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12619     return false;
12620   };
12621 
12622   bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
12623   bool IsEquality = E->isEqualityOp();
12624 
12625   QualType LHSTy = E->getLHS()->getType();
12626   QualType RHSTy = E->getRHS()->getType();
12627 
12628   if (LHSTy->isIntegralOrEnumerationType() &&
12629       RHSTy->isIntegralOrEnumerationType()) {
12630     APSInt LHS, RHS;
12631     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
12632     if (!LHSOK && !Info.noteFailure())
12633       return false;
12634     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
12635       return false;
12636     if (LHS < RHS)
12637       return Success(CmpResult::Less, E);
12638     if (LHS > RHS)
12639       return Success(CmpResult::Greater, E);
12640     return Success(CmpResult::Equal, E);
12641   }
12642 
12643   if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
12644     APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
12645     APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
12646 
12647     bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
12648     if (!LHSOK && !Info.noteFailure())
12649       return false;
12650     if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
12651       return false;
12652     if (LHSFX < RHSFX)
12653       return Success(CmpResult::Less, E);
12654     if (LHSFX > RHSFX)
12655       return Success(CmpResult::Greater, E);
12656     return Success(CmpResult::Equal, E);
12657   }
12658 
12659   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
12660     ComplexValue LHS, RHS;
12661     bool LHSOK;
12662     if (E->isAssignmentOp()) {
12663       LValue LV;
12664       EvaluateLValue(E->getLHS(), LV, Info);
12665       LHSOK = false;
12666     } else if (LHSTy->isRealFloatingType()) {
12667       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
12668       if (LHSOK) {
12669         LHS.makeComplexFloat();
12670         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
12671       }
12672     } else {
12673       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
12674     }
12675     if (!LHSOK && !Info.noteFailure())
12676       return false;
12677 
12678     if (E->getRHS()->getType()->isRealFloatingType()) {
12679       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
12680         return false;
12681       RHS.makeComplexFloat();
12682       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
12683     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
12684       return false;
12685 
12686     if (LHS.isComplexFloat()) {
12687       APFloat::cmpResult CR_r =
12688         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
12689       APFloat::cmpResult CR_i =
12690         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
12691       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
12692       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12693     } else {
12694       assert(IsEquality && "invalid complex comparison");
12695       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
12696                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
12697       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12698     }
12699   }
12700 
12701   if (LHSTy->isRealFloatingType() &&
12702       RHSTy->isRealFloatingType()) {
12703     APFloat RHS(0.0), LHS(0.0);
12704 
12705     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
12706     if (!LHSOK && !Info.noteFailure())
12707       return false;
12708 
12709     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
12710       return false;
12711 
12712     assert(E->isComparisonOp() && "Invalid binary operator!");
12713     llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
12714     if (!Info.InConstantContext &&
12715         APFloatCmpResult == APFloat::cmpUnordered &&
12716         E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
12717       // Note: Compares may raise invalid in some cases involving NaN or sNaN.
12718       Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
12719       return false;
12720     }
12721     auto GetCmpRes = [&]() {
12722       switch (APFloatCmpResult) {
12723       case APFloat::cmpEqual:
12724         return CmpResult::Equal;
12725       case APFloat::cmpLessThan:
12726         return CmpResult::Less;
12727       case APFloat::cmpGreaterThan:
12728         return CmpResult::Greater;
12729       case APFloat::cmpUnordered:
12730         return CmpResult::Unordered;
12731       }
12732       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
12733     };
12734     return Success(GetCmpRes(), E);
12735   }
12736 
12737   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
12738     LValue LHSValue, RHSValue;
12739 
12740     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12741     if (!LHSOK && !Info.noteFailure())
12742       return false;
12743 
12744     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12745       return false;
12746 
12747     // Reject differing bases from the normal codepath; we special-case
12748     // comparisons to null.
12749     if (!HasSameBase(LHSValue, RHSValue)) {
12750       // Inequalities and subtractions between unrelated pointers have
12751       // unspecified or undefined behavior.
12752       if (!IsEquality) {
12753         Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified);
12754         return false;
12755       }
12756       // A constant address may compare equal to the address of a symbol.
12757       // The one exception is that address of an object cannot compare equal
12758       // to a null pointer constant.
12759       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
12760           (!RHSValue.Base && !RHSValue.Offset.isZero()))
12761         return Error(E);
12762       // It's implementation-defined whether distinct literals will have
12763       // distinct addresses. In clang, the result of such a comparison is
12764       // unspecified, so it is not a constant expression. However, we do know
12765       // that the address of a literal will be non-null.
12766       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
12767           LHSValue.Base && RHSValue.Base)
12768         return Error(E);
12769       // We can't tell whether weak symbols will end up pointing to the same
12770       // object.
12771       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
12772         return Error(E);
12773       // We can't compare the address of the start of one object with the
12774       // past-the-end address of another object, per C++ DR1652.
12775       if ((LHSValue.Base && LHSValue.Offset.isZero() &&
12776            isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
12777           (RHSValue.Base && RHSValue.Offset.isZero() &&
12778            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
12779         return Error(E);
12780       // We can't tell whether an object is at the same address as another
12781       // zero sized object.
12782       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
12783           (LHSValue.Base && isZeroSized(RHSValue)))
12784         return Error(E);
12785       return Success(CmpResult::Unequal, E);
12786     }
12787 
12788     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12789     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12790 
12791     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12792     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12793 
12794     // C++11 [expr.rel]p3:
12795     //   Pointers to void (after pointer conversions) can be compared, with a
12796     //   result defined as follows: If both pointers represent the same
12797     //   address or are both the null pointer value, the result is true if the
12798     //   operator is <= or >= and false otherwise; otherwise the result is
12799     //   unspecified.
12800     // We interpret this as applying to pointers to *cv* void.
12801     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
12802       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
12803 
12804     // C++11 [expr.rel]p2:
12805     // - If two pointers point to non-static data members of the same object,
12806     //   or to subobjects or array elements fo such members, recursively, the
12807     //   pointer to the later declared member compares greater provided the
12808     //   two members have the same access control and provided their class is
12809     //   not a union.
12810     //   [...]
12811     // - Otherwise pointer comparisons are unspecified.
12812     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
12813       bool WasArrayIndex;
12814       unsigned Mismatch = FindDesignatorMismatch(
12815           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
12816       // At the point where the designators diverge, the comparison has a
12817       // specified value if:
12818       //  - we are comparing array indices
12819       //  - we are comparing fields of a union, or fields with the same access
12820       // Otherwise, the result is unspecified and thus the comparison is not a
12821       // constant expression.
12822       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
12823           Mismatch < RHSDesignator.Entries.size()) {
12824         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
12825         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
12826         if (!LF && !RF)
12827           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
12828         else if (!LF)
12829           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12830               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
12831               << RF->getParent() << RF;
12832         else if (!RF)
12833           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12834               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
12835               << LF->getParent() << LF;
12836         else if (!LF->getParent()->isUnion() &&
12837                  LF->getAccess() != RF->getAccess())
12838           Info.CCEDiag(E,
12839                        diag::note_constexpr_pointer_comparison_differing_access)
12840               << LF << LF->getAccess() << RF << RF->getAccess()
12841               << LF->getParent();
12842       }
12843     }
12844 
12845     // The comparison here must be unsigned, and performed with the same
12846     // width as the pointer.
12847     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
12848     uint64_t CompareLHS = LHSOffset.getQuantity();
12849     uint64_t CompareRHS = RHSOffset.getQuantity();
12850     assert(PtrSize <= 64 && "Unexpected pointer width");
12851     uint64_t Mask = ~0ULL >> (64 - PtrSize);
12852     CompareLHS &= Mask;
12853     CompareRHS &= Mask;
12854 
12855     // If there is a base and this is a relational operator, we can only
12856     // compare pointers within the object in question; otherwise, the result
12857     // depends on where the object is located in memory.
12858     if (!LHSValue.Base.isNull() && IsRelational) {
12859       QualType BaseTy = getType(LHSValue.Base);
12860       if (BaseTy->isIncompleteType())
12861         return Error(E);
12862       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
12863       uint64_t OffsetLimit = Size.getQuantity();
12864       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
12865         return Error(E);
12866     }
12867 
12868     if (CompareLHS < CompareRHS)
12869       return Success(CmpResult::Less, E);
12870     if (CompareLHS > CompareRHS)
12871       return Success(CmpResult::Greater, E);
12872     return Success(CmpResult::Equal, E);
12873   }
12874 
12875   if (LHSTy->isMemberPointerType()) {
12876     assert(IsEquality && "unexpected member pointer operation");
12877     assert(RHSTy->isMemberPointerType() && "invalid comparison");
12878 
12879     MemberPtr LHSValue, RHSValue;
12880 
12881     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
12882     if (!LHSOK && !Info.noteFailure())
12883       return false;
12884 
12885     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12886       return false;
12887 
12888     // C++11 [expr.eq]p2:
12889     //   If both operands are null, they compare equal. Otherwise if only one is
12890     //   null, they compare unequal.
12891     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
12892       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
12893       return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12894     }
12895 
12896     //   Otherwise if either is a pointer to a virtual member function, the
12897     //   result is unspecified.
12898     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
12899       if (MD->isVirtual())
12900         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12901     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
12902       if (MD->isVirtual())
12903         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12904 
12905     //   Otherwise they compare equal if and only if they would refer to the
12906     //   same member of the same most derived object or the same subobject if
12907     //   they were dereferenced with a hypothetical object of the associated
12908     //   class type.
12909     bool Equal = LHSValue == RHSValue;
12910     return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12911   }
12912 
12913   if (LHSTy->isNullPtrType()) {
12914     assert(E->isComparisonOp() && "unexpected nullptr operation");
12915     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
12916     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
12917     // are compared, the result is true of the operator is <=, >= or ==, and
12918     // false otherwise.
12919     return Success(CmpResult::Equal, E);
12920   }
12921 
12922   return DoAfter();
12923 }
12924 
12925 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
12926   if (!CheckLiteralType(Info, E))
12927     return false;
12928 
12929   auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12930     ComparisonCategoryResult CCR;
12931     switch (CR) {
12932     case CmpResult::Unequal:
12933       llvm_unreachable("should never produce Unequal for three-way comparison");
12934     case CmpResult::Less:
12935       CCR = ComparisonCategoryResult::Less;
12936       break;
12937     case CmpResult::Equal:
12938       CCR = ComparisonCategoryResult::Equal;
12939       break;
12940     case CmpResult::Greater:
12941       CCR = ComparisonCategoryResult::Greater;
12942       break;
12943     case CmpResult::Unordered:
12944       CCR = ComparisonCategoryResult::Unordered;
12945       break;
12946     }
12947     // Evaluation succeeded. Lookup the information for the comparison category
12948     // type and fetch the VarDecl for the result.
12949     const ComparisonCategoryInfo &CmpInfo =
12950         Info.Ctx.CompCategories.getInfoForType(E->getType());
12951     const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
12952     // Check and evaluate the result as a constant expression.
12953     LValue LV;
12954     LV.set(VD);
12955     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
12956       return false;
12957     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
12958                                    ConstantExprKind::Normal);
12959   };
12960   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12961     return ExprEvaluatorBaseTy::VisitBinCmp(E);
12962   });
12963 }
12964 
12965 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12966   // We don't support assignment in C. C++ assignments don't get here because
12967   // assignment is an lvalue in C++.
12968   if (E->isAssignmentOp()) {
12969     Error(E);
12970     if (!Info.noteFailure())
12971       return false;
12972   }
12973 
12974   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
12975     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
12976 
12977   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
12978           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
12979          "DataRecursiveIntBinOpEvaluator should have handled integral types");
12980 
12981   if (E->isComparisonOp()) {
12982     // Evaluate builtin binary comparisons by evaluating them as three-way
12983     // comparisons and then translating the result.
12984     auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12985       assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
12986              "should only produce Unequal for equality comparisons");
12987       bool IsEqual   = CR == CmpResult::Equal,
12988            IsLess    = CR == CmpResult::Less,
12989            IsGreater = CR == CmpResult::Greater;
12990       auto Op = E->getOpcode();
12991       switch (Op) {
12992       default:
12993         llvm_unreachable("unsupported binary operator");
12994       case BO_EQ:
12995       case BO_NE:
12996         return Success(IsEqual == (Op == BO_EQ), E);
12997       case BO_LT:
12998         return Success(IsLess, E);
12999       case BO_GT:
13000         return Success(IsGreater, E);
13001       case BO_LE:
13002         return Success(IsEqual || IsLess, E);
13003       case BO_GE:
13004         return Success(IsEqual || IsGreater, E);
13005       }
13006     };
13007     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
13008       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13009     });
13010   }
13011 
13012   QualType LHSTy = E->getLHS()->getType();
13013   QualType RHSTy = E->getRHS()->getType();
13014 
13015   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
13016       E->getOpcode() == BO_Sub) {
13017     LValue LHSValue, RHSValue;
13018 
13019     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
13020     if (!LHSOK && !Info.noteFailure())
13021       return false;
13022 
13023     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13024       return false;
13025 
13026     // Reject differing bases from the normal codepath; we special-case
13027     // comparisons to null.
13028     if (!HasSameBase(LHSValue, RHSValue)) {
13029       // Handle &&A - &&B.
13030       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
13031         return Error(E);
13032       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
13033       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
13034       if (!LHSExpr || !RHSExpr)
13035         return Error(E);
13036       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
13037       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
13038       if (!LHSAddrExpr || !RHSAddrExpr)
13039         return Error(E);
13040       // Make sure both labels come from the same function.
13041       if (LHSAddrExpr->getLabel()->getDeclContext() !=
13042           RHSAddrExpr->getLabel()->getDeclContext())
13043         return Error(E);
13044       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
13045     }
13046     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
13047     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
13048 
13049     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
13050     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
13051 
13052     // C++11 [expr.add]p6:
13053     //   Unless both pointers point to elements of the same array object, or
13054     //   one past the last element of the array object, the behavior is
13055     //   undefined.
13056     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
13057         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
13058                                 RHSDesignator))
13059       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
13060 
13061     QualType Type = E->getLHS()->getType();
13062     QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
13063 
13064     CharUnits ElementSize;
13065     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
13066       return false;
13067 
13068     // As an extension, a type may have zero size (empty struct or union in
13069     // C, array of zero length). Pointer subtraction in such cases has
13070     // undefined behavior, so is not constant.
13071     if (ElementSize.isZero()) {
13072       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
13073           << ElementType;
13074       return false;
13075     }
13076 
13077     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
13078     // and produce incorrect results when it overflows. Such behavior
13079     // appears to be non-conforming, but is common, so perhaps we should
13080     // assume the standard intended for such cases to be undefined behavior
13081     // and check for them.
13082 
13083     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
13084     // overflow in the final conversion to ptrdiff_t.
13085     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
13086     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
13087     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
13088                     false);
13089     APSInt TrueResult = (LHS - RHS) / ElemSize;
13090     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
13091 
13092     if (Result.extend(65) != TrueResult &&
13093         !HandleOverflow(Info, E, TrueResult, E->getType()))
13094       return false;
13095     return Success(Result, E);
13096   }
13097 
13098   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13099 }
13100 
13101 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
13102 /// a result as the expression's type.
13103 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
13104                                     const UnaryExprOrTypeTraitExpr *E) {
13105   switch(E->getKind()) {
13106   case UETT_PreferredAlignOf:
13107   case UETT_AlignOf: {
13108     if (E->isArgumentType())
13109       return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
13110                      E);
13111     else
13112       return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
13113                      E);
13114   }
13115 
13116   case UETT_VecStep: {
13117     QualType Ty = E->getTypeOfArgument();
13118 
13119     if (Ty->isVectorType()) {
13120       unsigned n = Ty->castAs<VectorType>()->getNumElements();
13121 
13122       // The vec_step built-in functions that take a 3-component
13123       // vector return 4. (OpenCL 1.1 spec 6.11.12)
13124       if (n == 3)
13125         n = 4;
13126 
13127       return Success(n, E);
13128     } else
13129       return Success(1, E);
13130   }
13131 
13132   case UETT_SizeOf: {
13133     QualType SrcTy = E->getTypeOfArgument();
13134     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
13135     //   the result is the size of the referenced type."
13136     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
13137       SrcTy = Ref->getPointeeType();
13138 
13139     CharUnits Sizeof;
13140     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
13141       return false;
13142     return Success(Sizeof, E);
13143   }
13144   case UETT_OpenMPRequiredSimdAlign:
13145     assert(E->isArgumentType());
13146     return Success(
13147         Info.Ctx.toCharUnitsFromBits(
13148                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
13149             .getQuantity(),
13150         E);
13151   }
13152 
13153   llvm_unreachable("unknown expr/type trait");
13154 }
13155 
13156 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
13157   CharUnits Result;
13158   unsigned n = OOE->getNumComponents();
13159   if (n == 0)
13160     return Error(OOE);
13161   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
13162   for (unsigned i = 0; i != n; ++i) {
13163     OffsetOfNode ON = OOE->getComponent(i);
13164     switch (ON.getKind()) {
13165     case OffsetOfNode::Array: {
13166       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
13167       APSInt IdxResult;
13168       if (!EvaluateInteger(Idx, IdxResult, Info))
13169         return false;
13170       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
13171       if (!AT)
13172         return Error(OOE);
13173       CurrentType = AT->getElementType();
13174       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
13175       Result += IdxResult.getSExtValue() * ElementSize;
13176       break;
13177     }
13178 
13179     case OffsetOfNode::Field: {
13180       FieldDecl *MemberDecl = ON.getField();
13181       const RecordType *RT = CurrentType->getAs<RecordType>();
13182       if (!RT)
13183         return Error(OOE);
13184       RecordDecl *RD = RT->getDecl();
13185       if (RD->isInvalidDecl()) return false;
13186       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13187       unsigned i = MemberDecl->getFieldIndex();
13188       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
13189       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
13190       CurrentType = MemberDecl->getType().getNonReferenceType();
13191       break;
13192     }
13193 
13194     case OffsetOfNode::Identifier:
13195       llvm_unreachable("dependent __builtin_offsetof");
13196 
13197     case OffsetOfNode::Base: {
13198       CXXBaseSpecifier *BaseSpec = ON.getBase();
13199       if (BaseSpec->isVirtual())
13200         return Error(OOE);
13201 
13202       // Find the layout of the class whose base we are looking into.
13203       const RecordType *RT = CurrentType->getAs<RecordType>();
13204       if (!RT)
13205         return Error(OOE);
13206       RecordDecl *RD = RT->getDecl();
13207       if (RD->isInvalidDecl()) return false;
13208       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13209 
13210       // Find the base class itself.
13211       CurrentType = BaseSpec->getType();
13212       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
13213       if (!BaseRT)
13214         return Error(OOE);
13215 
13216       // Add the offset to the base.
13217       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
13218       break;
13219     }
13220     }
13221   }
13222   return Success(Result, OOE);
13223 }
13224 
13225 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13226   switch (E->getOpcode()) {
13227   default:
13228     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
13229     // See C99 6.6p3.
13230     return Error(E);
13231   case UO_Extension:
13232     // FIXME: Should extension allow i-c-e extension expressions in its scope?
13233     // If so, we could clear the diagnostic ID.
13234     return Visit(E->getSubExpr());
13235   case UO_Plus:
13236     // The result is just the value.
13237     return Visit(E->getSubExpr());
13238   case UO_Minus: {
13239     if (!Visit(E->getSubExpr()))
13240       return false;
13241     if (!Result.isInt()) return Error(E);
13242     const APSInt &Value = Result.getInt();
13243     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
13244         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
13245                         E->getType()))
13246       return false;
13247     return Success(-Value, E);
13248   }
13249   case UO_Not: {
13250     if (!Visit(E->getSubExpr()))
13251       return false;
13252     if (!Result.isInt()) return Error(E);
13253     return Success(~Result.getInt(), E);
13254   }
13255   case UO_LNot: {
13256     bool bres;
13257     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13258       return false;
13259     return Success(!bres, E);
13260   }
13261   }
13262 }
13263 
13264 /// HandleCast - This is used to evaluate implicit or explicit casts where the
13265 /// result type is integer.
13266 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
13267   const Expr *SubExpr = E->getSubExpr();
13268   QualType DestType = E->getType();
13269   QualType SrcType = SubExpr->getType();
13270 
13271   switch (E->getCastKind()) {
13272   case CK_BaseToDerived:
13273   case CK_DerivedToBase:
13274   case CK_UncheckedDerivedToBase:
13275   case CK_Dynamic:
13276   case CK_ToUnion:
13277   case CK_ArrayToPointerDecay:
13278   case CK_FunctionToPointerDecay:
13279   case CK_NullToPointer:
13280   case CK_NullToMemberPointer:
13281   case CK_BaseToDerivedMemberPointer:
13282   case CK_DerivedToBaseMemberPointer:
13283   case CK_ReinterpretMemberPointer:
13284   case CK_ConstructorConversion:
13285   case CK_IntegralToPointer:
13286   case CK_ToVoid:
13287   case CK_VectorSplat:
13288   case CK_IntegralToFloating:
13289   case CK_FloatingCast:
13290   case CK_CPointerToObjCPointerCast:
13291   case CK_BlockPointerToObjCPointerCast:
13292   case CK_AnyPointerToBlockPointerCast:
13293   case CK_ObjCObjectLValueCast:
13294   case CK_FloatingRealToComplex:
13295   case CK_FloatingComplexToReal:
13296   case CK_FloatingComplexCast:
13297   case CK_FloatingComplexToIntegralComplex:
13298   case CK_IntegralRealToComplex:
13299   case CK_IntegralComplexCast:
13300   case CK_IntegralComplexToFloatingComplex:
13301   case CK_BuiltinFnToFnPtr:
13302   case CK_ZeroToOCLOpaqueType:
13303   case CK_NonAtomicToAtomic:
13304   case CK_AddressSpaceConversion:
13305   case CK_IntToOCLSampler:
13306   case CK_FloatingToFixedPoint:
13307   case CK_FixedPointToFloating:
13308   case CK_FixedPointCast:
13309   case CK_IntegralToFixedPoint:
13310   case CK_MatrixCast:
13311     llvm_unreachable("invalid cast kind for integral value");
13312 
13313   case CK_BitCast:
13314   case CK_Dependent:
13315   case CK_LValueBitCast:
13316   case CK_ARCProduceObject:
13317   case CK_ARCConsumeObject:
13318   case CK_ARCReclaimReturnedObject:
13319   case CK_ARCExtendBlockObject:
13320   case CK_CopyAndAutoreleaseBlockObject:
13321     return Error(E);
13322 
13323   case CK_UserDefinedConversion:
13324   case CK_LValueToRValue:
13325   case CK_AtomicToNonAtomic:
13326   case CK_NoOp:
13327   case CK_LValueToRValueBitCast:
13328     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13329 
13330   case CK_MemberPointerToBoolean:
13331   case CK_PointerToBoolean:
13332   case CK_IntegralToBoolean:
13333   case CK_FloatingToBoolean:
13334   case CK_BooleanToSignedIntegral:
13335   case CK_FloatingComplexToBoolean:
13336   case CK_IntegralComplexToBoolean: {
13337     bool BoolResult;
13338     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
13339       return false;
13340     uint64_t IntResult = BoolResult;
13341     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
13342       IntResult = (uint64_t)-1;
13343     return Success(IntResult, E);
13344   }
13345 
13346   case CK_FixedPointToIntegral: {
13347     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
13348     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13349       return false;
13350     bool Overflowed;
13351     llvm::APSInt Result = Src.convertToInt(
13352         Info.Ctx.getIntWidth(DestType),
13353         DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
13354     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
13355       return false;
13356     return Success(Result, E);
13357   }
13358 
13359   case CK_FixedPointToBoolean: {
13360     // Unsigned padding does not affect this.
13361     APValue Val;
13362     if (!Evaluate(Val, Info, SubExpr))
13363       return false;
13364     return Success(Val.getFixedPoint().getBoolValue(), E);
13365   }
13366 
13367   case CK_IntegralCast: {
13368     if (!Visit(SubExpr))
13369       return false;
13370 
13371     if (!Result.isInt()) {
13372       // Allow casts of address-of-label differences if they are no-ops
13373       // or narrowing.  (The narrowing case isn't actually guaranteed to
13374       // be constant-evaluatable except in some narrow cases which are hard
13375       // to detect here.  We let it through on the assumption the user knows
13376       // what they are doing.)
13377       if (Result.isAddrLabelDiff())
13378         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
13379       // Only allow casts of lvalues if they are lossless.
13380       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
13381     }
13382 
13383     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
13384                                       Result.getInt()), E);
13385   }
13386 
13387   case CK_PointerToIntegral: {
13388     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
13389 
13390     LValue LV;
13391     if (!EvaluatePointer(SubExpr, LV, Info))
13392       return false;
13393 
13394     if (LV.getLValueBase()) {
13395       // Only allow based lvalue casts if they are lossless.
13396       // FIXME: Allow a larger integer size than the pointer size, and allow
13397       // narrowing back down to pointer width in subsequent integral casts.
13398       // FIXME: Check integer type's active bits, not its type size.
13399       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
13400         return Error(E);
13401 
13402       LV.Designator.setInvalid();
13403       LV.moveInto(Result);
13404       return true;
13405     }
13406 
13407     APSInt AsInt;
13408     APValue V;
13409     LV.moveInto(V);
13410     if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
13411       llvm_unreachable("Can't cast this!");
13412 
13413     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
13414   }
13415 
13416   case CK_IntegralComplexToReal: {
13417     ComplexValue C;
13418     if (!EvaluateComplex(SubExpr, C, Info))
13419       return false;
13420     return Success(C.getComplexIntReal(), E);
13421   }
13422 
13423   case CK_FloatingToIntegral: {
13424     APFloat F(0.0);
13425     if (!EvaluateFloat(SubExpr, F, Info))
13426       return false;
13427 
13428     APSInt Value;
13429     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
13430       return false;
13431     return Success(Value, E);
13432   }
13433   }
13434 
13435   llvm_unreachable("unknown cast resulting in integral value");
13436 }
13437 
13438 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13439   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13440     ComplexValue LV;
13441     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13442       return false;
13443     if (!LV.isComplexInt())
13444       return Error(E);
13445     return Success(LV.getComplexIntReal(), E);
13446   }
13447 
13448   return Visit(E->getSubExpr());
13449 }
13450 
13451 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13452   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
13453     ComplexValue LV;
13454     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13455       return false;
13456     if (!LV.isComplexInt())
13457       return Error(E);
13458     return Success(LV.getComplexIntImag(), E);
13459   }
13460 
13461   VisitIgnoredValue(E->getSubExpr());
13462   return Success(0, E);
13463 }
13464 
13465 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
13466   return Success(E->getPackLength(), E);
13467 }
13468 
13469 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
13470   return Success(E->getValue(), E);
13471 }
13472 
13473 bool IntExprEvaluator::VisitConceptSpecializationExpr(
13474        const ConceptSpecializationExpr *E) {
13475   return Success(E->isSatisfied(), E);
13476 }
13477 
13478 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
13479   return Success(E->isSatisfied(), E);
13480 }
13481 
13482 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13483   switch (E->getOpcode()) {
13484     default:
13485       // Invalid unary operators
13486       return Error(E);
13487     case UO_Plus:
13488       // The result is just the value.
13489       return Visit(E->getSubExpr());
13490     case UO_Minus: {
13491       if (!Visit(E->getSubExpr())) return false;
13492       if (!Result.isFixedPoint())
13493         return Error(E);
13494       bool Overflowed;
13495       APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
13496       if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
13497         return false;
13498       return Success(Negated, E);
13499     }
13500     case UO_LNot: {
13501       bool bres;
13502       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13503         return false;
13504       return Success(!bres, E);
13505     }
13506   }
13507 }
13508 
13509 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
13510   const Expr *SubExpr = E->getSubExpr();
13511   QualType DestType = E->getType();
13512   assert(DestType->isFixedPointType() &&
13513          "Expected destination type to be a fixed point type");
13514   auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
13515 
13516   switch (E->getCastKind()) {
13517   case CK_FixedPointCast: {
13518     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13519     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13520       return false;
13521     bool Overflowed;
13522     APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
13523     if (Overflowed) {
13524       if (Info.checkingForUndefinedBehavior())
13525         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13526                                          diag::warn_fixedpoint_constant_overflow)
13527           << Result.toString() << E->getType();
13528       if (!HandleOverflow(Info, E, Result, E->getType()))
13529         return false;
13530     }
13531     return Success(Result, E);
13532   }
13533   case CK_IntegralToFixedPoint: {
13534     APSInt Src;
13535     if (!EvaluateInteger(SubExpr, Src, Info))
13536       return false;
13537 
13538     bool Overflowed;
13539     APFixedPoint IntResult = APFixedPoint::getFromIntValue(
13540         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13541 
13542     if (Overflowed) {
13543       if (Info.checkingForUndefinedBehavior())
13544         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13545                                          diag::warn_fixedpoint_constant_overflow)
13546           << IntResult.toString() << E->getType();
13547       if (!HandleOverflow(Info, E, IntResult, E->getType()))
13548         return false;
13549     }
13550 
13551     return Success(IntResult, E);
13552   }
13553   case CK_FloatingToFixedPoint: {
13554     APFloat Src(0.0);
13555     if (!EvaluateFloat(SubExpr, Src, Info))
13556       return false;
13557 
13558     bool Overflowed;
13559     APFixedPoint Result = APFixedPoint::getFromFloatValue(
13560         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13561 
13562     if (Overflowed) {
13563       if (Info.checkingForUndefinedBehavior())
13564         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13565                                          diag::warn_fixedpoint_constant_overflow)
13566           << Result.toString() << E->getType();
13567       if (!HandleOverflow(Info, E, Result, E->getType()))
13568         return false;
13569     }
13570 
13571     return Success(Result, E);
13572   }
13573   case CK_NoOp:
13574   case CK_LValueToRValue:
13575     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13576   default:
13577     return Error(E);
13578   }
13579 }
13580 
13581 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13582   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13583     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13584 
13585   const Expr *LHS = E->getLHS();
13586   const Expr *RHS = E->getRHS();
13587   FixedPointSemantics ResultFXSema =
13588       Info.Ctx.getFixedPointSemantics(E->getType());
13589 
13590   APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
13591   if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
13592     return false;
13593   APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
13594   if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
13595     return false;
13596 
13597   bool OpOverflow = false, ConversionOverflow = false;
13598   APFixedPoint Result(LHSFX.getSemantics());
13599   switch (E->getOpcode()) {
13600   case BO_Add: {
13601     Result = LHSFX.add(RHSFX, &OpOverflow)
13602                   .convert(ResultFXSema, &ConversionOverflow);
13603     break;
13604   }
13605   case BO_Sub: {
13606     Result = LHSFX.sub(RHSFX, &OpOverflow)
13607                   .convert(ResultFXSema, &ConversionOverflow);
13608     break;
13609   }
13610   case BO_Mul: {
13611     Result = LHSFX.mul(RHSFX, &OpOverflow)
13612                   .convert(ResultFXSema, &ConversionOverflow);
13613     break;
13614   }
13615   case BO_Div: {
13616     if (RHSFX.getValue() == 0) {
13617       Info.FFDiag(E, diag::note_expr_divide_by_zero);
13618       return false;
13619     }
13620     Result = LHSFX.div(RHSFX, &OpOverflow)
13621                   .convert(ResultFXSema, &ConversionOverflow);
13622     break;
13623   }
13624   case BO_Shl:
13625   case BO_Shr: {
13626     FixedPointSemantics LHSSema = LHSFX.getSemantics();
13627     llvm::APSInt RHSVal = RHSFX.getValue();
13628 
13629     unsigned ShiftBW =
13630         LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
13631     unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
13632     // Embedded-C 4.1.6.2.2:
13633     //   The right operand must be nonnegative and less than the total number
13634     //   of (nonpadding) bits of the fixed-point operand ...
13635     if (RHSVal.isNegative())
13636       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
13637     else if (Amt != RHSVal)
13638       Info.CCEDiag(E, diag::note_constexpr_large_shift)
13639           << RHSVal << E->getType() << ShiftBW;
13640 
13641     if (E->getOpcode() == BO_Shl)
13642       Result = LHSFX.shl(Amt, &OpOverflow);
13643     else
13644       Result = LHSFX.shr(Amt, &OpOverflow);
13645     break;
13646   }
13647   default:
13648     return false;
13649   }
13650   if (OpOverflow || ConversionOverflow) {
13651     if (Info.checkingForUndefinedBehavior())
13652       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13653                                        diag::warn_fixedpoint_constant_overflow)
13654         << Result.toString() << E->getType();
13655     if (!HandleOverflow(Info, E, Result, E->getType()))
13656       return false;
13657   }
13658   return Success(Result, E);
13659 }
13660 
13661 //===----------------------------------------------------------------------===//
13662 // Float Evaluation
13663 //===----------------------------------------------------------------------===//
13664 
13665 namespace {
13666 class FloatExprEvaluator
13667   : public ExprEvaluatorBase<FloatExprEvaluator> {
13668   APFloat &Result;
13669 public:
13670   FloatExprEvaluator(EvalInfo &info, APFloat &result)
13671     : ExprEvaluatorBaseTy(info), Result(result) {}
13672 
13673   bool Success(const APValue &V, const Expr *e) {
13674     Result = V.getFloat();
13675     return true;
13676   }
13677 
13678   bool ZeroInitialization(const Expr *E) {
13679     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
13680     return true;
13681   }
13682 
13683   bool VisitCallExpr(const CallExpr *E);
13684 
13685   bool VisitUnaryOperator(const UnaryOperator *E);
13686   bool VisitBinaryOperator(const BinaryOperator *E);
13687   bool VisitFloatingLiteral(const FloatingLiteral *E);
13688   bool VisitCastExpr(const CastExpr *E);
13689 
13690   bool VisitUnaryReal(const UnaryOperator *E);
13691   bool VisitUnaryImag(const UnaryOperator *E);
13692 
13693   // FIXME: Missing: array subscript of vector, member of vector
13694 };
13695 } // end anonymous namespace
13696 
13697 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
13698   assert(!E->isValueDependent());
13699   assert(E->isPRValue() && E->getType()->isRealFloatingType());
13700   return FloatExprEvaluator(Info, Result).Visit(E);
13701 }
13702 
13703 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
13704                                   QualType ResultTy,
13705                                   const Expr *Arg,
13706                                   bool SNaN,
13707                                   llvm::APFloat &Result) {
13708   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
13709   if (!S) return false;
13710 
13711   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
13712 
13713   llvm::APInt fill;
13714 
13715   // Treat empty strings as if they were zero.
13716   if (S->getString().empty())
13717     fill = llvm::APInt(32, 0);
13718   else if (S->getString().getAsInteger(0, fill))
13719     return false;
13720 
13721   if (Context.getTargetInfo().isNan2008()) {
13722     if (SNaN)
13723       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13724     else
13725       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13726   } else {
13727     // Prior to IEEE 754-2008, architectures were allowed to choose whether
13728     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
13729     // a different encoding to what became a standard in 2008, and for pre-
13730     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
13731     // sNaN. This is now known as "legacy NaN" encoding.
13732     if (SNaN)
13733       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13734     else
13735       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13736   }
13737 
13738   return true;
13739 }
13740 
13741 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
13742   switch (E->getBuiltinCallee()) {
13743   default:
13744     return ExprEvaluatorBaseTy::VisitCallExpr(E);
13745 
13746   case Builtin::BI__builtin_huge_val:
13747   case Builtin::BI__builtin_huge_valf:
13748   case Builtin::BI__builtin_huge_vall:
13749   case Builtin::BI__builtin_huge_valf128:
13750   case Builtin::BI__builtin_inf:
13751   case Builtin::BI__builtin_inff:
13752   case Builtin::BI__builtin_infl:
13753   case Builtin::BI__builtin_inff128: {
13754     const llvm::fltSemantics &Sem =
13755       Info.Ctx.getFloatTypeSemantics(E->getType());
13756     Result = llvm::APFloat::getInf(Sem);
13757     return true;
13758   }
13759 
13760   case Builtin::BI__builtin_nans:
13761   case Builtin::BI__builtin_nansf:
13762   case Builtin::BI__builtin_nansl:
13763   case Builtin::BI__builtin_nansf128:
13764     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13765                                true, Result))
13766       return Error(E);
13767     return true;
13768 
13769   case Builtin::BI__builtin_nan:
13770   case Builtin::BI__builtin_nanf:
13771   case Builtin::BI__builtin_nanl:
13772   case Builtin::BI__builtin_nanf128:
13773     // If this is __builtin_nan() turn this into a nan, otherwise we
13774     // can't constant fold it.
13775     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13776                                false, Result))
13777       return Error(E);
13778     return true;
13779 
13780   case Builtin::BI__builtin_fabs:
13781   case Builtin::BI__builtin_fabsf:
13782   case Builtin::BI__builtin_fabsl:
13783   case Builtin::BI__builtin_fabsf128:
13784     // The C standard says "fabs raises no floating-point exceptions,
13785     // even if x is a signaling NaN. The returned value is independent of
13786     // the current rounding direction mode."  Therefore constant folding can
13787     // proceed without regard to the floating point settings.
13788     // Reference, WG14 N2478 F.10.4.3
13789     if (!EvaluateFloat(E->getArg(0), Result, Info))
13790       return false;
13791 
13792     if (Result.isNegative())
13793       Result.changeSign();
13794     return true;
13795 
13796   case Builtin::BI__arithmetic_fence:
13797     return EvaluateFloat(E->getArg(0), Result, Info);
13798 
13799   // FIXME: Builtin::BI__builtin_powi
13800   // FIXME: Builtin::BI__builtin_powif
13801   // FIXME: Builtin::BI__builtin_powil
13802 
13803   case Builtin::BI__builtin_copysign:
13804   case Builtin::BI__builtin_copysignf:
13805   case Builtin::BI__builtin_copysignl:
13806   case Builtin::BI__builtin_copysignf128: {
13807     APFloat RHS(0.);
13808     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
13809         !EvaluateFloat(E->getArg(1), RHS, Info))
13810       return false;
13811     Result.copySign(RHS);
13812     return true;
13813   }
13814   }
13815 }
13816 
13817 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13818   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13819     ComplexValue CV;
13820     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13821       return false;
13822     Result = CV.FloatReal;
13823     return true;
13824   }
13825 
13826   return Visit(E->getSubExpr());
13827 }
13828 
13829 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13830   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13831     ComplexValue CV;
13832     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13833       return false;
13834     Result = CV.FloatImag;
13835     return true;
13836   }
13837 
13838   VisitIgnoredValue(E->getSubExpr());
13839   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
13840   Result = llvm::APFloat::getZero(Sem);
13841   return true;
13842 }
13843 
13844 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13845   switch (E->getOpcode()) {
13846   default: return Error(E);
13847   case UO_Plus:
13848     return EvaluateFloat(E->getSubExpr(), Result, Info);
13849   case UO_Minus:
13850     // In C standard, WG14 N2478 F.3 p4
13851     // "the unary - raises no floating point exceptions,
13852     // even if the operand is signalling."
13853     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
13854       return false;
13855     Result.changeSign();
13856     return true;
13857   }
13858 }
13859 
13860 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13861   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13862     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13863 
13864   APFloat RHS(0.0);
13865   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
13866   if (!LHSOK && !Info.noteFailure())
13867     return false;
13868   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
13869          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
13870 }
13871 
13872 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
13873   Result = E->getValue();
13874   return true;
13875 }
13876 
13877 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
13878   const Expr* SubExpr = E->getSubExpr();
13879 
13880   switch (E->getCastKind()) {
13881   default:
13882     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13883 
13884   case CK_IntegralToFloating: {
13885     APSInt IntResult;
13886     const FPOptions FPO = E->getFPFeaturesInEffect(
13887                                   Info.Ctx.getLangOpts());
13888     return EvaluateInteger(SubExpr, IntResult, Info) &&
13889            HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
13890                                 IntResult, E->getType(), Result);
13891   }
13892 
13893   case CK_FixedPointToFloating: {
13894     APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13895     if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
13896       return false;
13897     Result =
13898         FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
13899     return true;
13900   }
13901 
13902   case CK_FloatingCast: {
13903     if (!Visit(SubExpr))
13904       return false;
13905     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
13906                                   Result);
13907   }
13908 
13909   case CK_FloatingComplexToReal: {
13910     ComplexValue V;
13911     if (!EvaluateComplex(SubExpr, V, Info))
13912       return false;
13913     Result = V.getComplexFloatReal();
13914     return true;
13915   }
13916   }
13917 }
13918 
13919 //===----------------------------------------------------------------------===//
13920 // Complex Evaluation (for float and integer)
13921 //===----------------------------------------------------------------------===//
13922 
13923 namespace {
13924 class ComplexExprEvaluator
13925   : public ExprEvaluatorBase<ComplexExprEvaluator> {
13926   ComplexValue &Result;
13927 
13928 public:
13929   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
13930     : ExprEvaluatorBaseTy(info), Result(Result) {}
13931 
13932   bool Success(const APValue &V, const Expr *e) {
13933     Result.setFrom(V);
13934     return true;
13935   }
13936 
13937   bool ZeroInitialization(const Expr *E);
13938 
13939   //===--------------------------------------------------------------------===//
13940   //                            Visitor Methods
13941   //===--------------------------------------------------------------------===//
13942 
13943   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
13944   bool VisitCastExpr(const CastExpr *E);
13945   bool VisitBinaryOperator(const BinaryOperator *E);
13946   bool VisitUnaryOperator(const UnaryOperator *E);
13947   bool VisitInitListExpr(const InitListExpr *E);
13948   bool VisitCallExpr(const CallExpr *E);
13949 };
13950 } // end anonymous namespace
13951 
13952 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
13953                             EvalInfo &Info) {
13954   assert(!E->isValueDependent());
13955   assert(E->isPRValue() && E->getType()->isAnyComplexType());
13956   return ComplexExprEvaluator(Info, Result).Visit(E);
13957 }
13958 
13959 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
13960   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
13961   if (ElemTy->isRealFloatingType()) {
13962     Result.makeComplexFloat();
13963     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
13964     Result.FloatReal = Zero;
13965     Result.FloatImag = Zero;
13966   } else {
13967     Result.makeComplexInt();
13968     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
13969     Result.IntReal = Zero;
13970     Result.IntImag = Zero;
13971   }
13972   return true;
13973 }
13974 
13975 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
13976   const Expr* SubExpr = E->getSubExpr();
13977 
13978   if (SubExpr->getType()->isRealFloatingType()) {
13979     Result.makeComplexFloat();
13980     APFloat &Imag = Result.FloatImag;
13981     if (!EvaluateFloat(SubExpr, Imag, Info))
13982       return false;
13983 
13984     Result.FloatReal = APFloat(Imag.getSemantics());
13985     return true;
13986   } else {
13987     assert(SubExpr->getType()->isIntegerType() &&
13988            "Unexpected imaginary literal.");
13989 
13990     Result.makeComplexInt();
13991     APSInt &Imag = Result.IntImag;
13992     if (!EvaluateInteger(SubExpr, Imag, Info))
13993       return false;
13994 
13995     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
13996     return true;
13997   }
13998 }
13999 
14000 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
14001 
14002   switch (E->getCastKind()) {
14003   case CK_BitCast:
14004   case CK_BaseToDerived:
14005   case CK_DerivedToBase:
14006   case CK_UncheckedDerivedToBase:
14007   case CK_Dynamic:
14008   case CK_ToUnion:
14009   case CK_ArrayToPointerDecay:
14010   case CK_FunctionToPointerDecay:
14011   case CK_NullToPointer:
14012   case CK_NullToMemberPointer:
14013   case CK_BaseToDerivedMemberPointer:
14014   case CK_DerivedToBaseMemberPointer:
14015   case CK_MemberPointerToBoolean:
14016   case CK_ReinterpretMemberPointer:
14017   case CK_ConstructorConversion:
14018   case CK_IntegralToPointer:
14019   case CK_PointerToIntegral:
14020   case CK_PointerToBoolean:
14021   case CK_ToVoid:
14022   case CK_VectorSplat:
14023   case CK_IntegralCast:
14024   case CK_BooleanToSignedIntegral:
14025   case CK_IntegralToBoolean:
14026   case CK_IntegralToFloating:
14027   case CK_FloatingToIntegral:
14028   case CK_FloatingToBoolean:
14029   case CK_FloatingCast:
14030   case CK_CPointerToObjCPointerCast:
14031   case CK_BlockPointerToObjCPointerCast:
14032   case CK_AnyPointerToBlockPointerCast:
14033   case CK_ObjCObjectLValueCast:
14034   case CK_FloatingComplexToReal:
14035   case CK_FloatingComplexToBoolean:
14036   case CK_IntegralComplexToReal:
14037   case CK_IntegralComplexToBoolean:
14038   case CK_ARCProduceObject:
14039   case CK_ARCConsumeObject:
14040   case CK_ARCReclaimReturnedObject:
14041   case CK_ARCExtendBlockObject:
14042   case CK_CopyAndAutoreleaseBlockObject:
14043   case CK_BuiltinFnToFnPtr:
14044   case CK_ZeroToOCLOpaqueType:
14045   case CK_NonAtomicToAtomic:
14046   case CK_AddressSpaceConversion:
14047   case CK_IntToOCLSampler:
14048   case CK_FloatingToFixedPoint:
14049   case CK_FixedPointToFloating:
14050   case CK_FixedPointCast:
14051   case CK_FixedPointToBoolean:
14052   case CK_FixedPointToIntegral:
14053   case CK_IntegralToFixedPoint:
14054   case CK_MatrixCast:
14055     llvm_unreachable("invalid cast kind for complex value");
14056 
14057   case CK_LValueToRValue:
14058   case CK_AtomicToNonAtomic:
14059   case CK_NoOp:
14060   case CK_LValueToRValueBitCast:
14061     return ExprEvaluatorBaseTy::VisitCastExpr(E);
14062 
14063   case CK_Dependent:
14064   case CK_LValueBitCast:
14065   case CK_UserDefinedConversion:
14066     return Error(E);
14067 
14068   case CK_FloatingRealToComplex: {
14069     APFloat &Real = Result.FloatReal;
14070     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
14071       return false;
14072 
14073     Result.makeComplexFloat();
14074     Result.FloatImag = APFloat(Real.getSemantics());
14075     return true;
14076   }
14077 
14078   case CK_FloatingComplexCast: {
14079     if (!Visit(E->getSubExpr()))
14080       return false;
14081 
14082     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14083     QualType From
14084       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14085 
14086     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
14087            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
14088   }
14089 
14090   case CK_FloatingComplexToIntegralComplex: {
14091     if (!Visit(E->getSubExpr()))
14092       return false;
14093 
14094     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14095     QualType From
14096       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14097     Result.makeComplexInt();
14098     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
14099                                 To, Result.IntReal) &&
14100            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
14101                                 To, Result.IntImag);
14102   }
14103 
14104   case CK_IntegralRealToComplex: {
14105     APSInt &Real = Result.IntReal;
14106     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
14107       return false;
14108 
14109     Result.makeComplexInt();
14110     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
14111     return true;
14112   }
14113 
14114   case CK_IntegralComplexCast: {
14115     if (!Visit(E->getSubExpr()))
14116       return false;
14117 
14118     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14119     QualType From
14120       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14121 
14122     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
14123     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
14124     return true;
14125   }
14126 
14127   case CK_IntegralComplexToFloatingComplex: {
14128     if (!Visit(E->getSubExpr()))
14129       return false;
14130 
14131     const FPOptions FPO = E->getFPFeaturesInEffect(
14132                                   Info.Ctx.getLangOpts());
14133     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14134     QualType From
14135       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14136     Result.makeComplexFloat();
14137     return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
14138                                 To, Result.FloatReal) &&
14139            HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
14140                                 To, Result.FloatImag);
14141   }
14142   }
14143 
14144   llvm_unreachable("unknown cast resulting in complex value");
14145 }
14146 
14147 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14148   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14149     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14150 
14151   // Track whether the LHS or RHS is real at the type system level. When this is
14152   // the case we can simplify our evaluation strategy.
14153   bool LHSReal = false, RHSReal = false;
14154 
14155   bool LHSOK;
14156   if (E->getLHS()->getType()->isRealFloatingType()) {
14157     LHSReal = true;
14158     APFloat &Real = Result.FloatReal;
14159     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
14160     if (LHSOK) {
14161       Result.makeComplexFloat();
14162       Result.FloatImag = APFloat(Real.getSemantics());
14163     }
14164   } else {
14165     LHSOK = Visit(E->getLHS());
14166   }
14167   if (!LHSOK && !Info.noteFailure())
14168     return false;
14169 
14170   ComplexValue RHS;
14171   if (E->getRHS()->getType()->isRealFloatingType()) {
14172     RHSReal = true;
14173     APFloat &Real = RHS.FloatReal;
14174     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
14175       return false;
14176     RHS.makeComplexFloat();
14177     RHS.FloatImag = APFloat(Real.getSemantics());
14178   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
14179     return false;
14180 
14181   assert(!(LHSReal && RHSReal) &&
14182          "Cannot have both operands of a complex operation be real.");
14183   switch (E->getOpcode()) {
14184   default: return Error(E);
14185   case BO_Add:
14186     if (Result.isComplexFloat()) {
14187       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
14188                                        APFloat::rmNearestTiesToEven);
14189       if (LHSReal)
14190         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14191       else if (!RHSReal)
14192         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
14193                                          APFloat::rmNearestTiesToEven);
14194     } else {
14195       Result.getComplexIntReal() += RHS.getComplexIntReal();
14196       Result.getComplexIntImag() += RHS.getComplexIntImag();
14197     }
14198     break;
14199   case BO_Sub:
14200     if (Result.isComplexFloat()) {
14201       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
14202                                             APFloat::rmNearestTiesToEven);
14203       if (LHSReal) {
14204         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14205         Result.getComplexFloatImag().changeSign();
14206       } else if (!RHSReal) {
14207         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
14208                                               APFloat::rmNearestTiesToEven);
14209       }
14210     } else {
14211       Result.getComplexIntReal() -= RHS.getComplexIntReal();
14212       Result.getComplexIntImag() -= RHS.getComplexIntImag();
14213     }
14214     break;
14215   case BO_Mul:
14216     if (Result.isComplexFloat()) {
14217       // This is an implementation of complex multiplication according to the
14218       // constraints laid out in C11 Annex G. The implementation uses the
14219       // following naming scheme:
14220       //   (a + ib) * (c + id)
14221       ComplexValue LHS = Result;
14222       APFloat &A = LHS.getComplexFloatReal();
14223       APFloat &B = LHS.getComplexFloatImag();
14224       APFloat &C = RHS.getComplexFloatReal();
14225       APFloat &D = RHS.getComplexFloatImag();
14226       APFloat &ResR = Result.getComplexFloatReal();
14227       APFloat &ResI = Result.getComplexFloatImag();
14228       if (LHSReal) {
14229         assert(!RHSReal && "Cannot have two real operands for a complex op!");
14230         ResR = A * C;
14231         ResI = A * D;
14232       } else if (RHSReal) {
14233         ResR = C * A;
14234         ResI = C * B;
14235       } else {
14236         // In the fully general case, we need to handle NaNs and infinities
14237         // robustly.
14238         APFloat AC = A * C;
14239         APFloat BD = B * D;
14240         APFloat AD = A * D;
14241         APFloat BC = B * C;
14242         ResR = AC - BD;
14243         ResI = AD + BC;
14244         if (ResR.isNaN() && ResI.isNaN()) {
14245           bool Recalc = false;
14246           if (A.isInfinity() || B.isInfinity()) {
14247             A = APFloat::copySign(
14248                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14249             B = APFloat::copySign(
14250                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14251             if (C.isNaN())
14252               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14253             if (D.isNaN())
14254               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14255             Recalc = true;
14256           }
14257           if (C.isInfinity() || D.isInfinity()) {
14258             C = APFloat::copySign(
14259                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14260             D = APFloat::copySign(
14261                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14262             if (A.isNaN())
14263               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14264             if (B.isNaN())
14265               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14266             Recalc = true;
14267           }
14268           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
14269                           AD.isInfinity() || BC.isInfinity())) {
14270             if (A.isNaN())
14271               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14272             if (B.isNaN())
14273               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14274             if (C.isNaN())
14275               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14276             if (D.isNaN())
14277               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14278             Recalc = true;
14279           }
14280           if (Recalc) {
14281             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
14282             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
14283           }
14284         }
14285       }
14286     } else {
14287       ComplexValue LHS = Result;
14288       Result.getComplexIntReal() =
14289         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
14290          LHS.getComplexIntImag() * RHS.getComplexIntImag());
14291       Result.getComplexIntImag() =
14292         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
14293          LHS.getComplexIntImag() * RHS.getComplexIntReal());
14294     }
14295     break;
14296   case BO_Div:
14297     if (Result.isComplexFloat()) {
14298       // This is an implementation of complex division according to the
14299       // constraints laid out in C11 Annex G. The implementation uses the
14300       // following naming scheme:
14301       //   (a + ib) / (c + id)
14302       ComplexValue LHS = Result;
14303       APFloat &A = LHS.getComplexFloatReal();
14304       APFloat &B = LHS.getComplexFloatImag();
14305       APFloat &C = RHS.getComplexFloatReal();
14306       APFloat &D = RHS.getComplexFloatImag();
14307       APFloat &ResR = Result.getComplexFloatReal();
14308       APFloat &ResI = Result.getComplexFloatImag();
14309       if (RHSReal) {
14310         ResR = A / C;
14311         ResI = B / C;
14312       } else {
14313         if (LHSReal) {
14314           // No real optimizations we can do here, stub out with zero.
14315           B = APFloat::getZero(A.getSemantics());
14316         }
14317         int DenomLogB = 0;
14318         APFloat MaxCD = maxnum(abs(C), abs(D));
14319         if (MaxCD.isFinite()) {
14320           DenomLogB = ilogb(MaxCD);
14321           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
14322           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
14323         }
14324         APFloat Denom = C * C + D * D;
14325         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
14326                       APFloat::rmNearestTiesToEven);
14327         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
14328                       APFloat::rmNearestTiesToEven);
14329         if (ResR.isNaN() && ResI.isNaN()) {
14330           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
14331             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
14332             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
14333           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
14334                      D.isFinite()) {
14335             A = APFloat::copySign(
14336                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14337             B = APFloat::copySign(
14338                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14339             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
14340             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
14341           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
14342             C = APFloat::copySign(
14343                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14344             D = APFloat::copySign(
14345                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14346             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
14347             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
14348           }
14349         }
14350       }
14351     } else {
14352       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
14353         return Error(E, diag::note_expr_divide_by_zero);
14354 
14355       ComplexValue LHS = Result;
14356       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
14357         RHS.getComplexIntImag() * RHS.getComplexIntImag();
14358       Result.getComplexIntReal() =
14359         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
14360          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
14361       Result.getComplexIntImag() =
14362         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
14363          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
14364     }
14365     break;
14366   }
14367 
14368   return true;
14369 }
14370 
14371 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14372   // Get the operand value into 'Result'.
14373   if (!Visit(E->getSubExpr()))
14374     return false;
14375 
14376   switch (E->getOpcode()) {
14377   default:
14378     return Error(E);
14379   case UO_Extension:
14380     return true;
14381   case UO_Plus:
14382     // The result is always just the subexpr.
14383     return true;
14384   case UO_Minus:
14385     if (Result.isComplexFloat()) {
14386       Result.getComplexFloatReal().changeSign();
14387       Result.getComplexFloatImag().changeSign();
14388     }
14389     else {
14390       Result.getComplexIntReal() = -Result.getComplexIntReal();
14391       Result.getComplexIntImag() = -Result.getComplexIntImag();
14392     }
14393     return true;
14394   case UO_Not:
14395     if (Result.isComplexFloat())
14396       Result.getComplexFloatImag().changeSign();
14397     else
14398       Result.getComplexIntImag() = -Result.getComplexIntImag();
14399     return true;
14400   }
14401 }
14402 
14403 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
14404   if (E->getNumInits() == 2) {
14405     if (E->getType()->isComplexType()) {
14406       Result.makeComplexFloat();
14407       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
14408         return false;
14409       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
14410         return false;
14411     } else {
14412       Result.makeComplexInt();
14413       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
14414         return false;
14415       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
14416         return false;
14417     }
14418     return true;
14419   }
14420   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
14421 }
14422 
14423 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
14424   switch (E->getBuiltinCallee()) {
14425   case Builtin::BI__builtin_complex:
14426     Result.makeComplexFloat();
14427     if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
14428       return false;
14429     if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
14430       return false;
14431     return true;
14432 
14433   default:
14434     break;
14435   }
14436 
14437   return ExprEvaluatorBaseTy::VisitCallExpr(E);
14438 }
14439 
14440 //===----------------------------------------------------------------------===//
14441 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
14442 // implicit conversion.
14443 //===----------------------------------------------------------------------===//
14444 
14445 namespace {
14446 class AtomicExprEvaluator :
14447     public ExprEvaluatorBase<AtomicExprEvaluator> {
14448   const LValue *This;
14449   APValue &Result;
14450 public:
14451   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
14452       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
14453 
14454   bool Success(const APValue &V, const Expr *E) {
14455     Result = V;
14456     return true;
14457   }
14458 
14459   bool ZeroInitialization(const Expr *E) {
14460     ImplicitValueInitExpr VIE(
14461         E->getType()->castAs<AtomicType>()->getValueType());
14462     // For atomic-qualified class (and array) types in C++, initialize the
14463     // _Atomic-wrapped subobject directly, in-place.
14464     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
14465                 : Evaluate(Result, Info, &VIE);
14466   }
14467 
14468   bool VisitCastExpr(const CastExpr *E) {
14469     switch (E->getCastKind()) {
14470     default:
14471       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14472     case CK_NonAtomicToAtomic:
14473       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
14474                   : Evaluate(Result, Info, E->getSubExpr());
14475     }
14476   }
14477 };
14478 } // end anonymous namespace
14479 
14480 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
14481                            EvalInfo &Info) {
14482   assert(!E->isValueDependent());
14483   assert(E->isPRValue() && E->getType()->isAtomicType());
14484   return AtomicExprEvaluator(Info, This, Result).Visit(E);
14485 }
14486 
14487 //===----------------------------------------------------------------------===//
14488 // Void expression evaluation, primarily for a cast to void on the LHS of a
14489 // comma operator
14490 //===----------------------------------------------------------------------===//
14491 
14492 namespace {
14493 class VoidExprEvaluator
14494   : public ExprEvaluatorBase<VoidExprEvaluator> {
14495 public:
14496   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
14497 
14498   bool Success(const APValue &V, const Expr *e) { return true; }
14499 
14500   bool ZeroInitialization(const Expr *E) { return true; }
14501 
14502   bool VisitCastExpr(const CastExpr *E) {
14503     switch (E->getCastKind()) {
14504     default:
14505       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14506     case CK_ToVoid:
14507       VisitIgnoredValue(E->getSubExpr());
14508       return true;
14509     }
14510   }
14511 
14512   bool VisitCallExpr(const CallExpr *E) {
14513     switch (E->getBuiltinCallee()) {
14514     case Builtin::BI__assume:
14515     case Builtin::BI__builtin_assume:
14516       // The argument is not evaluated!
14517       return true;
14518 
14519     case Builtin::BI__builtin_operator_delete:
14520       return HandleOperatorDeleteCall(Info, E);
14521 
14522     default:
14523       break;
14524     }
14525 
14526     return ExprEvaluatorBaseTy::VisitCallExpr(E);
14527   }
14528 
14529   bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
14530 };
14531 } // end anonymous namespace
14532 
14533 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
14534   // We cannot speculatively evaluate a delete expression.
14535   if (Info.SpeculativeEvaluationDepth)
14536     return false;
14537 
14538   FunctionDecl *OperatorDelete = E->getOperatorDelete();
14539   if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
14540     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14541         << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
14542     return false;
14543   }
14544 
14545   const Expr *Arg = E->getArgument();
14546 
14547   LValue Pointer;
14548   if (!EvaluatePointer(Arg, Pointer, Info))
14549     return false;
14550   if (Pointer.Designator.Invalid)
14551     return false;
14552 
14553   // Deleting a null pointer has no effect.
14554   if (Pointer.isNullPointer()) {
14555     // This is the only case where we need to produce an extension warning:
14556     // the only other way we can succeed is if we find a dynamic allocation,
14557     // and we will have warned when we allocated it in that case.
14558     if (!Info.getLangOpts().CPlusPlus20)
14559       Info.CCEDiag(E, diag::note_constexpr_new);
14560     return true;
14561   }
14562 
14563   Optional<DynAlloc *> Alloc = CheckDeleteKind(
14564       Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
14565   if (!Alloc)
14566     return false;
14567   QualType AllocType = Pointer.Base.getDynamicAllocType();
14568 
14569   // For the non-array case, the designator must be empty if the static type
14570   // does not have a virtual destructor.
14571   if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
14572       !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
14573     Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
14574         << Arg->getType()->getPointeeType() << AllocType;
14575     return false;
14576   }
14577 
14578   // For a class type with a virtual destructor, the selected operator delete
14579   // is the one looked up when building the destructor.
14580   if (!E->isArrayForm() && !E->isGlobalDelete()) {
14581     const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
14582     if (VirtualDelete &&
14583         !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
14584       Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14585           << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
14586       return false;
14587     }
14588   }
14589 
14590   if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
14591                          (*Alloc)->Value, AllocType))
14592     return false;
14593 
14594   if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
14595     // The element was already erased. This means the destructor call also
14596     // deleted the object.
14597     // FIXME: This probably results in undefined behavior before we get this
14598     // far, and should be diagnosed elsewhere first.
14599     Info.FFDiag(E, diag::note_constexpr_double_delete);
14600     return false;
14601   }
14602 
14603   return true;
14604 }
14605 
14606 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
14607   assert(!E->isValueDependent());
14608   assert(E->isPRValue() && E->getType()->isVoidType());
14609   return VoidExprEvaluator(Info).Visit(E);
14610 }
14611 
14612 //===----------------------------------------------------------------------===//
14613 // Top level Expr::EvaluateAsRValue method.
14614 //===----------------------------------------------------------------------===//
14615 
14616 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
14617   assert(!E->isValueDependent());
14618   // In C, function designators are not lvalues, but we evaluate them as if they
14619   // are.
14620   QualType T = E->getType();
14621   if (E->isGLValue() || T->isFunctionType()) {
14622     LValue LV;
14623     if (!EvaluateLValue(E, LV, Info))
14624       return false;
14625     LV.moveInto(Result);
14626   } else if (T->isVectorType()) {
14627     if (!EvaluateVector(E, Result, Info))
14628       return false;
14629   } else if (T->isIntegralOrEnumerationType()) {
14630     if (!IntExprEvaluator(Info, Result).Visit(E))
14631       return false;
14632   } else if (T->hasPointerRepresentation()) {
14633     LValue LV;
14634     if (!EvaluatePointer(E, LV, Info))
14635       return false;
14636     LV.moveInto(Result);
14637   } else if (T->isRealFloatingType()) {
14638     llvm::APFloat F(0.0);
14639     if (!EvaluateFloat(E, F, Info))
14640       return false;
14641     Result = APValue(F);
14642   } else if (T->isAnyComplexType()) {
14643     ComplexValue C;
14644     if (!EvaluateComplex(E, C, Info))
14645       return false;
14646     C.moveInto(Result);
14647   } else if (T->isFixedPointType()) {
14648     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
14649   } else if (T->isMemberPointerType()) {
14650     MemberPtr P;
14651     if (!EvaluateMemberPointer(E, P, Info))
14652       return false;
14653     P.moveInto(Result);
14654     return true;
14655   } else if (T->isArrayType()) {
14656     LValue LV;
14657     APValue &Value =
14658         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14659     if (!EvaluateArray(E, LV, Value, Info))
14660       return false;
14661     Result = Value;
14662   } else if (T->isRecordType()) {
14663     LValue LV;
14664     APValue &Value =
14665         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14666     if (!EvaluateRecord(E, LV, Value, Info))
14667       return false;
14668     Result = Value;
14669   } else if (T->isVoidType()) {
14670     if (!Info.getLangOpts().CPlusPlus11)
14671       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
14672         << E->getType();
14673     if (!EvaluateVoid(E, Info))
14674       return false;
14675   } else if (T->isAtomicType()) {
14676     QualType Unqual = T.getAtomicUnqualifiedType();
14677     if (Unqual->isArrayType() || Unqual->isRecordType()) {
14678       LValue LV;
14679       APValue &Value = Info.CurrentCall->createTemporary(
14680           E, Unqual, ScopeKind::FullExpression, LV);
14681       if (!EvaluateAtomic(E, &LV, Value, Info))
14682         return false;
14683     } else {
14684       if (!EvaluateAtomic(E, nullptr, Result, Info))
14685         return false;
14686     }
14687   } else if (Info.getLangOpts().CPlusPlus11) {
14688     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
14689     return false;
14690   } else {
14691     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
14692     return false;
14693   }
14694 
14695   return true;
14696 }
14697 
14698 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
14699 /// cases, the in-place evaluation is essential, since later initializers for
14700 /// an object can indirectly refer to subobjects which were initialized earlier.
14701 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
14702                             const Expr *E, bool AllowNonLiteralTypes) {
14703   assert(!E->isValueDependent());
14704 
14705   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
14706     return false;
14707 
14708   if (E->isPRValue()) {
14709     // Evaluate arrays and record types in-place, so that later initializers can
14710     // refer to earlier-initialized members of the object.
14711     QualType T = E->getType();
14712     if (T->isArrayType())
14713       return EvaluateArray(E, This, Result, Info);
14714     else if (T->isRecordType())
14715       return EvaluateRecord(E, This, Result, Info);
14716     else if (T->isAtomicType()) {
14717       QualType Unqual = T.getAtomicUnqualifiedType();
14718       if (Unqual->isArrayType() || Unqual->isRecordType())
14719         return EvaluateAtomic(E, &This, Result, Info);
14720     }
14721   }
14722 
14723   // For any other type, in-place evaluation is unimportant.
14724   return Evaluate(Result, Info, E);
14725 }
14726 
14727 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
14728 /// lvalue-to-rvalue cast if it is an lvalue.
14729 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
14730   assert(!E->isValueDependent());
14731   if (Info.EnableNewConstInterp) {
14732     if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
14733       return false;
14734   } else {
14735     if (E->getType().isNull())
14736       return false;
14737 
14738     if (!CheckLiteralType(Info, E))
14739       return false;
14740 
14741     if (!::Evaluate(Result, Info, E))
14742       return false;
14743 
14744     if (E->isGLValue()) {
14745       LValue LV;
14746       LV.setFrom(Info.Ctx, Result);
14747       if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
14748         return false;
14749     }
14750   }
14751 
14752   // Check this core constant expression is a constant expression.
14753   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
14754                                  ConstantExprKind::Normal) &&
14755          CheckMemoryLeaks(Info);
14756 }
14757 
14758 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
14759                                  const ASTContext &Ctx, bool &IsConst) {
14760   // Fast-path evaluations of integer literals, since we sometimes see files
14761   // containing vast quantities of these.
14762   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
14763     Result.Val = APValue(APSInt(L->getValue(),
14764                                 L->getType()->isUnsignedIntegerType()));
14765     IsConst = true;
14766     return true;
14767   }
14768 
14769   // This case should be rare, but we need to check it before we check on
14770   // the type below.
14771   if (Exp->getType().isNull()) {
14772     IsConst = false;
14773     return true;
14774   }
14775 
14776   // FIXME: Evaluating values of large array and record types can cause
14777   // performance problems. Only do so in C++11 for now.
14778   if (Exp->isPRValue() &&
14779       (Exp->getType()->isArrayType() || Exp->getType()->isRecordType()) &&
14780       !Ctx.getLangOpts().CPlusPlus11) {
14781     IsConst = false;
14782     return true;
14783   }
14784   return false;
14785 }
14786 
14787 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
14788                                       Expr::SideEffectsKind SEK) {
14789   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
14790          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
14791 }
14792 
14793 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
14794                              const ASTContext &Ctx, EvalInfo &Info) {
14795   assert(!E->isValueDependent());
14796   bool IsConst;
14797   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
14798     return IsConst;
14799 
14800   return EvaluateAsRValue(Info, E, Result.Val);
14801 }
14802 
14803 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
14804                           const ASTContext &Ctx,
14805                           Expr::SideEffectsKind AllowSideEffects,
14806                           EvalInfo &Info) {
14807   assert(!E->isValueDependent());
14808   if (!E->getType()->isIntegralOrEnumerationType())
14809     return false;
14810 
14811   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
14812       !ExprResult.Val.isInt() ||
14813       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14814     return false;
14815 
14816   return true;
14817 }
14818 
14819 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
14820                                  const ASTContext &Ctx,
14821                                  Expr::SideEffectsKind AllowSideEffects,
14822                                  EvalInfo &Info) {
14823   assert(!E->isValueDependent());
14824   if (!E->getType()->isFixedPointType())
14825     return false;
14826 
14827   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
14828     return false;
14829 
14830   if (!ExprResult.Val.isFixedPoint() ||
14831       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14832     return false;
14833 
14834   return true;
14835 }
14836 
14837 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
14838 /// any crazy technique (that has nothing to do with language standards) that
14839 /// we want to.  If this function returns true, it returns the folded constant
14840 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
14841 /// will be applied to the result.
14842 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
14843                             bool InConstantContext) const {
14844   assert(!isValueDependent() &&
14845          "Expression evaluator can't be called on a dependent expression.");
14846   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14847   Info.InConstantContext = InConstantContext;
14848   return ::EvaluateAsRValue(this, Result, Ctx, Info);
14849 }
14850 
14851 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
14852                                       bool InConstantContext) const {
14853   assert(!isValueDependent() &&
14854          "Expression evaluator can't be called on a dependent expression.");
14855   EvalResult Scratch;
14856   return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
14857          HandleConversionToBool(Scratch.Val, Result);
14858 }
14859 
14860 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
14861                          SideEffectsKind AllowSideEffects,
14862                          bool InConstantContext) const {
14863   assert(!isValueDependent() &&
14864          "Expression evaluator can't be called on a dependent expression.");
14865   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14866   Info.InConstantContext = InConstantContext;
14867   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
14868 }
14869 
14870 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
14871                                 SideEffectsKind AllowSideEffects,
14872                                 bool InConstantContext) const {
14873   assert(!isValueDependent() &&
14874          "Expression evaluator can't be called on a dependent expression.");
14875   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14876   Info.InConstantContext = InConstantContext;
14877   return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
14878 }
14879 
14880 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
14881                            SideEffectsKind AllowSideEffects,
14882                            bool InConstantContext) const {
14883   assert(!isValueDependent() &&
14884          "Expression evaluator can't be called on a dependent expression.");
14885 
14886   if (!getType()->isRealFloatingType())
14887     return false;
14888 
14889   EvalResult ExprResult;
14890   if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
14891       !ExprResult.Val.isFloat() ||
14892       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14893     return false;
14894 
14895   Result = ExprResult.Val.getFloat();
14896   return true;
14897 }
14898 
14899 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
14900                             bool InConstantContext) const {
14901   assert(!isValueDependent() &&
14902          "Expression evaluator can't be called on a dependent expression.");
14903 
14904   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
14905   Info.InConstantContext = InConstantContext;
14906   LValue LV;
14907   CheckedTemporaries CheckedTemps;
14908   if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
14909       Result.HasSideEffects ||
14910       !CheckLValueConstantExpression(Info, getExprLoc(),
14911                                      Ctx.getLValueReferenceType(getType()), LV,
14912                                      ConstantExprKind::Normal, CheckedTemps))
14913     return false;
14914 
14915   LV.moveInto(Result.Val);
14916   return true;
14917 }
14918 
14919 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base,
14920                                 APValue DestroyedValue, QualType Type,
14921                                 SourceLocation Loc, Expr::EvalStatus &EStatus,
14922                                 bool IsConstantDestruction) {
14923   EvalInfo Info(Ctx, EStatus,
14924                 IsConstantDestruction ? EvalInfo::EM_ConstantExpression
14925                                       : EvalInfo::EM_ConstantFold);
14926   Info.setEvaluatingDecl(Base, DestroyedValue,
14927                          EvalInfo::EvaluatingDeclKind::Dtor);
14928   Info.InConstantContext = IsConstantDestruction;
14929 
14930   LValue LVal;
14931   LVal.set(Base);
14932 
14933   if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
14934       EStatus.HasSideEffects)
14935     return false;
14936 
14937   if (!Info.discardCleanups())
14938     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14939 
14940   return true;
14941 }
14942 
14943 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx,
14944                                   ConstantExprKind Kind) const {
14945   assert(!isValueDependent() &&
14946          "Expression evaluator can't be called on a dependent expression.");
14947 
14948   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
14949   EvalInfo Info(Ctx, Result, EM);
14950   Info.InConstantContext = true;
14951 
14952   // The type of the object we're initializing is 'const T' for a class NTTP.
14953   QualType T = getType();
14954   if (Kind == ConstantExprKind::ClassTemplateArgument)
14955     T.addConst();
14956 
14957   // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
14958   // represent the result of the evaluation. CheckConstantExpression ensures
14959   // this doesn't escape.
14960   MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
14961   APValue::LValueBase Base(&BaseMTE);
14962 
14963   Info.setEvaluatingDecl(Base, Result.Val);
14964   LValue LVal;
14965   LVal.set(Base);
14966 
14967   if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || Result.HasSideEffects)
14968     return false;
14969 
14970   if (!Info.discardCleanups())
14971     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14972 
14973   if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
14974                                Result.Val, Kind))
14975     return false;
14976   if (!CheckMemoryLeaks(Info))
14977     return false;
14978 
14979   // If this is a class template argument, it's required to have constant
14980   // destruction too.
14981   if (Kind == ConstantExprKind::ClassTemplateArgument &&
14982       (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result,
14983                             true) ||
14984        Result.HasSideEffects)) {
14985     // FIXME: Prefix a note to indicate that the problem is lack of constant
14986     // destruction.
14987     return false;
14988   }
14989 
14990   return true;
14991 }
14992 
14993 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
14994                                  const VarDecl *VD,
14995                                  SmallVectorImpl<PartialDiagnosticAt> &Notes,
14996                                  bool IsConstantInitialization) const {
14997   assert(!isValueDependent() &&
14998          "Expression evaluator can't be called on a dependent expression.");
14999 
15000   // FIXME: Evaluating initializers for large array and record types can cause
15001   // performance problems. Only do so in C++11 for now.
15002   if (isPRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
15003       !Ctx.getLangOpts().CPlusPlus11)
15004     return false;
15005 
15006   Expr::EvalStatus EStatus;
15007   EStatus.Diag = &Notes;
15008 
15009   EvalInfo Info(Ctx, EStatus,
15010                 (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11)
15011                     ? EvalInfo::EM_ConstantExpression
15012                     : EvalInfo::EM_ConstantFold);
15013   Info.setEvaluatingDecl(VD, Value);
15014   Info.InConstantContext = IsConstantInitialization;
15015 
15016   SourceLocation DeclLoc = VD->getLocation();
15017   QualType DeclTy = VD->getType();
15018 
15019   if (Info.EnableNewConstInterp) {
15020     auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
15021     if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
15022       return false;
15023   } else {
15024     LValue LVal;
15025     LVal.set(VD);
15026 
15027     if (!EvaluateInPlace(Value, Info, LVal, this,
15028                          /*AllowNonLiteralTypes=*/true) ||
15029         EStatus.HasSideEffects)
15030       return false;
15031 
15032     // At this point, any lifetime-extended temporaries are completely
15033     // initialized.
15034     Info.performLifetimeExtension();
15035 
15036     if (!Info.discardCleanups())
15037       llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15038   }
15039   return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
15040                                  ConstantExprKind::Normal) &&
15041          CheckMemoryLeaks(Info);
15042 }
15043 
15044 bool VarDecl::evaluateDestruction(
15045     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
15046   Expr::EvalStatus EStatus;
15047   EStatus.Diag = &Notes;
15048 
15049   // Only treat the destruction as constant destruction if we formally have
15050   // constant initialization (or are usable in a constant expression).
15051   bool IsConstantDestruction = hasConstantInitialization();
15052 
15053   // Make a copy of the value for the destructor to mutate, if we know it.
15054   // Otherwise, treat the value as default-initialized; if the destructor works
15055   // anyway, then the destruction is constant (and must be essentially empty).
15056   APValue DestroyedValue;
15057   if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
15058     DestroyedValue = *getEvaluatedValue();
15059   else if (!getDefaultInitValue(getType(), DestroyedValue))
15060     return false;
15061 
15062   if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
15063                            getType(), getLocation(), EStatus,
15064                            IsConstantDestruction) ||
15065       EStatus.HasSideEffects)
15066     return false;
15067 
15068   ensureEvaluatedStmt()->HasConstantDestruction = true;
15069   return true;
15070 }
15071 
15072 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
15073 /// constant folded, but discard the result.
15074 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
15075   assert(!isValueDependent() &&
15076          "Expression evaluator can't be called on a dependent expression.");
15077 
15078   EvalResult Result;
15079   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
15080          !hasUnacceptableSideEffect(Result, SEK);
15081 }
15082 
15083 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
15084                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
15085   assert(!isValueDependent() &&
15086          "Expression evaluator can't be called on a dependent expression.");
15087 
15088   EvalResult EVResult;
15089   EVResult.Diag = Diag;
15090   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15091   Info.InConstantContext = true;
15092 
15093   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
15094   (void)Result;
15095   assert(Result && "Could not evaluate expression");
15096   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
15097 
15098   return EVResult.Val.getInt();
15099 }
15100 
15101 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
15102     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
15103   assert(!isValueDependent() &&
15104          "Expression evaluator can't be called on a dependent expression.");
15105 
15106   EvalResult EVResult;
15107   EVResult.Diag = Diag;
15108   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15109   Info.InConstantContext = true;
15110   Info.CheckingForUndefinedBehavior = true;
15111 
15112   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
15113   (void)Result;
15114   assert(Result && "Could not evaluate expression");
15115   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
15116 
15117   return EVResult.Val.getInt();
15118 }
15119 
15120 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
15121   assert(!isValueDependent() &&
15122          "Expression evaluator can't be called on a dependent expression.");
15123 
15124   bool IsConst;
15125   EvalResult EVResult;
15126   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
15127     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15128     Info.CheckingForUndefinedBehavior = true;
15129     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
15130   }
15131 }
15132 
15133 bool Expr::EvalResult::isGlobalLValue() const {
15134   assert(Val.isLValue());
15135   return IsGlobalLValue(Val.getLValueBase());
15136 }
15137 
15138 /// isIntegerConstantExpr - this recursive routine will test if an expression is
15139 /// an integer constant expression.
15140 
15141 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
15142 /// comma, etc
15143 
15144 // CheckICE - This function does the fundamental ICE checking: the returned
15145 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
15146 // and a (possibly null) SourceLocation indicating the location of the problem.
15147 //
15148 // Note that to reduce code duplication, this helper does no evaluation
15149 // itself; the caller checks whether the expression is evaluatable, and
15150 // in the rare cases where CheckICE actually cares about the evaluated
15151 // value, it calls into Evaluate.
15152 
15153 namespace {
15154 
15155 enum ICEKind {
15156   /// This expression is an ICE.
15157   IK_ICE,
15158   /// This expression is not an ICE, but if it isn't evaluated, it's
15159   /// a legal subexpression for an ICE. This return value is used to handle
15160   /// the comma operator in C99 mode, and non-constant subexpressions.
15161   IK_ICEIfUnevaluated,
15162   /// This expression is not an ICE, and is not a legal subexpression for one.
15163   IK_NotICE
15164 };
15165 
15166 struct ICEDiag {
15167   ICEKind Kind;
15168   SourceLocation Loc;
15169 
15170   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
15171 };
15172 
15173 }
15174 
15175 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
15176 
15177 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
15178 
15179 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
15180   Expr::EvalResult EVResult;
15181   Expr::EvalStatus Status;
15182   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15183 
15184   Info.InConstantContext = true;
15185   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
15186       !EVResult.Val.isInt())
15187     return ICEDiag(IK_NotICE, E->getBeginLoc());
15188 
15189   return NoDiag();
15190 }
15191 
15192 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
15193   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
15194   if (!E->getType()->isIntegralOrEnumerationType())
15195     return ICEDiag(IK_NotICE, E->getBeginLoc());
15196 
15197   switch (E->getStmtClass()) {
15198 #define ABSTRACT_STMT(Node)
15199 #define STMT(Node, Base) case Expr::Node##Class:
15200 #define EXPR(Node, Base)
15201 #include "clang/AST/StmtNodes.inc"
15202   case Expr::PredefinedExprClass:
15203   case Expr::FloatingLiteralClass:
15204   case Expr::ImaginaryLiteralClass:
15205   case Expr::StringLiteralClass:
15206   case Expr::ArraySubscriptExprClass:
15207   case Expr::MatrixSubscriptExprClass:
15208   case Expr::OMPArraySectionExprClass:
15209   case Expr::OMPArrayShapingExprClass:
15210   case Expr::OMPIteratorExprClass:
15211   case Expr::MemberExprClass:
15212   case Expr::CompoundAssignOperatorClass:
15213   case Expr::CompoundLiteralExprClass:
15214   case Expr::ExtVectorElementExprClass:
15215   case Expr::DesignatedInitExprClass:
15216   case Expr::ArrayInitLoopExprClass:
15217   case Expr::ArrayInitIndexExprClass:
15218   case Expr::NoInitExprClass:
15219   case Expr::DesignatedInitUpdateExprClass:
15220   case Expr::ImplicitValueInitExprClass:
15221   case Expr::ParenListExprClass:
15222   case Expr::VAArgExprClass:
15223   case Expr::AddrLabelExprClass:
15224   case Expr::StmtExprClass:
15225   case Expr::CXXMemberCallExprClass:
15226   case Expr::CUDAKernelCallExprClass:
15227   case Expr::CXXAddrspaceCastExprClass:
15228   case Expr::CXXDynamicCastExprClass:
15229   case Expr::CXXTypeidExprClass:
15230   case Expr::CXXUuidofExprClass:
15231   case Expr::MSPropertyRefExprClass:
15232   case Expr::MSPropertySubscriptExprClass:
15233   case Expr::CXXNullPtrLiteralExprClass:
15234   case Expr::UserDefinedLiteralClass:
15235   case Expr::CXXThisExprClass:
15236   case Expr::CXXThrowExprClass:
15237   case Expr::CXXNewExprClass:
15238   case Expr::CXXDeleteExprClass:
15239   case Expr::CXXPseudoDestructorExprClass:
15240   case Expr::UnresolvedLookupExprClass:
15241   case Expr::TypoExprClass:
15242   case Expr::RecoveryExprClass:
15243   case Expr::DependentScopeDeclRefExprClass:
15244   case Expr::CXXConstructExprClass:
15245   case Expr::CXXInheritedCtorInitExprClass:
15246   case Expr::CXXStdInitializerListExprClass:
15247   case Expr::CXXBindTemporaryExprClass:
15248   case Expr::ExprWithCleanupsClass:
15249   case Expr::CXXTemporaryObjectExprClass:
15250   case Expr::CXXUnresolvedConstructExprClass:
15251   case Expr::CXXDependentScopeMemberExprClass:
15252   case Expr::UnresolvedMemberExprClass:
15253   case Expr::ObjCStringLiteralClass:
15254   case Expr::ObjCBoxedExprClass:
15255   case Expr::ObjCArrayLiteralClass:
15256   case Expr::ObjCDictionaryLiteralClass:
15257   case Expr::ObjCEncodeExprClass:
15258   case Expr::ObjCMessageExprClass:
15259   case Expr::ObjCSelectorExprClass:
15260   case Expr::ObjCProtocolExprClass:
15261   case Expr::ObjCIvarRefExprClass:
15262   case Expr::ObjCPropertyRefExprClass:
15263   case Expr::ObjCSubscriptRefExprClass:
15264   case Expr::ObjCIsaExprClass:
15265   case Expr::ObjCAvailabilityCheckExprClass:
15266   case Expr::ShuffleVectorExprClass:
15267   case Expr::ConvertVectorExprClass:
15268   case Expr::BlockExprClass:
15269   case Expr::NoStmtClass:
15270   case Expr::OpaqueValueExprClass:
15271   case Expr::PackExpansionExprClass:
15272   case Expr::SubstNonTypeTemplateParmPackExprClass:
15273   case Expr::FunctionParmPackExprClass:
15274   case Expr::AsTypeExprClass:
15275   case Expr::ObjCIndirectCopyRestoreExprClass:
15276   case Expr::MaterializeTemporaryExprClass:
15277   case Expr::PseudoObjectExprClass:
15278   case Expr::AtomicExprClass:
15279   case Expr::LambdaExprClass:
15280   case Expr::CXXFoldExprClass:
15281   case Expr::CoawaitExprClass:
15282   case Expr::DependentCoawaitExprClass:
15283   case Expr::CoyieldExprClass:
15284   case Expr::SYCLUniqueStableNameExprClass:
15285     return ICEDiag(IK_NotICE, E->getBeginLoc());
15286 
15287   case Expr::InitListExprClass: {
15288     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
15289     // form "T x = { a };" is equivalent to "T x = a;".
15290     // Unless we're initializing a reference, T is a scalar as it is known to be
15291     // of integral or enumeration type.
15292     if (E->isPRValue())
15293       if (cast<InitListExpr>(E)->getNumInits() == 1)
15294         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
15295     return ICEDiag(IK_NotICE, E->getBeginLoc());
15296   }
15297 
15298   case Expr::SizeOfPackExprClass:
15299   case Expr::GNUNullExprClass:
15300   case Expr::SourceLocExprClass:
15301     return NoDiag();
15302 
15303   case Expr::SubstNonTypeTemplateParmExprClass:
15304     return
15305       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
15306 
15307   case Expr::ConstantExprClass:
15308     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
15309 
15310   case Expr::ParenExprClass:
15311     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
15312   case Expr::GenericSelectionExprClass:
15313     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
15314   case Expr::IntegerLiteralClass:
15315   case Expr::FixedPointLiteralClass:
15316   case Expr::CharacterLiteralClass:
15317   case Expr::ObjCBoolLiteralExprClass:
15318   case Expr::CXXBoolLiteralExprClass:
15319   case Expr::CXXScalarValueInitExprClass:
15320   case Expr::TypeTraitExprClass:
15321   case Expr::ConceptSpecializationExprClass:
15322   case Expr::RequiresExprClass:
15323   case Expr::ArrayTypeTraitExprClass:
15324   case Expr::ExpressionTraitExprClass:
15325   case Expr::CXXNoexceptExprClass:
15326     return NoDiag();
15327   case Expr::CallExprClass:
15328   case Expr::CXXOperatorCallExprClass: {
15329     // C99 6.6/3 allows function calls within unevaluated subexpressions of
15330     // constant expressions, but they can never be ICEs because an ICE cannot
15331     // contain an operand of (pointer to) function type.
15332     const CallExpr *CE = cast<CallExpr>(E);
15333     if (CE->getBuiltinCallee())
15334       return CheckEvalInICE(E, Ctx);
15335     return ICEDiag(IK_NotICE, E->getBeginLoc());
15336   }
15337   case Expr::CXXRewrittenBinaryOperatorClass:
15338     return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
15339                     Ctx);
15340   case Expr::DeclRefExprClass: {
15341     const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
15342     if (isa<EnumConstantDecl>(D))
15343       return NoDiag();
15344 
15345     // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
15346     // integer variables in constant expressions:
15347     //
15348     // C++ 7.1.5.1p2
15349     //   A variable of non-volatile const-qualified integral or enumeration
15350     //   type initialized by an ICE can be used in ICEs.
15351     //
15352     // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
15353     // that mode, use of reference variables should not be allowed.
15354     const VarDecl *VD = dyn_cast<VarDecl>(D);
15355     if (VD && VD->isUsableInConstantExpressions(Ctx) &&
15356         !VD->getType()->isReferenceType())
15357       return NoDiag();
15358 
15359     return ICEDiag(IK_NotICE, E->getBeginLoc());
15360   }
15361   case Expr::UnaryOperatorClass: {
15362     const UnaryOperator *Exp = cast<UnaryOperator>(E);
15363     switch (Exp->getOpcode()) {
15364     case UO_PostInc:
15365     case UO_PostDec:
15366     case UO_PreInc:
15367     case UO_PreDec:
15368     case UO_AddrOf:
15369     case UO_Deref:
15370     case UO_Coawait:
15371       // C99 6.6/3 allows increment and decrement within unevaluated
15372       // subexpressions of constant expressions, but they can never be ICEs
15373       // because an ICE cannot contain an lvalue operand.
15374       return ICEDiag(IK_NotICE, E->getBeginLoc());
15375     case UO_Extension:
15376     case UO_LNot:
15377     case UO_Plus:
15378     case UO_Minus:
15379     case UO_Not:
15380     case UO_Real:
15381     case UO_Imag:
15382       return CheckICE(Exp->getSubExpr(), Ctx);
15383     }
15384     llvm_unreachable("invalid unary operator class");
15385   }
15386   case Expr::OffsetOfExprClass: {
15387     // Note that per C99, offsetof must be an ICE. And AFAIK, using
15388     // EvaluateAsRValue matches the proposed gcc behavior for cases like
15389     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
15390     // compliance: we should warn earlier for offsetof expressions with
15391     // array subscripts that aren't ICEs, and if the array subscripts
15392     // are ICEs, the value of the offsetof must be an integer constant.
15393     return CheckEvalInICE(E, Ctx);
15394   }
15395   case Expr::UnaryExprOrTypeTraitExprClass: {
15396     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
15397     if ((Exp->getKind() ==  UETT_SizeOf) &&
15398         Exp->getTypeOfArgument()->isVariableArrayType())
15399       return ICEDiag(IK_NotICE, E->getBeginLoc());
15400     return NoDiag();
15401   }
15402   case Expr::BinaryOperatorClass: {
15403     const BinaryOperator *Exp = cast<BinaryOperator>(E);
15404     switch (Exp->getOpcode()) {
15405     case BO_PtrMemD:
15406     case BO_PtrMemI:
15407     case BO_Assign:
15408     case BO_MulAssign:
15409     case BO_DivAssign:
15410     case BO_RemAssign:
15411     case BO_AddAssign:
15412     case BO_SubAssign:
15413     case BO_ShlAssign:
15414     case BO_ShrAssign:
15415     case BO_AndAssign:
15416     case BO_XorAssign:
15417     case BO_OrAssign:
15418       // C99 6.6/3 allows assignments within unevaluated subexpressions of
15419       // constant expressions, but they can never be ICEs because an ICE cannot
15420       // contain an lvalue operand.
15421       return ICEDiag(IK_NotICE, E->getBeginLoc());
15422 
15423     case BO_Mul:
15424     case BO_Div:
15425     case BO_Rem:
15426     case BO_Add:
15427     case BO_Sub:
15428     case BO_Shl:
15429     case BO_Shr:
15430     case BO_LT:
15431     case BO_GT:
15432     case BO_LE:
15433     case BO_GE:
15434     case BO_EQ:
15435     case BO_NE:
15436     case BO_And:
15437     case BO_Xor:
15438     case BO_Or:
15439     case BO_Comma:
15440     case BO_Cmp: {
15441       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15442       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15443       if (Exp->getOpcode() == BO_Div ||
15444           Exp->getOpcode() == BO_Rem) {
15445         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
15446         // we don't evaluate one.
15447         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
15448           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
15449           if (REval == 0)
15450             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15451           if (REval.isSigned() && REval.isAllOnes()) {
15452             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
15453             if (LEval.isMinSignedValue())
15454               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15455           }
15456         }
15457       }
15458       if (Exp->getOpcode() == BO_Comma) {
15459         if (Ctx.getLangOpts().C99) {
15460           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
15461           // if it isn't evaluated.
15462           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
15463             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15464         } else {
15465           // In both C89 and C++, commas in ICEs are illegal.
15466           return ICEDiag(IK_NotICE, E->getBeginLoc());
15467         }
15468       }
15469       return Worst(LHSResult, RHSResult);
15470     }
15471     case BO_LAnd:
15472     case BO_LOr: {
15473       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15474       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15475       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
15476         // Rare case where the RHS has a comma "side-effect"; we need
15477         // to actually check the condition to see whether the side
15478         // with the comma is evaluated.
15479         if ((Exp->getOpcode() == BO_LAnd) !=
15480             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
15481           return RHSResult;
15482         return NoDiag();
15483       }
15484 
15485       return Worst(LHSResult, RHSResult);
15486     }
15487     }
15488     llvm_unreachable("invalid binary operator kind");
15489   }
15490   case Expr::ImplicitCastExprClass:
15491   case Expr::CStyleCastExprClass:
15492   case Expr::CXXFunctionalCastExprClass:
15493   case Expr::CXXStaticCastExprClass:
15494   case Expr::CXXReinterpretCastExprClass:
15495   case Expr::CXXConstCastExprClass:
15496   case Expr::ObjCBridgedCastExprClass: {
15497     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
15498     if (isa<ExplicitCastExpr>(E)) {
15499       if (const FloatingLiteral *FL
15500             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
15501         unsigned DestWidth = Ctx.getIntWidth(E->getType());
15502         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
15503         APSInt IgnoredVal(DestWidth, !DestSigned);
15504         bool Ignored;
15505         // If the value does not fit in the destination type, the behavior is
15506         // undefined, so we are not required to treat it as a constant
15507         // expression.
15508         if (FL->getValue().convertToInteger(IgnoredVal,
15509                                             llvm::APFloat::rmTowardZero,
15510                                             &Ignored) & APFloat::opInvalidOp)
15511           return ICEDiag(IK_NotICE, E->getBeginLoc());
15512         return NoDiag();
15513       }
15514     }
15515     switch (cast<CastExpr>(E)->getCastKind()) {
15516     case CK_LValueToRValue:
15517     case CK_AtomicToNonAtomic:
15518     case CK_NonAtomicToAtomic:
15519     case CK_NoOp:
15520     case CK_IntegralToBoolean:
15521     case CK_IntegralCast:
15522       return CheckICE(SubExpr, Ctx);
15523     default:
15524       return ICEDiag(IK_NotICE, E->getBeginLoc());
15525     }
15526   }
15527   case Expr::BinaryConditionalOperatorClass: {
15528     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
15529     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
15530     if (CommonResult.Kind == IK_NotICE) return CommonResult;
15531     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15532     if (FalseResult.Kind == IK_NotICE) return FalseResult;
15533     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
15534     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
15535         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
15536     return FalseResult;
15537   }
15538   case Expr::ConditionalOperatorClass: {
15539     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
15540     // If the condition (ignoring parens) is a __builtin_constant_p call,
15541     // then only the true side is actually considered in an integer constant
15542     // expression, and it is fully evaluated.  This is an important GNU
15543     // extension.  See GCC PR38377 for discussion.
15544     if (const CallExpr *CallCE
15545         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
15546       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
15547         return CheckEvalInICE(E, Ctx);
15548     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
15549     if (CondResult.Kind == IK_NotICE)
15550       return CondResult;
15551 
15552     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
15553     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15554 
15555     if (TrueResult.Kind == IK_NotICE)
15556       return TrueResult;
15557     if (FalseResult.Kind == IK_NotICE)
15558       return FalseResult;
15559     if (CondResult.Kind == IK_ICEIfUnevaluated)
15560       return CondResult;
15561     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
15562       return NoDiag();
15563     // Rare case where the diagnostics depend on which side is evaluated
15564     // Note that if we get here, CondResult is 0, and at least one of
15565     // TrueResult and FalseResult is non-zero.
15566     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
15567       return FalseResult;
15568     return TrueResult;
15569   }
15570   case Expr::CXXDefaultArgExprClass:
15571     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
15572   case Expr::CXXDefaultInitExprClass:
15573     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
15574   case Expr::ChooseExprClass: {
15575     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
15576   }
15577   case Expr::BuiltinBitCastExprClass: {
15578     if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
15579       return ICEDiag(IK_NotICE, E->getBeginLoc());
15580     return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
15581   }
15582   }
15583 
15584   llvm_unreachable("Invalid StmtClass!");
15585 }
15586 
15587 /// Evaluate an expression as a C++11 integral constant expression.
15588 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
15589                                                     const Expr *E,
15590                                                     llvm::APSInt *Value,
15591                                                     SourceLocation *Loc) {
15592   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15593     if (Loc) *Loc = E->getExprLoc();
15594     return false;
15595   }
15596 
15597   APValue Result;
15598   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
15599     return false;
15600 
15601   if (!Result.isInt()) {
15602     if (Loc) *Loc = E->getExprLoc();
15603     return false;
15604   }
15605 
15606   if (Value) *Value = Result.getInt();
15607   return true;
15608 }
15609 
15610 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
15611                                  SourceLocation *Loc) const {
15612   assert(!isValueDependent() &&
15613          "Expression evaluator can't be called on a dependent expression.");
15614 
15615   if (Ctx.getLangOpts().CPlusPlus11)
15616     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
15617 
15618   ICEDiag D = CheckICE(this, Ctx);
15619   if (D.Kind != IK_ICE) {
15620     if (Loc) *Loc = D.Loc;
15621     return false;
15622   }
15623   return true;
15624 }
15625 
15626 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx,
15627                                                     SourceLocation *Loc,
15628                                                     bool isEvaluated) const {
15629   if (isValueDependent()) {
15630     // Expression evaluator can't succeed on a dependent expression.
15631     return None;
15632   }
15633 
15634   APSInt Value;
15635 
15636   if (Ctx.getLangOpts().CPlusPlus11) {
15637     if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc))
15638       return Value;
15639     return None;
15640   }
15641 
15642   if (!isIntegerConstantExpr(Ctx, Loc))
15643     return None;
15644 
15645   // The only possible side-effects here are due to UB discovered in the
15646   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
15647   // required to treat the expression as an ICE, so we produce the folded
15648   // value.
15649   EvalResult ExprResult;
15650   Expr::EvalStatus Status;
15651   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
15652   Info.InConstantContext = true;
15653 
15654   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
15655     llvm_unreachable("ICE cannot be evaluated!");
15656 
15657   return ExprResult.Val.getInt();
15658 }
15659 
15660 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
15661   assert(!isValueDependent() &&
15662          "Expression evaluator can't be called on a dependent expression.");
15663 
15664   return CheckICE(this, Ctx).Kind == IK_ICE;
15665 }
15666 
15667 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
15668                                SourceLocation *Loc) const {
15669   assert(!isValueDependent() &&
15670          "Expression evaluator can't be called on a dependent expression.");
15671 
15672   // We support this checking in C++98 mode in order to diagnose compatibility
15673   // issues.
15674   assert(Ctx.getLangOpts().CPlusPlus);
15675 
15676   // Build evaluation settings.
15677   Expr::EvalStatus Status;
15678   SmallVector<PartialDiagnosticAt, 8> Diags;
15679   Status.Diag = &Diags;
15680   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15681 
15682   APValue Scratch;
15683   bool IsConstExpr =
15684       ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
15685       // FIXME: We don't produce a diagnostic for this, but the callers that
15686       // call us on arbitrary full-expressions should generally not care.
15687       Info.discardCleanups() && !Status.HasSideEffects;
15688 
15689   if (!Diags.empty()) {
15690     IsConstExpr = false;
15691     if (Loc) *Loc = Diags[0].first;
15692   } else if (!IsConstExpr) {
15693     // FIXME: This shouldn't happen.
15694     if (Loc) *Loc = getExprLoc();
15695   }
15696 
15697   return IsConstExpr;
15698 }
15699 
15700 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
15701                                     const FunctionDecl *Callee,
15702                                     ArrayRef<const Expr*> Args,
15703                                     const Expr *This) const {
15704   assert(!isValueDependent() &&
15705          "Expression evaluator can't be called on a dependent expression.");
15706 
15707   Expr::EvalStatus Status;
15708   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
15709   Info.InConstantContext = true;
15710 
15711   LValue ThisVal;
15712   const LValue *ThisPtr = nullptr;
15713   if (This) {
15714 #ifndef NDEBUG
15715     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
15716     assert(MD && "Don't provide `this` for non-methods.");
15717     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
15718 #endif
15719     if (!This->isValueDependent() &&
15720         EvaluateObjectArgument(Info, This, ThisVal) &&
15721         !Info.EvalStatus.HasSideEffects)
15722       ThisPtr = &ThisVal;
15723 
15724     // Ignore any side-effects from a failed evaluation. This is safe because
15725     // they can't interfere with any other argument evaluation.
15726     Info.EvalStatus.HasSideEffects = false;
15727   }
15728 
15729   CallRef Call = Info.CurrentCall->createCall(Callee);
15730   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
15731        I != E; ++I) {
15732     unsigned Idx = I - Args.begin();
15733     if (Idx >= Callee->getNumParams())
15734       break;
15735     const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
15736     if ((*I)->isValueDependent() ||
15737         !EvaluateCallArg(PVD, *I, Call, Info) ||
15738         Info.EvalStatus.HasSideEffects) {
15739       // If evaluation fails, throw away the argument entirely.
15740       if (APValue *Slot = Info.getParamSlot(Call, PVD))
15741         *Slot = APValue();
15742     }
15743 
15744     // Ignore any side-effects from a failed evaluation. This is safe because
15745     // they can't interfere with any other argument evaluation.
15746     Info.EvalStatus.HasSideEffects = false;
15747   }
15748 
15749   // Parameter cleanups happen in the caller and are not part of this
15750   // evaluation.
15751   Info.discardCleanups();
15752   Info.EvalStatus.HasSideEffects = false;
15753 
15754   // Build fake call to Callee.
15755   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call);
15756   // FIXME: Missing ExprWithCleanups in enable_if conditions?
15757   FullExpressionRAII Scope(Info);
15758   return Evaluate(Value, Info, this) && Scope.destroy() &&
15759          !Info.EvalStatus.HasSideEffects;
15760 }
15761 
15762 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
15763                                    SmallVectorImpl<
15764                                      PartialDiagnosticAt> &Diags) {
15765   // FIXME: It would be useful to check constexpr function templates, but at the
15766   // moment the constant expression evaluator cannot cope with the non-rigorous
15767   // ASTs which we build for dependent expressions.
15768   if (FD->isDependentContext())
15769     return true;
15770 
15771   Expr::EvalStatus Status;
15772   Status.Diag = &Diags;
15773 
15774   EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
15775   Info.InConstantContext = true;
15776   Info.CheckingPotentialConstantExpression = true;
15777 
15778   // The constexpr VM attempts to compile all methods to bytecode here.
15779   if (Info.EnableNewConstInterp) {
15780     Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
15781     return Diags.empty();
15782   }
15783 
15784   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
15785   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
15786 
15787   // Fabricate an arbitrary expression on the stack and pretend that it
15788   // is a temporary being used as the 'this' pointer.
15789   LValue This;
15790   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
15791   This.set({&VIE, Info.CurrentCall->Index});
15792 
15793   ArrayRef<const Expr*> Args;
15794 
15795   APValue Scratch;
15796   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
15797     // Evaluate the call as a constant initializer, to allow the construction
15798     // of objects of non-literal types.
15799     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
15800     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
15801   } else {
15802     SourceLocation Loc = FD->getLocation();
15803     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
15804                        Args, CallRef(), FD->getBody(), Info, Scratch, nullptr);
15805   }
15806 
15807   return Diags.empty();
15808 }
15809 
15810 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
15811                                               const FunctionDecl *FD,
15812                                               SmallVectorImpl<
15813                                                 PartialDiagnosticAt> &Diags) {
15814   assert(!E->isValueDependent() &&
15815          "Expression evaluator can't be called on a dependent expression.");
15816 
15817   Expr::EvalStatus Status;
15818   Status.Diag = &Diags;
15819 
15820   EvalInfo Info(FD->getASTContext(), Status,
15821                 EvalInfo::EM_ConstantExpressionUnevaluated);
15822   Info.InConstantContext = true;
15823   Info.CheckingPotentialConstantExpression = true;
15824 
15825   // Fabricate a call stack frame to give the arguments a plausible cover story.
15826   CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef());
15827 
15828   APValue ResultScratch;
15829   Evaluate(ResultScratch, Info, E);
15830   return Diags.empty();
15831 }
15832 
15833 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
15834                                  unsigned Type) const {
15835   if (!getType()->isPointerType())
15836     return false;
15837 
15838   Expr::EvalStatus Status;
15839   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
15840   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
15841 }
15842 
15843 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
15844                                   EvalInfo &Info) {
15845   if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
15846     return false;
15847 
15848   LValue String;
15849 
15850   if (!EvaluatePointer(E, String, Info))
15851     return false;
15852 
15853   QualType CharTy = E->getType()->getPointeeType();
15854 
15855   // Fast path: if it's a string literal, search the string value.
15856   if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
15857           String.getLValueBase().dyn_cast<const Expr *>())) {
15858     StringRef Str = S->getBytes();
15859     int64_t Off = String.Offset.getQuantity();
15860     if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
15861         S->getCharByteWidth() == 1 &&
15862         // FIXME: Add fast-path for wchar_t too.
15863         Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
15864       Str = Str.substr(Off);
15865 
15866       StringRef::size_type Pos = Str.find(0);
15867       if (Pos != StringRef::npos)
15868         Str = Str.substr(0, Pos);
15869 
15870       Result = Str.size();
15871       return true;
15872     }
15873 
15874     // Fall through to slow path.
15875   }
15876 
15877   // Slow path: scan the bytes of the string looking for the terminating 0.
15878   for (uint64_t Strlen = 0; /**/; ++Strlen) {
15879     APValue Char;
15880     if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
15881         !Char.isInt())
15882       return false;
15883     if (!Char.getInt()) {
15884       Result = Strlen;
15885       return true;
15886     }
15887     if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
15888       return false;
15889   }
15890 }
15891 
15892 bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
15893   Expr::EvalStatus Status;
15894   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
15895   return EvaluateBuiltinStrLen(this, Result, Info);
15896 }
15897